am7xxx: pass the context to add_new_device() and find_device()
[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 <errno.h>
23 #include <libusb.h>
24
25 #include "am7xxx.h"
26 #include "serialize.h"
27
28 #define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))
29
30 struct am7xxx_usb_device_descriptor {
31         const char *name;
32         uint16_t vendor_id;
33         uint16_t product_id;
34 };
35
36 static struct am7xxx_usb_device_descriptor supported_devices[] = {
37         {
38                 .name       = "Acer C110",
39                 .vendor_id  = 0x1de1,
40                 .product_id = 0xc101,
41         },
42         {
43                 .name       = "Philips/Sagemcom PicoPix 1020",
44                 .vendor_id  = 0x21e7,
45                 .product_id = 0x000e,
46         },
47 };
48
49 /* The header size on the wire is known to be always 24 bytes, regardless of
50  * the memory configuration enforced by different architechtures or compilers
51  * for struct am7xxx_header
52  */
53 #define AM7XXX_HEADER_WIRE_SIZE 24
54
55 struct _am7xxx_device {
56         libusb_device_handle *usb_device;
57         uint8_t buffer[AM7XXX_HEADER_WIRE_SIZE];
58         am7xxx_device *next;
59 };
60
61 struct _am7xxx_context {
62         libusb_context *usb_context;
63         am7xxx_device *devices_list;
64 };
65
66 typedef enum {
67         AM7XXX_PACKET_TYPE_DEVINFO = 0x01,
68         AM7XXX_PACKET_TYPE_IMAGE   = 0x02,
69         AM7XXX_PACKET_TYPE_POWER   = 0x04,
70         AM7XXX_PACKET_TYPE_UNKNOWN = 0x05,
71 } am7xxx_packet_type;
72
73 struct am7xxx_generic_header {
74         uint32_t field0;
75         uint32_t field1;
76         uint32_t field2;
77         uint32_t field3;
78 };
79
80 struct am7xxx_devinfo_header {
81         uint32_t native_width;
82         uint32_t native_height;
83         uint32_t unknown0;
84         uint32_t unknown1;
85 };
86
87 struct am7xxx_image_header {
88         uint32_t format;
89         uint32_t width;
90         uint32_t height;
91         uint32_t image_size;
92 };
93
94 struct am7xxx_power_header {
95         uint32_t bit2;
96         uint32_t bit1;
97         uint32_t bit0;
98 };
99
100 /*
101  * Examples of packet headers:
102  *
103  * Image header:
104  * 02 00 00 00 00 10 3e 10 01 00 00 00 20 03 00 00 e0 01 00 00 53 E8 00 00
105  *
106  * Power header:
107  * 04 00 00 00 00 0c ff ff 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
108  */
109
110 struct am7xxx_header {
111         uint32_t packet_type;
112         uint8_t unknown0;
113         uint8_t header_data_len;
114         uint8_t unknown2;
115         uint8_t unknown3;
116         union {
117                 struct am7xxx_generic_header data;
118                 struct am7xxx_devinfo_header devinfo;
119                 struct am7xxx_image_header image;
120                 struct am7xxx_power_header power;
121         } header_data;
122 };
123
124
125 static void dump_devinfo_header(struct am7xxx_devinfo_header *d)
126 {
127         if (d == NULL)
128                 return;
129
130         printf("Info header:\n");
131         printf("\tnative_width:  0x%08x (%u)\n", d->native_width, d->native_width);
132         printf("\tnative_height: 0x%08x (%u)\n", d->native_height, d->native_height);
133         printf("\tunknown0:      0x%08x (%u)\n", d->unknown0, d->unknown0);
134         printf("\tunknown1:      0x%08x (%u)\n", d->unknown1, d->unknown1);
135 }
136
137 static void dump_image_header(struct am7xxx_image_header *i)
138 {
139         if (i == NULL)
140                 return;
141
142         printf("Image header:\n");
143         printf("\tformat:     0x%08x (%u)\n", i->format, i->format);
144         printf("\twidth:      0x%08x (%u)\n", i->width, i->width);
145         printf("\theight:     0x%08x (%u)\n", i->height, i->height);
146         printf("\timage size: 0x%08x (%u)\n", i->image_size, i->image_size);
147 }
148
149 static void dump_power_header(struct am7xxx_power_header *p)
150 {
151         if (p == NULL)
152                 return;
153
154         printf("Power header:\n");
155         printf("\tbit2: 0x%08x (%u)\n", p->bit2, p->bit2);
156         printf("\tbit1: 0x%08x (%u)\n", p->bit1, p->bit1);
157         printf("\tbit0: 0x%08x (%u)\n", p->bit0, p->bit0);
158 }
159
160 static void dump_header(struct am7xxx_header *h)
161 {
162         if (h == NULL)
163                 return;
164
165         printf("packet_type:     0x%08x (%u)\n", h->packet_type, h->packet_type);
166         printf("unknown0:        0x%02hhx (%hhu)\n", h->unknown0, h->unknown0);
167         printf("header_data_len: 0x%02hhx (%hhu)\n", h->header_data_len, h->header_data_len);
168         printf("unknown2:        0x%02hhx (%hhu)\n", h->unknown2, h->unknown2);
169         printf("unknown3:        0x%02hhx (%hhu)\n", h->unknown3, h->unknown3);
170
171         switch(h->packet_type) {
172         case AM7XXX_PACKET_TYPE_DEVINFO:
173                 dump_devinfo_header(&(h->header_data.devinfo));
174                 break;
175
176         case AM7XXX_PACKET_TYPE_IMAGE:
177                 dump_image_header(&(h->header_data.image));
178                 break;
179
180         case AM7XXX_PACKET_TYPE_POWER:
181                 dump_power_header(&(h->header_data.power));
182                 break;
183
184         default:
185                 printf("Packet type not supported!\n");
186                 break;
187         }
188
189         fflush(stdout);
190 }
191
192 static inline unsigned int in_80chars(unsigned int i)
193 {
194         /* The 3 below is the length of "xx " where xx is the hex string
195          * representation of a byte */
196         return ((i+1) % (80/3));
197 }
198
199 static void dump_buffer(uint8_t *buffer, unsigned int len)
200 {
201         unsigned int i;
202
203         if (buffer == NULL || len == 0)
204                 return;
205
206         for (i = 0; i < len; i++) {
207                 printf("%02hhX%c", buffer[i], (in_80chars(i) && (i < len - 1)) ? ' ' : '\n');
208         }
209         fflush(stdout);
210 }
211
212 static int read_data(am7xxx_device *dev, uint8_t *buffer, unsigned int len)
213 {
214         int ret;
215         int transferred = 0;
216
217         ret = libusb_bulk_transfer(dev->usb_device, 0x81, buffer, len, &transferred, 0);
218         if (ret != 0 || (unsigned int)transferred != len) {
219                 fprintf(stderr, "Error: ret: %d\ttransferred: %d (expected %u)\n",
220                         ret, transferred, len);
221                 return ret;
222         }
223
224 #if DEBUG
225         printf("\n<-- received\n");
226         dump_buffer(buffer, len);
227         printf("\n");
228 #endif
229
230         return 0;
231 }
232
233 static int send_data(am7xxx_device *dev, uint8_t *buffer, unsigned int len)
234 {
235         int ret;
236         int transferred = 0;
237
238 #if DEBUG
239         printf("\nsending -->\n");
240         dump_buffer(buffer, len);
241         printf("\n");
242 #endif
243
244         ret = libusb_bulk_transfer(dev->usb_device, 1, buffer, len, &transferred, 0);
245         if (ret != 0 || (unsigned int)transferred != len) {
246                 fprintf(stderr, "Error: ret: %d\ttransferred: %d (expected %u)\n",
247                         ret, transferred, len);
248                 return ret;
249         }
250
251         return 0;
252 }
253
254 static void serialize_header(struct am7xxx_header *h, uint8_t *buffer)
255 {
256         uint8_t **buffer_iterator = &buffer;
257
258         put_le32(h->packet_type, buffer_iterator);
259         put_8(h->unknown0, buffer_iterator);
260         put_8(h->header_data_len, buffer_iterator);
261         put_8(h->unknown2, buffer_iterator);
262         put_8(h->unknown3, buffer_iterator);
263         put_le32(h->header_data.data.field0, buffer_iterator);
264         put_le32(h->header_data.data.field1, buffer_iterator);
265         put_le32(h->header_data.data.field2, buffer_iterator);
266         put_le32(h->header_data.data.field3, buffer_iterator);
267 }
268
269 static void unserialize_header(uint8_t *buffer, struct am7xxx_header *h)
270 {
271         uint8_t **buffer_iterator = &buffer;
272
273         h->packet_type = get_le32(buffer_iterator);
274         h->unknown0 = get_8(buffer_iterator);
275         h->header_data_len = get_8(buffer_iterator);
276         h->unknown2 = get_8(buffer_iterator);
277         h->unknown3 = get_8(buffer_iterator);
278         h->header_data.data.field0 = get_le32(buffer_iterator);
279         h->header_data.data.field1 = get_le32(buffer_iterator);
280         h->header_data.data.field2 = get_le32(buffer_iterator);
281         h->header_data.data.field3 = get_le32(buffer_iterator);
282 }
283
284 static int read_header(am7xxx_device *dev, struct am7xxx_header *h)
285 {
286         int ret;
287
288         ret = read_data(dev, dev->buffer, AM7XXX_HEADER_WIRE_SIZE);
289         if (ret < 0)
290                 goto out;
291
292         unserialize_header(dev->buffer, h);
293
294 #if DEBUG
295         printf("\n");
296         dump_header(h);
297         printf("\n");
298 #endif
299
300         ret = 0;
301
302 out:
303         return ret;
304 }
305
306 static int send_header(am7xxx_device *dev, struct am7xxx_header *h)
307 {
308         int ret;
309
310 #if DEBUG
311         printf("\n");
312         dump_header(h);
313         printf("\n");
314 #endif
315
316         serialize_header(h, dev->buffer);
317         ret = send_data(dev, dev->buffer, AM7XXX_HEADER_WIRE_SIZE);
318         if (ret < 0)
319                 fprintf(stderr, "send_header: failed to send data.\n");
320
321         return ret;
322 }
323
324 static am7xxx_device *add_new_device(am7xxx_context *ctx)
325 {
326         am7xxx_device **devices_list;
327         am7xxx_device *new_device;
328
329         if (ctx == NULL) {
330                 fprintf(stderr, "%s: context must not be NULL!\n", __func__);
331                 return NULL;
332         }
333
334         devices_list = &(ctx->devices_list);
335
336         new_device = malloc(sizeof(*new_device));
337         if (new_device == NULL) {
338                 perror("malloc");
339                 return NULL;
340         }
341         memset(new_device, 0, sizeof(*new_device));
342
343         if (*devices_list == NULL) {
344                 *devices_list = new_device;
345         } else {
346                 am7xxx_device *prev = *devices_list;
347                 while (prev->next)
348                         prev = prev->next;
349                 prev->next = new_device;
350         }
351         return new_device;
352 }
353
354 static am7xxx_device *find_device(am7xxx_context *ctx,
355                                   unsigned int device_index)
356 {
357         unsigned int i = 0;
358         am7xxx_device *current;
359
360         if (ctx == NULL) {
361                 fprintf(stderr, "%s: context must not be NULL!\n", __func__);
362                 return NULL;
363         }
364
365         current = ctx->devices_list;
366         while (current && i++ < device_index)
367                 current = current->next;
368
369         return current;
370 }
371
372 typedef enum {
373         SCAN_OP_BUILD_DEVLIST,
374         SCAN_OP_OPEN_DEVICE,
375 } scan_op;
376
377 /**
378  * This is where the central logic of multi-device support is.
379  *
380  * When 'op' == SCAN_OP_BUILD_DEVLIST the parameters 'open_device_index' and
381  * 'dev' are ignored; the function returns 0 on success and a negative value
382  * on error.
383  *
384  * When 'op' == SCAN_OP_OPEN_DEVICE the function opens the supported USB
385  * device with index 'open_device_index' and returns the correspondent
386  * am7xxx_device in the 'dev' parameter; the function returns 0 on success,
387  * 1 if the device was already open and a negative value on error.
388  * 
389  * NOTES:
390  * if scan_devices() fails when called with 'op' == SCAN_OP_BUILD_DEVLIST,
391  * the caller might want to call am7xxx_shutdown() in order to remove
392  * devices possibly added before the failure.
393  */
394 static int scan_devices(am7xxx_context *ctx, scan_op op,
395                         unsigned int open_device_index, am7xxx_device **dev)
396 {
397         int num_devices;
398         libusb_device** list;
399         unsigned int current_index;
400         int i;
401         int ret;
402
403         if (ctx == NULL) {
404                 fprintf(stderr, "%s: context must not be NULL!\n", __func__);
405                 return -EINVAL;
406         }
407         if (op == SCAN_OP_BUILD_DEVLIST && ctx->devices_list != NULL) {
408                 fprintf(stderr, "%s: device scan done already? Abort!\n", __func__);
409                 return -EINVAL;
410         }
411
412         num_devices = libusb_get_device_list(ctx->usb_context, &list);
413         if (num_devices < 0) {
414                 ret = -ENODEV;
415                 goto out;
416         }
417
418         current_index = 0;
419         for (i = 0; i < num_devices; i++) {
420                 struct libusb_device_descriptor desc;
421                 unsigned int j;
422
423                 ret = libusb_get_device_descriptor(list[i], &desc);
424                 if (ret < 0)
425                         continue;
426
427                 for (j = 0; j < ARRAY_SIZE(supported_devices); j++) {
428                         if (desc.idVendor == supported_devices[j].vendor_id
429                             && desc.idProduct == supported_devices[j].product_id) {
430
431                                 if (op == SCAN_OP_BUILD_DEVLIST) {
432                                         am7xxx_device *new_device;
433                                         /* debug */
434                                         printf("am7xxx device found, index: %d, name: %s\n",
435                                                current_index,
436                                                supported_devices[j].name);
437                                         new_device = add_new_device(ctx);
438                                         if (new_device == NULL) {
439                                                 /* XXX, the caller may want
440                                                  * to call am7xxx_shutdown() if
441                                                  * we fail here, as we may have
442                                                  * added some devices already
443                                                  */
444                                                 ret = -ENODEV;
445                                                 goto out;
446                                         }
447                                 } else if (op == SCAN_OP_OPEN_DEVICE &&
448                                            current_index == open_device_index) {
449
450                                         *dev = find_device(ctx, open_device_index);
451                                         if (*dev == NULL) {
452                                                 ret = -ENODEV;
453                                                 goto out;
454                                         }
455
456                                         /* the usb device has already been opened */
457                                         if ((*dev)->usb_device) {
458                                                 ret = 1;
459                                                 goto out;
460                                         }
461
462                                         ret = libusb_open(list[i], &((*dev)->usb_device));
463                                         if (ret < 0)
464                                                 goto out;
465
466                                         libusb_set_configuration((*dev)->usb_device, 1);
467                                         libusb_claim_interface((*dev)->usb_device, 0);
468                                         goto out;
469                                 }
470                                 current_index++;
471                         }
472                 }
473         }
474
475         /* if we made it up to here we didn't find any device to open */
476         if (op == SCAN_OP_OPEN_DEVICE) {
477                 ret = -ENODEV;
478                 goto out;
479         }
480
481         /* everything went fine when building the device list */
482         ret = 0;
483 out:
484         libusb_free_device_list(list, 1);
485         return ret;
486 }
487
488 int am7xxx_init(am7xxx_context **ctx)
489 {
490         int ret = 0;
491
492         *ctx = malloc(sizeof(**ctx));
493         if (*ctx == NULL) {
494                 perror("malloc");
495                 ret = -ENOMEM;
496                 goto out;
497         }
498         memset(*ctx, 0, sizeof(**ctx));
499
500         ret = libusb_init(&((*ctx)->usb_context));
501         if (ret < 0)
502                 goto out_free_context;
503
504         libusb_set_debug((*ctx)->usb_context, 3);
505
506         ret = scan_devices(*ctx, SCAN_OP_BUILD_DEVLIST , 0, NULL);
507         if (ret < 0) {
508                 fprintf(stderr, "%s: scan_devices failed\n", __func__);
509                 am7xxx_shutdown(*ctx);
510                 goto out;
511         }
512
513         return 0;
514
515 out_free_context:
516         free(*ctx);
517         *ctx = NULL;
518 out:
519         return ret;
520 }
521
522 void am7xxx_shutdown(am7xxx_context *ctx)
523 {
524         am7xxx_device *current;
525
526         if (ctx == NULL) {
527                 fprintf(stderr, "%s: context must not be NULL!\n", __func__);
528                 return;
529         }
530
531         current = ctx->devices_list;
532         while (current) {
533                 am7xxx_device *next = current->next;
534                 am7xxx_close_device(current);
535                 free(current);
536                 current = next;
537         }
538
539         libusb_exit(ctx->usb_context);
540         free(ctx);
541         ctx = NULL;
542 }
543
544 int am7xxx_open_device(am7xxx_context *ctx, am7xxx_device **dev,
545                        unsigned int device_index)
546 {
547         int ret;
548
549         if (ctx == NULL) {
550                 fprintf(stderr, "%s: context must not be NULL!\n", __func__);
551                 return -EINVAL;
552         }
553
554         ret = scan_devices(ctx, SCAN_OP_OPEN_DEVICE, device_index, dev);
555         if (ret < 0) {
556                 errno = ENODEV;
557         } else if (ret > 0) {
558                 /* warning */
559                 fprintf(stderr, "%s: device %d already open\n", __func__, device_index);
560                 errno = EBUSY;
561                 ret = -EBUSY;
562         }
563
564         return ret;
565 }
566
567 int am7xxx_close_device(am7xxx_device *dev)
568 {
569         if (dev == NULL) {
570                 fprintf(stderr, "%s: dev must not be NULL!\n", __func__);
571                 return -EINVAL;
572         }
573         if (dev->usb_device) {
574                 libusb_release_interface(dev->usb_device, 0);
575                 libusb_close(dev->usb_device);
576                 dev->usb_device = NULL;
577         }
578         return 0;
579 }
580
581 int am7xxx_get_device_info(am7xxx_device *dev,
582                            unsigned int *native_width,
583                            unsigned int *native_height,
584                            unsigned int *unknown0,
585                            unsigned int *unknown1)
586 {
587         int ret;
588         struct am7xxx_header h = {
589                 .packet_type     = AM7XXX_PACKET_TYPE_DEVINFO,
590                 .unknown0        = 0x00,
591                 .header_data_len = 0x00,
592                 .unknown2        = 0x3e,
593                 .unknown3        = 0x10,
594                 .header_data = {
595                         .devinfo = {
596                                 .native_width  = 0,
597                                 .native_height = 0,
598                                 .unknown0      = 0,
599                                 .unknown1      = 0,
600                         },
601                 },
602         };
603
604         ret = send_header(dev, &h);
605         if (ret < 0)
606                 return ret;
607
608         ret = read_header(dev, &h);
609         if (ret < 0)
610                 return ret;
611
612         *native_width = h.header_data.devinfo.native_width;
613         *native_height = h.header_data.devinfo.native_height;
614         *unknown0 = h.header_data.devinfo.unknown0;
615         *unknown1 = h.header_data.devinfo.unknown1;
616
617         return 0;
618 }
619
620 int am7xxx_send_image(am7xxx_device *dev,
621                       am7xxx_image_format format,
622                       unsigned int width,
623                       unsigned int height,
624                       uint8_t *image,
625                       unsigned int size)
626 {
627         int ret;
628         struct am7xxx_header h = {
629                 .packet_type     = AM7XXX_PACKET_TYPE_IMAGE,
630                 .unknown0        = 0x00,
631                 .header_data_len = sizeof(struct am7xxx_image_header),
632                 .unknown2        = 0x3e,
633                 .unknown3        = 0x10,
634                 .header_data = {
635                         .image = {
636                                 .format     = format,
637                                 .width      = width,
638                                 .height     = height,
639                                 .image_size = size,
640                         },
641                 },
642         };
643
644         ret = send_header(dev, &h);
645         if (ret < 0)
646                 return ret;
647
648         if (image == NULL || size == 0)
649                 return 0;
650
651         return send_data(dev, image, size);
652 }
653
654 int am7xxx_set_power_mode(am7xxx_device *dev, am7xxx_power_mode mode)
655 {
656         int ret;
657         struct am7xxx_header h = {
658                 .packet_type     = AM7XXX_PACKET_TYPE_POWER,
659                 .unknown0        = 0x00,
660                 .header_data_len = sizeof(struct am7xxx_power_header),
661                 .unknown2        = 0x3e,
662                 .unknown3        = 0x10,
663         };
664
665         switch(mode) {
666         case AM7XXX_POWER_OFF:
667                 h.header_data.power.bit2 = 0;
668                 h.header_data.power.bit1 = 0;
669                 h.header_data.power.bit0 = 0;
670                 break;
671
672         case AM7XXX_POWER_LOW:
673                 h.header_data.power.bit2 = 0;
674                 h.header_data.power.bit1 = 0;
675                 h.header_data.power.bit0 = 1;
676
677         case AM7XXX_POWER_MIDDLE:
678                 h.header_data.power.bit2 = 0;
679                 h.header_data.power.bit1 = 1;
680                 h.header_data.power.bit0 = 0;
681                 break;
682
683         case AM7XXX_POWER_HIGH:
684                 h.header_data.power.bit2 = 0;
685                 h.header_data.power.bit1 = 1;
686                 h.header_data.power.bit0 = 1;
687                 break;
688
689         case AM7XXX_POWER_TURBO:
690                 h.header_data.power.bit2 = 1;
691                 h.header_data.power.bit1 = 0;
692                 h.header_data.power.bit0 = 0;
693                 break;
694
695         default:
696                 fprintf(stderr, "Unsupported power mode.\n");
697                 return -EINVAL;
698         };
699
700         ret = send_header(dev, &h);
701         if (ret < 0)
702                 return ret;
703
704         return 0;
705 }