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