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