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