]> sigrok.org Git - libsigrok.git/blob - src/input/input.c
48660d379b9b6e69fde4546cbe8f91a7a67669b9
[libsigrok.git] / src / input / input.c
1 /*
2  * This file is part of the libsigrok project.
3  *
4  * Copyright (C) 2014 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 <string.h>
22 #include <errno.h>
23 #include <glib.h>
24 #include <glib/gstdio.h>
25 #include <libsigrok/libsigrok.h>
26 #include "libsigrok-internal.h"
27
28 /** @cond PRIVATE */
29 #define LOG_PREFIX "input"
30 /** @endcond */
31
32 /**
33  * @file
34  *
35  * Input module handling.
36  */
37
38 /**
39  * @defgroup grp_input Input modules
40  *
41  * Input file/data module handling.
42  *
43  * libsigrok can process acquisition data in several different ways.
44  * Aside from acquiring data from a hardware device, it can also take it
45  * from a file in various formats (binary, CSV, VCD, and so on).
46  *
47  * Like all libsigrok data handling, processing is done in a streaming
48  * manner: input should be supplied a chunk at a time. This way anything
49  * that processes data can do so in real time, without the user having
50  * to wait for the whole thing to be finished.
51  *
52  * Every input module is "pluggable", meaning it's handled as being separate
53  * from the main libsigrok, but linked in to it statically. To keep things
54  * modular and separate like this, functions within an input module should be
55  * declared static, with only the respective 'struct sr_input_module' being
56  * exported for use into the wider libsigrok namespace.
57  *
58  * @{
59  */
60
61 /** @cond PRIVATE */
62 extern SR_PRIV struct sr_input_module input_chronovu_la8;
63 extern SR_PRIV struct sr_input_module input_csv;
64 extern SR_PRIV struct sr_input_module input_binary;
65 extern SR_PRIV struct sr_input_module input_trace32_ad;
66 extern SR_PRIV struct sr_input_module input_vcd;
67 extern SR_PRIV struct sr_input_module input_wav;
68 extern SR_PRIV struct sr_input_module input_raw_analog;
69 extern SR_PRIV struct sr_input_module input_logicport;
70 extern SR_PRIV struct sr_input_module input_null;
71 /* @endcond */
72
73 static const struct sr_input_module *input_module_list[] = {
74         &input_binary,
75         &input_chronovu_la8,
76         &input_csv,
77         &input_trace32_ad,
78         &input_vcd,
79         &input_wav,
80         &input_raw_analog,
81         &input_logicport,
82         &input_null,
83         NULL,
84 };
85
86 /**
87  * Returns a NULL-terminated list of all available input modules.
88  *
89  * @since 0.4.0
90  */
91 SR_API const struct sr_input_module **sr_input_list(void)
92 {
93         return input_module_list;
94 }
95
96 /**
97  * Returns the specified input module's ID.
98  *
99  * @since 0.4.0
100  */
101 SR_API const char *sr_input_id_get(const struct sr_input_module *imod)
102 {
103         if (!imod) {
104                 sr_err("Invalid input module NULL!");
105                 return NULL;
106         }
107
108         return imod->id;
109 }
110
111 /**
112  * Returns the specified input module's name.
113  *
114  * @since 0.4.0
115  */
116 SR_API const char *sr_input_name_get(const struct sr_input_module *imod)
117 {
118         if (!imod) {
119                 sr_err("Invalid input module NULL!");
120                 return NULL;
121         }
122
123         return imod->name;
124 }
125
126 /**
127  * Returns the specified input module's description.
128  *
129  * @since 0.4.0
130  */
131 SR_API const char *sr_input_description_get(const struct sr_input_module *imod)
132 {
133         if (!imod) {
134                 sr_err("Invalid input module NULL!");
135                 return NULL;
136         }
137
138         return imod->desc;
139 }
140
141 /**
142  * Returns the specified input module's file extensions typical for the file
143  * format, as a NULL terminated array, or returns a NULL pointer if there is
144  * no preferred extension.
145  * @note these are a suggestions only.
146  *
147  * @since 0.4.0
148  */
149 SR_API const char *const *sr_input_extensions_get(
150                 const struct sr_input_module *imod)
151 {
152         if (!imod) {
153                 sr_err("Invalid input module NULL!");
154                 return NULL;
155         }
156
157         return imod->exts;
158 }
159
160 /**
161  * Return the input module with the specified ID, or NULL if no module
162  * with that id is found.
163  *
164  * @since 0.4.0
165  */
166 SR_API const struct sr_input_module *sr_input_find(char *id)
167 {
168         int i;
169
170         for (i = 0; input_module_list[i]; i++) {
171                 if (!strcmp(input_module_list[i]->id, id))
172                         return input_module_list[i];
173         }
174
175         return NULL;
176 }
177
178 /**
179  * Returns a NULL-terminated array of struct sr_option, or NULL if the
180  * module takes no options.
181  *
182  * Each call to this function must be followed by a call to
183  * sr_input_options_free().
184  *
185  * @since 0.4.0
186  */
187 SR_API const struct sr_option **sr_input_options_get(const struct sr_input_module *imod)
188 {
189         const struct sr_option *mod_opts, **opts;
190         int size, i;
191
192         if (!imod || !imod->options)
193                 return NULL;
194
195         mod_opts = imod->options();
196
197         for (size = 0; mod_opts[size].id; size++)
198                 ;
199         opts = g_malloc((size + 1) * sizeof(struct sr_option *));
200
201         for (i = 0; i < size; i++)
202                 opts[i] = &mod_opts[i];
203         opts[i] = NULL;
204
205         return opts;
206 }
207
208 /**
209  * After a call to sr_input_options_get(), this function cleans up all
210  * resources returned by that call.
211  *
212  * @since 0.4.0
213  */
214 SR_API void sr_input_options_free(const struct sr_option **options)
215 {
216         int i;
217
218         if (!options)
219                 return;
220
221         for (i = 0; options[i]; i++) {
222                 if (options[i]->def) {
223                         g_variant_unref(options[i]->def);
224                         ((struct sr_option *)options[i])->def = NULL;
225                 }
226
227                 if (options[i]->values) {
228                         g_slist_free_full(options[i]->values, (GDestroyNotify)g_variant_unref);
229                         ((struct sr_option *)options[i])->values = NULL;
230                 }
231         }
232         g_free(options);
233 }
234
235 /**
236  * Create a new input instance using the specified input module.
237  *
238  * This function is used when a client wants to use a specific input
239  * module to parse a stream. No effort is made to identify the format.
240  *
241  * @param imod The input module to use. Must not be NULL.
242  * @param options GHashTable consisting of keys corresponding with
243  * the module options @c id field. The values should be GVariant
244  * pointers with sunk references, of the same GVariantType as the option's
245  * default value.
246  *
247  * @since 0.4.0
248  */
249 SR_API struct sr_input *sr_input_new(const struct sr_input_module *imod,
250                 GHashTable *options)
251 {
252         struct sr_input *in;
253         const struct sr_option *mod_opts;
254         const GVariantType *gvt;
255         GHashTable *new_opts;
256         GHashTableIter iter;
257         gpointer key, value;
258         int i;
259
260         in = g_malloc0(sizeof(struct sr_input));
261         in->module = imod;
262
263         new_opts = g_hash_table_new_full(g_str_hash, g_str_equal, g_free,
264                         (GDestroyNotify)g_variant_unref);
265         if (imod->options) {
266                 mod_opts = imod->options();
267                 for (i = 0; mod_opts[i].id; i++) {
268                         if (options && g_hash_table_lookup_extended(options,
269                                         mod_opts[i].id, &key, &value)) {
270                                 /* Option not given: insert the default value. */
271                                 gvt = g_variant_get_type(mod_opts[i].def);
272                                 if (!g_variant_is_of_type(value, gvt)) {
273                                         sr_err("Invalid type for '%s' option.",
274                                                 (char *)key);
275                                         g_free(in);
276                                         return NULL;
277                                 }
278                                 g_hash_table_insert(new_opts, g_strdup(mod_opts[i].id),
279                                                 g_variant_ref(value));
280                         } else {
281                                 /* Pass option along. */
282                                 g_hash_table_insert(new_opts, g_strdup(mod_opts[i].id),
283                                                 g_variant_ref(mod_opts[i].def));
284                         }
285                 }
286
287                 /* Make sure no invalid options were given. */
288                 if (options) {
289                         g_hash_table_iter_init(&iter, options);
290                         while (g_hash_table_iter_next(&iter, &key, &value)) {
291                                 if (!g_hash_table_lookup(new_opts, key)) {
292                                         sr_err("Input module '%s' has no option '%s'",
293                                                 imod->id, (char *)key);
294                                         g_hash_table_destroy(new_opts);
295                                         g_free(in);
296                                         return NULL;
297                                 }
298                         }
299                 }
300         }
301
302         if (in->module->init && in->module->init(in, new_opts) != SR_OK) {
303                 g_free(in);
304                 in = NULL;
305         } else {
306                 in->buf = g_string_sized_new(128);
307         }
308
309         if (new_opts)
310                 g_hash_table_destroy(new_opts);
311
312         return in;
313 }
314
315 /* Returns TRUE if all required meta items are available. */
316 static gboolean check_required_metadata(const uint8_t *metadata, uint8_t *avail)
317 {
318         int m, a;
319         uint8_t reqd;
320
321         for (m = 0; metadata[m]; m++) {
322                 if (!(metadata[m] & SR_INPUT_META_REQUIRED))
323                         continue;
324                 reqd = metadata[m] & ~SR_INPUT_META_REQUIRED;
325                 for (a = 0; avail[a]; a++) {
326                         if (avail[a] == reqd)
327                                 break;
328                 }
329                 if (!avail[a])
330                         /* Found a required meta item that isn't available. */
331                         return FALSE;
332         }
333
334         return TRUE;
335 }
336
337 /**
338  * Try to find an input module that can parse the given buffer.
339  *
340  * The buffer must contain enough of the beginning of the file for
341  * the input modules to find a match. This is format-dependent, but
342  * 128 bytes is normally enough.
343  *
344  * If an input module is found, an instance is created into *in.
345  * Otherwise, *in contains NULL. When multiple input moduless claim
346  * support for the format, the one with highest confidence takes
347  * precedence. Applications will see at most one input module spec.
348  *
349  * If an instance is created, it has the given buffer used for scanning
350  * already submitted to it, to be processed before more data is sent.
351  * This allows a frontend to submit an initial chunk of a non-seekable
352  * stream, such as stdin, without having to keep it around and submit
353  * it again later.
354  *
355  */
356 SR_API int sr_input_scan_buffer(GString *buf, const struct sr_input **in)
357 {
358         const struct sr_input_module *imod, *best_imod;
359         GHashTable *meta;
360         unsigned int m, i;
361         unsigned int conf, best_conf;
362         int ret;
363         uint8_t mitem, avail_metadata[8];
364
365         /* No more metadata to be had from a buffer. */
366         avail_metadata[0] = SR_INPUT_META_HEADER;
367         avail_metadata[1] = 0;
368
369         *in = NULL;
370         best_imod = NULL;
371         best_conf = ~0;
372         for (i = 0; input_module_list[i]; i++) {
373                 imod = input_module_list[i];
374                 if (!imod->metadata[0]) {
375                         /* Module has no metadata for matching so will take
376                          * any input. No point in letting it try to match. */
377                         continue;
378                 }
379                 if (!check_required_metadata(imod->metadata, avail_metadata))
380                         /* Cannot satisfy this module's requirements. */
381                         continue;
382
383                 meta = g_hash_table_new(NULL, NULL);
384                 for (m = 0; m < sizeof(imod->metadata); m++) {
385                         mitem = imod->metadata[m] & ~SR_INPUT_META_REQUIRED;
386                         if (mitem == SR_INPUT_META_HEADER)
387                                 g_hash_table_insert(meta, GINT_TO_POINTER(mitem), buf);
388                 }
389                 if (g_hash_table_size(meta) == 0) {
390                         /* No metadata for this module, so nothing to match. */
391                         g_hash_table_destroy(meta);
392                         continue;
393                 }
394                 sr_spew("Trying module %s.", imod->id);
395                 ret = imod->format_match(meta, &conf);
396                 g_hash_table_destroy(meta);
397                 if (ret == SR_ERR_DATA) {
398                         /* Module recognized this buffer, but cannot handle it. */
399                         continue;
400                 } else if (ret == SR_ERR) {
401                         /* Module didn't recognize this buffer. */
402                         continue;
403                 } else if (ret != SR_OK) {
404                         /* Can be SR_ERR_NA. */
405                         continue;
406                 }
407
408                 /* Found a matching module. */
409                 sr_spew("Module %s matched, confidence %u.", imod->id, conf);
410                 if (conf >= best_conf)
411                         continue;
412                 best_imod = imod;
413                 best_conf = conf;
414         }
415
416         if (best_imod) {
417                 *in = sr_input_new(best_imod, NULL);
418                 g_string_insert_len((*in)->buf, 0, buf->str, buf->len);
419                 return SR_OK;
420         }
421
422         return SR_ERR;
423 }
424
425 /**
426  * Try to find an input module that can parse the given file.
427  *
428  * If an input module is found, an instance is created into *in.
429  * Otherwise, *in contains NULL. When multiple input moduless claim
430  * support for the format, the one with highest confidence takes
431  * precedence. Applications will see at most one input module spec.
432  *
433  */
434 SR_API int sr_input_scan_file(const char *filename, const struct sr_input **in)
435 {
436         int64_t filesize;
437         FILE *stream;
438         const struct sr_input_module *imod, *best_imod;
439         GHashTable *meta;
440         GString *header;
441         size_t count;
442         unsigned int midx, i;
443         unsigned int conf, best_conf;
444         int ret;
445         uint8_t avail_metadata[8];
446
447         *in = NULL;
448
449         if (!filename || !filename[0]) {
450                 sr_err("Invalid filename.");
451                 return SR_ERR_ARG;
452         }
453         stream = g_fopen(filename, "rb");
454         if (!stream) {
455                 sr_err("Failed to open %s: %s", filename, g_strerror(errno));
456                 return SR_ERR;
457         }
458         filesize = sr_file_get_size(stream);
459         if (filesize < 0) {
460                 sr_err("Failed to get size of %s: %s",
461                         filename, g_strerror(errno));
462                 fclose(stream);
463                 return SR_ERR;
464         }
465         /* This actually allocates 256 bytes to allow for NUL termination. */
466         header = g_string_sized_new(255);
467         count = fread(header->str, 1, header->allocated_len - 1, stream);
468
469         if (count != header->allocated_len - 1 && ferror(stream)) {
470                 sr_err("Failed to read %s: %s", filename, g_strerror(errno));
471                 fclose(stream);
472                 g_string_free(header, TRUE);
473                 return SR_ERR;
474         }
475         fclose(stream);
476         g_string_set_size(header, count);
477
478         meta = g_hash_table_new(NULL, NULL);
479         g_hash_table_insert(meta, GINT_TO_POINTER(SR_INPUT_META_FILENAME),
480                         (char *)filename);
481         g_hash_table_insert(meta, GINT_TO_POINTER(SR_INPUT_META_FILESIZE),
482                         GSIZE_TO_POINTER(MIN(filesize, G_MAXSSIZE)));
483         g_hash_table_insert(meta, GINT_TO_POINTER(SR_INPUT_META_HEADER),
484                         header);
485         midx = 0;
486         avail_metadata[midx++] = SR_INPUT_META_FILENAME;
487         avail_metadata[midx++] = SR_INPUT_META_FILESIZE;
488         avail_metadata[midx++] = SR_INPUT_META_HEADER;
489         avail_metadata[midx] = 0;
490         /* TODO: MIME type */
491
492         best_imod = NULL;
493         best_conf = ~0;
494         for (i = 0; input_module_list[i]; i++) {
495                 imod = input_module_list[i];
496                 if (!imod->metadata[0]) {
497                         /* Module has no metadata for matching so will take
498                          * any input. No point in letting it try to match. */
499                         continue;
500                 }
501                 if (!check_required_metadata(imod->metadata, avail_metadata))
502                         /* Cannot satisfy this module's requirements. */
503                         continue;
504
505                 sr_dbg("Trying module %s.", imod->id);
506
507                 ret = imod->format_match(meta, &conf);
508                 if (ret == SR_ERR) {
509                         /* Module didn't recognize this buffer. */
510                         continue;
511                 } else if (ret != SR_OK) {
512                         /* Module recognized this buffer, but cannot handle it. */
513                         continue;
514                 }
515                 /* Found a matching module. */
516                 sr_dbg("Module %s matched, confidence %u.", imod->id, conf);
517                 if (conf >= best_conf)
518                         continue;
519                 best_imod = imod;
520                 best_conf = conf;
521         }
522         g_hash_table_destroy(meta);
523         g_string_free(header, TRUE);
524
525         if (best_imod) {
526                 *in = sr_input_new(best_imod, NULL);
527                 return SR_OK;
528         }
529
530         return SR_ERR;
531 }
532
533 /**
534  * Return the input instance's (virtual) device instance. This can be
535  * used to find out the number of channels and other information.
536  *
537  * If the device instance has not yet been fully populated by the input
538  * module, NULL is returned. This indicates the module needs more data
539  * to identify the number of channels and so on.
540  *
541  * @since 0.4.0
542  */
543 SR_API struct sr_dev_inst *sr_input_dev_inst_get(const struct sr_input *in)
544 {
545         if (in->sdi_ready)
546                 return in->sdi;
547         else
548                 return NULL;
549 }
550
551 /**
552  * Send data to the specified input instance.
553  *
554  * When an input module instance is created with sr_input_new(), this
555  * function is used to feed data to the instance.
556  *
557  * As enough data gets fed into this function to completely populate
558  * the device instance associated with this input instance, this is
559  * guaranteed to return the moment it's ready. This gives the caller
560  * the chance to examine the device instance, attach session callbacks
561  * and so on.
562  *
563  * @since 0.4.0
564  */
565 SR_API int sr_input_send(const struct sr_input *in, GString *buf)
566 {
567         sr_spew("Sending %" G_GSIZE_FORMAT " bytes to %s module.",
568                 buf->len, in->module->id);
569         return in->module->receive((struct sr_input *)in, buf);
570 }
571
572 /**
573  * Signal the input module no more data will come.
574  *
575  * This will cause the module to process any data it may have buffered.
576  * The SR_DF_END packet will also typically be sent at this time.
577  *
578  * @since 0.4.0
579  */
580 SR_API int sr_input_end(const struct sr_input *in)
581 {
582         sr_spew("Calling end() on %s module.", in->module->id);
583         return in->module->end((struct sr_input *)in);
584 }
585
586 /**
587  * Reset the input module's input handling structures.
588  *
589  * Causes the input module to reset its internal state so that we can re-send
590  * the input data from the beginning without having to re-create the entire
591  * input module.
592  *
593  * @since 0.5.0
594  */
595 SR_API int sr_input_reset(const struct sr_input *in)
596 {
597         if (!in->module->reset) {
598                 sr_spew("Tried to reset %s module but no reset handler found.",
599                         in->module->id);
600                 return SR_OK;
601         }
602
603         sr_spew("Resetting %s module.", in->module->id);
604         return in->module->reset((struct sr_input *)in);
605 }
606
607 /**
608  * Free the specified input instance and all associated resources.
609  *
610  * @since 0.4.0
611  */
612 SR_API void sr_input_free(const struct sr_input *in)
613 {
614         if (!in)
615                 return;
616
617         if (in->module->cleanup)
618                 in->module->cleanup((struct sr_input *)in);
619         sr_dev_inst_free(in->sdi);
620         if (in->buf->len > 64) {
621                 /* That seems more than just some sub-unitsize leftover... */
622                 sr_warn("Found %" G_GSIZE_FORMAT
623                         " unprocessed bytes at free time.", in->buf->len);
624         }
625         g_string_free(in->buf, TRUE);
626         g_free(in->priv);
627         g_free((gpointer)in);
628 }
629
630 /** @} */