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