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