implement stream restart on r key
[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 | ICANON;
265   else {
266     tty.c_lflag &= ~(ECHO | ICANON);
267     tty.c_cc[VMIN] = tty.c_cc[VTIME] = 0;
268   }
269
270   ret = tcsetattr(fd, TCSANOW, &tty);
271   if (ret != 0) {
272     perror("tcsetattr");
273     goto out;
274   }
275
276   retval = 0;
277 out:
278   close(fd);
279
280   return retval;
281 }
282
283 static void signal_handler(int sig)
284 {
285   enable_echo(1);
286   signal(sig, SIG_DFL);
287   raise(sig);
288 }
289
290 /* ?0SA 00DU, ?1CB RLDU */
291 #define STATE_BYTES 2
292
293 static uint8_t fixed_input_state[STATE_BYTES] = { 0x33, 0x3f };
294
295 enum mdbtn {
296   MDBTN_UP = 1,
297   MDBTN_DOWN,
298   MDBTN_LEFT,
299   MDBTN_RIGHT,
300   MDBTN_A,
301   MDBTN_B,
302   MDBTN_C,
303   MDBTN_START,
304 };
305
306 static const enum mdbtn evdev_md_map[KEY_CNT] = {
307   [KEY_UP]       = MDBTN_UP,
308   [KEY_DOWN]     = MDBTN_DOWN,
309   [KEY_LEFT]     = MDBTN_LEFT,
310   [KEY_RIGHT]    = MDBTN_RIGHT,
311   [KEY_HOME]     = MDBTN_A,
312   [KEY_PAGEDOWN] = MDBTN_B,
313   [KEY_END]      = MDBTN_C,
314   [KEY_LEFTALT]  = MDBTN_START,
315 };
316
317 int do_evdev_input(int fd)
318 {
319   uint8_t old_state[STATE_BYTES];
320   uint8_t changed_bits[STATE_BYTES] = { 0, };
321   struct input_event ev;
322   enum mdbtn mdbtn;
323   int i, ret;
324
325   ret = read(fd, &ev, sizeof(ev));
326   if (ret != sizeof(ev)) {
327     fprintf(stderr, "evdev read %d/%zd: ", ret, sizeof(ev));
328     perror("");
329     return 0;
330   }
331
332   if (ev.type != EV_KEY)
333     return 0;
334
335   if (ev.value != 0 && ev.value != 1)
336     return 0;
337
338   if ((uint32_t)ev.code >= ARRAY_SIZE(evdev_md_map)) {
339     fprintf(stderr, "evdev read bad key: %u\n", ev.code);
340     return 0;
341   }
342
343   mdbtn = evdev_md_map[ev.code];
344   if (mdbtn == 0)
345     return 0;
346
347   memcpy(old_state, fixed_input_state, STATE_BYTES);
348
349   /* ?0SA 00DU, ?1CB RLDU */
350   switch (mdbtn) {
351   case MDBTN_UP:
352     changed_bits[0] = 0x01;
353     changed_bits[1] = 0x01;
354     break;
355   case MDBTN_DOWN:
356     changed_bits[0] = 0x02;
357     changed_bits[1] = 0x02;
358     break;
359   case MDBTN_LEFT:
360     changed_bits[0] = 0x00;
361     changed_bits[1] = 0x04;
362     break;
363   case MDBTN_RIGHT:
364     changed_bits[0] = 0x00;
365     changed_bits[1] = 0x08;
366     break;
367   case MDBTN_A:
368     changed_bits[0] = 0x10;
369     changed_bits[1] = 0x00;
370     break;
371   case MDBTN_B:
372     changed_bits[0] = 0x00;
373     changed_bits[1] = 0x10;
374     break;
375   case MDBTN_C:
376     changed_bits[0] = 0x00;
377     changed_bits[1] = 0x20;
378     break;
379   case MDBTN_START:
380     changed_bits[0] = 0x20;
381     changed_bits[1] = 0x00;
382     break;
383   }
384
385   if (ev.value) {
386     // key press
387     for (i = 0; i < STATE_BYTES; i++)
388       fixed_input_state[i] &= ~changed_bits[i];
389   }
390   else {
391     // key release
392     for (i = 0; i < STATE_BYTES; i++)
393       fixed_input_state[i] |=  changed_bits[i];
394   }
395
396   return memcmp(old_state, fixed_input_state, STATE_BYTES) ? 1 : 0;
397 }
398
399 struct gmv_tas {
400   char sig[15];
401   char ver;
402   uint32_t rerecord_count;
403   char ctrl1;
404   char ctrl2;
405   uint16_t flags;
406   char name[40];
407   uint8_t data[0][3];
408 };
409
410 static uint8_t *import_gmv(FILE *f, long size, int *frame_count)
411 {
412   struct gmv_tas *gmv;
413   uint8_t *out;
414   int ret;
415   int i;
416
417   if (size < (long)sizeof(*gmv)) {
418     fprintf(stderr, "bad gmv size: %ld\n", size);
419     return NULL;
420   }
421
422   gmv = malloc(size);
423   if (gmv == NULL) {
424     fprintf(stderr, "OOM?\n");
425     return NULL;
426   }
427   ret = fread(gmv, 1, size, f);
428   if (ret != size) {
429     fprintf(stderr, "fread %d/%ld: ", ret, size);
430     perror("");
431     return NULL;
432   }
433
434   *frame_count = (size - sizeof(*gmv)) / sizeof(gmv->data[0]);
435
436   /* check the GMV.. */
437   if (*frame_count <= 0 || size != sizeof(*gmv) + *frame_count * 3) {
438     fprintf(stderr, "broken gmv? frames=%d\n", *frame_count);
439     return NULL;
440   }
441
442   if (strncmp(gmv->sig, "Gens Movie TEST", 15) != 0) {
443     fprintf(stderr, "bad GMV sig\n");
444     return NULL;
445   }
446   if (gmv->ctrl1 != '3') {
447     fprintf(stderr, "unhandled controlled config: '%c'\n", gmv->ctrl1);
448     //return NULL;
449   }
450   if (gmv->ver >= 'A') {
451     if (gmv->flags & 0x40) {
452       fprintf(stderr, "unhandled flag: movie requires a savestate\n");
453       return NULL;
454     }
455     if (gmv->flags & 0x20) {
456       fprintf(stderr, "unhandled flag: 3-player movie\n");
457       return NULL;
458     }
459     if (gmv->flags & ~0x80) {
460       //fprintf(stderr, "unhandled flag(s): %04x\n", gmv->flags);
461       //return 1;
462     }
463   }
464   gmv->name[39] = 0;
465   printf("loaded GMV: %s\n", gmv->name);
466   printf("%d frames, %u rerecords\n",
467          *frame_count, gmv->rerecord_count);
468
469   out = malloc(*frame_count * sizeof(out[0]));
470   if (out == NULL) {
471     fprintf(stderr, "OOM?\n");
472     return NULL;
473   }
474
475   for (i = 0; i < *frame_count; i++) {
476     out[i] = gmv->data[i][0];
477
478     if (gmv->data[i][1] != 0xff || gmv->data[i][2] != 0xff)
479     {
480       fprintf(stderr, "f %d: unhandled byte(s) %02x %02x\n",
481         i, gmv->data[i][1], gmv->data[i][2]);
482     }
483   }
484
485   return out;
486 }
487
488 static int do_bkm_char(char c, char expect, uint8_t *val, int bit)
489 {
490   if (c == expect) {
491     *val &= ~(1 << bit);
492     return 0;
493   }
494   if (c == '.')
495     return 0;
496
497   fprintf(stderr, "unexpected bkm char: '%c' instead of '%c'\n",
498           c, expect);
499   return 1;
500 }
501
502 static uint8_t *import_bkm(FILE *f, int *frame_count)
503 {
504   uint8_t *out = NULL, val;
505   int count = 0;
506   int alloc = 0;
507   int line = 0;
508   char buf[256];
509   const char *r;
510   char *p;
511   int i;
512
513   while ((p = fgets(buf, sizeof(buf), f)) != NULL) {
514     line++;
515     if (p[0] != '|')
516       continue;
517
518     if (strlen(p) < 30)
519       goto unhandled_line;
520     if (p[30] != '\r' && p[30] != '\n')
521       goto unhandled_line;
522     p[30] = 0;
523
524     if (count >= alloc) {
525       alloc = alloc * 2 + 64;
526       out = realloc(out, alloc * sizeof(out[0]));
527       if (out == NULL) {
528         fprintf(stderr, "OOM?\n");
529         return NULL;
530       }
531     }
532
533     val = 0xff;
534
535     if (strncmp(p, "|.|", 3) != 0)
536       goto unhandled_line;
537     p += 3;
538
539     const char ref[] = "UDLRABCS";
540     for (r = ref, i = 0; *r != 0; p++, r++, i++) {
541       if (do_bkm_char(*p, *r, &val, i))
542         goto unhandled_line;
543     }
544
545     if (strcmp(p, "....|............||") != 0)
546       goto unhandled_line;
547
548     out[count++] = val;
549     continue;
550
551 unhandled_line:
552     fprintf(stderr, "unhandled bkm line %d: '%s'\n", line, buf);
553     return NULL;
554   }
555
556   printf("loaded bkm, %d frames\n", count);
557   *frame_count = count;
558   return out;
559 }
560
561 static int submit_urb(int fd, struct usbdevfs_urb *urb, int ep,
562   void *buf, size_t buf_size)
563 {
564   memset(urb, 0, sizeof(*urb));
565   urb->type = USBDEVFS_URB_TYPE_INTERRUPT;
566   urb->endpoint = ep;
567   urb->buffer = buf;
568   urb->buffer_length = buf_size;
569
570   return ioctl(fd, USBDEVFS_SUBMITURB, urb);
571 }
572
573 enum my_urbs {
574   URB_DATA_IN,
575   URB_DATA_OUT,
576   URB_DBG_IN,
577   URB_CNT
578 };
579
580 static void missing_arg(int a)
581 {
582   fprintf(stderr, "missing arg: %d\n", a);
583   exit(1);
584 }
585
586 int main(int argc, char *argv[])
587 {
588   struct teensy_dev dev;
589   struct usbdevfs_urb urb[URB_CNT];
590   struct usbdevfs_urb *reaped_urb;
591   int fixed_input_changed;
592   int evdev_fds[16];
593   int evdev_fd_cnt = 0;
594   int evdev_support;
595   int wait_device = 0;
596   int dbg_in_sent = 0;
597   int data_in_sent = 0;
598   fd_set rfds, wfds;
599   const char *tasfn = NULL;
600   uint8_t *tas_data = NULL;
601   int use_readinc = 0; // frame increment on read
602   int tas_skip = 0;
603   int enable_sent = 0;
604   int frame_count = 0;
605   int frames_sent = 0;
606   char buf_dbg[64 + 1];
607   struct tas_pkt pkt_in;
608   struct tas_pkt pkt_out;
609   struct timeval *timeout = NULL;
610   struct timeval tout;
611   int i, ret;
612   int fd;
613
614   for (i = 1; i < argc; i++) {
615     if (argv[i][0] == '-') {
616       switch (argv[i][1] | (argv[i][2] << 8)) {
617       case 'm':
618         i++;
619         if (argv[i] == NULL)
620           missing_arg(i);
621         tasfn = argv[i];
622         continue;
623       case 's':
624         i++;
625         if (argv[i] == NULL)
626           missing_arg(i);
627         tas_skip = atoi(argv[i]);
628         continue;
629       case 'r':
630         use_readinc = 1;
631         continue;
632       default:
633         fprintf(stderr, "bad arg: %s\n", argv[i]);
634         return 1;
635       }
636     }
637     if (evdev_fd_cnt >= ARRAY_SIZE(evdev_fds)) {
638       fprintf(stderr, "too many evdevs\n");
639       break;
640     }
641     fd = open(argv[i], O_RDONLY);
642     if (fd == -1) {
643       fprintf(stderr, "open %s: ", argv[i]);
644       perror("");
645       continue;
646     }
647     evdev_support = 0;
648     ret = ioctl(fd, EVIOCGBIT(0, sizeof(evdev_support)),
649                 &evdev_support);
650     if (ret < 0)
651       perror("EVIOCGBIT");
652     if (!(evdev_support & (1 << EV_KEY))) {
653       fprintf(stderr, "%s doesn't have keys\n", argv[i]);
654       close(fd);
655       continue;
656     }
657     evdev_fds[evdev_fd_cnt++] = fd;
658   }
659
660   if (tasfn != NULL) {
661     const char *ext;
662     long size;
663     FILE *f;
664
665     f = fopen(tasfn, "rb");
666     if (f == NULL) {
667       fprintf(stderr, "fopen %s: ", tasfn);
668       perror("");
669       return 1;
670     }
671
672     fseek(f, 0, SEEK_END);
673     size = ftell(f);
674     fseek(f, 0, SEEK_SET);
675     if (size <= 0) {
676       fprintf(stderr, "bad size: %ld\n", size);
677       return 1;
678     }
679
680     ext = strrchr(tasfn, '.');
681     if (ext == NULL)
682       ext = tasfn;
683     else
684       ext++;
685
686     if (strcasecmp(ext, "gmv") == 0)
687       tas_data = import_gmv(f, size, &frame_count);
688     else if (strcasecmp(ext, "bkm") == 0)
689       tas_data = import_bkm(f, &frame_count);
690     else {
691       fprintf(stderr, "unknown movie type: '%s'\n", ext);
692       return 1;
693     }
694     fclose(f);
695
696     if (tas_data == NULL) {
697       fprintf(stderr, "failed fo parse %s\n", tasfn);
698       return 1;
699     }
700
701     if (tas_skip != 0) {
702       if (tas_skip >= frame_count || tas_skip <= -frame_count) {
703         printf("skip out of range: %d/%d\n", tas_skip, frame_count);
704         return 1;
705       }
706       if (tas_skip > 0) {
707         frame_count -= tas_skip;
708         memmove(&tas_data[0], &tas_data[tas_skip],
709           sizeof(tas_data[0]) * frame_count);
710       }
711       else {
712         tas_data = realloc(tas_data,
713                      (frame_count - tas_skip) * sizeof(tas_data[0]));
714         if (tas_data == NULL) {
715           fprintf(stderr, "OOM?\n");
716           return 1;
717         }
718         memmove(&tas_data[-tas_skip], &tas_data[0],
719           sizeof(tas_data[0]) * frame_count);
720         memset(&tas_data[0], 0xff, sizeof(tas_data[0]) * -tas_skip);
721         frame_count -= tas_skip;
722       }
723     }
724   }
725
726   enable_echo(0);
727   signal(SIGINT, signal_handler);
728
729   dev.fd = -1;
730
731   while (1)
732   {
733     if (dev.fd == -1) {
734       ret = find_device(&dev, 0x16C0, 0x0486);
735       if (ret < 0)
736         break;
737
738       if (ret == 0) {
739         if (!wait_device) {
740           printf("waiting for device..\n");
741           wait_device = 1;
742         }
743         usleep(250000);
744         continue;
745       }
746
747       wait_device = 0;
748       data_in_sent = 0;
749       dbg_in_sent = 0;
750       enable_sent = 0;
751       frames_sent = 0;
752
753       /* we wait first, then send commands, but if teensy
754        * is started already, it won't send anything */
755       tout.tv_sec = 1;
756       tout.tv_usec = 0;
757       timeout = &tout;
758     }
759
760     if (!data_in_sent) {
761       memset(&pkt_in, 0, sizeof(pkt_in));
762       ret = submit_urb(dev.fd, &urb[URB_DATA_IN], dev.ifaces[0].ep_in,
763                        &pkt_in, sizeof(pkt_in));
764       if (ret != 0) {
765         perror("USBDEVFS_SUBMITURB URB_DATA_IN");
766         break;
767       }
768
769       data_in_sent = 1;
770     }
771     if (!dbg_in_sent) {
772       ret = submit_urb(dev.fd, &urb[URB_DBG_IN], dev.ifaces[1].ep_in,
773                        buf_dbg, sizeof(buf_dbg) - 1);
774       if (ret != 0) {
775         perror("USBDEVFS_SUBMITURB URB_DBG_IN");
776         break;
777       }
778
779       dbg_in_sent = 1;
780     }
781
782     FD_ZERO(&rfds);
783     FD_SET(STDIN_FILENO, &rfds);
784     for (i = 0; i < evdev_fd_cnt; i++)
785       FD_SET(evdev_fds[i], &rfds);
786
787     FD_ZERO(&wfds);
788     FD_SET(dev.fd, &wfds);
789
790     ret = select(dev.fd + 1, &rfds, &wfds, NULL, timeout);
791     if (ret < 0) {
792       perror("select");
793       break;
794     }
795     timeout = NULL;
796
797     /* sometihng form stdin? */
798     /* something from input devices? */
799     if (FD_ISSET(STDIN_FILENO, &rfds)) {
800       char c = 0;
801       ret = read(STDIN_FILENO, &c, 1);
802       if (ret <= 0) {
803         perror("read stdin");
804         break;
805       }
806
807       switch (c) {
808       case 'r':
809         enable_sent = 0;
810         break;
811       }
812     }
813
814     fixed_input_changed = 0;
815     for (i = 0; i < evdev_fd_cnt; i++) {
816       if (FD_ISSET(evdev_fds[i], &rfds)) {
817         fixed_input_changed |=
818           do_evdev_input(evdev_fds[i]);
819       }
820     }
821
822     /* something from USB? */
823     if (FD_ISSET(dev.fd, &wfds))
824     {
825       reaped_urb = NULL;
826       ret = ioctl(dev.fd, USBDEVFS_REAPURB, &reaped_urb);
827       if (ret != 0) {
828         if (errno == ENODEV)
829           goto dev_close;
830         perror("USBDEVFS_REAPURB");
831         break;
832       }
833
834       if (reaped_urb != NULL && reaped_urb->status != 0) {
835         errno = -reaped_urb->status;
836         if ((unsigned long)(reaped_urb - urb) < ARRAY_SIZE(urb))
837           fprintf(stderr, "urb #%zu: ", reaped_urb - urb);
838         else
839           fprintf(stderr, "unknown urb: ");
840         perror("");
841         if (reaped_urb->status == -EILSEQ) {
842           /* this is usually a sign of disconnect.. */
843           usleep(250000);
844           goto dev_close;
845         }
846       }
847
848       if (reaped_urb == &urb[URB_DATA_IN]) {
849         /* some request from teensy */
850         int count;
851         uint8_t b;
852
853         switch (pkt_in.type) {
854         case PKT_STREAM_REQ:
855           printf("%d/%d/%d\n", pkt_in.req.frame,
856             frames_sent, frame_count);
857
858           for (i = 0; i < sizeof(pkt_out.data); i++) {
859             pkt_out.data[i * 2 + 0] = 0x33;
860             pkt_out.data[i * 2 + 1] = 0x3f;
861           }
862           if (frames_sent < frame_count) {
863             pkt_out.type = PKT_STREAM_DATA;
864
865             count = frame_count - frames_sent;
866             if (count > sizeof(pkt_out.data) / 2)
867               count = sizeof(pkt_out.data) / 2;
868             for (i = 0; i < count; i++) {
869               /* SCBA RLDU */
870               b = tas_data[frames_sent];
871
872               /* ?0SA 00DU, ?1CB RLDU */
873               pkt_out.data[i * 2 + 0] = (b & 0x13) | ((b >> 2) & 0x20);
874               pkt_out.data[i * 2 + 1] = (b & 0x0f) | ((b >> 1) & 0x30);
875               frames_sent++;
876             }
877           }
878           else
879             pkt_out.type = PKT_STREAM_END;
880
881           ret = submit_urb(dev.fd, &urb[URB_DATA_OUT],
882                   dev.ifaces[0].ep_out, &pkt_out, sizeof(pkt_out));
883           if (ret != 0)
884             perror("USBDEVFS_SUBMITURB URB_DATA_OUT PKT_STREAM_DATA");
885           break;
886
887         default:
888           printf("host: got unknown pkt type: %04x\n", pkt_in.type);
889           break;
890         }
891
892         data_in_sent = 0;
893       }
894       else if (reaped_urb == &urb[URB_DATA_OUT]) {
895       }
896       else if (reaped_urb == &urb[URB_DBG_IN]) {
897         /* debug text */
898         buf_dbg[reaped_urb->actual_length] = 0;
899         printf("%s", buf_dbg);
900         dbg_in_sent = 0;
901       }
902       else {
903         fprintf(stderr, "reaped unknown urb? %p #%zu\n",
904           reaped_urb, reaped_urb - urb);
905       }
906     }
907
908     /* something to send? */
909     if (tas_data != NULL && !enable_sent) {
910       memset(&pkt_out, 0, sizeof(pkt_out));
911       pkt_out.type = PKT_STREAM_ENABLE;
912       pkt_out.start.use_readinc = use_readinc;
913
914       ret = submit_urb(dev.fd, &urb[URB_DATA_OUT], dev.ifaces[0].ep_out,
915                        &pkt_out, sizeof(pkt_out));
916       if (ret != 0) {
917         perror("USBDEVFS_SUBMITURB PKT_STREAM_ENABLE");
918         continue;
919       }
920       enable_sent = 1;
921       frames_sent = 0;
922     }
923     if (tas_data == NULL && fixed_input_changed) {
924       memset(&pkt_out, 0, sizeof(pkt_out));
925       pkt_out.type = PKT_FIXED_STATE;
926       memcpy(pkt_out.data, fixed_input_state, sizeof(fixed_input_state));
927
928       ret = submit_urb(dev.fd, &urb[URB_DATA_OUT], dev.ifaces[0].ep_out,
929                        &pkt_out, sizeof(pkt_out));
930       if (ret != 0) {
931         perror("USBDEVFS_SUBMITURB URB_DATA_OUT");
932         break;
933       }
934     }
935
936     continue;
937
938 dev_close:
939     close(dev.fd);
940     dev.fd = -1;
941   }
942
943   enable_echo(1);
944
945   return ret;
946 }
947
948 // vim: ts=2:sw=2:expandtab