76237cdf5f053da311066a90c2efb51ec42aaadb
[megadrive.git] / host / main.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4 #include <stdint.h>
5 #include <sys/types.h>
6 #include <sys/stat.h>
7 #include <fcntl.h>
8 #include <sys/ioctl.h>
9 #include <sys/select.h>
10 #include <unistd.h>
11 #include <dirent.h>
12 #include <signal.h>
13 #include <termios.h>
14 #include <errno.h>
15 #include <linux/usbdevice_fs.h>
16 #include <linux/usb/ch9.h>
17 #include <linux/input.h>
18 #include "../pkts.h"
19
20 #define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0]))
21
22 struct teensy_dev {
23   int fd;
24   struct {
25     int ep_in;
26     int ep_out;
27   } ifaces[2];
28 };
29
30 /* return 1 if founf, 0 if not, < 0 on error */
31 static int find_device(struct teensy_dev *dev,
32   uint16_t vendor, uint16_t product)
33 {
34   const char path_root[] = "/dev/bus/usb";
35   union {
36     struct usb_descriptor_header hdr;
37     struct usb_device_descriptor d;
38     struct usb_config_descriptor c;
39     struct usb_interface_descriptor i;
40     struct usb_endpoint_descriptor e;
41     char space[0x100]; /* enough? */
42   } desc;
43   char path_bus[256], path_dev[256];
44   struct dirent *ent, *ent_bus;
45   DIR *dir = NULL, *dir_bus = NULL;
46   int num, fd = -1;
47   int iface = -1;
48   int retval = -1;
49   int ret;
50
51   memset(dev, 0xff, sizeof(*dev));
52
53   dir = opendir(path_root);
54   if (dir == NULL) {
55     perror("opendir");
56     return -1;
57   }
58
59   for (ent = readdir(dir); ent != NULL; ent = readdir(dir)) {
60     /* should be a number like 000 */
61     if (sscanf(ent->d_name, "%03d", &num) != 1)
62       continue;
63
64     snprintf(path_bus, sizeof(path_bus), "%s/%s",
65         path_root, ent->d_name);
66
67     dir_bus = opendir(path_bus);
68     if (dir_bus == NULL)
69       continue;
70
71     ent_bus = readdir(dir_bus);
72     for (; ent_bus != NULL; ent_bus = readdir(dir_bus)) {
73       if (sscanf(ent->d_name, "%03d", &num) != 1)
74         continue;
75
76       snprintf(path_dev, sizeof(path_dev), "%s/%s/%s",
77           path_root, ent->d_name, ent_bus->d_name);
78
79       fd = open(path_dev, O_RDWR);
80       if (fd == -1)
81         continue;
82
83       ret = read(fd, &desc.d, sizeof(desc.d));
84       if (ret != sizeof(desc.d)) {
85         fprintf(stderr, "desc read: %d/%zd: ", ret, sizeof(desc.d));
86         perror("");
87         goto next;
88       }
89
90       if (desc.d.bDescriptorType != USB_DT_DEVICE) {
91         fprintf(stderr, "%s: bad DT: 0x%02x\n",
92             path_dev, desc.d.bDescriptorType);
93         goto next;
94       }
95
96       if (desc.d.idVendor == vendor && desc.d.idProduct == product)
97         goto found;
98
99 next:
100       close(fd);
101       fd = -1;
102     }
103
104     closedir(dir_bus);
105     dir_bus = NULL;
106   }
107
108   /* not found */
109   retval = 0;
110   goto out;
111
112 found:
113   if (desc.d.bNumConfigurations != 1) {
114     fprintf(stderr, "unexpected bNumConfigurations: %u\n",
115         desc.d.bNumConfigurations);
116     goto out;
117   }
118
119   /* walk through all descriptors */
120   while (1)
121   {
122     ret = read(fd, &desc.hdr, sizeof(desc.hdr));
123     if (ret == 0)
124       break;
125     if (ret != sizeof(desc.hdr)) {
126       fprintf(stderr, "desc.hdr read: %d/%zd: ", ret, sizeof(desc.hdr));
127       perror("");
128       break;
129     }
130
131     ret = (int)lseek(fd, -sizeof(desc.hdr), SEEK_CUR);
132     if (ret == -1) {
133       perror("lseek");
134       break;
135     }
136
137     ret = read(fd, &desc, desc.hdr.bLength);
138     if (ret != desc.hdr.bLength) {
139       fprintf(stderr, "desc read: %d/%u: ", ret, desc.hdr.bLength);
140       perror("");
141       break;
142     }
143
144     switch (desc.hdr.bDescriptorType) {
145       case USB_DT_CONFIG:
146         if (desc.c.bNumInterfaces != 2) {
147           fprintf(stderr, "unexpected bNumInterfaces: %u\n",
148               desc.c.bNumInterfaces);
149           goto out;
150         }
151         break;
152
153       case USB_DT_INTERFACE:
154         if (desc.i.bInterfaceClass != USB_CLASS_HID
155             || desc.i.bInterfaceSubClass != 0
156             || desc.i.bInterfaceProtocol != 0) {
157           fprintf(stderr, "unexpected interface %x:%x:%x\n",
158             desc.i.bInterfaceClass, desc.i.bInterfaceSubClass,
159             desc.i.bInterfaceProtocol);
160           goto out;
161         }
162         if (desc.i.bNumEndpoints != 2) {
163           fprintf(stderr, "unexpected bNumEndpoints: %u\n",
164             desc.i.bNumEndpoints);
165           goto out;
166         }
167         iface++;
168         break;
169
170       case USB_DT_ENDPOINT:
171         if (iface < 0 || iface >= ARRAY_SIZE(dev->ifaces)) {
172           fprintf(stderr, "bad iface: %d\n", iface);
173           goto out;
174         }
175         if (desc.e.wMaxPacketSize != 64 && desc.e.wMaxPacketSize != 32) {
176           fprintf(stderr, "iface %d, EP %02x: "
177             "unexpected wMaxPacketSize: %u\n",
178             iface, desc.e.bEndpointAddress, desc.e.wMaxPacketSize);
179           goto out;
180         }
181         if (desc.e.bEndpointAddress & 0x80)
182           dev->ifaces[iface].ep_in = desc.e.bEndpointAddress; // & 0x7F;
183         else
184           dev->ifaces[iface].ep_out = desc.e.bEndpointAddress;
185         break;
186
187       case 0x21:
188         /* ignore */
189         break;
190
191       default:
192         fprintf(stderr, "skipping desc 0x%02x\n",
193           desc.hdr.bDescriptorType);
194         break;
195     }
196   }
197
198   /* claim interfaces */
199   for (iface = 0; iface < ARRAY_SIZE(dev->ifaces); iface++) {
200     struct usbdevfs_ioctl usbio;
201
202     if (dev->ifaces[iface].ep_in == -1) {
203       fprintf(stderr, "missing ep_in, iface: %d\n", iface);
204       goto out;
205     }
206     if (dev->ifaces[iface].ep_out == -1) {
207       fprintf(stderr, "missing ep_out, iface: %d\n", iface);
208       goto out;
209     }
210
211     /* disconnect default driver */
212     memset(&usbio, 0, sizeof(usbio));
213     usbio.ifno = iface;
214     usbio.ioctl_code = USBDEVFS_DISCONNECT;
215     ret = ioctl(fd, USBDEVFS_IOCTL, &usbio);
216     if (ret != 0 && errno != ENODATA)
217       perror("USBDEVFS_DISCONNECT");
218
219     ret = ioctl(fd, USBDEVFS_CLAIMINTERFACE, &iface);
220     if (ret != 0)
221       perror("USBDEVFS_CLAIMINTERFACE");
222   }
223
224   dev->fd = fd;
225   fd = -1;
226   retval = 1;
227
228 out:
229   if (fd != -1)
230     close(fd);
231   if (dir_bus != NULL)
232     closedir(dir_bus);
233   if (dir != NULL)
234     closedir(dir);
235
236   return retval;
237 }
238
239 static int enable_echo(int enable)
240 {
241   const char *portname = "/dev/tty";
242   struct termios tty;
243   int retval = -1;
244   int ret;
245   int fd;
246
247   memset(&tty, 0, sizeof(tty));
248
249   fd = open(portname, O_RDWR | O_NOCTTY | O_SYNC);
250   if (fd < 0) {
251     fprintf(stderr, "open %s: ", portname);
252     perror("");
253     return 1;
254   }
255
256   ret = tcgetattr(fd, &tty);
257   if (ret != 0) {
258     perror("tcgetattr");
259     goto out;
260   }
261
262   // printf("lflag: 0%o\n", tty.c_lflag);
263   if (enable)
264     tty.c_lflag |= ECHO;
265   else
266     tty.c_lflag &= ~ECHO;
267
268   ret = tcsetattr(fd, TCSANOW, &tty);
269   if (ret != 0) {
270     perror("tcsetattr");
271     goto out;
272   }
273
274   retval = 0;
275 out:
276   close(fd);
277
278   return retval;
279 }
280
281 static void signal_handler(int sig)
282 {
283   enable_echo(1);
284   signal(sig, SIG_DFL);
285   raise(sig);
286 }
287
288 /* ?0SA 00DU, ?1CB RLDU */
289 #define STATE_BYTES 2
290
291 static uint8_t fixed_input_state[STATE_BYTES] = { 0x33, 0x3f };
292
293 enum mdbtn {
294   MDBTN_UP = 1,
295   MDBTN_DOWN,
296   MDBTN_LEFT,
297   MDBTN_RIGHT,
298   MDBTN_A,
299   MDBTN_B,
300   MDBTN_C,
301   MDBTN_START,
302 };
303
304 static const enum mdbtn evdev_md_map[KEY_CNT] = {
305   [KEY_UP]       = MDBTN_UP,
306   [KEY_DOWN]     = MDBTN_DOWN,
307   [KEY_LEFT]     = MDBTN_LEFT,
308   [KEY_RIGHT]    = MDBTN_RIGHT,
309   [KEY_HOME]     = MDBTN_A,
310   [KEY_PAGEDOWN] = MDBTN_B,
311   [KEY_END]      = MDBTN_C,
312   [KEY_LEFTALT]  = MDBTN_START,
313 };
314
315 int do_evdev_input(int fd)
316 {
317   uint8_t old_state[STATE_BYTES];
318   uint8_t changed_bits[STATE_BYTES] = { 0, };
319   struct input_event ev;
320   enum mdbtn mdbtn;
321   int i, ret;
322
323   ret = read(fd, &ev, sizeof(ev));
324   if (ret != sizeof(ev)) {
325     fprintf(stderr, "evdev read %d/%zd: ", ret, sizeof(ev));
326     perror("");
327     return 0;
328   }
329
330   if (ev.type != EV_KEY)
331     return 0;
332
333   if (ev.value != 0 && ev.value != 1)
334     return 0;
335
336   if ((uint32_t)ev.code >= ARRAY_SIZE(evdev_md_map)) {
337     fprintf(stderr, "evdev read bad key: %u\n", ev.code);
338     return 0;
339   }
340
341   mdbtn = evdev_md_map[ev.code];
342   if (mdbtn == 0)
343     return 0;
344
345   memcpy(old_state, fixed_input_state, STATE_BYTES);
346
347   /* ?0SA 00DU, ?1CB RLDU */
348   switch (mdbtn) {
349   case MDBTN_UP:
350     changed_bits[0] = 0x01;
351     changed_bits[1] = 0x01;
352     break;
353   case MDBTN_DOWN:
354     changed_bits[0] = 0x02;
355     changed_bits[1] = 0x02;
356     break;
357   case MDBTN_LEFT:
358     changed_bits[0] = 0x00;
359     changed_bits[1] = 0x04;
360     break;
361   case MDBTN_RIGHT:
362     changed_bits[0] = 0x00;
363     changed_bits[1] = 0x08;
364     break;
365   case MDBTN_A:
366     changed_bits[0] = 0x10;
367     changed_bits[1] = 0x00;
368     break;
369   case MDBTN_B:
370     changed_bits[0] = 0x00;
371     changed_bits[1] = 0x10;
372     break;
373   case MDBTN_C:
374     changed_bits[0] = 0x00;
375     changed_bits[1] = 0x20;
376     break;
377   case MDBTN_START:
378     changed_bits[0] = 0x20;
379     changed_bits[1] = 0x00;
380     break;
381   }
382
383   if (ev.value) {
384     // key press
385     for (i = 0; i < STATE_BYTES; i++)
386       fixed_input_state[i] &= ~changed_bits[i];
387   }
388   else {
389     // key release
390     for (i = 0; i < STATE_BYTES; i++)
391       fixed_input_state[i] |=  changed_bits[i];
392   }
393
394   return memcmp(old_state, fixed_input_state, STATE_BYTES) ? 1 : 0;
395 }
396
397 struct gmv_tas {
398   char sig[15];
399   char ver;
400   uint32_t rerecord_count;
401   char ctrl1;
402   char ctrl2;
403   uint16_t flags;
404   char name[40];
405   uint8_t data[0][3];
406 };
407
408 static uint8_t *import_gmv(FILE *f, long size, int *frame_count)
409 {
410   struct gmv_tas *gmv;
411   uint8_t *out;
412   int ret;
413   int i;
414
415   if (size < (long)sizeof(*gmv)) {
416     fprintf(stderr, "bad gmv size: %ld\n", size);
417     return NULL;
418   }
419
420   gmv = malloc(size);
421   if (gmv == NULL) {
422     fprintf(stderr, "OOM?\n");
423     return NULL;
424   }
425   ret = fread(gmv, 1, size, f);
426   if (ret != size) {
427     fprintf(stderr, "fread %d/%ld: ", ret, size);
428     perror("");
429     return NULL;
430   }
431
432   *frame_count = (size - sizeof(*gmv)) / sizeof(gmv->data[0]);
433
434   /* check the GMV.. */
435   if (*frame_count <= 0 || size != sizeof(*gmv) + *frame_count * 3) {
436     fprintf(stderr, "broken gmv? frames=%d\n", *frame_count);
437     return NULL;
438   }
439
440   if (strncmp(gmv->sig, "Gens Movie TEST", 15) != 0) {
441     fprintf(stderr, "bad GMV sig\n");
442     return NULL;
443   }
444   if (gmv->ctrl1 != '3') {
445     fprintf(stderr, "unhandled controlled config: '%c'\n", gmv->ctrl1);
446     //return NULL;
447   }
448   if (gmv->ver >= 'A') {
449     if (gmv->flags & 0x40) {
450       fprintf(stderr, "unhandled flag: movie requires a savestate\n");
451       return NULL;
452     }
453     if (gmv->flags & 0x20) {
454       fprintf(stderr, "unhandled flag: 3-player movie\n");
455       return NULL;
456     }
457     if (gmv->flags & ~0x80) {
458       //fprintf(stderr, "unhandled flag(s): %04x\n", gmv->flags);
459       //return 1;
460     }
461   }
462   gmv->name[39] = 0;
463   printf("loaded GMV: %s\n", gmv->name);
464   printf("%d frames, %u rerecords\n",
465          *frame_count, gmv->rerecord_count);
466
467   out = malloc(*frame_count * sizeof(out[0]));
468   if (out == NULL) {
469     fprintf(stderr, "OOM?\n");
470     return NULL;
471   }
472
473   for (i = 0; i < *frame_count; i++) {
474     out[i] = gmv->data[i][0];
475
476     if (gmv->data[i][1] != 0xff || gmv->data[i][2] != 0xff)
477     {
478       fprintf(stderr, "f %d: unhandled byte(s) %02x %02x\n",
479         i, gmv->data[i][1], gmv->data[i][2]);
480     }
481   }
482
483   return out;
484 }
485
486 static int do_bkm_char(char c, char expect, uint8_t *val, int bit)
487 {
488   if (c == expect) {
489     *val &= ~(1 << bit);
490     return 0;
491   }
492   if (c == '.')
493     return 0;
494
495   fprintf(stderr, "unexpected bkm char: '%c' instead of '%c'\n",
496           c, expect);
497   return 1;
498 }
499
500 static uint8_t *import_bkm(FILE *f, int *frame_count)
501 {
502   uint8_t *out = NULL, val;
503   int count = 0;
504   int alloc = 0;
505   int line = 0;
506   char buf[256];
507   const char *r;
508   char *p;
509   int i;
510
511   while ((p = fgets(buf, sizeof(buf), f)) != NULL) {
512     line++;
513     if (p[0] != '|')
514       continue;
515
516     if (strlen(p) < 30)
517       goto unhandled_line;
518     if (p[30] != '\r' && p[30] != '\n')
519       goto unhandled_line;
520     p[30] = 0;
521
522     if (count >= alloc) {
523       alloc = alloc * 2 + 64;
524       out = realloc(out, alloc * sizeof(out[0]));
525       if (out == NULL) {
526         fprintf(stderr, "OOM?\n");
527         return NULL;
528       }
529     }
530
531     val = 0xff;
532
533     if (strncmp(p, "|.|", 3) != 0)
534       goto unhandled_line;
535     p += 3;
536
537     const char ref[] = "UDLRABCS";
538     for (r = ref, i = 0; *r != 0; p++, r++, i++) {
539       if (do_bkm_char(*p, *r, &val, i))
540         goto unhandled_line;
541     }
542
543     if (strcmp(p, "....|............||") != 0)
544       goto unhandled_line;
545
546     out[count++] = val;
547     continue;
548
549 unhandled_line:
550     fprintf(stderr, "unhandled bkm line %d: '%s'\n", line, buf);
551     return NULL;
552   }
553
554   printf("loaded bkm, %d frames\n", count);
555   *frame_count = count;
556   return out;
557 }
558
559 static int submit_urb(int fd, struct usbdevfs_urb *urb, int ep,
560   void *buf, size_t buf_size)
561 {
562   memset(urb, 0, sizeof(*urb));
563   urb->type = USBDEVFS_URB_TYPE_INTERRUPT;
564   urb->endpoint = ep;
565   urb->buffer = buf;
566   urb->buffer_length = buf_size;
567
568   return ioctl(fd, USBDEVFS_SUBMITURB, urb);
569 }
570
571 enum my_urbs {
572   URB_DATA_IN,
573   URB_DATA_OUT,
574   URB_DBG_IN,
575   URB_CNT
576 };
577
578 static void missing_arg(int a)
579 {
580   fprintf(stderr, "missing arg: %d\n", a);
581   exit(1);
582 }
583
584 int main(int argc, char *argv[])
585 {
586   struct teensy_dev dev;
587   struct usbdevfs_urb urb[URB_CNT];
588   struct usbdevfs_urb *reaped_urb;
589   int fixed_input_changed;
590   int evdev_fds[16];
591   int evdev_fd_cnt = 0;
592   int evdev_support;
593   int wait_device = 0;
594   int dbg_in_sent = 0;
595   int data_in_sent = 0;
596   fd_set rfds, wfds;
597   const char *tasfn = NULL;
598   uint8_t *tas_data = NULL;
599   int use_readinc = 0; // frame increment on read
600   int tas_skip = 0;
601   int enable_sent = 0;
602   int frame_count = 0;
603   int frames_sent = 0;
604   char buf_dbg[64 + 1];
605   struct tas_pkt pkt_in;
606   struct tas_pkt pkt_out;
607   struct timeval *timeout = NULL;
608   struct timeval tout;
609   int i, ret;
610   int fd;
611
612   for (i = 1; i < argc; i++) {
613     if (argv[i][0] == '-') {
614       switch (argv[i][1] | (argv[i][2] << 8)) {
615       case 'm':
616         i++;
617         if (argv[i] == NULL)
618           missing_arg(i);
619         tasfn = argv[i];
620         continue;
621       case 's':
622         i++;
623         if (argv[i] == NULL)
624           missing_arg(i);
625         tas_skip = atoi(argv[i]);
626         continue;
627       case 'r':
628         use_readinc = 1;
629         continue;
630       default:
631         fprintf(stderr, "bad arg: %s\n", argv[i]);
632         return 1;
633       }
634     }
635     if (evdev_fd_cnt >= ARRAY_SIZE(evdev_fds)) {
636       fprintf(stderr, "too many evdevs\n");
637       break;
638     }
639     fd = open(argv[i], O_RDONLY);
640     if (fd == -1) {
641       fprintf(stderr, "open %s: ", argv[i]);
642       perror("");
643       continue;
644     }
645     evdev_support = 0;
646     ret = ioctl(fd, EVIOCGBIT(0, sizeof(evdev_support)),
647                 &evdev_support);
648     if (ret < 0)
649       perror("EVIOCGBIT");
650     if (!(evdev_support & (1 << EV_KEY))) {
651       fprintf(stderr, "%s doesn't have keys\n", argv[i]);
652       close(fd);
653       continue;
654     }
655     evdev_fds[evdev_fd_cnt++] = fd;
656   }
657
658   if (tasfn != NULL) {
659     const char *ext;
660     long size;
661     FILE *f;
662
663     f = fopen(tasfn, "rb");
664     if (f == NULL) {
665       fprintf(stderr, "fopen %s: ", tasfn);
666       perror("");
667       return 1;
668     }
669
670     fseek(f, 0, SEEK_END);
671     size = ftell(f);
672     fseek(f, 0, SEEK_SET);
673     if (size <= 0) {
674       fprintf(stderr, "bad size: %ld\n", size);
675       return 1;
676     }
677
678     ext = strrchr(tasfn, '.');
679     if (ext == NULL)
680       ext = tasfn;
681     else
682       ext++;
683
684     if (strcasecmp(ext, "gmv") == 0)
685       tas_data = import_gmv(f, size, &frame_count);
686     else if (strcasecmp(ext, "bkm") == 0)
687       tas_data = import_bkm(f, &frame_count);
688     else {
689       fprintf(stderr, "unknown movie type: '%s'\n", ext);
690       return 1;
691     }
692     fclose(f);
693
694     if (tas_data == NULL) {
695       fprintf(stderr, "failed fo parse %s\n", tasfn);
696       return 1;
697     }
698
699     if (tas_skip != 0) {
700       if (tas_skip >= frame_count || tas_skip <= -frame_count) {
701         printf("skip out of range: %d/%d\n", tas_skip, frame_count);
702         return 1;
703       }
704       if (tas_skip > 0) {
705         frame_count -= tas_skip;
706         memmove(&tas_data[0], &tas_data[tas_skip],
707           sizeof(tas_data[0]) * frame_count);
708       }
709       else {
710         tas_data = realloc(tas_data,
711                      (frame_count - tas_skip) * sizeof(tas_data[0]));
712         if (tas_data == NULL) {
713           fprintf(stderr, "OOM?\n");
714           return 1;
715         }
716         memmove(&tas_data[-tas_skip], &tas_data[0],
717           sizeof(tas_data[0]) * frame_count);
718         memset(&tas_data[0], 0xff, sizeof(tas_data[0]) * -tas_skip);
719         frame_count -= tas_skip;
720       }
721     }
722   }
723
724   enable_echo(0);
725   signal(SIGINT, signal_handler);
726
727   dev.fd = -1;
728
729   while (1)
730   {
731     if (dev.fd == -1) {
732       ret = find_device(&dev, 0x16C0, 0x0486);
733       if (ret < 0)
734         break;
735
736       if (ret == 0) {
737         if (!wait_device) {
738           printf("waiting for device..\n");
739           wait_device = 1;
740         }
741         usleep(250000);
742         continue;
743       }
744
745       wait_device = 0;
746       data_in_sent = 0;
747       dbg_in_sent = 0;
748       enable_sent = 0;
749       frames_sent = 0;
750
751       /* we wait first, then send commands, but if teensy
752        * is started already, it won't send anything */
753       tout.tv_sec = 1;
754       tout.tv_usec = 0;
755       timeout = &tout;
756     }
757
758     if (!data_in_sent) {
759       memset(&pkt_in, 0, sizeof(pkt_in));
760       ret = submit_urb(dev.fd, &urb[URB_DATA_IN], dev.ifaces[0].ep_in,
761                        &pkt_in, sizeof(pkt_in));
762       if (ret != 0) {
763         perror("USBDEVFS_SUBMITURB URB_DATA_IN");
764         break;
765       }
766
767       data_in_sent = 1;
768     }
769     if (!dbg_in_sent) {
770       ret = submit_urb(dev.fd, &urb[URB_DBG_IN], dev.ifaces[1].ep_in,
771                        buf_dbg, sizeof(buf_dbg) - 1);
772       if (ret != 0) {
773         perror("USBDEVFS_SUBMITURB URB_DBG_IN");
774         break;
775       }
776
777       dbg_in_sent = 1;
778     }
779
780     FD_ZERO(&rfds);
781     for (i = 0; i < evdev_fd_cnt; i++)
782       FD_SET(evdev_fds[i], &rfds);
783
784     FD_ZERO(&wfds);
785     FD_SET(dev.fd, &wfds);
786
787     ret = select(dev.fd + 1, &rfds, &wfds, NULL, timeout);
788     if (ret < 0) {
789       perror("select");
790       break;
791     }
792     timeout = NULL;
793
794     /* something from input devices? */
795     fixed_input_changed = 0;
796     for (i = 0; i < evdev_fd_cnt; i++) {
797       if (FD_ISSET(evdev_fds[i], &rfds)) {
798         fixed_input_changed |=
799           do_evdev_input(evdev_fds[i]);
800       }
801     }
802
803     /* something from USB? */
804     if (FD_ISSET(dev.fd, &wfds))
805     {
806       reaped_urb = NULL;
807       ret = ioctl(dev.fd, USBDEVFS_REAPURB, &reaped_urb);
808       if (ret != 0) {
809         if (errno == ENODEV)
810           goto dev_close;
811         perror("USBDEVFS_REAPURB");
812         break;
813       }
814
815       if (reaped_urb != NULL && reaped_urb->status != 0) {
816         errno = -reaped_urb->status;
817         if ((unsigned long)(reaped_urb - urb) < ARRAY_SIZE(urb))
818           fprintf(stderr, "urb #%zu: ", reaped_urb - urb);
819         else
820           fprintf(stderr, "unknown urb: ");
821         perror("");
822         if (reaped_urb->status == -EILSEQ) {
823           /* this is usually a sign of disconnect.. */
824           usleep(250000);
825           goto dev_close;
826         }
827       }
828
829       if (reaped_urb == &urb[URB_DATA_IN]) {
830         /* some request from teensy */
831         int count;
832         uint8_t b;
833
834         switch (pkt_in.type) {
835         case PKT_STREAM_REQ:
836           printf("%d/%d/%d\n", pkt_in.req.frame,
837             frames_sent, frame_count);
838
839           for (i = 0; i < sizeof(pkt_out.data); i++) {
840             pkt_out.data[i * 2 + 0] = 0x33;
841             pkt_out.data[i * 2 + 1] = 0x3f;
842           }
843           if (frames_sent < frame_count) {
844             pkt_out.type = PKT_STREAM_DATA;
845
846             count = frame_count - frames_sent;
847             if (count > sizeof(pkt_out.data) / 2)
848               count = sizeof(pkt_out.data) / 2;
849             for (i = 0; i < count; i++) {
850               /* SCBA RLDU */
851               b = tas_data[frames_sent];
852
853               /* ?0SA 00DU, ?1CB RLDU */
854               pkt_out.data[i * 2 + 0] = (b & 0x13) | ((b >> 2) & 0x20);
855               pkt_out.data[i * 2 + 1] = (b & 0x0f) | ((b >> 1) & 0x30);
856               frames_sent++;
857             }
858           }
859           else
860             pkt_out.type = PKT_STREAM_END;
861
862           ret = submit_urb(dev.fd, &urb[URB_DATA_OUT],
863                   dev.ifaces[0].ep_out, &pkt_out, sizeof(pkt_out));
864           if (ret != 0)
865             perror("USBDEVFS_SUBMITURB URB_DATA_OUT PKT_STREAM_DATA");
866           break;
867
868         default:
869           printf("host: got unknown pkt type: %04x\n", pkt_in.type);
870           break;
871         }
872
873         data_in_sent = 0;
874       }
875       else if (reaped_urb == &urb[URB_DATA_OUT]) {
876       }
877       else if (reaped_urb == &urb[URB_DBG_IN]) {
878         /* debug text */
879         buf_dbg[reaped_urb->actual_length] = 0;
880         printf("%s", buf_dbg);
881         dbg_in_sent = 0;
882       }
883       else {
884         fprintf(stderr, "reaped unknown urb? %p #%zu\n",
885           reaped_urb, reaped_urb - urb);
886       }
887     }
888
889     /* something to send? */
890     if (tas_data != NULL && !enable_sent) {
891       memset(&pkt_out, 0, sizeof(pkt_out));
892       pkt_out.type = PKT_STREAM_ENABLE;
893       pkt_out.start.use_readinc = use_readinc;
894
895       ret = submit_urb(dev.fd, &urb[URB_DATA_OUT], dev.ifaces[0].ep_out,
896                        &pkt_out, sizeof(pkt_out));
897       if (ret != 0) {
898         perror("USBDEVFS_SUBMITURB PKT_STREAM_ENABLE");
899         continue;
900       }
901       enable_sent = 1;
902     }
903     if (tas_data == NULL && fixed_input_changed) {
904       memset(&pkt_out, 0, sizeof(pkt_out));
905       pkt_out.type = PKT_FIXED_STATE;
906       memcpy(pkt_out.data, fixed_input_state, sizeof(fixed_input_state));
907
908       ret = submit_urb(dev.fd, &urb[URB_DATA_OUT], dev.ifaces[0].ep_out,
909                        &pkt_out, sizeof(pkt_out));
910       if (ret != 0) {
911         perror("USBDEVFS_SUBMITURB URB_DATA_OUT");
912         break;
913       }
914     }
915
916     continue;
917
918 dev_close:
919     close(dev.fd);
920     dev.fd = -1;
921   }
922
923   enable_echo(1);
924
925   return ret;
926 }
927
928 // vim: ts=2:sw=2:expandtab