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