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