2 * This file is part of the libsigrok project.
4 * Copyright (C) 2014 Bert Vermeulen <bert@biot.com>
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.
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.
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/>.
24 #include <glib/gstdio.h>
25 #include <libsigrok/libsigrok.h>
26 #include "libsigrok-internal.h"
29 #define LOG_PREFIX "input"
35 * Input module handling.
39 * @defgroup grp_input Input modules
41 * Input file/data module handling.
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).
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.
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.
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_vcd;
66 extern SR_PRIV struct sr_input_module input_wav;
67 extern SR_PRIV struct sr_input_module input_raw_analog;
70 static const struct sr_input_module *input_module_list[] = {
81 * Returns a NULL-terminated list of all available input modules.
85 SR_API const struct sr_input_module **sr_input_list(void)
87 return input_module_list;
91 * Returns the specified input module's ID.
95 SR_API const char *sr_input_id_get(const struct sr_input_module *imod)
98 sr_err("Invalid input module NULL!");
106 * Returns the specified input module's name.
110 SR_API const char *sr_input_name_get(const struct sr_input_module *imod)
113 sr_err("Invalid input module NULL!");
121 * Returns the specified input module's description.
125 SR_API const char *sr_input_description_get(const struct sr_input_module *imod)
128 sr_err("Invalid input module NULL!");
136 * Returns the specified input module's file extensions typical for the file
137 * format, as a NULL terminated array, or returns a NULL pointer if there is
138 * no preferred extension.
139 * @note these are a suggestions only.
143 SR_API const char *const *sr_input_extensions_get(
144 const struct sr_input_module *imod)
147 sr_err("Invalid input module NULL!");
155 * Return the input module with the specified ID, or NULL if no module
156 * with that id is found.
160 SR_API const struct sr_input_module *sr_input_find(char *id)
164 for (i = 0; input_module_list[i]; i++) {
165 if (!strcmp(input_module_list[i]->id, id))
166 return input_module_list[i];
173 * Returns a NULL-terminated array of struct sr_option, or NULL if the
174 * module takes no options.
176 * Each call to this function must be followed by a call to
177 * sr_input_options_free().
181 SR_API const struct sr_option **sr_input_options_get(const struct sr_input_module *imod)
183 const struct sr_option *mod_opts, **opts;
186 if (!imod || !imod->options)
189 mod_opts = imod->options();
191 for (size = 0; mod_opts[size].id; size++)
193 opts = g_malloc((size + 1) * sizeof(struct sr_option *));
195 for (i = 0; i < size; i++)
196 opts[i] = &mod_opts[i];
203 * After a call to sr_input_options_get(), this function cleans up all
204 * resources returned by that call.
208 SR_API void sr_input_options_free(const struct sr_option **options)
215 for (i = 0; options[i]; i++) {
216 if (options[i]->def) {
217 g_variant_unref(options[i]->def);
218 ((struct sr_option *)options[i])->def = NULL;
221 if (options[i]->values) {
222 g_slist_free_full(options[i]->values, (GDestroyNotify)g_variant_unref);
223 ((struct sr_option *)options[i])->values = NULL;
230 * Create a new input instance using the specified input module.
232 * This function is used when a client wants to use a specific input
233 * module to parse a stream. No effort is made to identify the format.
235 * @param imod The input module to use. Must not be NULL.
236 * @param options GHashTable consisting of keys corresponding with
237 * the module options @c id field. The values should be GVariant
238 * pointers with sunk references, of the same GVariantType as the option's
243 SR_API struct sr_input *sr_input_new(const struct sr_input_module *imod,
247 const struct sr_option *mod_opts;
248 const GVariantType *gvt;
249 GHashTable *new_opts;
254 in = g_malloc0(sizeof(struct sr_input));
257 new_opts = g_hash_table_new_full(g_str_hash, g_str_equal, g_free,
258 (GDestroyNotify)g_variant_unref);
260 mod_opts = imod->options();
261 for (i = 0; mod_opts[i].id; i++) {
262 if (options && g_hash_table_lookup_extended(options,
263 mod_opts[i].id, &key, &value)) {
264 /* Option not given: insert the default value. */
265 gvt = g_variant_get_type(mod_opts[i].def);
266 if (!g_variant_is_of_type(value, gvt)) {
267 sr_err("Invalid type for '%s' option.",
272 g_hash_table_insert(new_opts, g_strdup(mod_opts[i].id),
273 g_variant_ref(value));
275 /* Pass option along. */
276 g_hash_table_insert(new_opts, g_strdup(mod_opts[i].id),
277 g_variant_ref(mod_opts[i].def));
281 /* Make sure no invalid options were given. */
283 g_hash_table_iter_init(&iter, options);
284 while (g_hash_table_iter_next(&iter, &key, &value)) {
285 if (!g_hash_table_lookup(new_opts, key)) {
286 sr_err("Input module '%s' has no option '%s'",
287 imod->id, (char *)key);
288 g_hash_table_destroy(new_opts);
296 if (in->module->init && in->module->init(in, new_opts) != SR_OK) {
300 in->buf = g_string_sized_new(128);
304 g_hash_table_destroy(new_opts);
309 /* Returns TRUE if all required meta items are available. */
310 static gboolean check_required_metadata(const uint8_t *metadata, uint8_t *avail)
315 for (m = 0; metadata[m]; m++) {
316 if (!(metadata[m] & SR_INPUT_META_REQUIRED))
318 reqd = metadata[m] & ~SR_INPUT_META_REQUIRED;
319 for (a = 0; avail[a]; a++) {
320 if (avail[a] == reqd)
324 /* Found a required meta item that isn't available. */
332 * Try to find an input module that can parse the given buffer.
334 * The buffer must contain enough of the beginning of the file for
335 * the input modules to find a match. This is format-dependent, but
336 * 128 bytes is normally enough.
338 * If an input module is found, an instance is created into *in.
339 * Otherwise, *in contains NULL.
341 * If an instance is created, it has the given buffer used for scanning
342 * already submitted to it, to be processed before more data is sent.
343 * This allows a frontend to submit an initial chunk of a non-seekable
344 * stream, such as stdin, without having to keep it around and submit
348 SR_API int sr_input_scan_buffer(GString *buf, const struct sr_input **in)
350 const struct sr_input_module *imod;
354 uint8_t mitem, avail_metadata[8];
356 /* No more metadata to be had from a buffer. */
357 avail_metadata[0] = SR_INPUT_META_HEADER;
358 avail_metadata[1] = 0;
362 for (i = 0; input_module_list[i]; i++) {
363 imod = input_module_list[i];
364 if (!imod->metadata[0]) {
365 /* Module has no metadata for matching so will take
366 * any input. No point in letting it try to match. */
369 if (!check_required_metadata(imod->metadata, avail_metadata))
370 /* Cannot satisfy this module's requirements. */
373 meta = g_hash_table_new(NULL, NULL);
374 for (m = 0; m < sizeof(imod->metadata); m++) {
375 mitem = imod->metadata[m] & ~SR_INPUT_META_REQUIRED;
376 if (mitem == SR_INPUT_META_HEADER)
377 g_hash_table_insert(meta, GINT_TO_POINTER(mitem), buf);
379 if (g_hash_table_size(meta) == 0) {
380 /* No metadata for this module, so nothing to match. */
381 g_hash_table_destroy(meta);
384 sr_spew("Trying module %s.", imod->id);
385 ret = imod->format_match(meta);
386 g_hash_table_destroy(meta);
387 if (ret == SR_ERR_DATA) {
388 /* Module recognized this buffer, but cannot handle it. */
390 } else if (ret == SR_ERR) {
391 /* Module didn't recognize this buffer. */
393 } else if (ret != SR_OK) {
394 /* Can be SR_ERR_NA. */
398 /* Found a matching module. */
399 sr_spew("Module %s matched.", imod->id);
400 *in = sr_input_new(imod, NULL);
401 g_string_insert_len((*in)->buf, 0, buf->str, buf->len);
409 * Try to find an input module that can parse the given file.
411 * If an input module is found, an instance is created into *in.
412 * Otherwise, *in contains NULL.
415 SR_API int sr_input_scan_file(const char *filename, const struct sr_input **in)
419 const struct sr_input_module *imod;
423 unsigned int midx, i;
425 uint8_t avail_metadata[8];
429 if (!filename || !filename[0]) {
430 sr_err("Invalid filename.");
433 stream = g_fopen(filename, "rb");
435 sr_err("Failed to open %s: %s", filename, g_strerror(errno));
438 filesize = sr_file_get_size(stream);
440 sr_err("Failed to get size of %s: %s",
441 filename, g_strerror(errno));
445 /* This actually allocates 256 bytes to allow for NUL termination. */
446 header = g_string_sized_new(255);
447 count = fread(header->str, 1, header->allocated_len - 1, stream);
449 if (count != header->allocated_len - 1 && ferror(stream)) {
450 sr_err("Failed to read %s: %s", filename, g_strerror(errno));
452 g_string_free(header, TRUE);
456 g_string_set_size(header, count);
458 meta = g_hash_table_new(NULL, NULL);
459 g_hash_table_insert(meta, GINT_TO_POINTER(SR_INPUT_META_FILENAME),
461 g_hash_table_insert(meta, GINT_TO_POINTER(SR_INPUT_META_FILESIZE),
462 GSIZE_TO_POINTER(MIN(filesize, G_MAXSSIZE)));
463 g_hash_table_insert(meta, GINT_TO_POINTER(SR_INPUT_META_HEADER),
466 avail_metadata[midx++] = SR_INPUT_META_FILENAME;
467 avail_metadata[midx++] = SR_INPUT_META_FILESIZE;
468 avail_metadata[midx++] = SR_INPUT_META_HEADER;
469 avail_metadata[midx] = 0;
470 /* TODO: MIME type */
474 for (i = 0; input_module_list[i]; i++) {
475 imod = input_module_list[i];
476 if (!imod->metadata[0]) {
477 /* Module has no metadata for matching so will take
478 * any input. No point in letting it try to match. */
481 if (!check_required_metadata(imod->metadata, avail_metadata))
482 /* Cannot satisfy this module's requirements. */
485 sr_dbg("Trying module %s.", imod->id);
487 ret = imod->format_match(meta);
489 /* Module didn't recognize this buffer. */
491 } else if (ret != SR_OK) {
492 /* Module recognized this buffer, but cannot handle it. */
495 /* Found a matching module. */
496 sr_dbg("Module %s matched.", imod->id);
498 *in = sr_input_new(imod, NULL);
501 g_hash_table_destroy(meta);
502 g_string_free(header, TRUE);
508 * Return the input instance's (virtual) device instance. This can be
509 * used to find out the number of channels and other information.
511 * If the device instance has not yet been fully populated by the input
512 * module, NULL is returned. This indicates the module needs more data
513 * to identify the number of channels and so on.
517 SR_API struct sr_dev_inst *sr_input_dev_inst_get(const struct sr_input *in)
526 * Send data to the specified input instance.
528 * When an input module instance is created with sr_input_new(), this
529 * function is used to feed data to the instance.
531 * As enough data gets fed into this function to completely populate
532 * the device instance associated with this input instance, this is
533 * guaranteed to return the moment it's ready. This gives the caller
534 * the chance to examine the device instance, attach session callbacks
539 SR_API int sr_input_send(const struct sr_input *in, GString *buf)
541 sr_spew("Sending %" G_GSIZE_FORMAT " bytes to %s module.",
542 buf->len, in->module->id);
543 return in->module->receive((struct sr_input *)in, buf);
547 * Signal the input module no more data will come.
549 * This will cause the module to process any data it may have buffered.
550 * The SR_DF_END packet will also typically be sent at this time.
554 SR_API int sr_input_end(const struct sr_input *in)
556 sr_spew("Calling end() on %s module.", in->module->id);
557 return in->module->end((struct sr_input *)in);
561 * Free the specified input instance and all associated resources.
565 SR_API void sr_input_free(const struct sr_input *in)
570 if (in->module->cleanup)
571 in->module->cleanup((struct sr_input *)in);
573 sr_dev_inst_free(in->sdi);
574 if (in->buf->len > 64) {
575 /* That seems more than just some sub-unitsize leftover... */
576 sr_warn("Found %" G_GSIZE_FORMAT
577 " unprocessed bytes at free time.", in->buf->len);
579 g_string_free(in->buf, TRUE);
581 g_free((gpointer)in);