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