am7xxx: fail if USB configuration or interface are not right
[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                                         /* XXX, the device is now open, if any
602                                          * of the calls below fail we need to
603                                          * close it again before bailing out.
604                                          */
605
606                                         ret = libusb_set_configuration((*dev)->usb_device, 2);
607                                         if (ret < 0) {
608                                                 debug(ctx, "libusb_set_configuration failed\n");
609                                                 debug(ctx, "Cannot set configuration 2\n");
610                                                 goto out_libusb_close;
611                                         }
612
613                                         ret = libusb_claim_interface((*dev)->usb_device, 0);
614                                         if (ret < 0) {
615                                                 debug(ctx, "libusb_claim_interface failed\n");
616                                                 debug(ctx, "Cannot claim interface 0\n");
617 out_libusb_close:
618                                                 libusb_close((*dev)->usb_device);
619                                                 (*dev)->usb_device = NULL;
620                                                 goto out;
621                                         }
622
623                                         goto out;
624                                 }
625                                 current_index++;
626                         }
627                 }
628         }
629
630         /* if we made it up to here we didn't find any device to open */
631         if (op == SCAN_OP_OPEN_DEVICE) {
632                 error(ctx, "Cannot find any device to open\n");
633                 ret = -ENODEV;
634                 goto out;
635         }
636
637         /* everything went fine when building the device list */
638         ret = 0;
639 out:
640         libusb_free_device_list(list, 1);
641         return ret;
642 }
643
644 /* Public API */
645
646 AM7XXX_PUBLIC int am7xxx_init(am7xxx_context **ctx)
647 {
648         int ret = 0;
649
650         *ctx = malloc(sizeof(**ctx));
651         if (*ctx == NULL) {
652                 fatal("cannot allocate the context (%s)\n", strerror(errno));
653                 ret = -ENOMEM;
654                 goto out;
655         }
656         memset(*ctx, 0, sizeof(**ctx));
657
658         /* Set the highest log level during initialization */
659         (*ctx)->log_level = AM7XXX_LOG_TRACE;
660
661         ret = libusb_init(&((*ctx)->usb_context));
662         if (ret < 0)
663                 goto out_free_context;
664
665         libusb_set_debug((*ctx)->usb_context, 3);
666
667         ret = scan_devices(*ctx, SCAN_OP_BUILD_DEVLIST , 0, NULL);
668         if (ret < 0) {
669                 error(*ctx, "scan_devices() failed\n");
670                 am7xxx_shutdown(*ctx);
671                 goto out;
672         }
673
674         /* Set a quieter log level as default for normal operation */
675         (*ctx)->log_level = AM7XXX_LOG_ERROR;
676         return 0;
677
678 out_free_context:
679         free(*ctx);
680         *ctx = NULL;
681 out:
682         return ret;
683 }
684
685 AM7XXX_PUBLIC void am7xxx_shutdown(am7xxx_context *ctx)
686 {
687         am7xxx_device *current;
688
689         if (ctx == NULL) {
690                 fatal("context must not be NULL!\n");
691                 return;
692         }
693
694         current = ctx->devices_list;
695         while (current) {
696                 am7xxx_device *next = current->next;
697                 am7xxx_close_device(current);
698                 free(current->device_info);
699                 free(current);
700                 current = next;
701         }
702
703         libusb_exit(ctx->usb_context);
704         free(ctx);
705         ctx = NULL;
706 }
707
708 AM7XXX_PUBLIC void am7xxx_set_log_level(am7xxx_context *ctx, am7xxx_log_level log_level)
709 {
710         ctx->log_level = log_level;
711 }
712
713 AM7XXX_PUBLIC int am7xxx_open_device(am7xxx_context *ctx, am7xxx_device **dev,
714                        unsigned int device_index)
715 {
716         int ret;
717
718         if (ctx == NULL) {
719                 fatal("context must not be NULL!\n");
720                 return -EINVAL;
721         }
722
723         ret = scan_devices(ctx, SCAN_OP_OPEN_DEVICE, device_index, dev);
724         if (ret < 0) {
725                 errno = ENODEV;
726                 goto out;
727         } else if (ret > 0) {
728                 warning(ctx, "device %d already open\n", device_index);
729                 errno = EBUSY;
730                 ret = -EBUSY;
731                 goto out;
732         }
733
734         /* Philips/Sagemcom PicoPix projectors require that the DEVINFO packet
735          * is the first one to be sent to the device in order for it to
736          * successfully return the correct device information.
737          *
738          * So, if there is not a cached version of it (from a previous open),
739          * we ask for device info at open time,
740          */
741         if ((*dev)->device_info == NULL) {
742                 ret = am7xxx_get_device_info(*dev, NULL);
743                 if (ret < 0)
744                         error(ctx, "cannot get device info\n");
745         }
746
747 out:
748         return ret;
749 }
750
751 AM7XXX_PUBLIC int am7xxx_close_device(am7xxx_device *dev)
752 {
753         if (dev == NULL) {
754                 fatal("dev must not be NULL!\n");
755                 return -EINVAL;
756         }
757         if (dev->usb_device) {
758                 libusb_release_interface(dev->usb_device, 0);
759                 libusb_close(dev->usb_device);
760                 dev->usb_device = NULL;
761         }
762         return 0;
763 }
764
765 AM7XXX_PUBLIC int am7xxx_get_device_info(am7xxx_device *dev,
766                            am7xxx_device_info *device_info)
767 {
768         int ret;
769         struct am7xxx_header h = {
770                 .packet_type     = AM7XXX_PACKET_TYPE_DEVINFO,
771                 .direction       = AM7XXX_DIRECTION_OUT,
772                 .header_data_len = 0x00,
773                 .unknown2        = 0x3e,
774                 .unknown3        = 0x10,
775                 .header_data = {
776                         .devinfo = {
777                                 .native_width  = 0,
778                                 .native_height = 0,
779                                 .unknown0      = 0,
780                                 .unknown1      = 0,
781                         },
782                 },
783         };
784
785         if (dev->device_info) {
786                 memcpy(device_info, dev->device_info, sizeof(*device_info));
787                 return 0;
788         }
789
790         ret = send_header(dev, &h);
791         if (ret < 0)
792                 return ret;
793
794         ret = read_header(dev, &h);
795         if (ret < 0)
796                 return ret;
797
798         if (h.packet_type != AM7XXX_PACKET_TYPE_DEVINFO) {
799                 error(dev->ctx, "expected packet type: %d, got %d instead!\n",
800                       AM7XXX_PACKET_TYPE_DEVINFO, h.packet_type);
801                 errno = ENOTSUP;
802                 return -ENOTSUP;
803         }
804
805         dev->device_info = malloc(sizeof(*dev->device_info));
806         if (dev->device_info == NULL) {
807                 error(dev->ctx, "cannot allocate a device info (%s)\n",
808                        strerror(errno));
809                 return -ENOMEM;
810         }
811         memset(dev->device_info, 0, sizeof(*dev->device_info));
812
813         dev->device_info->native_width = h.header_data.devinfo.native_width;
814         dev->device_info->native_height = h.header_data.devinfo.native_height;
815 #if 0
816         /* No reason to expose these in the public API until we know what they mean */
817         dev->device_info->unknown0 = h.header_data.devinfo.unknown0;
818         dev->device_info->unknown1 = h.header_data.devinfo.unknown1;
819 #endif
820
821         return 0;
822 }
823
824 AM7XXX_PUBLIC int am7xxx_calc_scaled_image_dimensions(am7xxx_device *dev,
825                                         unsigned int upscale,
826                                         unsigned int original_width,
827                                         unsigned int original_height,
828                                         unsigned int *scaled_width,
829                                         unsigned int *scaled_height)
830 {
831
832         am7xxx_device_info device_info;
833         float width_ratio;
834         float height_ratio;
835         int ret;
836
837         ret = am7xxx_get_device_info(dev, &device_info);
838         if (ret < 0) {
839                 error(dev->ctx, "cannot get device info\n");
840                 return ret;
841         }
842
843         /*
844          * Check if we need to rescale; if the input image fits the native
845          * dimensions there is no need to, unless we want to upscale.
846          */
847         if (!upscale &&
848             original_width <= device_info.native_width &&
849             original_height <= device_info.native_height ) {
850                 debug(dev->ctx, "CASE 0, no rescaling, the original image fits already\n");
851                 *scaled_width = original_width;
852                 *scaled_height = original_height;
853                 return 0;
854         }
855
856         /* Input dimensions relative to the device native dimensions */
857         width_ratio =  (float)original_width / device_info.native_width;
858         height_ratio = (float)original_height / device_info.native_height;
859
860         if (width_ratio > height_ratio) {
861                 /*
862                  * The input is proportionally "wider" than the device viewport
863                  * so its height needs to be adjusted
864                  */
865                 debug(dev->ctx, "CASE 1, original image wider, adjust the scaled height\n");
866                 *scaled_width = device_info.native_width;
867                 *scaled_height = (unsigned int)lroundf(original_height / width_ratio);
868         } else if (width_ratio < height_ratio) {
869                 /*
870                  * The input is proportionally "taller" than the device viewport
871                  * so its width needs to be adjusted
872                  */
873                 debug(dev->ctx, "CASE 2 original image taller, adjust the scaled width\n");
874                 *scaled_width = (unsigned int)lroundf(original_width / height_ratio);
875                 *scaled_height = device_info.native_height;
876         } else {
877                 debug(dev->ctx, "CASE 3, just rescale, same aspect ratio already\n");
878                 *scaled_width = device_info.native_width;
879                 *scaled_height = device_info.native_height;
880         }
881         debug(dev->ctx, "scaled dimensions: %dx%d\n", *scaled_width, *scaled_height);
882
883         return 0;
884 }
885
886 AM7XXX_PUBLIC int am7xxx_send_image(am7xxx_device *dev,
887                       am7xxx_image_format format,
888                       unsigned int width,
889                       unsigned int height,
890                       uint8_t *image,
891                       unsigned int image_size)
892 {
893         int ret;
894         struct am7xxx_header h = {
895                 .packet_type     = AM7XXX_PACKET_TYPE_IMAGE,
896                 .direction       = AM7XXX_DIRECTION_OUT,
897                 .header_data_len = sizeof(struct am7xxx_image_header),
898                 .unknown2        = 0x3e,
899                 .unknown3        = 0x10,
900                 .header_data = {
901                         .image = {
902                                 .format     = format,
903                                 .width      = width,
904                                 .height     = height,
905                                 .image_size = image_size,
906                         },
907                 },
908         };
909
910         ret = send_header(dev, &h);
911         if (ret < 0)
912                 return ret;
913
914         if (image == NULL || image_size == 0) {
915                 warning(dev->ctx, "Not sending any data, check the 'image' or 'image_size' parameters\n");
916                 return 0;
917         }
918
919         return send_data(dev, image, image_size);
920 }
921
922 AM7XXX_PUBLIC int am7xxx_set_power_mode(am7xxx_device *dev, am7xxx_power_mode power)
923 {
924         int ret;
925         struct am7xxx_header h = {
926                 .packet_type     = AM7XXX_PACKET_TYPE_POWER,
927                 .direction       = AM7XXX_DIRECTION_OUT,
928                 .header_data_len = sizeof(struct am7xxx_power_header),
929                 .unknown2        = 0x3e,
930                 .unknown3        = 0x10,
931         };
932
933         switch(power) {
934         case AM7XXX_POWER_OFF:
935                 h.header_data.power.bit2 = 0;
936                 h.header_data.power.bit1 = 0;
937                 h.header_data.power.bit0 = 0;
938                 break;
939
940         case AM7XXX_POWER_LOW:
941                 h.header_data.power.bit2 = 0;
942                 h.header_data.power.bit1 = 0;
943                 h.header_data.power.bit0 = 1;
944                 break;
945
946         case AM7XXX_POWER_MIDDLE:
947                 h.header_data.power.bit2 = 0;
948                 h.header_data.power.bit1 = 1;
949                 h.header_data.power.bit0 = 0;
950                 break;
951
952         case AM7XXX_POWER_HIGH:
953                 h.header_data.power.bit2 = 0;
954                 h.header_data.power.bit1 = 1;
955                 h.header_data.power.bit0 = 1;
956                 break;
957
958         case AM7XXX_POWER_TURBO:
959                 h.header_data.power.bit2 = 1;
960                 h.header_data.power.bit1 = 0;
961                 h.header_data.power.bit0 = 0;
962                 break;
963
964         default:
965                 error(dev->ctx, "Unsupported power mode.\n");
966                 return -EINVAL;
967         };
968
969         ret = send_header(dev, &h);
970         if (ret < 0)
971                 return ret;
972
973         return 0;
974 }
975
976 AM7XXX_PUBLIC int am7xxx_set_zoom_mode(am7xxx_device *dev, am7xxx_zoom_mode zoom)
977 {
978         int ret;
979         struct am7xxx_header h = {
980                 .packet_type     = AM7XXX_PACKET_TYPE_ZOOM,
981                 .direction       = AM7XXX_DIRECTION_OUT,
982                 .header_data_len = sizeof(struct am7xxx_zoom_header),
983                 .unknown2        = 0x3e,
984                 .unknown3        = 0x10,
985         };
986
987         switch(zoom) {
988         case AM7XXX_ZOOM_ORIGINAL:
989                 h.header_data.zoom.bit1 = 0;
990                 h.header_data.zoom.bit0 = 0;
991                 break;
992
993         case AM7XXX_ZOOM_H:
994                 h.header_data.zoom.bit1 = 0;
995                 h.header_data.zoom.bit0 = 1;
996                 break;
997
998         case AM7XXX_ZOOM_H_V:
999                 h.header_data.zoom.bit1 = 1;
1000                 h.header_data.zoom.bit0 = 0;
1001                 break;
1002
1003         case AM7XXX_ZOOM_TEST:
1004                 h.header_data.zoom.bit1 = 1;
1005                 h.header_data.zoom.bit0 = 1;
1006                 break;
1007
1008         default:
1009                 error(dev->ctx, "Unsupported zoom mode.\n");
1010                 return -EINVAL;
1011         };
1012
1013         ret = send_header(dev, &h);
1014         if (ret < 0)
1015                 return ret;
1016
1017         return 0;
1018 }