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