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