am7xxx: use hex notation for USB endpoints
[libam7xxx.git] / src / am7xxx.c
index 272a249..528c1b6 100644 (file)
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
+#include <stdarg.h>
 #include <errno.h>
 #include <libusb.h>
 #include <errno.h>
 #include <libusb.h>
+#include <math.h>
 
 #include "am7xxx.h"
 #include "serialize.h"
 
 #define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))
 
 
 #include "am7xxx.h"
 #include "serialize.h"
 
 #define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))
 
+/* If we're not using GNU C, elide __attribute__
+ * taken from: http://unixwiz.net/techtips/gnu-c-attributes.html)
+ */
+#ifndef __GNUC__
+#  define  __attribute__(x)  /*NOTHING*/
+#endif
+
+/* Control shared library symbols visibility */
+#if defined _WIN32 || defined __CYGWIN__
+       #define AM7XXX_PUBLIC __declspec(dllexport)
+       #define AM7XXX_LOCAL
+#else
+       #if __GNUC__ >= 4
+               #define AM7XXX_PUBLIC __attribute__ ((visibility ("default")))
+               #define AM7XXX_LOCAL  __attribute__ ((visibility ("hidden")))
+       #else
+               #define AM7XXX_PUBLIC
+               #define AM7XXX_LOCAL
+       #endif
+#endif
+
+static void log_message(am7xxx_context *ctx,
+                       int level,
+                       const char *function,
+                       int line,
+                       const char *fmt,
+                       ...) __attribute__ ((format (printf, 5, 6)));
+
+#define fatal(...)        log_message(NULL, AM7XXX_LOG_FATAL,   __func__, __LINE__, __VA_ARGS__)
+#define error(ctx, ...)   log_message(ctx,  AM7XXX_LOG_ERROR,   __func__, __LINE__, __VA_ARGS__)
+#define warning(ctx, ...) log_message(ctx,  AM7XXX_LOG_WARNING, __func__, 0,        __VA_ARGS__)
+#define info(ctx, ...)    log_message(ctx,  AM7XXX_LOG_INFO,    __func__, 0,        __VA_ARGS__)
+#define debug(ctx, ...)   log_message(ctx,  AM7XXX_LOG_DEBUG,   __func__, 0,        __VA_ARGS__)
+#define trace(ctx, ...)   log_message(ctx,  AM7XXX_LOG_TRACE,   NULL,     0,        __VA_ARGS__)
+
 struct am7xxx_usb_device_descriptor {
        const char *name;
        uint16_t vendor_id;
 struct am7xxx_usb_device_descriptor {
        const char *name;
        uint16_t vendor_id;
@@ -47,7 +84,7 @@ static struct am7xxx_usb_device_descriptor supported_devices[] = {
 };
 
 /* The header size on the wire is known to be always 24 bytes, regardless of
 };
 
 /* The header size on the wire is known to be always 24 bytes, regardless of
- * the memory configuration enforced by different architechtures or compilers
+ * the memory configuration enforced by different architectures or compilers
  * for struct am7xxx_header
  */
 #define AM7XXX_HEADER_WIRE_SIZE 24
  * for struct am7xxx_header
  */
 #define AM7XXX_HEADER_WIRE_SIZE 24
@@ -55,6 +92,14 @@ static struct am7xxx_usb_device_descriptor supported_devices[] = {
 struct _am7xxx_device {
        libusb_device_handle *usb_device;
        uint8_t buffer[AM7XXX_HEADER_WIRE_SIZE];
 struct _am7xxx_device {
        libusb_device_handle *usb_device;
        uint8_t buffer[AM7XXX_HEADER_WIRE_SIZE];
+       am7xxx_context *ctx;
+       am7xxx_device *next;
+};
+
+struct _am7xxx_context {
+       libusb_context *usb_context;
+       int log_level;
+       am7xxx_device *devices_list;
 };
 
 typedef enum {
 };
 
 typedef enum {
@@ -116,71 +161,72 @@ struct am7xxx_header {
 };
 
 
 };
 
 
-static void dump_devinfo_header(struct am7xxx_devinfo_header *d)
+#ifdef DEBUG
+static void debug_dump_devinfo_header(am7xxx_context *ctx, struct am7xxx_devinfo_header *d)
 {
 {
-       if (d == NULL)
+       if (ctx == NULL || d == NULL)
                return;
 
                return;
 
-       printf("Info header:\n");
-       printf("\tnative_width:  0x%08x (%u)\n", d->native_width, d->native_width);
-       printf("\tnative_height: 0x%08x (%u)\n", d->native_height, d->native_height);
-       printf("\tunknown0:      0x%08x (%u)\n", d->unknown0, d->unknown0);
-       printf("\tunknown1:      0x%08x (%u)\n", d->unknown1, d->unknown1);
+       debug(ctx, "Info header:\n");
+       debug(ctx, "\tnative_width:  0x%08x (%u)\n", d->native_width, d->native_width);
+       debug(ctx, "\tnative_height: 0x%08x (%u)\n", d->native_height, d->native_height);
+       debug(ctx, "\tunknown0:      0x%08x (%u)\n", d->unknown0, d->unknown0);
+       debug(ctx, "\tunknown1:      0x%08x (%u)\n", d->unknown1, d->unknown1);
 }
 
 }
 
-static void dump_image_header(struct am7xxx_image_header *i)
+static void debug_dump_image_header(am7xxx_context *ctx, struct am7xxx_image_header *i)
 {
 {
-       if (i == NULL)
+       if (ctx == NULL || i == NULL)
                return;
 
                return;
 
-       printf("Image header:\n");
-       printf("\tformat:     0x%08x (%u)\n", i->format, i->format);
-       printf("\twidth:      0x%08x (%u)\n", i->width, i->width);
-       printf("\theight:     0x%08x (%u)\n", i->height, i->height);
-       printf("\timage size: 0x%08x (%u)\n", i->image_size, i->image_size);
+       debug(ctx, "Image header:\n");
+       debug(ctx, "\tformat:     0x%08x (%u)\n", i->format, i->format);
+       debug(ctx, "\twidth:      0x%08x (%u)\n", i->width, i->width);
+       debug(ctx, "\theight:     0x%08x (%u)\n", i->height, i->height);
+       debug(ctx, "\timage size: 0x%08x (%u)\n", i->image_size, i->image_size);
 }
 
 }
 
-static void dump_power_header(struct am7xxx_power_header *p)
+static void debug_dump_power_header(am7xxx_context *ctx, struct am7xxx_power_header *p)
 {
 {
-       if (p == NULL)
+       if (ctx == NULL || p == NULL)
                return;
 
                return;
 
-       printf("Power header:\n");
-       printf("\tbit2: 0x%08x (%u)\n", p->bit2, p->bit2);
-       printf("\tbit1: 0x%08x (%u)\n", p->bit1, p->bit1);
-       printf("\tbit0: 0x%08x (%u)\n", p->bit0, p->bit0);
+       debug(ctx, "Power header:\n");
+       debug(ctx, "\tbit2: 0x%08x (%u)\n", p->bit2, p->bit2);
+       debug(ctx, "\tbit1: 0x%08x (%u)\n", p->bit1, p->bit1);
+       debug(ctx, "\tbit0: 0x%08x (%u)\n", p->bit0, p->bit0);
 }
 
 }
 
-static void dump_header(struct am7xxx_header *h)
+static void debug_dump_header(am7xxx_context *ctx, struct am7xxx_header *h)
 {
 {
-       if (h == NULL)
+       if (ctx == NULL || h == NULL)
                return;
 
                return;
 
-       printf("packet_type:     0x%08x (%u)\n", h->packet_type, h->packet_type);
-       printf("unknown0:        0x%02hhx (%hhu)\n", h->unknown0, h->unknown0);
-       printf("header_data_len: 0x%02hhx (%hhu)\n", h->header_data_len, h->header_data_len);
-       printf("unknown2:        0x%02hhx (%hhu)\n", h->unknown2, h->unknown2);
-       printf("unknown3:        0x%02hhx (%hhu)\n", h->unknown3, h->unknown3);
+       debug(ctx, "BEGIN\n");
+       debug(ctx, "packet_type:     0x%08x (%u)\n", h->packet_type, h->packet_type);
+       debug(ctx, "unknown0:        0x%02hhx (%hhu)\n", h->unknown0, h->unknown0);
+       debug(ctx, "header_data_len: 0x%02hhx (%hhu)\n", h->header_data_len, h->header_data_len);
+       debug(ctx, "unknown2:        0x%02hhx (%hhu)\n", h->unknown2, h->unknown2);
+       debug(ctx, "unknown3:        0x%02hhx (%hhu)\n", h->unknown3, h->unknown3);
 
        switch(h->packet_type) {
        case AM7XXX_PACKET_TYPE_DEVINFO:
 
        switch(h->packet_type) {
        case AM7XXX_PACKET_TYPE_DEVINFO:
-               dump_devinfo_header(&(h->header_data.devinfo));
+               debug_dump_devinfo_header(ctx, &(h->header_data.devinfo));
                break;
 
        case AM7XXX_PACKET_TYPE_IMAGE:
                break;
 
        case AM7XXX_PACKET_TYPE_IMAGE:
-               dump_image_header(&(h->header_data.image));
+               debug_dump_image_header(ctx, &(h->header_data.image));
                break;
 
        case AM7XXX_PACKET_TYPE_POWER:
                break;
 
        case AM7XXX_PACKET_TYPE_POWER:
-               dump_power_header(&(h->header_data.power));
+               debug_dump_power_header(ctx, &(h->header_data.power));
                break;
 
        default:
                break;
 
        default:
-               printf("Packet type not supported!\n");
+               debug(ctx, "Packet type not supported!\n");
                break;
        }
                break;
        }
-
-       fflush(stdout);
+       debug(ctx, "END\n\n");
 }
 
 static inline unsigned int in_80chars(unsigned int i)
 }
 
 static inline unsigned int in_80chars(unsigned int i)
@@ -190,18 +236,39 @@ static inline unsigned int in_80chars(unsigned int i)
        return ((i+1) % (80/3));
 }
 
        return ((i+1) % (80/3));
 }
 
-static void dump_buffer(uint8_t *buffer, unsigned int len)
+static void trace_dump_buffer(am7xxx_context *ctx, const char *message,
+                             uint8_t *buffer, unsigned int len)
 {
        unsigned int i;
 
 {
        unsigned int i;
 
-       if (buffer == NULL || len == 0)
+       if (ctx == NULL || buffer == NULL || len == 0)
                return;
 
                return;
 
+       trace(ctx, "\n");
+       if (message)
+               trace(ctx, "%s\n", message);
+
        for (i = 0; i < len; i++) {
        for (i = 0; i < len; i++) {
-               printf("%02hhX%c", buffer[i], (in_80chars(i) && (i < len - 1)) ? ' ' : '\n');
+               trace(ctx, "%02hhX%c", buffer[i], (in_80chars(i) && (i < len - 1)) ? ' ' : '\n');
        }
        }
-       fflush(stdout);
+       trace(ctx, "\n");
+}
+#else
+static void debug_dump_header(am7xxx_context *ctx, struct am7xxx_header *h)
+{
+       (void)ctx;
+       (void)h;
+}
+
+static void trace_dump_buffer(am7xxx_context *ctx, const char *message,
+                             uint8_t *buffer, unsigned int len)
+{
+       (void)ctx;
+       (void)message;
+       (void)buffer;
+       (void)len;
 }
 }
+#endif /* DEBUG */
 
 static int read_data(am7xxx_device *dev, uint8_t *buffer, unsigned int len)
 {
 
 static int read_data(am7xxx_device *dev, uint8_t *buffer, unsigned int len)
 {
@@ -210,16 +277,12 @@ static int read_data(am7xxx_device *dev, uint8_t *buffer, unsigned int len)
 
        ret = libusb_bulk_transfer(dev->usb_device, 0x81, buffer, len, &transferred, 0);
        if (ret != 0 || (unsigned int)transferred != len) {
 
        ret = libusb_bulk_transfer(dev->usb_device, 0x81, buffer, len, &transferred, 0);
        if (ret != 0 || (unsigned int)transferred != len) {
-               fprintf(stderr, "Error: ret: %d\ttransferred: %d (expected %u)\n",
-                       ret, transferred, len);
+               error(dev->ctx, "ret: %d\ttransferred: %d (expected %u)\n",
+                     ret, transferred, len);
                return ret;
        }
 
                return ret;
        }
 
-#if DEBUG
-       printf("\n<-- received\n");
-       dump_buffer(buffer, len);
-       printf("\n");
-#endif
+       trace_dump_buffer(dev->ctx, "<-- received", buffer, len);
 
        return 0;
 }
 
        return 0;
 }
@@ -229,16 +292,12 @@ static int send_data(am7xxx_device *dev, uint8_t *buffer, unsigned int len)
        int ret;
        int transferred = 0;
 
        int ret;
        int transferred = 0;
 
-#if DEBUG
-       printf("\nsending -->\n");
-       dump_buffer(buffer, len);
-       printf("\n");
-#endif
+       trace_dump_buffer(dev->ctx, "sending -->", buffer, len);
 
 
-       ret = libusb_bulk_transfer(dev->usb_device, 1, buffer, len, &transferred, 0);
+       ret = libusb_bulk_transfer(dev->usb_device, 0x1, buffer, len, &transferred, 0);
        if (ret != 0 || (unsigned int)transferred != len) {
        if (ret != 0 || (unsigned int)transferred != len) {
-               fprintf(stderr, "Error: ret: %d\ttransferred: %d (expected %u)\n",
-                       ret, transferred, len);
+               error(dev->ctx, "ret: %d\ttransferred: %d (expected %u)\n",
+                     ret, transferred, len);
                return ret;
        }
 
                return ret;
        }
 
@@ -285,11 +344,7 @@ static int read_header(am7xxx_device *dev, struct am7xxx_header *h)
 
        unserialize_header(dev->buffer, h);
 
 
        unserialize_header(dev->buffer, h);
 
-#if DEBUG
-       printf("\n");
-       dump_header(h);
-       printf("\n");
-#endif
+       debug_dump_header(dev->ctx, h);
 
        ret = 0;
 
 
        ret = 0;
 
@@ -301,76 +356,321 @@ static int send_header(am7xxx_device *dev, struct am7xxx_header *h)
 {
        int ret;
 
 {
        int ret;
 
-#if DEBUG
-       printf("\n");
-       dump_header(h);
-       printf("\n");
-#endif
+       debug_dump_header(dev->ctx, h);
 
        serialize_header(h, dev->buffer);
        ret = send_data(dev, dev->buffer, AM7XXX_HEADER_WIRE_SIZE);
        if (ret < 0)
 
        serialize_header(h, dev->buffer);
        ret = send_data(dev, dev->buffer, AM7XXX_HEADER_WIRE_SIZE);
        if (ret < 0)
-               fprintf(stderr, "send_header: failed to send data.\n");
+               error(dev->ctx, "failed to send data\n");
 
        return ret;
 }
 
 
        return ret;
 }
 
-am7xxx_device *am7xxx_init(void)
+/* When level == AM7XXX_LOG_FATAL do not check the log_level from the context
+ * and print the message unconditionally, this makes it possible to print
+ * fatal messages even early on initialization, before the context has been
+ * set up */
+static void log_message(am7xxx_context *ctx,
+                       int level,
+                       const char *function,
+                       int line,
+                       const char *fmt,
+                       ...)
 {
 {
-       unsigned int i;
+       va_list ap;
+
+       if (level == AM7XXX_LOG_FATAL || (ctx && level <= ctx->log_level)) {
+               if (function) {
+                       fprintf(stderr, "%s", function);
+                       if (line)
+                               fprintf(stderr, "[%d]", line);
+                       fprintf(stderr, ": ");
+               }
 
 
-       am7xxx_device *dev = malloc(sizeof(*dev));
-       if (dev == NULL) {
-               perror("malloc");
+               va_start(ap, fmt);
+               vfprintf(stderr, fmt, ap);
+               va_end(ap);
+       }
+
+       return;
+}
+
+static am7xxx_device *add_new_device(am7xxx_context *ctx)
+{
+       am7xxx_device **devices_list;
+       am7xxx_device *new_device;
+
+       if (ctx == NULL) {
+               fatal("context must not be NULL!\n");
+               return NULL;
+       }
+
+       devices_list = &(ctx->devices_list);
+
+       new_device = malloc(sizeof(*new_device));
+       if (new_device == NULL) {
+               fatal("cannot allocate a new device (%s)\n", strerror(errno));
+               return NULL;
+       }
+       memset(new_device, 0, sizeof(*new_device));
+
+       new_device->ctx = ctx;
+
+       if (*devices_list == NULL) {
+               *devices_list = new_device;
+       } else {
+               am7xxx_device *prev = *devices_list;
+               while (prev->next)
+                       prev = prev->next;
+               prev->next = new_device;
+       }
+       return new_device;
+}
+
+static am7xxx_device *find_device(am7xxx_context *ctx,
+                                 unsigned int device_index)
+{
+       unsigned int i = 0;
+       am7xxx_device *current;
+
+       if (ctx == NULL) {
+               fatal("context must not be NULL!\n");
+               return NULL;
+       }
+
+       current = ctx->devices_list;
+       while (current && i++ < device_index)
+               current = current->next;
+
+       return current;
+}
+
+typedef enum {
+       SCAN_OP_BUILD_DEVLIST,
+       SCAN_OP_OPEN_DEVICE,
+} scan_op;
+
+/**
+ * This is where the central logic of multi-device support is.
+ *
+ * When 'op' == SCAN_OP_BUILD_DEVLIST the parameters 'open_device_index' and
+ * 'dev' are ignored; the function returns 0 on success and a negative value
+ * on error.
+ *
+ * When 'op' == SCAN_OP_OPEN_DEVICE the function opens the supported USB
+ * device with index 'open_device_index' and returns the correspondent
+ * am7xxx_device in the 'dev' parameter; the function returns 0 on success,
+ * 1 if the device was already open and a negative value on error.
+ *
+ * NOTES:
+ * if scan_devices() fails when called with 'op' == SCAN_OP_BUILD_DEVLIST,
+ * the caller might want to call am7xxx_shutdown() in order to remove
+ * devices possibly added before the failure.
+ */
+static int scan_devices(am7xxx_context *ctx, scan_op op,
+                       unsigned int open_device_index, am7xxx_device **dev)
+{
+       int num_devices;
+       libusb_device** list;
+       unsigned int current_index;
+       int i;
+       int ret;
+
+       if (ctx == NULL) {
+               fatal("context must not be NULL!\n");
+               return -EINVAL;
+       }
+       if (op == SCAN_OP_BUILD_DEVLIST && ctx->devices_list != NULL) {
+               error(ctx, "device scan done already? Abort!\n");
+               return -EINVAL;
+       }
+
+       num_devices = libusb_get_device_list(ctx->usb_context, &list);
+       if (num_devices < 0) {
+               ret = -ENODEV;
                goto out;
        }
                goto out;
        }
-       memset(dev, 0, sizeof(*dev));
-
-       libusb_init(NULL);
-       libusb_set_debug(NULL, 3);
-
-       for (i = 0; i < ARRAY_SIZE(supported_devices); i++) {
-               dev->usb_device = libusb_open_device_with_vid_pid(NULL,
-                                                     supported_devices[i].vendor_id,
-                                                     supported_devices[i].product_id);
-               if (dev->usb_device) {
-                       printf("%s: device found: %s\n", __func__, supported_devices[i].name);
-                       break;
+
+       current_index = 0;
+       for (i = 0; i < num_devices; i++) {
+               struct libusb_device_descriptor desc;
+               unsigned int j;
+
+               ret = libusb_get_device_descriptor(list[i], &desc);
+               if (ret < 0)
+                       continue;
+
+               for (j = 0; j < ARRAY_SIZE(supported_devices); j++) {
+                       if (desc.idVendor == supported_devices[j].vendor_id
+                           && desc.idProduct == supported_devices[j].product_id) {
+
+                               if (op == SCAN_OP_BUILD_DEVLIST) {
+                                       am7xxx_device *new_device;
+                                       info(ctx, "am7xxx device found, index: %d, name: %s\n",
+                                            current_index,
+                                            supported_devices[j].name);
+                                       new_device = add_new_device(ctx);
+                                       if (new_device == NULL) {
+                                               /* XXX, the caller may want
+                                                * to call am7xxx_shutdown() if
+                                                * we fail here, as we may have
+                                                * added some devices already
+                                                */
+                                               debug(ctx, "Cannot create a new device\n");
+                                               ret = -ENODEV;
+                                               goto out;
+                                       }
+                               } else if (op == SCAN_OP_OPEN_DEVICE &&
+                                          current_index == open_device_index) {
+
+                                       *dev = find_device(ctx, open_device_index);
+                                       if (*dev == NULL) {
+                                               ret = -ENODEV;
+                                               goto out;
+                                       }
+
+                                       /* the usb device has already been opened */
+                                       if ((*dev)->usb_device) {
+                                               debug(ctx, "(*dev)->usb_device already set\n");
+                                               ret = 1;
+                                               goto out;
+                                       }
+
+                                       ret = libusb_open(list[i], &((*dev)->usb_device));
+                                       if (ret < 0) {
+                                               debug(ctx, "libusb_open failed\n");
+                                               goto out;
+                                       }
+
+                                       libusb_set_configuration((*dev)->usb_device, 1);
+                                       libusb_claim_interface((*dev)->usb_device, 0);
+                                       goto out;
+                               }
+                               current_index++;
+                       }
                }
        }
                }
        }
-       if (dev->usb_device == NULL) {
-               errno = ENODEV;
-               perror("libusb_open_device_with_vid_pid");
-               goto out_libusb_exit;
+
+       /* if we made it up to here we didn't find any device to open */
+       if (op == SCAN_OP_OPEN_DEVICE) {
+               error(ctx, "Cannot find any device to open\n");
+               ret = -ENODEV;
+               goto out;
        }
 
        }
 
-       libusb_set_configuration(dev->usb_device, 1);
-       libusb_claim_interface(dev->usb_device, 0);
+       /* everything went fine when building the device list */
+       ret = 0;
+out:
+       libusb_free_device_list(list, 1);
+       return ret;
+}
+
+/* Public API */
+
+AM7XXX_PUBLIC int am7xxx_init(am7xxx_context **ctx)
+{
+       int ret = 0;
+
+       *ctx = malloc(sizeof(**ctx));
+       if (*ctx == NULL) {
+               fatal("cannot allocate the context (%s)\n", strerror(errno));
+               ret = -ENOMEM;
+               goto out;
+       }
+       memset(*ctx, 0, sizeof(**ctx));
+
+       /* Set the highest log level during initialization */
+       (*ctx)->log_level = AM7XXX_LOG_TRACE;
+
+       ret = libusb_init(&((*ctx)->usb_context));
+       if (ret < 0)
+               goto out_free_context;
+
+       libusb_set_debug((*ctx)->usb_context, 3);
+
+       ret = scan_devices(*ctx, SCAN_OP_BUILD_DEVLIST , 0, NULL);
+       if (ret < 0) {
+               error(*ctx, "scan_devices() failed\n");
+               am7xxx_shutdown(*ctx);
+               goto out;
+       }
 
 
-       return dev;
+       /* Set a quieter log level as default for normal operation */
+       (*ctx)->log_level = AM7XXX_LOG_ERROR;
+       return 0;
 
 
-out_libusb_exit:
-       libusb_exit(NULL);
-       free(dev);
+out_free_context:
+       free(*ctx);
+       *ctx = NULL;
 out:
 out:
-       return NULL;
+       return ret;
+}
+
+AM7XXX_PUBLIC void am7xxx_shutdown(am7xxx_context *ctx)
+{
+       am7xxx_device *current;
+
+       if (ctx == NULL) {
+               fatal("context must not be NULL!\n");
+               return;
+       }
+
+       current = ctx->devices_list;
+       while (current) {
+               am7xxx_device *next = current->next;
+               am7xxx_close_device(current);
+               free(current);
+               current = next;
+       }
+
+       libusb_exit(ctx->usb_context);
+       free(ctx);
+       ctx = NULL;
+}
+
+AM7XXX_PUBLIC void am7xxx_set_log_level(am7xxx_context *ctx, am7xxx_log_level log_level)
+{
+       ctx->log_level = log_level;
 }
 
 }
 
-void am7xxx_shutdown(am7xxx_device *dev)
+AM7XXX_PUBLIC int am7xxx_open_device(am7xxx_context *ctx, am7xxx_device **dev,
+                      unsigned int device_index)
 {
 {
-       if (dev) {
+       int ret;
+
+       if (ctx == NULL) {
+               fatal("context must not be NULL!\n");
+               return -EINVAL;
+       }
+
+       ret = scan_devices(ctx, SCAN_OP_OPEN_DEVICE, device_index, dev);
+       if (ret < 0) {
+               errno = ENODEV;
+       } else if (ret > 0) {
+               warning(ctx, "device %d already open\n", device_index);
+               errno = EBUSY;
+               ret = -EBUSY;
+       }
+
+       return ret;
+}
+
+AM7XXX_PUBLIC int am7xxx_close_device(am7xxx_device *dev)
+{
+       if (dev == NULL) {
+               fatal("dev must not be NULL!\n");
+               return -EINVAL;
+       }
+       if (dev->usb_device) {
+               libusb_release_interface(dev->usb_device, 0);
                libusb_close(dev->usb_device);
                libusb_close(dev->usb_device);
-               libusb_exit(NULL);
-               free(dev);
-               dev = NULL;
+               dev->usb_device = NULL;
        }
        }
+       return 0;
 }
 
 }
 
-int am7xxx_get_device_info(am7xxx_device *dev,
-                          unsigned int *native_width,
-                          unsigned int *native_height,
-                          unsigned int *unknown0,
-                          unsigned int *unknown1)
+AM7XXX_PUBLIC int am7xxx_get_device_info(am7xxx_device *dev,
+                          am7xxx_device_info *device_info)
 {
        int ret;
        struct am7xxx_header h = {
 {
        int ret;
        struct am7xxx_header h = {
@@ -397,20 +697,85 @@ int am7xxx_get_device_info(am7xxx_device *dev,
        if (ret < 0)
                return ret;
 
        if (ret < 0)
                return ret;
 
-       *native_width = h.header_data.devinfo.native_width;
-       *native_height = h.header_data.devinfo.native_height;
-       *unknown0 = h.header_data.devinfo.unknown0;
-       *unknown1 = h.header_data.devinfo.unknown1;
+       device_info->native_width = h.header_data.devinfo.native_width;
+       device_info->native_height = h.header_data.devinfo.native_height;
+#if 0
+       /* No reason to expose these in the public API until we know what they mean */
+       device_info->unknown0 = h.header_data.devinfo.unknown0;
+       device_info->unknown1 = h.header_data.devinfo.unknown1;
+#endif
 
        return 0;
 }
 
 
        return 0;
 }
 
-int am7xxx_send_image(am7xxx_device *dev,
+AM7XXX_PUBLIC int am7xxx_calc_scaled_image_dimensions(am7xxx_device *dev,
+                                       unsigned int upscale,
+                                       unsigned int original_width,
+                                       unsigned int original_height,
+                                       unsigned int *scaled_width,
+                                       unsigned int *scaled_height)
+{
+
+       am7xxx_device_info device_info;
+       float width_ratio;
+       float height_ratio;
+       int ret;
+
+       ret = am7xxx_get_device_info(dev, &device_info);
+       if (ret < 0) {
+               error(dev->ctx, "cannot get device info\n");
+               return ret;
+       }
+
+       /*
+        * Check if we need to rescale; if the input image fits the native
+        * dimensions there is no need to, unless we want to upscale.
+        */
+       if (!upscale &&
+           original_width <= device_info.native_width &&
+           original_height <= device_info.native_height ) {
+               debug(dev->ctx, "CASE 0, no rescaling, the original image fits already\n");
+               *scaled_width = original_width;
+               *scaled_height = original_height;
+               return 0;
+       }
+
+       /* Input dimensions relative to the device native dimensions */
+       width_ratio =  (float)original_width / device_info.native_width;
+       height_ratio = (float)original_height / device_info.native_height;
+
+       if (width_ratio > height_ratio) {
+               /*
+                * The input is proportionally "wider" than the device viewport
+                * so its height needs to be adjusted
+                */
+               debug(dev->ctx, "CASE 1, original image wider, adjust the scaled height\n");
+               *scaled_width = device_info.native_width;
+               *scaled_height = (unsigned int)lroundf(original_height / width_ratio);
+       } else if (width_ratio < height_ratio) {
+               /*
+                * The input is proportionally "taller" than the device viewport
+                * so its width needs to be adjusted
+                */
+               debug(dev->ctx, "CASE 2 original image taller, adjust the scaled width\n");
+               *scaled_width = (unsigned int)lroundf(original_width / height_ratio);
+               *scaled_height = device_info.native_height;
+       } else {
+               debug(dev->ctx, "CASE 3, just rescale, same aspect ratio already\n");
+               *scaled_width = device_info.native_width;
+               *scaled_height = device_info.native_height;
+       }
+       debug(dev->ctx, "scaled dimensions: %dx%d\n", *scaled_width, *scaled_height);
+
+       return 0;
+}
+
+AM7XXX_PUBLIC int am7xxx_send_image(am7xxx_device *dev,
                      am7xxx_image_format format,
                      unsigned int width,
                      unsigned int height,
                      uint8_t *image,
                      am7xxx_image_format format,
                      unsigned int width,
                      unsigned int height,
                      uint8_t *image,
-                     unsigned int size)
+                     unsigned int image_size)
 {
        int ret;
        struct am7xxx_header h = {
 {
        int ret;
        struct am7xxx_header h = {
@@ -424,7 +789,7 @@ int am7xxx_send_image(am7xxx_device *dev,
                                .format     = format,
                                .width      = width,
                                .height     = height,
                                .format     = format,
                                .width      = width,
                                .height     = height,
-                               .image_size = size,
+                               .image_size = image_size,
                        },
                },
        };
                        },
                },
        };
@@ -433,13 +798,15 @@ int am7xxx_send_image(am7xxx_device *dev,
        if (ret < 0)
                return ret;
 
        if (ret < 0)
                return ret;
 
-       if (image == NULL || size == 0)
+       if (image == NULL || image_size == 0) {
+               warning(dev->ctx, "Not sending any data, check the 'image' or 'image_size' parameters\n");
                return 0;
                return 0;
+       }
 
 
-       return send_data(dev, image, size);
+       return send_data(dev, image, image_size);
 }
 
 }
 
-int am7xxx_set_power_mode(am7xxx_device *dev, am7xxx_power_mode mode)
+AM7XXX_PUBLIC int am7xxx_set_power_mode(am7xxx_device *dev, am7xxx_power_mode mode)
 {
        int ret;
        struct am7xxx_header h = {
 {
        int ret;
        struct am7xxx_header h = {
@@ -481,7 +848,7 @@ int am7xxx_set_power_mode(am7xxx_device *dev, am7xxx_power_mode mode)
                break;
 
        default:
                break;
 
        default:
-               fprintf(stderr, "Unsupported power mode.\n");
+               error(dev->ctx, "Power mode not supported!\n");
                return -EINVAL;
        };
 
                return -EINVAL;
        };