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