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