d22a417dd5e862d72db3b1eccb0eb09661cd2752
[libam7xxx.git] / src / am7xxx.c
1 /* am7xxx - communication with AM7xxx based USB Pico Projectors and DPFs
2  *
3  * Copyright (C) 2012  Antonio Ospite <ospite@studenti.unina.it>
4  *
5  * This program is free software: you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation, either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
17  */
18
19 #include <stdio.h>
20 #include <stdlib.h>
21 #include <string.h>
22 #include <stdarg.h>
23 #include <errno.h>
24 #include <libusb.h>
25 #include <math.h>
26
27 #include "am7xxx.h"
28 #include "serialize.h"
29
30 #define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))
31
32 /* If we're not using GNU C, elide __attribute__
33  * taken from: http://unixwiz.net/techtips/gnu-c-attributes.html)
34  */
35 #ifndef __GNUC__
36 #  define  __attribute__(x)  /*NOTHING*/
37 #endif
38
39 /* Control shared library symbols visibility */
40 #if defined _WIN32 || defined __CYGWIN__
41         #define AM7XXX_PUBLIC __declspec(dllexport)
42         #define AM7XXX_LOCAL
43 #else
44         #if __GNUC__ >= 4
45                 #define AM7XXX_PUBLIC __attribute__ ((visibility ("default")))
46                 #define AM7XXX_LOCAL  __attribute__ ((visibility ("hidden")))
47         #else
48                 #define AM7XXX_PUBLIC
49                 #define AM7XXX_LOCAL
50         #endif
51 #endif
52
53 static void log_message(am7xxx_context *ctx,
54                         int level,
55                         const char *function,
56                         int line,
57                         const char *fmt,
58                         ...) __attribute__ ((format (printf, 5, 6)));
59
60 #define fatal(...)        log_message(NULL, AM7XXX_LOG_FATAL,   __func__, __LINE__, __VA_ARGS__)
61 #define error(ctx, ...)   log_message(ctx,  AM7XXX_LOG_ERROR,   __func__, __LINE__, __VA_ARGS__)
62 #define warning(ctx, ...) log_message(ctx,  AM7XXX_LOG_WARNING, __func__, 0,        __VA_ARGS__)
63 #define info(ctx, ...)    log_message(ctx,  AM7XXX_LOG_INFO,    __func__, 0,        __VA_ARGS__)
64 #define debug(ctx, ...)   log_message(ctx,  AM7XXX_LOG_DEBUG,   __func__, 0,        __VA_ARGS__)
65 #define trace(ctx, ...)   log_message(ctx,  AM7XXX_LOG_TRACE,   NULL,     0,        __VA_ARGS__)
66
67 struct am7xxx_usb_device_descriptor {
68         const char *name;
69         uint16_t vendor_id;
70         uint16_t product_id;
71 };
72
73 static struct am7xxx_usb_device_descriptor supported_devices[] = {
74         {
75                 .name       = "Acer C110",
76                 .vendor_id  = 0x1de1,
77                 .product_id = 0xc101,
78         },
79         {
80                 .name       = "Philips/Sagemcom PicoPix 1020",
81                 .vendor_id  = 0x21e7,
82                 .product_id = 0x000e,
83         },
84 };
85
86 /* The header size on the wire is known to be always 24 bytes, regardless of
87  * the memory configuration enforced by different architectures or compilers
88  * for struct am7xxx_header
89  */
90 #define AM7XXX_HEADER_WIRE_SIZE 24
91
92 struct _am7xxx_device {
93         libusb_device_handle *usb_device;
94         uint8_t buffer[AM7XXX_HEADER_WIRE_SIZE];
95         am7xxx_context *ctx;
96         am7xxx_device *next;
97 };
98
99 struct _am7xxx_context {
100         libusb_context *usb_context;
101         int log_level;
102         am7xxx_device *devices_list;
103 };
104
105 typedef enum {
106         AM7XXX_PACKET_TYPE_DEVINFO = 0x01,
107         AM7XXX_PACKET_TYPE_IMAGE   = 0x02,
108         AM7XXX_PACKET_TYPE_POWER   = 0x04,
109         AM7XXX_PACKET_TYPE_UNKNOWN = 0x05,
110 } am7xxx_packet_type;
111
112 struct am7xxx_generic_header {
113         uint32_t field0;
114         uint32_t field1;
115         uint32_t field2;
116         uint32_t field3;
117 };
118
119 struct am7xxx_devinfo_header {
120         uint32_t native_width;
121         uint32_t native_height;
122         uint32_t unknown0;
123         uint32_t unknown1;
124 };
125
126 struct am7xxx_image_header {
127         uint32_t format;
128         uint32_t width;
129         uint32_t height;
130         uint32_t image_size;
131 };
132
133 struct am7xxx_power_header {
134         uint32_t bit2;
135         uint32_t bit1;
136         uint32_t bit0;
137 };
138
139 /*
140  * Examples of packet headers:
141  *
142  * Image header:
143  * 02 00 00 00 00 10 3e 10 01 00 00 00 20 03 00 00 e0 01 00 00 53 E8 00 00
144  *
145  * Power header:
146  * 04 00 00 00 00 0c ff ff 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
147  */
148
149 struct am7xxx_header {
150         uint32_t packet_type;
151         uint8_t unknown0;
152         uint8_t header_data_len;
153         uint8_t unknown2;
154         uint8_t unknown3;
155         union {
156                 struct am7xxx_generic_header data;
157                 struct am7xxx_devinfo_header devinfo;
158                 struct am7xxx_image_header image;
159                 struct am7xxx_power_header power;
160         } header_data;
161 };
162
163
164 #ifdef DEBUG
165 static void debug_dump_devinfo_header(am7xxx_context *ctx, struct am7xxx_devinfo_header *d)
166 {
167         if (ctx == NULL || d == NULL)
168                 return;
169
170         debug(ctx, "Info header:\n");
171         debug(ctx, "\tnative_width:  0x%08x (%u)\n", d->native_width, d->native_width);
172         debug(ctx, "\tnative_height: 0x%08x (%u)\n", d->native_height, d->native_height);
173         debug(ctx, "\tunknown0:      0x%08x (%u)\n", d->unknown0, d->unknown0);
174         debug(ctx, "\tunknown1:      0x%08x (%u)\n", d->unknown1, d->unknown1);
175 }
176
177 static void debug_dump_image_header(am7xxx_context *ctx, struct am7xxx_image_header *i)
178 {
179         if (ctx == NULL || i == NULL)
180                 return;
181
182         debug(ctx, "Image header:\n");
183         debug(ctx, "\tformat:     0x%08x (%u)\n", i->format, i->format);
184         debug(ctx, "\twidth:      0x%08x (%u)\n", i->width, i->width);
185         debug(ctx, "\theight:     0x%08x (%u)\n", i->height, i->height);
186         debug(ctx, "\timage size: 0x%08x (%u)\n", i->image_size, i->image_size);
187 }
188
189 static void debug_dump_power_header(am7xxx_context *ctx, struct am7xxx_power_header *p)
190 {
191         if (ctx == NULL || p == NULL)
192                 return;
193
194         debug(ctx, "Power header:\n");
195         debug(ctx, "\tbit2: 0x%08x (%u)\n", p->bit2, p->bit2);
196         debug(ctx, "\tbit1: 0x%08x (%u)\n", p->bit1, p->bit1);
197         debug(ctx, "\tbit0: 0x%08x (%u)\n", p->bit0, p->bit0);
198 }
199
200 static void debug_dump_header(am7xxx_context *ctx, struct am7xxx_header *h)
201 {
202         if (ctx == NULL || h == NULL)
203                 return;
204
205         debug(ctx, "BEGIN\n");
206         debug(ctx, "packet_type:     0x%08x (%u)\n", h->packet_type, h->packet_type);
207         debug(ctx, "unknown0:        0x%02hhx (%hhu)\n", h->unknown0, h->unknown0);
208         debug(ctx, "header_data_len: 0x%02hhx (%hhu)\n", h->header_data_len, h->header_data_len);
209         debug(ctx, "unknown2:        0x%02hhx (%hhu)\n", h->unknown2, h->unknown2);
210         debug(ctx, "unknown3:        0x%02hhx (%hhu)\n", h->unknown3, h->unknown3);
211
212         switch(h->packet_type) {
213         case AM7XXX_PACKET_TYPE_DEVINFO:
214                 debug_dump_devinfo_header(ctx, &(h->header_data.devinfo));
215                 break;
216
217         case AM7XXX_PACKET_TYPE_IMAGE:
218                 debug_dump_image_header(ctx, &(h->header_data.image));
219                 break;
220
221         case AM7XXX_PACKET_TYPE_POWER:
222                 debug_dump_power_header(ctx, &(h->header_data.power));
223                 break;
224
225         default:
226                 debug(ctx, "Packet type not supported!\n");
227                 break;
228         }
229         debug(ctx, "END\n\n");
230 }
231
232 static inline unsigned int in_80chars(unsigned int i)
233 {
234         /* The 3 below is the length of "xx " where xx is the hex string
235          * representation of a byte */
236         return ((i+1) % (80/3));
237 }
238
239 static void trace_dump_buffer(am7xxx_context *ctx, const char *message,
240                               uint8_t *buffer, unsigned int len)
241 {
242         unsigned int i;
243
244         if (ctx == NULL || buffer == NULL || len == 0)
245                 return;
246
247         trace(ctx, "\n");
248         if (message)
249                 trace(ctx, "%s\n", message);
250
251         for (i = 0; i < len; i++) {
252                 trace(ctx, "%02hhX%c", buffer[i], (in_80chars(i) && (i < len - 1)) ? ' ' : '\n');
253         }
254         trace(ctx, "\n");
255 }
256 #else
257 static void debug_dump_header(am7xxx_context *ctx, struct am7xxx_header *h)
258 {
259         (void)ctx;
260         (void)h;
261 }
262
263 static void trace_dump_buffer(am7xxx_context *ctx, const char *message,
264                               uint8_t *buffer, unsigned int len)
265 {
266         (void)ctx;
267         (void)message;
268         (void)buffer;
269         (void)len;
270 }
271 #endif /* DEBUG */
272
273 static int read_data(am7xxx_device *dev, uint8_t *buffer, unsigned int len)
274 {
275         int ret;
276         int transferred = 0;
277
278         ret = libusb_bulk_transfer(dev->usb_device, 0x81, buffer, len, &transferred, 0);
279         if (ret != 0 || (unsigned int)transferred != len) {
280                 error(dev->ctx, "ret: %d\ttransferred: %d (expected %u)\n",
281                       ret, transferred, len);
282                 return ret;
283         }
284
285         trace_dump_buffer(dev->ctx, "<-- received", buffer, len);
286
287         return 0;
288 }
289
290 static int send_data(am7xxx_device *dev, uint8_t *buffer, unsigned int len)
291 {
292         int ret;
293         int transferred = 0;
294
295         trace_dump_buffer(dev->ctx, "sending -->", buffer, len);
296
297         ret = libusb_bulk_transfer(dev->usb_device, 0x1, buffer, len, &transferred, 0);
298         if (ret != 0 || (unsigned int)transferred != len) {
299                 error(dev->ctx, "ret: %d\ttransferred: %d (expected %u)\n",
300                       ret, transferred, len);
301                 return ret;
302         }
303
304         return 0;
305 }
306
307 static void serialize_header(struct am7xxx_header *h, uint8_t *buffer)
308 {
309         uint8_t **buffer_iterator = &buffer;
310
311         put_le32(h->packet_type, buffer_iterator);
312         put_8(h->unknown0, buffer_iterator);
313         put_8(h->header_data_len, buffer_iterator);
314         put_8(h->unknown2, buffer_iterator);
315         put_8(h->unknown3, buffer_iterator);
316         put_le32(h->header_data.data.field0, buffer_iterator);
317         put_le32(h->header_data.data.field1, buffer_iterator);
318         put_le32(h->header_data.data.field2, buffer_iterator);
319         put_le32(h->header_data.data.field3, buffer_iterator);
320 }
321
322 static void unserialize_header(uint8_t *buffer, struct am7xxx_header *h)
323 {
324         uint8_t **buffer_iterator = &buffer;
325
326         h->packet_type = get_le32(buffer_iterator);
327         h->unknown0 = get_8(buffer_iterator);
328         h->header_data_len = get_8(buffer_iterator);
329         h->unknown2 = get_8(buffer_iterator);
330         h->unknown3 = get_8(buffer_iterator);
331         h->header_data.data.field0 = get_le32(buffer_iterator);
332         h->header_data.data.field1 = get_le32(buffer_iterator);
333         h->header_data.data.field2 = get_le32(buffer_iterator);
334         h->header_data.data.field3 = get_le32(buffer_iterator);
335 }
336
337 static int read_header(am7xxx_device *dev, struct am7xxx_header *h)
338 {
339         int ret;
340
341         ret = read_data(dev, dev->buffer, AM7XXX_HEADER_WIRE_SIZE);
342         if (ret < 0)
343                 goto out;
344
345         unserialize_header(dev->buffer, h);
346
347         debug_dump_header(dev->ctx, h);
348
349         ret = 0;
350
351 out:
352         return ret;
353 }
354
355 static int send_header(am7xxx_device *dev, struct am7xxx_header *h)
356 {
357         int ret;
358
359         debug_dump_header(dev->ctx, h);
360
361         serialize_header(h, dev->buffer);
362         ret = send_data(dev, dev->buffer, AM7XXX_HEADER_WIRE_SIZE);
363         if (ret < 0)
364                 error(dev->ctx, "failed to send data\n");
365
366         return ret;
367 }
368
369 /* When level == AM7XXX_LOG_FATAL do not check the log_level from the context
370  * and print the message unconditionally, this makes it possible to print
371  * fatal messages even early on initialization, before the context has been
372  * set up */
373 static void log_message(am7xxx_context *ctx,
374                         int level,
375                         const char *function,
376                         int line,
377                         const char *fmt,
378                         ...)
379 {
380         va_list ap;
381
382         if (level == AM7XXX_LOG_FATAL || (ctx && level <= ctx->log_level)) {
383                 if (function) {
384                         fprintf(stderr, "%s", function);
385                         if (line)
386                                 fprintf(stderr, "[%d]", line);
387                         fprintf(stderr, ": ");
388                 }
389
390                 va_start(ap, fmt);
391                 vfprintf(stderr, fmt, ap);
392                 va_end(ap);
393         }
394
395         return;
396 }
397
398 static am7xxx_device *add_new_device(am7xxx_context *ctx)
399 {
400         am7xxx_device **devices_list;
401         am7xxx_device *new_device;
402
403         if (ctx == NULL) {
404                 fatal("context must not be NULL!\n");
405                 return NULL;
406         }
407
408         devices_list = &(ctx->devices_list);
409
410         new_device = malloc(sizeof(*new_device));
411         if (new_device == NULL) {
412                 fatal("cannot allocate a new device (%s)\n", strerror(errno));
413                 return NULL;
414         }
415         memset(new_device, 0, sizeof(*new_device));
416
417         new_device->ctx = ctx;
418
419         if (*devices_list == NULL) {
420                 *devices_list = new_device;
421         } else {
422                 am7xxx_device *prev = *devices_list;
423                 while (prev->next)
424                         prev = prev->next;
425                 prev->next = new_device;
426         }
427         return new_device;
428 }
429
430 static am7xxx_device *find_device(am7xxx_context *ctx,
431                                   unsigned int device_index)
432 {
433         unsigned int i = 0;
434         am7xxx_device *current;
435
436         if (ctx == NULL) {
437                 fatal("context must not be NULL!\n");
438                 return NULL;
439         }
440
441         current = ctx->devices_list;
442         while (current && i++ < device_index)
443                 current = current->next;
444
445         return current;
446 }
447
448 typedef enum {
449         SCAN_OP_BUILD_DEVLIST,
450         SCAN_OP_OPEN_DEVICE,
451 } scan_op;
452
453 /**
454  * This is where the central logic of multi-device support is.
455  *
456  * When 'op' == SCAN_OP_BUILD_DEVLIST the parameters 'open_device_index' and
457  * 'dev' are ignored; the function returns 0 on success and a negative value
458  * on error.
459  *
460  * When 'op' == SCAN_OP_OPEN_DEVICE the function opens the supported USB
461  * device with index 'open_device_index' and returns the correspondent
462  * am7xxx_device in the 'dev' parameter; the function returns 0 on success,
463  * 1 if the device was already open and a negative value on error.
464  *
465  * NOTES:
466  * if scan_devices() fails when called with 'op' == SCAN_OP_BUILD_DEVLIST,
467  * the caller might want to call am7xxx_shutdown() in order to remove
468  * devices possibly added before the failure.
469  */
470 static int scan_devices(am7xxx_context *ctx, scan_op op,
471                         unsigned int open_device_index, am7xxx_device **dev)
472 {
473         int num_devices;
474         libusb_device** list;
475         unsigned int current_index;
476         int i;
477         int ret;
478
479         if (ctx == NULL) {
480                 fatal("context must not be NULL!\n");
481                 return -EINVAL;
482         }
483         if (op == SCAN_OP_BUILD_DEVLIST && ctx->devices_list != NULL) {
484                 error(ctx, "device scan done already? Abort!\n");
485                 return -EINVAL;
486         }
487
488         num_devices = libusb_get_device_list(ctx->usb_context, &list);
489         if (num_devices < 0) {
490                 ret = -ENODEV;
491                 goto out;
492         }
493
494         current_index = 0;
495         for (i = 0; i < num_devices; i++) {
496                 struct libusb_device_descriptor desc;
497                 unsigned int j;
498
499                 ret = libusb_get_device_descriptor(list[i], &desc);
500                 if (ret < 0)
501                         continue;
502
503                 for (j = 0; j < ARRAY_SIZE(supported_devices); j++) {
504                         if (desc.idVendor == supported_devices[j].vendor_id
505                             && desc.idProduct == supported_devices[j].product_id) {
506
507                                 if (op == SCAN_OP_BUILD_DEVLIST) {
508                                         am7xxx_device *new_device;
509                                         info(ctx, "am7xxx device found, index: %d, name: %s\n",
510                                              current_index,
511                                              supported_devices[j].name);
512                                         new_device = add_new_device(ctx);
513                                         if (new_device == NULL) {
514                                                 /* XXX, the caller may want
515                                                  * to call am7xxx_shutdown() if
516                                                  * we fail here, as we may have
517                                                  * added some devices already
518                                                  */
519                                                 debug(ctx, "Cannot create a new device\n");
520                                                 ret = -ENODEV;
521                                                 goto out;
522                                         }
523                                 } else if (op == SCAN_OP_OPEN_DEVICE &&
524                                            current_index == open_device_index) {
525
526                                         *dev = find_device(ctx, open_device_index);
527                                         if (*dev == NULL) {
528                                                 ret = -ENODEV;
529                                                 goto out;
530                                         }
531
532                                         /* the usb device has already been opened */
533                                         if ((*dev)->usb_device) {
534                                                 debug(ctx, "(*dev)->usb_device already set\n");
535                                                 ret = 1;
536                                                 goto out;
537                                         }
538
539                                         ret = libusb_open(list[i], &((*dev)->usb_device));
540                                         if (ret < 0) {
541                                                 debug(ctx, "libusb_open failed\n");
542                                                 goto out;
543                                         }
544
545                                         libusb_set_configuration((*dev)->usb_device, 2);
546                                         libusb_claim_interface((*dev)->usb_device, 0);
547                                         goto out;
548                                 }
549                                 current_index++;
550                         }
551                 }
552         }
553
554         /* if we made it up to here we didn't find any device to open */
555         if (op == SCAN_OP_OPEN_DEVICE) {
556                 error(ctx, "Cannot find any device to open\n");
557                 ret = -ENODEV;
558                 goto out;
559         }
560
561         /* everything went fine when building the device list */
562         ret = 0;
563 out:
564         libusb_free_device_list(list, 1);
565         return ret;
566 }
567
568 /* Public API */
569
570 AM7XXX_PUBLIC int am7xxx_init(am7xxx_context **ctx)
571 {
572         int ret = 0;
573
574         *ctx = malloc(sizeof(**ctx));
575         if (*ctx == NULL) {
576                 fatal("cannot allocate the context (%s)\n", strerror(errno));
577                 ret = -ENOMEM;
578                 goto out;
579         }
580         memset(*ctx, 0, sizeof(**ctx));
581
582         /* Set the highest log level during initialization */
583         (*ctx)->log_level = AM7XXX_LOG_TRACE;
584
585         ret = libusb_init(&((*ctx)->usb_context));
586         if (ret < 0)
587                 goto out_free_context;
588
589         libusb_set_debug((*ctx)->usb_context, 3);
590
591         ret = scan_devices(*ctx, SCAN_OP_BUILD_DEVLIST , 0, NULL);
592         if (ret < 0) {
593                 error(*ctx, "scan_devices() failed\n");
594                 am7xxx_shutdown(*ctx);
595                 goto out;
596         }
597
598         /* Set a quieter log level as default for normal operation */
599         (*ctx)->log_level = AM7XXX_LOG_ERROR;
600         return 0;
601
602 out_free_context:
603         free(*ctx);
604         *ctx = NULL;
605 out:
606         return ret;
607 }
608
609 AM7XXX_PUBLIC void am7xxx_shutdown(am7xxx_context *ctx)
610 {
611         am7xxx_device *current;
612
613         if (ctx == NULL) {
614                 fatal("context must not be NULL!\n");
615                 return;
616         }
617
618         current = ctx->devices_list;
619         while (current) {
620                 am7xxx_device *next = current->next;
621                 am7xxx_close_device(current);
622                 free(current);
623                 current = next;
624         }
625
626         libusb_exit(ctx->usb_context);
627         free(ctx);
628         ctx = NULL;
629 }
630
631 AM7XXX_PUBLIC void am7xxx_set_log_level(am7xxx_context *ctx, am7xxx_log_level log_level)
632 {
633         ctx->log_level = log_level;
634 }
635
636 AM7XXX_PUBLIC int am7xxx_open_device(am7xxx_context *ctx, am7xxx_device **dev,
637                        unsigned int device_index)
638 {
639         int ret;
640
641         if (ctx == NULL) {
642                 fatal("context must not be NULL!\n");
643                 return -EINVAL;
644         }
645
646         ret = scan_devices(ctx, SCAN_OP_OPEN_DEVICE, device_index, dev);
647         if (ret < 0) {
648                 errno = ENODEV;
649         } else if (ret > 0) {
650                 warning(ctx, "device %d already open\n", device_index);
651                 errno = EBUSY;
652                 ret = -EBUSY;
653         }
654
655         return ret;
656 }
657
658 AM7XXX_PUBLIC int am7xxx_close_device(am7xxx_device *dev)
659 {
660         if (dev == NULL) {
661                 fatal("dev must not be NULL!\n");
662                 return -EINVAL;
663         }
664         if (dev->usb_device) {
665                 libusb_release_interface(dev->usb_device, 0);
666                 libusb_close(dev->usb_device);
667                 dev->usb_device = NULL;
668         }
669         return 0;
670 }
671
672 AM7XXX_PUBLIC int am7xxx_get_device_info(am7xxx_device *dev,
673                            am7xxx_device_info *device_info)
674 {
675         int ret;
676         struct am7xxx_header h = {
677                 .packet_type     = AM7XXX_PACKET_TYPE_DEVINFO,
678                 .unknown0        = 0x00,
679                 .header_data_len = 0x00,
680                 .unknown2        = 0x3e,
681                 .unknown3        = 0x10,
682                 .header_data = {
683                         .devinfo = {
684                                 .native_width  = 0,
685                                 .native_height = 0,
686                                 .unknown0      = 0,
687                                 .unknown1      = 0,
688                         },
689                 },
690         };
691
692         ret = send_header(dev, &h);
693         if (ret < 0)
694                 return ret;
695
696         ret = read_header(dev, &h);
697         if (ret < 0)
698                 return ret;
699
700         device_info->native_width = h.header_data.devinfo.native_width;
701         device_info->native_height = h.header_data.devinfo.native_height;
702 #if 0
703         /* No reason to expose these in the public API until we know what they mean */
704         device_info->unknown0 = h.header_data.devinfo.unknown0;
705         device_info->unknown1 = h.header_data.devinfo.unknown1;
706 #endif
707
708         return 0;
709 }
710
711 AM7XXX_PUBLIC int am7xxx_calc_scaled_image_dimensions(am7xxx_device *dev,
712                                         unsigned int upscale,
713                                         unsigned int original_width,
714                                         unsigned int original_height,
715                                         unsigned int *scaled_width,
716                                         unsigned int *scaled_height)
717 {
718
719         am7xxx_device_info device_info;
720         float width_ratio;
721         float height_ratio;
722         int ret;
723
724         ret = am7xxx_get_device_info(dev, &device_info);
725         if (ret < 0) {
726                 error(dev->ctx, "cannot get device info\n");
727                 return ret;
728         }
729
730         /*
731          * Check if we need to rescale; if the input image fits the native
732          * dimensions there is no need to, unless we want to upscale.
733          */
734         if (!upscale &&
735             original_width <= device_info.native_width &&
736             original_height <= device_info.native_height ) {
737                 debug(dev->ctx, "CASE 0, no rescaling, the original image fits already\n");
738                 *scaled_width = original_width;
739                 *scaled_height = original_height;
740                 return 0;
741         }
742
743         /* Input dimensions relative to the device native dimensions */
744         width_ratio =  (float)original_width / device_info.native_width;
745         height_ratio = (float)original_height / device_info.native_height;
746
747         if (width_ratio > height_ratio) {
748                 /*
749                  * The input is proportionally "wider" than the device viewport
750                  * so its height needs to be adjusted
751                  */
752                 debug(dev->ctx, "CASE 1, original image wider, adjust the scaled height\n");
753                 *scaled_width = device_info.native_width;
754                 *scaled_height = (unsigned int)lroundf(original_height / width_ratio);
755         } else if (width_ratio < height_ratio) {
756                 /*
757                  * The input is proportionally "taller" than the device viewport
758                  * so its width needs to be adjusted
759                  */
760                 debug(dev->ctx, "CASE 2 original image taller, adjust the scaled width\n");
761                 *scaled_width = (unsigned int)lroundf(original_width / height_ratio);
762                 *scaled_height = device_info.native_height;
763         } else {
764                 debug(dev->ctx, "CASE 3, just rescale, same aspect ratio already\n");
765                 *scaled_width = device_info.native_width;
766                 *scaled_height = device_info.native_height;
767         }
768         debug(dev->ctx, "scaled dimensions: %dx%d\n", *scaled_width, *scaled_height);
769
770         return 0;
771 }
772
773 AM7XXX_PUBLIC int am7xxx_send_image(am7xxx_device *dev,
774                       am7xxx_image_format format,
775                       unsigned int width,
776                       unsigned int height,
777                       uint8_t *image,
778                       unsigned int image_size)
779 {
780         int ret;
781         struct am7xxx_header h = {
782                 .packet_type     = AM7XXX_PACKET_TYPE_IMAGE,
783                 .unknown0        = 0x00,
784                 .header_data_len = sizeof(struct am7xxx_image_header),
785                 .unknown2        = 0x3e,
786                 .unknown3        = 0x10,
787                 .header_data = {
788                         .image = {
789                                 .format     = format,
790                                 .width      = width,
791                                 .height     = height,
792                                 .image_size = image_size,
793                         },
794                 },
795         };
796
797         ret = send_header(dev, &h);
798         if (ret < 0)
799                 return ret;
800
801         if (image == NULL || image_size == 0) {
802                 warning(dev->ctx, "Not sending any data, check the 'image' or 'image_size' parameters\n");
803                 return 0;
804         }
805
806         return send_data(dev, image, image_size);
807 }
808
809 AM7XXX_PUBLIC int am7xxx_set_power_mode(am7xxx_device *dev, am7xxx_power_mode mode)
810 {
811         int ret;
812         struct am7xxx_header h = {
813                 .packet_type     = AM7XXX_PACKET_TYPE_POWER,
814                 .unknown0        = 0x00,
815                 .header_data_len = sizeof(struct am7xxx_power_header),
816                 .unknown2        = 0x3e,
817                 .unknown3        = 0x10,
818         };
819
820         switch(mode) {
821         case AM7XXX_POWER_OFF:
822                 h.header_data.power.bit2 = 0;
823                 h.header_data.power.bit1 = 0;
824                 h.header_data.power.bit0 = 0;
825                 break;
826
827         case AM7XXX_POWER_LOW:
828                 h.header_data.power.bit2 = 0;
829                 h.header_data.power.bit1 = 0;
830                 h.header_data.power.bit0 = 1;
831
832         case AM7XXX_POWER_MIDDLE:
833                 h.header_data.power.bit2 = 0;
834                 h.header_data.power.bit1 = 1;
835                 h.header_data.power.bit0 = 0;
836                 break;
837
838         case AM7XXX_POWER_HIGH:
839                 h.header_data.power.bit2 = 0;
840                 h.header_data.power.bit1 = 1;
841                 h.header_data.power.bit0 = 1;
842                 break;
843
844         case AM7XXX_POWER_TURBO:
845                 h.header_data.power.bit2 = 1;
846                 h.header_data.power.bit1 = 0;
847                 h.header_data.power.bit0 = 0;
848                 break;
849
850         default:
851                 error(dev->ctx, "Power mode not supported!\n");
852                 return -EINVAL;
853         };
854
855         ret = send_header(dev, &h);
856         if (ret < 0)
857                 return ret;
858
859         return 0;
860 }