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