session: Supply filename to the output module directly
[sigrok-cli.git] / session.c
1 /*
2  * This file is part of the sigrok-cli project.
3  *
4  * Copyright (C) 2013 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 <glib.h>
21 #include <glib/gstdio.h>
22 #include <string.h>
23 #include <stdlib.h>
24 #include "sigrok-cli.h"
25
26 static uint64_t limit_samples = 0;
27 static uint64_t limit_frames = 0;
28
29 #ifdef HAVE_SRD
30 extern struct srd_session *srd_sess;
31 #endif
32
33 static int set_limit_time(const struct sr_dev_inst *sdi)
34 {
35         GVariant *gvar;
36         uint64_t time_msec;
37         uint64_t samplerate;
38         struct sr_dev_driver *driver;
39
40         driver = sr_dev_inst_driver_get(sdi);
41
42         if (!(time_msec = sr_parse_timestring(opt_time))) {
43                 g_critical("Invalid time '%s'", opt_time);
44                 return SR_ERR;
45         }
46
47         if (config_key_has_cap(driver, sdi, NULL, SR_CONF_LIMIT_MSEC, SR_CONF_SET)) {
48                 gvar = g_variant_new_uint64(time_msec);
49                 if (sr_config_set(sdi, NULL, SR_CONF_LIMIT_MSEC, gvar) != SR_OK) {
50                         g_critical("Failed to configure time limit.");
51                         return SR_ERR;
52                 }
53         } else if (config_key_has_cap(driver, sdi, NULL, SR_CONF_SAMPLERATE,
54                         SR_CONF_GET | SR_CONF_SET)) {
55                 /* Convert to samples based on the samplerate. */
56                 sr_config_get(driver, sdi, NULL, SR_CONF_SAMPLERATE, &gvar);
57                 samplerate = g_variant_get_uint64(gvar);
58                 g_variant_unref(gvar);
59                 limit_samples = (samplerate) * time_msec / (uint64_t)1000;
60                 if (limit_samples == 0) {
61                         g_critical("Not enough time at this samplerate.");
62                         return SR_ERR;
63                 }
64                 gvar = g_variant_new_uint64(limit_samples);
65                 if (sr_config_set(sdi, NULL, SR_CONF_LIMIT_SAMPLES, gvar) != SR_OK) {
66                         g_critical("Failed to configure time-based sample limit.");
67                         return SR_ERR;
68                 }
69         } else {
70                 g_critical("This device does not support time limits.");
71                 return SR_ERR;
72         }
73
74         return SR_OK;
75 }
76
77 const struct sr_output *setup_output_format(const struct sr_dev_inst *sdi)
78 {
79         const struct sr_output_module *omod;
80         const struct sr_option **options;
81         const struct sr_output *o;
82         GHashTable *fmtargs, *fmtopts;
83         char *fmtspec;
84
85         if (!opt_output_format) {
86                 if (opt_output_file) {
87                         opt_output_format = DEFAULT_OUTPUT_FORMAT_FILE;
88                 } else {
89                         opt_output_format = DEFAULT_OUTPUT_FORMAT_NOFILE;
90                 }
91         }
92
93         fmtargs = parse_generic_arg(opt_output_format, TRUE);
94         fmtspec = g_hash_table_lookup(fmtargs, "sigrok_key");
95         if (!fmtspec)
96                 g_critical("Invalid output format.");
97         if (!(omod = sr_output_find(fmtspec)))
98                 g_critical("Unknown output module '%s'.", fmtspec);
99         g_hash_table_remove(fmtargs, "sigrok_key");
100         if ((options = sr_output_options_get(omod))) {
101                 fmtopts = generic_arg_to_opt(options, fmtargs);
102                 sr_output_options_free(options);
103         } else
104                 fmtopts = NULL;
105         o = sr_output_new(omod, fmtopts, sdi, opt_output_file);
106
107         if (fmtopts)
108                 g_hash_table_destroy(fmtopts);
109         g_hash_table_destroy(fmtargs);
110
111         return o;
112 }
113
114 const struct sr_transform *setup_transform_module(const struct sr_dev_inst *sdi)
115 {
116         const struct sr_transform_module *tmod;
117         const struct sr_option **options;
118         const struct sr_transform *t;
119         GHashTable *fmtargs, *fmtopts;
120         char *fmtspec;
121
122         if (!opt_transform_module)
123                 opt_transform_module = "nop";
124
125         fmtargs = parse_generic_arg(opt_transform_module, TRUE);
126         fmtspec = g_hash_table_lookup(fmtargs, "sigrok_key");
127         if (!fmtspec)
128                 g_critical("Invalid transform module.");
129         if (!(tmod = sr_transform_find(fmtspec)))
130                 g_critical("Unknown transform module '%s'.", fmtspec);
131         g_hash_table_remove(fmtargs, "sigrok_key");
132         if ((options = sr_transform_options_get(tmod))) {
133                 fmtopts = generic_arg_to_opt(options, fmtargs);
134                 sr_transform_options_free(options);
135         } else
136                 fmtopts = NULL;
137         t = sr_transform_new(tmod, fmtopts, sdi);
138         if (fmtopts)
139                 g_hash_table_destroy(fmtopts);
140         g_hash_table_destroy(fmtargs);
141
142         return t;
143 }
144
145 void datafeed_in(const struct sr_dev_inst *sdi,
146                 const struct sr_datafeed_packet *packet, void *cb_data)
147 {
148         const struct sr_datafeed_meta *meta;
149         const struct sr_datafeed_logic *logic;
150         const struct sr_datafeed_analog *analog;
151         struct sr_session *session;
152         struct sr_config *src;
153         static const struct sr_output *o = NULL;
154         static const struct sr_output *oa = NULL;
155         static uint64_t rcvd_samples_logic = 0;
156         static uint64_t rcvd_samples_analog = 0;
157         static uint64_t samplerate = 0;
158         static int triggered = 0;
159         static FILE *outfile = NULL;
160         GSList *l;
161         GString *out;
162         GVariant *gvar;
163         uint64_t end_sample;
164         uint64_t input_len;
165         struct sr_dev_driver *driver;
166
167         driver = sr_dev_inst_driver_get(sdi);
168
169         /* If the first packet to come in isn't a header, don't even try. */
170         if (packet->type != SR_DF_HEADER && !o)
171                 return;
172
173         session = cb_data;
174         switch (packet->type) {
175         case SR_DF_HEADER:
176                 g_debug("cli: Received SR_DF_HEADER.");
177                 if (!(o = setup_output_format(sdi)))
178                         g_critical("Failed to initialize output module.");
179
180                 /* Set up backup analog output module. */
181                 oa = sr_output_new(sr_output_find("analog"), NULL, sdi, NULL);
182
183                 if (opt_output_file)
184                         outfile = g_fopen(opt_output_file, "wb");
185                 else
186                         outfile = stdout;
187
188                 rcvd_samples_logic = rcvd_samples_analog = 0;
189
190                 if (maybe_config_get(driver, sdi, NULL, SR_CONF_SAMPLERATE,
191                                 &gvar) == SR_OK) {
192                         samplerate = g_variant_get_uint64(gvar);
193                         g_variant_unref(gvar);
194                 }
195
196 #ifdef HAVE_SRD
197                 if (opt_pds) {
198                         if (samplerate) {
199                                 if (srd_session_metadata_set(srd_sess, SRD_CONF_SAMPLERATE,
200                                                 g_variant_new_uint64(samplerate)) != SRD_OK) {
201                                         g_critical("Failed to configure decode session.");
202                                         break;
203                                 }
204                         }
205                         if (srd_session_start(srd_sess) != SRD_OK) {
206                                 g_critical("Failed to start decode session.");
207                                 break;
208                         }
209                 }
210 #endif
211                 break;
212
213         case SR_DF_META:
214                 g_debug("cli: Received SR_DF_META.");
215                 meta = packet->payload;
216                 for (l = meta->config; l; l = l->next) {
217                         src = l->data;
218                         switch (src->key) {
219                         case SR_CONF_SAMPLERATE:
220                                 samplerate = g_variant_get_uint64(src->data);
221                                 g_debug("cli: Got samplerate %"PRIu64" Hz.", samplerate);
222 #ifdef HAVE_SRD
223                                 if (opt_pds) {
224                                         if (srd_session_metadata_set(srd_sess, SRD_CONF_SAMPLERATE,
225                                                         g_variant_new_uint64(samplerate)) != SRD_OK) {
226                                                 g_critical("Failed to pass samplerate to decoder.");
227                                         }
228                                 }
229 #endif
230                                 break;
231                         case SR_CONF_SAMPLE_INTERVAL:
232                                 samplerate = g_variant_get_uint64(src->data);
233                                 g_debug("cli: Got sample interval %"PRIu64" ms.", samplerate);
234                                 break;
235                         default:
236                                 /* Unknown metadata is not an error. */
237                                 break;
238                         }
239                 }
240                 break;
241
242         case SR_DF_TRIGGER:
243                 g_debug("cli: Received SR_DF_TRIGGER.");
244                 triggered = 1;
245                 break;
246
247         case SR_DF_LOGIC:
248                 logic = packet->payload;
249                 g_message("cli: Received SR_DF_LOGIC (%"PRIu64" bytes, unitsize = %d).",
250                                 logic->length, logic->unitsize);
251                 if (logic->length == 0)
252                         break;
253
254                 /* Don't store any samples until triggered. */
255                 if (opt_wait_trigger && !triggered)
256                         break;
257
258                 if (limit_samples && rcvd_samples_logic >= limit_samples)
259                         break;
260
261                 end_sample = rcvd_samples_logic + logic->length / logic->unitsize;
262                 /* Cut off last packet according to the sample limit. */
263                 if (limit_samples && end_sample > limit_samples)
264                         end_sample = limit_samples;
265                 input_len = (end_sample - rcvd_samples_logic) * logic->unitsize;
266
267                 if (opt_pds) {
268 #ifdef HAVE_SRD
269                         if (srd_session_send(srd_sess, rcvd_samples_logic, end_sample,
270                                         logic->data, input_len) != SRD_OK)
271                                 sr_session_stop(session);
272 #endif
273                 }
274
275                 rcvd_samples_logic = end_sample;
276                 break;
277
278         case SR_DF_ANALOG:
279                 analog = packet->payload;
280                 g_message("cli: Received SR_DF_ANALOG (%d samples).", analog->num_samples);
281                 if (analog->num_samples == 0)
282                         break;
283
284                 if (limit_samples && rcvd_samples_analog >= limit_samples)
285                         break;
286
287                 rcvd_samples_analog += analog->num_samples;
288                 break;
289
290         case SR_DF_FRAME_BEGIN:
291                 g_debug("cli: Received SR_DF_FRAME_BEGIN.");
292                 break;
293
294         case SR_DF_FRAME_END:
295                 g_debug("cli: Received SR_DF_FRAME_END.");
296                 break;
297
298         default:
299                 break;
300         }
301
302         if (o && outfile && !opt_pds) {
303                 if (sr_output_send(o, packet, &out) == SR_OK) {
304                         if (!out || (out->len == 0
305                                         && !opt_output_format
306                                         && packet->type == SR_DF_ANALOG)) {
307                                 /*
308                                  * The user didn't specify an output module,
309                                  * but needs to see this analog data.
310                                  */
311                                 sr_output_send(oa, packet, &out);
312                         }
313                         if (out && out->len > 0) {
314                                 fwrite(out->str, 1, out->len, outfile);
315                                 fflush(outfile);
316                         }
317                         if (out)
318                                 g_string_free(out, TRUE);
319                 }
320         }
321
322         /*
323          * SR_DF_END needs to be handled after the output module's receive()
324          * is called, so it can properly clean up that module.
325          */
326         if (packet->type == SR_DF_END) {
327                 g_debug("cli: Received SR_DF_END.");
328
329                 if (o)
330                         sr_output_free(o);
331                 o = NULL;
332
333                 sr_output_free(oa);
334                 oa = NULL;
335
336                 if (outfile && outfile != stdout)
337                         fclose(outfile);
338
339                 if (limit_samples) {
340                         if (rcvd_samples_logic > 0 && rcvd_samples_logic < limit_samples)
341                                 g_warning("Device only sent %" PRIu64 " samples.",
342                                            rcvd_samples_logic);
343                         else if (rcvd_samples_analog > 0 && rcvd_samples_analog < limit_samples)
344                                 g_warning("Device only sent %" PRIu64 " samples.",
345                                            rcvd_samples_analog);
346                 }
347         }
348
349 }
350
351 int opt_to_gvar(char *key, char *value, struct sr_config *src)
352 {
353         const struct sr_config_info *srci;
354         double tmp_double, dlow, dhigh;
355         uint64_t tmp_u64, p, q, low, high;
356         GVariant *rational[2], *range[2];
357         GVariantBuilder *vbl;
358         gboolean tmp_bool;
359         gchar **keyval;
360         int ret;
361
362         if (!(srci = sr_config_info_name_get(key))) {
363                 g_critical("Unknown device option '%s'.", (char *) key);
364                 return -1;
365         }
366         src->key = srci->key;
367
368         if ((!value || strlen(value) == 0) &&
369                 (srci->datatype != SR_T_BOOL)) {
370                 g_critical("Option '%s' needs a value.", (char *)key);
371                 return -1;
372         }
373
374         ret = 0;
375         switch (srci->datatype) {
376         case SR_T_UINT64:
377                 ret = sr_parse_sizestring(value, &tmp_u64);
378                 if (ret != 0)
379                         break;
380                 src->data = g_variant_new_uint64(tmp_u64);
381                 break;
382         case SR_T_INT32:
383                 ret = sr_parse_sizestring(value, &tmp_u64);
384                 if (ret != 0)
385                         break;
386                 src->data = g_variant_new_int32(tmp_u64);
387                 break;
388         case SR_T_STRING:
389                 src->data = g_variant_new_string(value);
390                 break;
391         case SR_T_BOOL:
392                 if (!value)
393                         tmp_bool = TRUE;
394                 else
395                         tmp_bool = sr_parse_boolstring(value);
396                 src->data = g_variant_new_boolean(tmp_bool);
397                 break;
398         case SR_T_FLOAT:
399                 tmp_double = strtof(value, NULL);
400                 src->data = g_variant_new_double(tmp_double);
401                 break;
402         case SR_T_RATIONAL_PERIOD:
403                 if ((ret = sr_parse_period(value, &p, &q)) != SR_OK)
404                         break;
405                 rational[0] = g_variant_new_uint64(p);
406                 rational[1] = g_variant_new_uint64(q);
407                 src->data = g_variant_new_tuple(rational, 2);
408                 break;
409         case SR_T_RATIONAL_VOLT:
410                 if ((ret = sr_parse_voltage(value, &p, &q)) != SR_OK)
411                         break;
412                 rational[0] = g_variant_new_uint64(p);
413                 rational[1] = g_variant_new_uint64(q);
414                 src->data = g_variant_new_tuple(rational, 2);
415                 break;
416         case SR_T_UINT64_RANGE:
417                 if (sscanf(value, "%"PRIu64"-%"PRIu64, &low, &high) != 2) {
418                         ret = -1;
419                         break;
420                 } else {
421                         range[0] = g_variant_new_uint64(low);
422                         range[1] = g_variant_new_uint64(high);
423                         src->data = g_variant_new_tuple(range, 2);
424                 }
425                 break;
426         case SR_T_DOUBLE_RANGE:
427                 if (sscanf(value, "%lf-%lf", &dlow, &dhigh) != 2) {
428                         ret = -1;
429                         break;
430                 } else {
431                         range[0] = g_variant_new_double(dlow);
432                         range[1] = g_variant_new_double(dhigh);
433                         src->data = g_variant_new_tuple(range, 2);
434                 }
435                 break;
436         case SR_T_KEYVALUE:
437                 /* Expects the argument to be in the form of key=value. */
438                 keyval = g_strsplit(value, "=", 2);
439                 if (!keyval[0] || !keyval[1]) {
440                         g_strfreev(keyval);
441                         ret = -1;
442                         break;
443                 } else {
444                         vbl = g_variant_builder_new(G_VARIANT_TYPE_DICTIONARY);
445                         g_variant_builder_add(vbl, "{ss}",
446                                               keyval[0], keyval[1]);
447                         src->data = g_variant_builder_end(vbl);
448                         g_strfreev(keyval);
449                 }
450                 break;
451         default:
452                 g_critical("Unknown data type specified for option '%s' "
453                            "(driver implementation bug?).", key);
454                 ret = -1;
455         }
456
457         if (ret < 0)
458                 g_critical("Invalid value: '%s' for option '%s'", value, key);
459
460         return ret;
461 }
462
463 int set_dev_options(struct sr_dev_inst *sdi, GHashTable *args)
464 {
465         struct sr_config src;
466         struct sr_channel_group *cg;
467         GHashTableIter iter;
468         gpointer key, value;
469         int ret;
470
471         g_hash_table_iter_init(&iter, args);
472         while (g_hash_table_iter_next(&iter, &key, &value)) {
473                 if ((ret = opt_to_gvar(key, value, &src)) != 0)
474                         return ret;
475                 cg = select_channel_group(sdi);
476                 if ((ret = maybe_config_set(sr_dev_inst_driver_get(sdi), sdi, cg,
477                                 src.key, src.data)) != SR_OK) {
478                         g_critical("Failed to set device option '%s': %s.",
479                                    (char *)key, sr_strerror(ret));
480                         return ret;
481                 }
482         }
483
484         return SR_OK;
485 }
486
487 void run_session(void)
488 {
489         GSList *devices, *real_devices, *sd;
490         GHashTable *devargs;
491         GVariant *gvar;
492         struct sr_session *session;
493         struct sr_trigger *trigger;
494         struct sr_dev_inst *sdi;
495         uint64_t min_samples, max_samples;
496         gsize n_elements, i;
497         const uint32_t *dev_opts;
498         int is_demo_dev;
499         struct sr_dev_driver *driver;
500         const struct sr_transform *t;
501
502         devices = device_scan();
503         if (!devices) {
504                 g_critical("No devices found.");
505                 return;
506         }
507
508         real_devices = NULL;
509         for (sd = devices; sd; sd = sd->next) {
510                 sdi = sd->data;
511
512                 driver = sr_dev_inst_driver_get(sdi);
513
514                 if (sr_config_list(driver, sdi, NULL, SR_CONF_DEVICE_OPTIONS, &gvar) != SR_OK) {
515                         g_critical("Failed to query list device options.");
516                         return;
517                 }
518
519                 dev_opts = g_variant_get_fixed_array(gvar, &n_elements, sizeof(uint32_t));
520
521                 is_demo_dev = 0;
522                 for (i = 0; i < n_elements; i++) {
523                         if (dev_opts[i] == SR_CONF_DEMO_DEV)
524                                 is_demo_dev = 1;
525                 }
526
527                 g_variant_unref(gvar);
528
529                 if (!is_demo_dev)
530                         real_devices = g_slist_append(real_devices, sdi);
531         }
532
533         if (g_slist_length(devices) > 1) {
534                 if (g_slist_length(real_devices) != 1) {
535                         g_critical("sigrok-cli only supports one device for capturing.");
536                         return;
537                 } else {
538                         /* We only have one non-demo device. */
539                         g_slist_free(devices);
540                         devices = real_devices;
541                         real_devices = NULL;
542                 }
543         }
544
545         sdi = devices->data;
546         g_slist_free(devices);
547         g_slist_free(real_devices);
548
549         sr_session_new(sr_ctx, &session);
550         sr_session_datafeed_callback_add(session, datafeed_in, NULL);
551
552         if (sr_dev_open(sdi) != SR_OK) {
553                 g_critical("Failed to open device.");
554                 return;
555         }
556
557         if (sr_session_dev_add(session, sdi) != SR_OK) {
558                 g_critical("Failed to add device to session.");
559                 sr_session_destroy(session);
560                 return;
561         }
562
563         if (opt_config) {
564                 if ((devargs = parse_generic_arg(opt_config, FALSE))) {
565                         if (set_dev_options(sdi, devargs) != SR_OK)
566                                 return;
567                         g_hash_table_destroy(devargs);
568                 }
569         }
570
571         if (select_channels(sdi) != SR_OK) {
572                 g_critical("Failed to set channels.");
573                 sr_session_destroy(session);
574                 return;
575         }
576
577         if (opt_triggers) {
578                 if (!parse_triggerstring(sdi, opt_triggers, &trigger)) {
579                         sr_session_destroy(session);
580                         return;
581                 }
582                 if (sr_session_trigger_set(session, trigger) != SR_OK) {
583                         sr_session_destroy(session);
584                         return;
585                 }
586         }
587
588         if (opt_continuous) {
589                 if (!sr_dev_has_option(sdi, SR_CONF_CONTINUOUS)) {
590                         g_critical("This device does not support continuous sampling.");
591                         sr_session_destroy(session);
592                         return;
593                 }
594         }
595
596         if (opt_time) {
597                 if (set_limit_time(sdi) != SR_OK) {
598                         sr_session_destroy(session);
599                         return;
600                 }
601         }
602
603         if (opt_samples) {
604                 if ((sr_parse_sizestring(opt_samples, &limit_samples) != SR_OK)) {
605                         g_critical("Invalid sample limit '%s'.", opt_samples);
606                         sr_session_destroy(session);
607                         return;
608                 }
609                 if (maybe_config_list(driver, sdi, NULL, SR_CONF_LIMIT_SAMPLES,
610                                 &gvar) == SR_OK) {
611                         /*
612                          * The device has no compression, or compression is turned
613                          * off, and publishes its sample memory size.
614                          */
615                         g_variant_get(gvar, "(tt)", &min_samples, &max_samples);
616                         g_variant_unref(gvar);
617                         if (limit_samples < min_samples) {
618                                 g_critical("The device stores at least %"PRIu64
619                                                 " samples with the current settings.", min_samples);
620                         }
621                         if (limit_samples > max_samples) {
622                                 g_critical("The device can store only %"PRIu64
623                                                 " samples with the current settings.", max_samples);
624                         }
625                 }
626                 gvar = g_variant_new_uint64(limit_samples);
627                 if (maybe_config_set(sr_dev_inst_driver_get(sdi), sdi, NULL, SR_CONF_LIMIT_SAMPLES, gvar) != SR_OK) {
628                         g_critical("Failed to configure sample limit.");
629                         sr_session_destroy(session);
630                         return;
631                 }
632         }
633
634         if (opt_frames) {
635                 if ((sr_parse_sizestring(opt_frames, &limit_frames) != SR_OK)) {
636                         g_critical("Invalid sample limit '%s'.", opt_samples);
637                         sr_session_destroy(session);
638                         return;
639                 }
640                 gvar = g_variant_new_uint64(limit_frames);
641                 if (maybe_config_set(sr_dev_inst_driver_get(sdi), sdi, NULL, SR_CONF_LIMIT_FRAMES, gvar) != SR_OK) {
642                         g_critical("Failed to configure frame limit.");
643                         sr_session_destroy(session);
644                         return;
645                 }
646         }
647
648         if (!(t = setup_transform_module(sdi)))
649                 g_critical("Failed to initialize transform module.");
650
651         if (sr_session_start(session) != SR_OK) {
652                 g_critical("Failed to start session.");
653                 sr_session_destroy(session);
654                 return;
655         }
656
657         if (opt_continuous)
658                 add_anykey(session);
659
660         sr_session_run(session);
661
662         if (opt_continuous)
663                 clear_anykey();
664
665         sr_session_datafeed_callback_remove_all(session);
666         sr_session_destroy(session);
667
668 }