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