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