]> sigrok.org Git - sigrok-cli.git/blob - sigrok-cli.c
0fa343d6fd3b480ae8e5c85821314ce3631eabe5
[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 if (hwo->hwcap == SR_HWCAP_VDIV) {
336                         /* Supported volts/div values */
337                         printf("    %s", hwo->shortname);
338                         if (sr_dev_info_get(dev, SR_DI_VDIVS,
339                                         (const void **)&rationals) != SR_OK) {
340                                 printf("\n");
341                                 continue;
342                         }
343                         printf(" - supported volts/div:\n");
344                         for (i = 0; rationals[i].p && rationals[i].q; i++)
345                                 printf("      %s\n", sr_voltage_string( &rationals[i]));
346
347                 } else {
348                         /* Everything else */
349                         printf("    %s\n", hwo->shortname);
350                 }
351         }
352 }
353
354 static void show_pd_detail(void)
355 {
356         GSList *l;
357         struct srd_decoder *dec;
358         char **pdtokens, **pdtok, **ann, *doc;
359         struct srd_probe *p;
360
361         pdtokens = g_strsplit(opt_pds, ",", -1);
362         for (pdtok = pdtokens; *pdtok; pdtok++) {
363                 if (!(dec = srd_decoder_get_by_id(*pdtok))) {
364                         printf("Protocol decoder %s not found.\n", *pdtok);
365                         return;
366                 }
367                 printf("ID: %s\nName: %s\nLong name: %s\nDescription: %s\n",
368                                 dec->id, dec->name, dec->longname, dec->desc);
369                 printf("License: %s\n", dec->license);
370                 printf("Annotations:\n");
371                 if (dec->annotations) {
372                         for (l = dec->annotations; l; l = l->next) {
373                                 ann = l->data;
374                                 printf("- %s\n  %s\n", ann[0], ann[1]);
375                         }
376                 } else {
377                         printf("None.\n");
378                 }
379                 /* TODO: Print supported decoder options. */
380                 printf("Required probes:\n");
381                 if (dec->probes) {
382                         for (l = dec->probes; l; l = l->next) {
383                                 p = l->data;
384                                 printf("- %s (%s): %s\n",
385                                        p->name, p->id, p->desc);
386                         }
387                 } else {
388                         printf("None.\n");
389                 }
390                 printf("Optional probes:\n");
391                 if (dec->opt_probes) {
392                         for (l = dec->opt_probes; l; l = l->next) {
393                                 p = l->data;
394                                 printf("- %s (%s): %s\n",
395                                        p->name, p->id, p->desc);
396                         }
397                 } else {
398                         printf("None.\n");
399                 }
400                 if ((doc = srd_decoder_doc_get(dec))) {
401                         printf("Documentation:\n%s\n",
402                                doc[0] == '\n' ? doc + 1 : doc);
403                         g_free(doc);
404                 }
405         }
406
407         g_strfreev(pdtokens);
408 }
409
410 static void datafeed_in(struct sr_dev *dev, struct sr_datafeed_packet *packet)
411 {
412         static struct sr_output *o = NULL;
413         static int logic_probelist[SR_MAX_NUM_PROBES] = { 0 };
414         static struct sr_probe *analog_probelist[SR_MAX_NUM_PROBES];
415         static uint64_t received_samples = 0;
416         static int unitsize = 0;
417         static int triggered = 0;
418         static FILE *outfile = NULL;
419         static int num_analog_probes = 0;
420         struct sr_probe *probe;
421         struct sr_datafeed_logic *logic;
422         struct sr_datafeed_meta_logic *meta_logic;
423         struct sr_datafeed_analog *analog;
424         struct sr_datafeed_meta_analog *meta_analog;
425         static int num_enabled_analog_probes = 0;
426         int num_enabled_probes, sample_size, data_offset, ret, i, j;
427         uint64_t output_len, filter_out_len;
428         uint8_t *output_buf, *filter_out;
429         float asample;
430
431         /* If the first packet to come in isn't a header, don't even try. */
432         if (packet->type != SR_DF_HEADER && o == NULL)
433                 return;
434
435         sample_size = -1;
436         switch (packet->type) {
437         case SR_DF_HEADER:
438                 g_debug("cli: Received SR_DF_HEADER");
439                 /* Initialize the output module. */
440                 if (!(o = g_try_malloc(sizeof(struct sr_output)))) {
441                         g_critical("Output module malloc failed.");
442                         exit(1);
443                 }
444                 o->format = output_format;
445                 o->dev = dev;
446                 o->param = output_format_param;
447                 if (o->format->init) {
448                         if (o->format->init(o) != SR_OK) {
449                                 g_critical("Output format initialization failed.");
450                                 exit(1);
451                         }
452                 }
453                 break;
454
455         case SR_DF_END:
456                 g_debug("cli: Received SR_DF_END");
457                 if (!o) {
458                         g_debug("cli: double end!");
459                         break;
460                 }
461                 if (o->format->event) {
462                         o->format->event(o, SR_DF_END, &output_buf, &output_len);
463                         if (output_len) {
464                                 if (outfile)
465                                         fwrite(output_buf, 1, output_len, outfile);
466                                 g_free(output_buf);
467                                 output_len = 0;
468                         }
469                 }
470                 if (limit_samples && received_samples < limit_samples)
471                         g_warning("Device only sent %" PRIu64 " samples.",
472                                received_samples);
473                 if (opt_continuous)
474                         g_warning("Device stopped after %" PRIu64 " samples.",
475                                received_samples);
476                 sr_session_halt();
477                 if (outfile && outfile != stdout)
478                         fclose(outfile);
479                 g_free(o);
480                 o = NULL;
481                 break;
482
483         case SR_DF_TRIGGER:
484                 g_debug("cli: received SR_DF_TRIGGER");
485                 if (o->format->event)
486                         o->format->event(o, SR_DF_TRIGGER, &output_buf,
487                                          &output_len);
488                 triggered = 1;
489                 break;
490
491         case SR_DF_META_LOGIC:
492                 g_message("cli: Received SR_DF_META_LOGIC");
493                 meta_logic = packet->payload;
494                 num_enabled_probes = 0;
495                 for (i = 0; i < meta_logic->num_probes; i++) {
496                         probe = g_slist_nth_data(dev->probes, i);
497                         if (probe->enabled)
498                                 logic_probelist[num_enabled_probes++] = probe->index;
499                 }
500                 /* How many bytes we need to store num_enabled_probes bits */
501                 unitsize = (num_enabled_probes + 7) / 8;
502
503                 outfile = stdout;
504                 if (opt_output_file) {
505                         if (default_output_format) {
506                                 /* output file is in session format, which means we'll
507                                  * dump everything in the datastore as it comes in,
508                                  * and save from there after the session. */
509                                 outfile = NULL;
510                                 ret = sr_datastore_new(unitsize, &(dev->datastore));
511                                 if (ret != SR_OK) {
512                                         printf("Failed to create datastore.\n");
513                                         exit(1);
514                                 }
515                         } else {
516                                 /* saving to a file in whatever format was set
517                                  * with --format, so all we need is a filehandle */
518                                 outfile = g_fopen(opt_output_file, "wb");
519                         }
520                 }
521                 if (opt_pds)
522                         srd_session_start(num_enabled_probes, unitsize,
523                                         meta_logic->samplerate);
524                 break;
525
526         case SR_DF_LOGIC:
527                 logic = packet->payload;
528                 g_message("cli: received SR_DF_LOGIC, %"PRIu64" bytes", logic->length);
529                 sample_size = logic->unitsize;
530                 if (logic->length == 0)
531                         break;
532
533                 /* Don't store any samples until triggered. */
534                 if (opt_wait_trigger && !triggered)
535                         break;
536
537                 if (limit_samples && received_samples >= limit_samples)
538                         break;
539
540                 ret = sr_filter_probes(sample_size, unitsize, logic_probelist,
541                                            logic->data, logic->length,
542                                            &filter_out, &filter_out_len);
543                 if (ret != SR_OK)
544                         break;
545
546                 /* what comes out of the filter is guaranteed to be packed into the
547                  * minimum size needed to support the number of samples at this sample
548                  * size. however, the driver may have submitted too much -- cut off
549                  * the buffer of the last packet according to the sample limit.
550                  */
551                 if (limit_samples && (received_samples + logic->length / sample_size >
552                                 limit_samples * sample_size))
553                         filter_out_len = limit_samples * sample_size - received_samples;
554
555                 if (dev->datastore)
556                         sr_datastore_put(dev->datastore, filter_out,
557                                          filter_out_len, sample_size, logic_probelist);
558
559                 if (opt_output_file && default_output_format)
560                         /* saving to a session file, don't need to do anything else
561                          * to this data for now. */
562                         goto cleanup;
563
564                 if (opt_pds) {
565                         if (srd_session_send(received_samples, (uint8_t*)filter_out,
566                                         filter_out_len) != SRD_OK)
567                                 sr_session_halt();
568                 } else {
569                         output_len = 0;
570                         if (o->format->data && packet->type == o->format->df_type)
571                                 o->format->data(o, filter_out, filter_out_len, &output_buf, &output_len);
572                         if (output_len) {
573                                 fwrite(output_buf, 1, output_len, outfile);
574                                 g_free(output_buf);
575                         }
576                 }
577
578                 cleanup:
579                 g_free(filter_out);
580                 received_samples += logic->length / sample_size;
581                 break;
582
583         case SR_DF_META_ANALOG:
584                 g_message("cli: Received SR_DF_META_ANALOG");
585                 meta_analog = packet->payload;
586                 num_analog_probes = meta_analog->num_probes;
587                 num_enabled_analog_probes = 0;
588                 for (i = 0; i < num_analog_probes; i++) {
589                         probe = g_slist_nth_data(dev->probes, i);
590                         if (probe->enabled)
591                                 analog_probelist[num_enabled_analog_probes++] = probe;
592                 }
593
594                 outfile = stdout;
595                 if (opt_output_file) {
596                         if (default_output_format) {
597                                 /* output file is in session format, which means we'll
598                                  * dump everything in the datastore as it comes in,
599                                  * and save from there after the session. */
600                                 outfile = NULL;
601                                 ret = sr_datastore_new(unitsize, &(dev->datastore));
602                                 if (ret != SR_OK) {
603                                         printf("Failed to create datastore.\n");
604                                         exit(1);
605                                 }
606                         } else {
607                                 /* saving to a file in whatever format was set
608                                  * with --format, so all we need is a filehandle */
609                                 outfile = g_fopen(opt_output_file, "wb");
610                         }
611                 }
612 //              if (opt_pds)
613 //                      srd_session_start(num_enabled_probes, unitsize,
614 //                                      meta_logic->samplerate);
615                 break;
616
617         case SR_DF_ANALOG:
618                 analog = packet->payload;
619                 g_message("cli: received SR_DF_ANALOG, %d samples", analog->num_samples);
620                 if (analog->num_samples == 0)
621                         break;
622
623                 if (limit_samples && received_samples >= limit_samples)
624                         break;
625
626                 data_offset = 0;
627                 for (i = 0; i < analog->num_samples; i++) {
628                         for (j = 0; j < num_enabled_analog_probes; j++) {
629                                 asample = analog->data[data_offset++];
630                                 printf("%s: %f\n", analog_probelist[j]->name, asample);
631                         }
632 //                      asample1 = asample2 = 0.0;
633 //                      asample1 = analog->data[data_offset++];
634 //                      asample2 = analog->data[i * num_analog_probes + 1];
635 //                      printf("%d\t%f\t%f\n", received_samples+i+1, asample1, asample2);
636                 }
637
638 //              output_len = 0;
639 //              if (o->format->data && packet->type == o->format->df_type)
640 //                      o->format->data(o, filter_out, filter_out_len, &output_buf, &output_len);
641
642                 received_samples += analog->num_samples;
643                 break;
644
645         case SR_DF_FRAME_BEGIN:
646                 /* TODO */
647                 printf("BEGIN\n");
648                 break;
649
650         case SR_DF_FRAME_END:
651                 /* TODO */
652                 printf("END\n");
653                 break;
654
655         default:
656                 g_message("received unknown packet type %d", packet->type);
657         }
658
659 }
660
661 /* Register the given PDs for this session.
662  * Accepts a string of the form: "spi:sck=3:sdata=4,spi:sck=3:sdata=5"
663  * That will instantiate two SPI decoders on the clock but different data
664  * lines.
665  */
666 static int register_pds(struct sr_dev *dev, const char *pdstring)
667 {
668         GHashTable *pd_opthash;
669         struct srd_decoder_inst *di;
670         int ret;
671         char **pdtokens, **pdtok, *pd_name;
672
673         /* Avoid compiler warnings. */
674         (void)dev;
675
676         ret = 0;
677         pd_ann_visible = g_hash_table_new_full(g_str_hash, g_int_equal,
678                         g_free, NULL);
679         pd_name = NULL;
680         pd_opthash = NULL;
681         pdtokens = g_strsplit(pdstring, ",", 0);
682         for (pdtok = pdtokens; *pdtok; pdtok++) {
683                 if (!(pd_opthash = parse_generic_arg(*pdtok))) {
684                         g_critical("Invalid protocol decoder option '%s'.", *pdtok);
685                         goto err_out;
686                 }
687
688                 pd_name = g_strdup(g_hash_table_lookup(pd_opthash, "sigrok_key"));
689                 g_hash_table_remove(pd_opthash, "sigrok_key");
690                 if (srd_decoder_load(pd_name) != SRD_OK) {
691                         g_critical("Failed to load protocol decoder %s.", pd_name);
692                         ret = 1;
693                         goto err_out;
694                 }
695                 if (!(di = srd_inst_new(pd_name, pd_opthash))) {
696                         g_critical("Failed to instantiate protocol decoder %s.", pd_name);
697                         ret = 1;
698                         goto err_out;
699                 }
700
701                 /* If no annotation list was specified, add them all in now.
702                  * This will be pared down later to leave only the last PD
703                  * in the stack.
704                  */
705                 if (!opt_pd_annotations)
706                         g_hash_table_insert(pd_ann_visible,
707                                             g_strdup(di->inst_id), NULL);
708
709                 /* Any keys left in the options hash are probes, where the key
710                  * is the probe name as specified in the decoder class, and the
711                  * value is the probe number i.e. the order in which the PD's
712                  * incoming samples are arranged. */
713                 if (srd_inst_probe_set_all(di, pd_opthash) != SRD_OK) {
714                         ret = 1;
715                         goto err_out;
716                 }
717                 g_hash_table_destroy(pd_opthash);
718                 pd_opthash = NULL;
719         }
720
721 err_out:
722         g_strfreev(pdtokens);
723         if (pd_opthash)
724                 g_hash_table_destroy(pd_opthash);
725         if (pd_name)
726                 g_free(pd_name);
727
728         return ret;
729 }
730
731 int setup_pd_stack(void)
732 {
733         struct srd_decoder_inst *di_from, *di_to;
734         int ret, i;
735         char **pds;
736
737         /* Set up the protocol decoder stack. */
738         pds = g_strsplit(opt_pds, ",", 0);
739         if (g_strv_length(pds) > 1) {
740                 if (opt_pd_stack) {
741                         /* A stack setup was specified, use that. */
742                         g_strfreev(pds);
743                         pds = g_strsplit(opt_pd_stack, ",", 0);
744                         if (g_strv_length(pds) < 2) {
745                                 g_strfreev(pds);
746                                 g_critical("Specify at least two protocol decoders to stack.");
747                                 return 1;
748                         }
749                 }
750
751                 if (!(di_from = srd_inst_find_by_id(pds[0]))) {
752                         g_critical("Cannot stack protocol decoder '%s': "
753                                         "instance not found.", pds[0]);
754                         return 1;
755                 }
756                 for (i = 1; pds[i]; i++) {
757                         if (!(di_to = srd_inst_find_by_id(pds[i]))) {
758                                 g_critical("Cannot stack protocol decoder '%s': "
759                                                 "instance not found.", pds[i]);
760                                 return 1;
761                         }
762                         if ((ret = srd_inst_stack(di_from, di_to)) != SRD_OK)
763                                 return 1;
764
765                         /* Don't show annotation from this PD. Only the last PD in
766                          * the stack will be left on the annotation list (unless
767                          * the annotation list was specifically provided).
768                          */
769                         if (!opt_pd_annotations)
770                                 g_hash_table_remove(pd_ann_visible,
771                                                     di_from->inst_id);
772
773                         di_from = di_to;
774                 }
775         }
776         g_strfreev(pds);
777
778         return 0;
779 }
780
781 int setup_pd_annotations(void)
782 {
783         GSList *l;
784         struct srd_decoder *dec;
785         int ann;
786         char **pds, **pdtok, **keyval, **ann_descr;
787
788         /* Set up custom list of PDs and annotations to show. */
789         if (opt_pd_annotations) {
790                 pds = g_strsplit(opt_pd_annotations, ",", 0);
791                 for (pdtok = pds; *pdtok && **pdtok; pdtok++) {
792                         ann = 0;
793                         keyval = g_strsplit(*pdtok, "=", 0);
794                         if (!(dec = srd_decoder_get_by_id(keyval[0]))) {
795                                 g_critical("Protocol decoder '%s' not found.", keyval[0]);
796                                 return 1;
797                         }
798                         if (!dec->annotations) {
799                                 g_critical("Protocol decoder '%s' has no annotations.", keyval[0]);
800                                 return 1;
801                         }
802                         if (g_strv_length(keyval) == 2) {
803                                 for (l = dec->annotations; l; l = l->next, ann++) {
804                                         ann_descr = l->data;
805                                         if (!canon_cmp(ann_descr[0], keyval[1]))
806                                                 /* Found it. */
807                                                 break;
808                                 }
809                                 if (!l) {
810                                         g_critical("Annotation '%s' not found "
811                                                         "for protocol decoder '%s'.", keyval[1], keyval[0]);
812                                         return 1;
813                                 }
814                         }
815                         g_debug("cli: showing protocol decoder annotation %d from '%s'", ann, keyval[0]);
816                         g_hash_table_insert(pd_ann_visible, g_strdup(keyval[0]), GINT_TO_POINTER(ann));
817                         g_strfreev(keyval);
818                 }
819                 g_strfreev(pds);
820         }
821
822         return 0;
823 }
824
825 int setup_output_format(void)
826 {
827         GHashTable *fmtargs;
828         GHashTableIter iter;
829         gpointer key, value;
830         struct sr_output_format **outputs;
831         int i;
832         char *fmtspec;
833
834         if (!opt_output_format) {
835                 opt_output_format = DEFAULT_OUTPUT_FORMAT;
836                 /* we'll need to remember this so when saving to a file
837                  * later, sigrok session format will be used.
838                  */
839                 default_output_format = TRUE;
840         }
841         fmtargs = parse_generic_arg(opt_output_format);
842         fmtspec = g_hash_table_lookup(fmtargs, "sigrok_key");
843         if (!fmtspec) {
844                 g_critical("Invalid output format.");
845                 return 1;
846         }
847         outputs = sr_output_list();
848         for (i = 0; outputs[i]; i++) {
849                 if (strcmp(outputs[i]->id, fmtspec))
850                         continue;
851                 g_hash_table_remove(fmtargs, "sigrok_key");
852                 output_format = outputs[i];
853                 g_hash_table_iter_init(&iter, fmtargs);
854                 while (g_hash_table_iter_next(&iter, &key, &value)) {
855                         /* only supporting one parameter per output module
856                          * for now, and only its value */
857                         output_format_param = g_strdup(value);
858                         break;
859                 }
860                 break;
861         }
862         if (!output_format) {
863                 g_critical("Invalid output format %s.", opt_output_format);
864                 return 1;
865         }
866         g_hash_table_destroy(fmtargs);
867
868         return 0;
869 }
870
871 void show_pd_annotations(struct srd_proto_data *pdata, void *cb_data)
872 {
873         int i;
874         char **annotations;
875         gpointer ann_format;
876
877         /* 'cb_data' is not used in this specific callback. */
878         (void)cb_data;
879
880         if (!pd_ann_visible)
881                 return;
882
883         if (!g_hash_table_lookup_extended(pd_ann_visible, pdata->pdo->di->inst_id,
884                         NULL, &ann_format))
885                 /* Not in the list of PDs whose annotations we're showing. */
886                 return;
887
888         if (pdata->ann_format != GPOINTER_TO_INT(ann_format))
889                 /* We don't want this particular format from the PD. */
890                 return;
891
892         annotations = pdata->data;
893         if (opt_loglevel > SR_LOG_WARN)
894                 printf("%"PRIu64"-%"PRIu64" ", pdata->start_sample, pdata->end_sample);
895         printf("%s: ", pdata->pdo->proto_id);
896         for (i = 0; annotations[i]; i++)
897                 printf("\"%s\" ", annotations[i]);
898         printf("\n");
899 }
900
901 static int select_probes(struct sr_dev *dev)
902 {
903         struct sr_probe *probe;
904         char **probelist;
905         int max_probes, i;
906
907         if (!opt_probes)
908                 return SR_OK;
909
910         /*
911          * This only works because a device by default initializes
912          * and enables all its probes.
913          */
914         max_probes = g_slist_length(dev->probes);
915         probelist = parse_probestring(max_probes, opt_probes);
916         if (!probelist) {
917                 return SR_ERR;
918         }
919
920         for (i = 0; i < max_probes; i++) {
921                 if (probelist[i]) {
922                         sr_dev_probe_name_set(dev, i + 1, probelist[i]);
923                         g_free(probelist[i]);
924                 } else {
925                         probe = sr_dev_probe_find(dev, i + 1);
926                         probe->enabled = FALSE;
927                 }
928         }
929         g_free(probelist);
930
931         return SR_OK;
932 }
933
934 /**
935  * Return the input file format which the CLI tool should use.
936  *
937  * If the user specified -I / --input-format, use that one. Otherwise, try to
938  * autodetect the format as good as possible. Failing that, return NULL.
939  *
940  * @param filename The filename of the input file. Must not be NULL.
941  * @param opt The -I / --input-file option the user specified (or NULL).
942  *
943  * @return A pointer to the 'struct sr_input_format' that should be used,
944  *         or NULL if no input format was selected or auto-detected.
945  */
946 static struct sr_input_format *determine_input_file_format(
947                         const char *filename, const char *opt)
948 {
949         int i;
950         struct sr_input_format **inputs;
951
952         /* If there are no input formats, return NULL right away. */
953         inputs = sr_input_list();
954         if (!inputs) {
955                 g_critical("No supported input formats available.");
956                 return NULL;
957         }
958
959         /* If the user specified -I / --input-format, use that one. */
960         if (opt) {
961                 for (i = 0; inputs[i]; i++) {
962                         if (strcasecmp(inputs[i]->id, opt_input_format))
963                                 continue;
964                         g_debug("Using user-specified input file format '%s'.",
965                                         inputs[i]->id);
966                         return inputs[i];
967                 }
968
969                 /* The user specified an unknown input format, return NULL. */
970                 g_critical("Error: specified input file format '%s' is "
971                         "unknown.", opt_input_format);
972                 return NULL;
973         }
974
975         /* Otherwise, try to find an input module that can handle this file. */
976         for (i = 0; inputs[i]; i++) {
977                 if (inputs[i]->format_match(filename))
978                         break;
979         }
980
981         /* Return NULL if no input module wanted to touch this. */
982         if (!inputs[i]) {
983                 g_critical("Error: no matching input module found.");
984                 return NULL;
985         }
986
987         g_debug("cli: Autodetected '%s' input format for file '%s'.",
988                 inputs[i]->id, filename);
989                 
990         return inputs[i];
991 }
992
993 static void load_input_file_format(void)
994 {
995         struct stat st;
996         struct sr_input *in;
997         struct sr_input_format *input_format;
998
999         if (!(input_format = determine_input_file_format(opt_input_file,
1000                                                    opt_input_format)))
1001                 /* The exact cause was already logged. */
1002                 return;
1003
1004         if (stat(opt_input_file, &st) == -1) {
1005                 g_critical("Failed to load %s: %s", opt_input_file,
1006                         strerror(errno));
1007                 exit(1);
1008         }
1009
1010         /* Initialize the input module. */
1011         if (!(in = g_try_malloc(sizeof(struct sr_input)))) {
1012                 g_critical("Failed to allocate input module.");
1013                 exit(1);
1014         }
1015         in->format = input_format;
1016         in->param = input_format_param;
1017         if (in->format->init) {
1018                 if (in->format->init(in) != SR_OK) {
1019                         g_critical("Input format init failed.");
1020                         exit(1);
1021                 }
1022         }
1023
1024         if (select_probes(in->vdev) > 0)
1025             return;
1026
1027         sr_session_new();
1028         sr_session_datafeed_callback_add(datafeed_in);
1029         if (sr_session_dev_add(in->vdev) != SR_OK) {
1030                 g_critical("Failed to use device.");
1031                 sr_session_destroy();
1032                 return;
1033         }
1034
1035         input_format->loadfile(in, opt_input_file);
1036         if (opt_output_file && default_output_format) {
1037                 if (sr_session_save(opt_output_file) != SR_OK)
1038                         g_critical("Failed to save session.");
1039         }
1040         sr_session_destroy();
1041 }
1042
1043 static void load_input_file(void)
1044 {
1045
1046         if (sr_session_load(opt_input_file) == SR_OK) {
1047                 /* sigrok session file */
1048                 sr_session_datafeed_callback_add(datafeed_in);
1049                 sr_session_start();
1050                 sr_session_run();
1051                 sr_session_stop();
1052         }
1053         else {
1054                 /* fall back on input modules */
1055                 load_input_file_format();
1056         }
1057 }
1058
1059 int num_real_devs(void)
1060 {
1061         struct sr_dev *dev;
1062         GSList *devs, *l;
1063         int num_devs;
1064
1065         num_devs = 0;
1066         devs = sr_dev_list();
1067         for (l = devs; l; l = l->next) {
1068                 dev = l->data;
1069                 if (!sr_dev_has_hwcap(dev, SR_HWCAP_DEMO_DEV))
1070                         num_devs++;
1071         }
1072
1073         return num_devs;
1074 }
1075
1076 static int set_dev_options(struct sr_dev *dev, GHashTable *args)
1077 {
1078         GHashTableIter iter;
1079         gpointer key, value;
1080         int ret, i;
1081         float tmp_float;
1082         uint64_t tmp_u64;
1083         struct sr_rational tmp_rat;
1084         gboolean tmp_bool;
1085         gboolean found;
1086
1087         g_hash_table_iter_init(&iter, args);
1088         while (g_hash_table_iter_next(&iter, &key, &value)) {
1089                 found = FALSE;
1090                 for (i = 0; sr_hwcap_options[i].hwcap; i++) {
1091                         if (strcmp(sr_hwcap_options[i].shortname, key))
1092                                 continue;
1093                         if ((value == NULL) && 
1094                             (sr_hwcap_options[i].type != SR_T_BOOL)) {
1095                                 g_critical("Option '%s' needs a value.", (char *)key);
1096                                 return SR_ERR;
1097                         }
1098                         found = TRUE;
1099                         switch (sr_hwcap_options[i].type) {
1100                         case SR_T_UINT64:
1101                                 ret = sr_parse_sizestring(value, &tmp_u64);
1102                                 if (ret != SR_OK)
1103                                         break;
1104                                 ret = dev->driver->dev_config_set(dev->driver_index,
1105                                         sr_hwcap_options[i].hwcap, &tmp_u64);
1106                                 break;
1107                         case SR_T_CHAR:
1108                                 ret = dev->driver->dev_config_set(dev->driver_index,
1109                                         sr_hwcap_options[i].hwcap, value);
1110                                 break;
1111                         case SR_T_BOOL:
1112                                 if (!value)
1113                                         tmp_bool = TRUE;
1114                                 else 
1115                                         tmp_bool = sr_parse_boolstring(value);
1116                                 ret = dev->driver->dev_config_set(dev->driver_index,
1117                                                 sr_hwcap_options[i].hwcap, 
1118                                                 GINT_TO_POINTER(tmp_bool));
1119                                 break;
1120                         case SR_T_FLOAT:
1121                                 tmp_float = strtof(value, NULL);
1122                                 ret = dev->driver->dev_config_set(dev->driver_index,
1123                                                 sr_hwcap_options[i].hwcap, &tmp_float);
1124                                 break;
1125                         case SR_T_RATIONAL_PERIOD:
1126                                 if ((ret = sr_parse_period(value, &tmp_rat)) != SR_OK)
1127                                         break;
1128                                 ret = dev->driver->dev_config_set(dev->driver_index,
1129                                                 sr_hwcap_options[i].hwcap, &tmp_rat);
1130                                 break;
1131                         case SR_T_RATIONAL_VOLT:
1132                                 if ((ret = sr_parse_voltage(value, &tmp_rat)) != SR_OK)
1133                                         break;
1134                                 ret = dev->driver->dev_config_set(dev->driver_index,
1135                                                 sr_hwcap_options[i].hwcap, &tmp_rat);
1136                                 break;
1137                         default:
1138                                 ret = SR_ERR;
1139                         }
1140
1141                         if (ret != SR_OK) {
1142                                 g_critical("Failed to set device option '%s'.", (char *)key);
1143                                 return ret;
1144                         }
1145                         else
1146                                 break;
1147                 }
1148                 if (!found) {
1149                         g_critical("Unknown device option '%s'.", (char *) key);
1150                         return SR_ERR;
1151                 }
1152         }
1153
1154         return SR_OK;
1155 }
1156
1157 static void run_session(void)
1158 {
1159         struct sr_dev *dev;
1160         GHashTable *devargs;
1161         int num_devs, max_probes, i;
1162         uint64_t time_msec;
1163         char **probelist, *devspec;
1164
1165         devargs = NULL;
1166         if (opt_dev) {
1167                 devargs = parse_generic_arg(opt_dev);
1168                 devspec = g_hash_table_lookup(devargs, "sigrok_key");
1169                 dev = parse_devstring(devspec);
1170                 if (!dev) {
1171                         g_critical("Device not found.");
1172                         return;
1173                 }
1174                 g_hash_table_remove(devargs, "sigrok_key");
1175         } else {
1176                 num_devs = num_real_devs();
1177                 if (num_devs == 1) {
1178                         /* No device specified, but there is only one. */
1179                         devargs = NULL;
1180                         dev = parse_devstring("0");
1181                 } else if (num_devs == 0) {
1182                         g_critical("No devices found.");
1183                         return;
1184                 } else {
1185                         g_critical("%d devices found, please select one.", num_devs);
1186                         return;
1187                 }
1188         }
1189
1190         sr_session_new();
1191         sr_session_datafeed_callback_add(datafeed_in);
1192
1193         if (sr_session_dev_add(dev) != SR_OK) {
1194                 g_critical("Failed to use device.");
1195                 sr_session_destroy();
1196                 return;
1197         }
1198
1199         if (devargs) {
1200                 if (set_dev_options(dev, devargs) != SR_OK) {
1201                         sr_session_destroy();
1202                         return;
1203                 }
1204                 g_hash_table_destroy(devargs);
1205         }
1206
1207         if (select_probes(dev) != SR_OK)
1208             return;
1209
1210         if (opt_continuous) {
1211                 if (!sr_driver_hwcap_exists(dev->driver, SR_HWCAP_CONTINUOUS)) {
1212                         g_critical("This device does not support continuous sampling.");
1213                         sr_session_destroy();
1214                         return;
1215                 }
1216         }
1217
1218         if (opt_triggers) {
1219                 probelist = sr_parse_triggerstring(dev, opt_triggers);
1220                 if (!probelist) {
1221                         sr_session_destroy();
1222                         return;
1223                 }
1224
1225                 max_probes = g_slist_length(dev->probes);
1226                 for (i = 0; i < max_probes; i++) {
1227                         if (probelist[i]) {
1228                                 sr_dev_trigger_set(dev, i + 1, probelist[i]);
1229                                 g_free(probelist[i]);
1230                         }
1231                 }
1232                 g_free(probelist);
1233         }
1234
1235         if (opt_time) {
1236                 time_msec = sr_parse_timestring(opt_time);
1237                 if (time_msec == 0) {
1238                         g_critical("Invalid time '%s'", opt_time);
1239                         sr_session_destroy();
1240                         return;
1241                 }
1242
1243                 if (sr_driver_hwcap_exists(dev->driver, SR_HWCAP_LIMIT_MSEC)) {
1244                         if (dev->driver->dev_config_set(dev->driver_index,
1245                             SR_HWCAP_LIMIT_MSEC, &time_msec) != SR_OK) {
1246                                 g_critical("Failed to configure time limit.");
1247                                 sr_session_destroy();
1248                                 return;
1249                         }
1250                 }
1251                 else {
1252                         /* time limit set, but device doesn't support this...
1253                          * convert to samples based on the samplerate.
1254                          */
1255                         limit_samples = 0;
1256                         if (sr_dev_has_hwcap(dev, SR_HWCAP_SAMPLERATE)) {
1257                                 const uint64_t *samplerate;
1258
1259                                 sr_dev_info_get(dev, SR_DI_CUR_SAMPLERATE,
1260                                                 (const void **)&samplerate);
1261                                 limit_samples = (*samplerate) * time_msec / (uint64_t)1000;
1262                         }
1263                         if (limit_samples == 0) {
1264                                 g_critical("Not enough time at this samplerate.");
1265                                 sr_session_destroy();
1266                                 return;
1267                         }
1268
1269                         if (dev->driver->dev_config_set(dev->driver_index,
1270                             SR_HWCAP_LIMIT_SAMPLES, &limit_samples) != SR_OK) {
1271                                 g_critical("Failed to configure time-based sample limit.");
1272                                 sr_session_destroy();
1273                                 return;
1274                         }
1275                 }
1276         }
1277
1278         if (opt_samples) {
1279                 if ((sr_parse_sizestring(opt_samples, &limit_samples) != SR_OK)
1280                         || (dev->driver->dev_config_set(dev->driver_index,
1281                             SR_HWCAP_LIMIT_SAMPLES, &limit_samples) != SR_OK)) {
1282                         g_critical("Failed to configure sample limit.");
1283                         sr_session_destroy();
1284                         return;
1285                 }
1286         }
1287
1288         if (opt_frames) {
1289                 if ((sr_parse_sizestring(opt_frames, &limit_frames) != SR_OK)
1290                         || (dev->driver->dev_config_set(dev->driver_index,
1291                             SR_HWCAP_LIMIT_FRAMES, &limit_frames) != SR_OK)) {
1292                         printf("Failed to configure frame limit.\n");
1293                         sr_session_destroy();
1294                         return;
1295                 }
1296         }
1297
1298         if (dev->driver->dev_config_set(dev->driver_index,
1299                   SR_HWCAP_PROBECONFIG, (char *)dev->probes) != SR_OK) {
1300                 g_critical("Failed to configure probes.");
1301                 sr_session_destroy();
1302                 return;
1303         }
1304
1305         if (sr_session_start() != SR_OK) {
1306                 g_critical("Failed to start session.");
1307                 sr_session_destroy();
1308                 return;
1309         }
1310
1311         if (opt_continuous)
1312                 add_anykey();
1313
1314         sr_session_run();
1315
1316         if (opt_continuous)
1317                 clear_anykey();
1318
1319         if (opt_output_file && default_output_format) {
1320                 if (sr_session_save(opt_output_file) != SR_OK)
1321                         g_critical("Failed to save session.");
1322         }
1323         sr_session_destroy();
1324 }
1325
1326 static void logger(const gchar *log_domain, GLogLevelFlags log_level,
1327                    const gchar *message, gpointer cb_data)
1328 {
1329         /* Avoid compiler warnings. */
1330         (void)log_domain;
1331         (void)cb_data;
1332
1333         /*
1334          * All messages, warnings, errors etc. go to stderr (not stdout) in
1335          * order to not mess up the CLI tool data output, e.g. VCD output.
1336          */
1337         if (log_level & (G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_WARNING)
1338                         || opt_loglevel > SR_LOG_WARN) {
1339                 fprintf(stderr, "%s\n", message);
1340                 fflush(stderr);
1341         }
1342 }
1343
1344 int main(int argc, char **argv)
1345 {
1346         GOptionContext *context;
1347         GError *error;
1348
1349         g_log_set_default_handler(logger, NULL);
1350
1351         error = NULL;
1352         context = g_option_context_new(NULL);
1353         g_option_context_add_main_entries(context, optargs, NULL);
1354
1355         if (!g_option_context_parse(context, &argc, &argv, &error)) {
1356                 g_critical("%s", error->message);
1357                 return 1;
1358         }
1359
1360         /* Set the loglevel (amount of messages to output) for libsigrok. */
1361         if (sr_log_loglevel_set(opt_loglevel) != SR_OK)
1362                 return 1;
1363
1364         /* Set the loglevel (amount of messages to output) for libsigrokdecode. */
1365         if (srd_log_loglevel_set(opt_loglevel) != SRD_OK)
1366                 return 1;
1367
1368         if (sr_init() != SR_OK)
1369                 return 1;
1370
1371         if (opt_pds) {
1372                 if (srd_init(NULL) != SRD_OK)
1373                         return 1;
1374                 if (register_pds(NULL, opt_pds) != 0)
1375                         return 1;
1376                 if (srd_pd_output_callback_add(SRD_OUTPUT_ANN,
1377                                 show_pd_annotations, NULL) != SRD_OK)
1378                         return 1;
1379                 if (setup_pd_stack() != 0)
1380                         return 1;
1381                 if (setup_pd_annotations() != 0)
1382                         return 1;
1383         }
1384
1385         if (setup_output_format() != 0)
1386                 return 1;
1387
1388         if (opt_version)
1389                 show_version();
1390         else if (opt_list_devs)
1391                 show_dev_list();
1392         else if (opt_input_file)
1393                 load_input_file();
1394         else if (opt_samples || opt_time || opt_frames || opt_continuous)
1395                 run_session();
1396         else if (opt_dev)
1397                 show_dev_detail();
1398         else if (opt_pds)
1399                 show_pd_detail();
1400         else
1401                 printf("%s", g_option_context_get_help(context, TRUE, NULL));
1402
1403         if (opt_pds)
1404                 srd_exit();
1405
1406         g_option_context_free(context);
1407         sr_exit();
1408
1409         return 0;
1410 }