remove -s option
[megadrive.git] / host / main.c
1 /*
2  * TeensyTAS, TAS input player for MegaDrive
3  * Copyright (c) 2014 notaz
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining
6  * a copy of this software and associated documentation files (the
7  * "Software"), to deal in the Software without restriction, including
8  * without limitation the rights to use, copy, modify, merge, publish,
9  * distribute, sublicense, and/or sell copies of the Software, and to
10  * permit persons to whom the Software is furnished to do so, subject to
11  * the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be
14  * included in all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19  * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
20  * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
21  * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
22  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23  * SOFTWARE.
24  */
25
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <stdint.h>
30 #include <sys/types.h>
31 #include <sys/stat.h>
32 #include <fcntl.h>
33 #include <sys/ioctl.h>
34 #include <sys/select.h>
35 #include <unistd.h>
36 #include <dirent.h>
37 #include <signal.h>
38 #include <termios.h>
39 #include <errno.h>
40 #include <linux/usbdevice_fs.h>
41 #include <linux/usb/ch9.h>
42 #include <linux/input.h>
43 #include "../pkts.h"
44
45 #define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0]))
46
47 struct teensy_dev {
48   int fd;
49   struct {
50     int ep_in;
51     int ep_out;
52   } ifaces[2];
53 };
54
55 /* return 1 if founf, 0 if not, < 0 on error */
56 static int find_device(struct teensy_dev *dev,
57   uint16_t vendor, uint16_t product)
58 {
59   const char path_root[] = "/dev/bus/usb";
60   union {
61     struct usb_descriptor_header hdr;
62     struct usb_device_descriptor d;
63     struct usb_config_descriptor c;
64     struct usb_interface_descriptor i;
65     struct usb_endpoint_descriptor e;
66     char space[0x100]; /* enough? */
67   } desc;
68   char path_bus[256], path_dev[256];
69   struct dirent *ent, *ent_bus;
70   DIR *dir = NULL, *dir_bus = NULL;
71   int num, fd = -1;
72   int iface = -1;
73   int retval = -1;
74   int ret;
75
76   memset(dev, 0xff, sizeof(*dev));
77
78   dir = opendir(path_root);
79   if (dir == NULL) {
80     perror("opendir");
81     return -1;
82   }
83
84   for (ent = readdir(dir); ent != NULL; ent = readdir(dir)) {
85     /* should be a number like 000 */
86     if (sscanf(ent->d_name, "%03d", &num) != 1)
87       continue;
88
89     snprintf(path_bus, sizeof(path_bus), "%s/%s",
90         path_root, ent->d_name);
91
92     dir_bus = opendir(path_bus);
93     if (dir_bus == NULL)
94       continue;
95
96     ent_bus = readdir(dir_bus);
97     for (; ent_bus != NULL; ent_bus = readdir(dir_bus)) {
98       if (sscanf(ent->d_name, "%03d", &num) != 1)
99         continue;
100
101       snprintf(path_dev, sizeof(path_dev), "%s/%s/%s",
102           path_root, ent->d_name, ent_bus->d_name);
103
104       fd = open(path_dev, O_RDWR);
105       if (fd == -1)
106         continue;
107
108       ret = read(fd, &desc.d, sizeof(desc.d));
109       if (ret != sizeof(desc.d)) {
110         fprintf(stderr, "desc read: %d/%zd: ", ret, sizeof(desc.d));
111         perror("");
112         goto next;
113       }
114
115       if (desc.d.bDescriptorType != USB_DT_DEVICE) {
116         fprintf(stderr, "%s: bad DT: 0x%02x\n",
117             path_dev, desc.d.bDescriptorType);
118         goto next;
119       }
120
121       if (desc.d.idVendor == vendor && desc.d.idProduct == product)
122         goto found;
123
124 next:
125       close(fd);
126       fd = -1;
127     }
128
129     closedir(dir_bus);
130     dir_bus = NULL;
131   }
132
133   /* not found */
134   retval = 0;
135   goto out;
136
137 found:
138   if (desc.d.bNumConfigurations != 1) {
139     fprintf(stderr, "unexpected bNumConfigurations: %u\n",
140         desc.d.bNumConfigurations);
141     goto out;
142   }
143
144   /* walk through all descriptors */
145   while (1)
146   {
147     ret = read(fd, &desc.hdr, sizeof(desc.hdr));
148     if (ret == 0)
149       break;
150     if (ret != sizeof(desc.hdr)) {
151       fprintf(stderr, "desc.hdr read: %d/%zd: ", ret, sizeof(desc.hdr));
152       perror("");
153       break;
154     }
155
156     ret = (int)lseek(fd, -sizeof(desc.hdr), SEEK_CUR);
157     if (ret == -1) {
158       perror("lseek");
159       break;
160     }
161
162     ret = read(fd, &desc, desc.hdr.bLength);
163     if (ret != desc.hdr.bLength) {
164       fprintf(stderr, "desc read: %d/%u: ", ret, desc.hdr.bLength);
165       perror("");
166       break;
167     }
168
169     switch (desc.hdr.bDescriptorType) {
170       case USB_DT_CONFIG:
171         if (desc.c.bNumInterfaces != 2) {
172           fprintf(stderr, "unexpected bNumInterfaces: %u\n",
173               desc.c.bNumInterfaces);
174           goto out;
175         }
176         break;
177
178       case USB_DT_INTERFACE:
179         if (desc.i.bInterfaceClass != USB_CLASS_HID
180             || desc.i.bInterfaceSubClass != 0
181             || desc.i.bInterfaceProtocol != 0) {
182           fprintf(stderr, "unexpected interface %x:%x:%x\n",
183             desc.i.bInterfaceClass, desc.i.bInterfaceSubClass,
184             desc.i.bInterfaceProtocol);
185           goto out;
186         }
187         if (desc.i.bNumEndpoints != 2) {
188           fprintf(stderr, "unexpected bNumEndpoints: %u\n",
189             desc.i.bNumEndpoints);
190           goto out;
191         }
192         iface++;
193         break;
194
195       case USB_DT_ENDPOINT:
196         if (iface < 0 || iface >= ARRAY_SIZE(dev->ifaces)) {
197           fprintf(stderr, "bad iface: %d\n", iface);
198           goto out;
199         }
200         if (desc.e.wMaxPacketSize != 64 && desc.e.wMaxPacketSize != 32) {
201           fprintf(stderr, "iface %d, EP %02x: "
202             "unexpected wMaxPacketSize: %u\n",
203             iface, desc.e.bEndpointAddress, desc.e.wMaxPacketSize);
204           goto out;
205         }
206         if (desc.e.bEndpointAddress & 0x80)
207           dev->ifaces[iface].ep_in = desc.e.bEndpointAddress; // & 0x7F;
208         else
209           dev->ifaces[iface].ep_out = desc.e.bEndpointAddress;
210         break;
211
212       case 0x21:
213         /* ignore */
214         break;
215
216       default:
217         fprintf(stderr, "skipping desc 0x%02x\n",
218           desc.hdr.bDescriptorType);
219         break;
220     }
221   }
222
223   /* claim interfaces */
224   for (iface = 0; iface < ARRAY_SIZE(dev->ifaces); iface++) {
225     struct usbdevfs_ioctl usbio;
226
227     if (dev->ifaces[iface].ep_in == -1) {
228       fprintf(stderr, "missing ep_in, iface: %d\n", iface);
229       goto out;
230     }
231     if (dev->ifaces[iface].ep_out == -1) {
232       fprintf(stderr, "missing ep_out, iface: %d\n", iface);
233       goto out;
234     }
235
236     /* disconnect default driver */
237     memset(&usbio, 0, sizeof(usbio));
238     usbio.ifno = iface;
239     usbio.ioctl_code = USBDEVFS_DISCONNECT;
240     ret = ioctl(fd, USBDEVFS_IOCTL, &usbio);
241     if (ret != 0 && errno != ENODATA)
242       perror("USBDEVFS_DISCONNECT");
243
244     ret = ioctl(fd, USBDEVFS_CLAIMINTERFACE, &iface);
245     if (ret != 0)
246       perror("USBDEVFS_CLAIMINTERFACE");
247   }
248
249   dev->fd = fd;
250   fd = -1;
251   retval = 1;
252
253 out:
254   if (fd != -1)
255     close(fd);
256   if (dir_bus != NULL)
257     closedir(dir_bus);
258   if (dir != NULL)
259     closedir(dir);
260
261   return retval;
262 }
263
264 static int enable_echo(int enable)
265 {
266   const char *portname = "/dev/tty";
267   struct termios tty;
268   int retval = -1;
269   int ret;
270   int fd;
271
272   memset(&tty, 0, sizeof(tty));
273
274   fd = open(portname, O_RDWR | O_NOCTTY | O_SYNC);
275   if (fd < 0) {
276     fprintf(stderr, "open %s: ", portname);
277     perror("");
278     return 1;
279   }
280
281   ret = tcgetattr(fd, &tty);
282   if (ret != 0) {
283     perror("tcgetattr");
284     goto out;
285   }
286
287   // printf("lflag: 0%o\n", tty.c_lflag);
288   if (enable)
289     tty.c_lflag |= ECHO | ICANON;
290   else {
291     tty.c_lflag &= ~(ECHO | ICANON);
292     tty.c_cc[VMIN] = tty.c_cc[VTIME] = 0;
293   }
294
295   ret = tcsetattr(fd, TCSANOW, &tty);
296   if (ret != 0) {
297     perror("tcsetattr");
298     goto out;
299   }
300
301   retval = 0;
302 out:
303   close(fd);
304
305   return retval;
306 }
307
308 static int g_exit;
309
310 static void signal_handler(int sig)
311 {
312   g_exit = 1;
313   signal(sig, SIG_DFL);
314 }
315
316 /* ?0SA 00DU, ?1CB RLDU */
317 #define STATE_BYTES 2
318
319 static uint8_t fixed_input_state[STATE_BYTES] = { 0x33, 0x3f };
320
321 enum mdbtn {
322   MDBTN_UP = 1,
323   MDBTN_DOWN,
324   MDBTN_LEFT,
325   MDBTN_RIGHT,
326   MDBTN_A,
327   MDBTN_B,
328   MDBTN_C,
329   MDBTN_START,
330 };
331
332 static const enum mdbtn evdev_md_map[KEY_CNT] = {
333   [KEY_UP]       = MDBTN_UP,
334   [KEY_DOWN]     = MDBTN_DOWN,
335   [KEY_LEFT]     = MDBTN_LEFT,
336   [KEY_RIGHT]    = MDBTN_RIGHT,
337   [KEY_HOME]     = MDBTN_A,
338   [KEY_PAGEDOWN] = MDBTN_B,
339   [KEY_END]      = MDBTN_C,
340   [KEY_LEFTALT]  = MDBTN_START,
341 };
342
343 int do_evdev_input(int fd)
344 {
345   uint8_t old_state[STATE_BYTES];
346   uint8_t changed_bits[STATE_BYTES] = { 0, };
347   struct input_event ev;
348   enum mdbtn mdbtn;
349   int i, ret;
350
351   ret = read(fd, &ev, sizeof(ev));
352   if (ret != sizeof(ev)) {
353     fprintf(stderr, "evdev read %d/%zd: ", ret, sizeof(ev));
354     perror("");
355     return 0;
356   }
357
358   if (ev.type != EV_KEY)
359     return 0;
360
361   if (ev.value != 0 && ev.value != 1)
362     return 0;
363
364   if ((uint32_t)ev.code >= ARRAY_SIZE(evdev_md_map)) {
365     fprintf(stderr, "evdev read bad key: %u\n", ev.code);
366     return 0;
367   }
368
369   mdbtn = evdev_md_map[ev.code];
370   if (mdbtn == 0)
371     return 0;
372
373   memcpy(old_state, fixed_input_state, STATE_BYTES);
374
375   /* ?0SA 00DU, ?1CB RLDU */
376   switch (mdbtn) {
377   case MDBTN_UP:
378     changed_bits[0] = 0x01;
379     changed_bits[1] = 0x01;
380     break;
381   case MDBTN_DOWN:
382     changed_bits[0] = 0x02;
383     changed_bits[1] = 0x02;
384     break;
385   case MDBTN_LEFT:
386     changed_bits[0] = 0x00;
387     changed_bits[1] = 0x04;
388     break;
389   case MDBTN_RIGHT:
390     changed_bits[0] = 0x00;
391     changed_bits[1] = 0x08;
392     break;
393   case MDBTN_A:
394     changed_bits[0] = 0x10;
395     changed_bits[1] = 0x00;
396     break;
397   case MDBTN_B:
398     changed_bits[0] = 0x00;
399     changed_bits[1] = 0x10;
400     break;
401   case MDBTN_C:
402     changed_bits[0] = 0x00;
403     changed_bits[1] = 0x20;
404     break;
405   case MDBTN_START:
406     changed_bits[0] = 0x20;
407     changed_bits[1] = 0x00;
408     break;
409   }
410
411   if (ev.value) {
412     // key press
413     for (i = 0; i < STATE_BYTES; i++)
414       fixed_input_state[i] &= ~changed_bits[i];
415   }
416   else {
417     // key release
418     for (i = 0; i < STATE_BYTES; i++)
419       fixed_input_state[i] |=  changed_bits[i];
420   }
421
422   return memcmp(old_state, fixed_input_state, STATE_BYTES) ? 1 : 0;
423 }
424
425 #define MAX_INPUT_BYTES 2
426
427 // TODO: 6btn
428 static int tas_data_to_teensy(uint16_t b, uint8_t *data, FILE *logf)
429 {
430   uint8_t t;
431
432   /* SCBA RLDU */
433   /*     v     */
434   /* ?0SA 00DU, ?1CB RLDU */
435   data[0] = (b & 0x13) | ((b >> 2) & 0x20);
436   data[1] = (b & 0x0f) | ((b >> 1) & 0x30);
437
438   if (logf != NULL) {
439     fwrite(&data[0], 1, 1, logf);
440     t = data[1] | 0x40; // expected TH
441     fwrite(&t, 1, 1, logf);
442   }
443
444   return 2;
445 }
446
447 struct gmv_tas {
448   char sig[15];
449   char ver;
450   uint32_t rerecord_count;
451   char ctrl1;
452   char ctrl2;
453   uint16_t flags;
454   char name[40];
455   uint8_t data[0][3];
456 };
457
458 static uint8_t *import_gmv(FILE *f, long size, int *byte_count, FILE *logf)
459 {
460   struct gmv_tas *gmv;
461   int frame_count;
462   int count = 0;
463   uint16_t val;
464   uint8_t *out;
465   int ret;
466   int i;
467
468   *byte_count = 0;
469
470   if (size < (long)sizeof(*gmv)) {
471     fprintf(stderr, "bad gmv size: %ld\n", size);
472     return NULL;
473   }
474
475   gmv = malloc(size);
476   if (gmv == NULL) {
477     fprintf(stderr, "OOM?\n");
478     return NULL;
479   }
480   ret = fread(gmv, 1, size, f);
481   if (ret != size) {
482     fprintf(stderr, "fread %d/%ld: ", ret, size);
483     perror("");
484     return NULL;
485   }
486
487   frame_count = (size - sizeof(*gmv)) / sizeof(gmv->data[0]);
488
489   /* check the GMV.. */
490   if (frame_count <= 0 || size != sizeof(*gmv) + frame_count * 3) {
491     fprintf(stderr, "broken gmv? frames=%d\n", frame_count);
492     return NULL;
493   }
494
495   if (strncmp(gmv->sig, "Gens Movie TEST", 15) != 0) {
496     fprintf(stderr, "bad GMV sig\n");
497     return NULL;
498   }
499   if (gmv->ctrl1 != '3') {
500     fprintf(stderr, "unhandled controlled config: '%c'\n", gmv->ctrl1);
501     //return NULL;
502   }
503   if (gmv->ver >= 'A') {
504     if (gmv->flags & 0x40) {
505       fprintf(stderr, "unhandled flag: movie requires a savestate\n");
506       return NULL;
507     }
508     if (gmv->flags & 0x20) {
509       fprintf(stderr, "unhandled flag: 3-player movie\n");
510       return NULL;
511     }
512     if (gmv->flags & ~0x80) {
513       //fprintf(stderr, "unhandled flag(s): %04x\n", gmv->flags);
514       //return 1;
515     }
516   }
517   gmv->name[39] = 0;
518   printf("loaded GMV: %s\n", gmv->name);
519   printf("%d frames, %u rerecords\n",
520          frame_count, gmv->rerecord_count);
521
522   out = malloc(frame_count * MAX_INPUT_BYTES);
523   if (out == NULL) {
524     fprintf(stderr, "OOM?\n");
525     return NULL;
526   }
527
528   for (i = 0; i < frame_count; i++) {
529     val = gmv->data[i][0] | ((gmv->data[i][2] & 0x0f) << 8);
530     count += tas_data_to_teensy(val, out + count, logf);
531
532     if (gmv->data[i][1] != 0xff || gmv->data[i][2] != 0xff)
533     {
534       fprintf(stderr, "f %d: unhandled byte(s) %02x %02x\n",
535         i, gmv->data[i][1], gmv->data[i][2]);
536     }
537   }
538
539   *byte_count = count;
540   return out;
541 }
542
543 static int do_bkm_char(char c, char expect, uint16_t *val, int bit)
544 {
545   if (c == expect) {
546     *val &= ~(1 << bit);
547     return 0;
548   }
549   if (c == '.')
550     return 0;
551
552   fprintf(stderr, "unexpected bkm char: '%c' instead of '%c'\n",
553           c, expect);
554   return 1;
555 }
556
557 static uint8_t *import_bkm(FILE *f, int *byte_count, FILE *logf)
558 {
559   uint8_t *out = NULL;
560   uint16_t val;
561   int frames = 0;
562   int count = 0;
563   int alloc = 0;
564   int line = 0;
565   char buf[256];
566   const char *r;
567   char *p;
568   int i;
569
570   while ((p = fgets(buf, sizeof(buf), f)) != NULL)
571   {
572     line++;
573     if (p[0] != '|')
574       continue;
575
576     if (strlen(p) < 30)
577       goto unhandled_line;
578     if (p[30] != '\r' && p[30] != '\n')
579       goto unhandled_line;
580     p[30] = 0;
581
582     if (count >= alloc - MAX_INPUT_BYTES) {
583       alloc = alloc * 2 + 64;
584       out = realloc(out, alloc * sizeof(out[0]));
585       if (out == NULL) {
586         fprintf(stderr, "OOM?\n");
587         return NULL;
588       }
589     }
590
591     val = 0xfff;
592
593     if (strncmp(p, "|.|", 3) != 0)
594       goto unhandled_line;
595     p += 3;
596
597     const char ref[] = "UDLRABCS";
598     for (r = ref, i = 0; *r != 0; p++, r++, i++) {
599       if (do_bkm_char(*p, *r, &val, i))
600         goto unhandled_line;
601     }
602
603     if (strcmp(p, "....|............||") != 0)
604       goto unhandled_line;
605
606     count += tas_data_to_teensy(val, out + count, logf);
607     frames++;
608     continue;
609
610 unhandled_line:
611     fprintf(stderr, "unhandled bkm line %d: '%s'\n", line, buf);
612     return NULL;
613   }
614
615   printf("loaded bkm, %d frames, %d bytes\n", frames, count);
616   *byte_count = count;
617   return out;
618 }
619
620 static uint8_t *import_raw(FILE *f, int *byte_count, FILE *logf)
621 {
622   uint8_t *out = NULL, val;
623   int count = 0;
624   int alloc = 0;
625   int line = 0;
626   int first = 1;
627   char buf[256];
628   char *p;
629   int i;
630
631   while ((p = fgets(buf, sizeof(buf), f)) != NULL)
632   {
633     line++;
634     if (p[0] == '#')
635       continue;
636     if (p[0] != 'e') {
637       printf("skipping: %s", p);
638       continue;
639     }
640
641     val = 0;
642     p++;
643     for (i = 6; i >= 0; i--, p++) {
644       if (*p != '0' && *p != '1')
645         goto bad;
646       if (*p == '1')
647         val |= 1 << i;
648     }
649     if (*p != ' ')
650       goto bad;
651
652     if (first && (val & 0x40))
653       continue; // XXX..
654     first = 0;
655
656     if (count >= alloc) {
657       alloc = alloc * 2 + 64;
658       out = realloc(out, alloc * sizeof(out[0]));
659       if (out == NULL) {
660         fprintf(stderr, "OOM?\n");
661         return NULL;
662       }
663     }
664
665     if (logf)
666       fwrite(&val, 1, 1, logf);
667
668     out[count++] = val & 0x3f;
669     continue;
670
671 bad:
672     fprintf(stderr, "bad raw line %d: '%s'\n", line, buf);
673     return NULL;
674   }
675
676   printf("loaded raw, %d bytes\n", count);
677   *byte_count = count;
678   return out;
679 }
680
681 static int write_bkm_frame(FILE *f, const uint8_t *data)
682 {
683   /* ?0SA 00DU, ?1CB RLDU */
684   static const char ref[]  = "UDLRABCSXYZM";
685   static const char bits[] = { 0,1,2,3, 12,4,5,13, 16,16,16,16 };
686   uint32_t idata[2];
687   int p, i;
688
689   if (f == NULL) {
690     fprintf(stderr, "%s called without outfile\n", __func__);
691     goto out;
692   }
693
694   idata[0] = 0x10000 | (data[0] << 8) | data[1];
695   idata[1] = ~0;
696
697   fprintf(f, "|.|");
698   for (p = 0; p < 2; p++) {
699     for (i = 0; i < 12; i++)
700       fprintf(f, "%c", (idata[p] & (1 << bits[i])) ? '.' : ref[i]);
701     fprintf(f, "|");
702   }
703   fprintf(f, "|\n");
704
705 out:
706   return 2;
707 }
708
709 static int submit_urb(int fd, struct usbdevfs_urb *urb, int ep,
710   void *buf, size_t buf_size)
711 {
712   memset(urb, 0, sizeof(*urb));
713   urb->type = USBDEVFS_URB_TYPE_INTERRUPT;
714   urb->endpoint = ep;
715   urb->buffer = buf;
716   urb->buffer_length = buf_size;
717
718   return ioctl(fd, USBDEVFS_SUBMITURB, urb);
719 }
720
721 enum my_urbs {
722   URB_DATA_IN,
723   URB_DATA_OUT,
724   URB_DBG_IN,
725   URB_CNT
726 };
727
728 static void missing_arg(int a)
729 {
730   fprintf(stderr, "missing arg: %d\n", a);
731   exit(1);
732 }
733
734 int main(int argc, char *argv[])
735 {
736   struct teensy_dev dev;
737   struct usbdevfs_urb urb[URB_CNT];
738   struct usbdevfs_urb *reaped_urb;
739   int fixed_input_changed = 0;
740   int evdev_fds[16];
741   int evdev_fd_cnt = 0;
742   int evdev_support;
743   int wait_device = 0;
744   int pending_urbs = 0;
745   fd_set rfds, wfds;
746   const char *tasfn = NULL;
747   const char *outfn = NULL;
748   const char *logfn = NULL;
749   uint8_t *tas_data = NULL;
750   int tas_data_size = 0;
751   int bytes_sent = 0;
752   int use_vsync = 0; // frame increment on vsync
753   int no_start_seq = 0;
754   int tas_skip = 0;
755   int enable_sent = 0;
756   int abort_sent = 0;
757   int frame_count = 0;
758   char buf_dbg[64 + 1];
759   struct tas_pkt pkt_in;
760   struct tas_pkt pkt_out;
761   struct timeval *timeout = NULL;
762   struct timeval tout;
763   FILE *outf = NULL;
764   FILE *logf = NULL;
765   int i, ret = -1;
766   int fd;
767
768   for (i = 1; i < argc; i++) {
769     if (argv[i][0] == '-') {
770       switch (argv[i][1] | (argv[i][2] << 8)) {
771       case 'm':
772         i++;
773         if (argv[i] == NULL)
774           missing_arg(i);
775         tasfn = argv[i];
776         continue;
777       case 'w':
778         i++;
779         if (argv[i] == NULL)
780           missing_arg(i);
781         outfn = argv[i];
782         continue;
783       case 'l':
784         i++;
785         if (argv[i] == NULL)
786           missing_arg(i);
787         logfn = argv[i];
788         continue;
789       case 'v':
790         use_vsync = 1;
791         continue;
792       case 'n':
793         no_start_seq = 1;
794         continue;
795       default:
796         fprintf(stderr, "bad arg: %s\n", argv[i]);
797         return 1;
798       }
799     }
800
801     /* remaining args are evdev filenames */
802     if (evdev_fd_cnt >= ARRAY_SIZE(evdev_fds)) {
803       fprintf(stderr, "too many evdevs\n");
804       break;
805     }
806     fd = open(argv[i], O_RDONLY);
807     if (fd == -1) {
808       fprintf(stderr, "open %s: ", argv[i]);
809       perror("");
810       continue;
811     }
812     evdev_support = 0;
813     ret = ioctl(fd, EVIOCGBIT(0, sizeof(evdev_support)),
814                 &evdev_support);
815     if (ret < 0)
816       perror("EVIOCGBIT");
817     if (!(evdev_support & (1 << EV_KEY))) {
818       fprintf(stderr, "%s doesn't have keys\n", argv[i]);
819       close(fd);
820       continue;
821     }
822     evdev_fds[evdev_fd_cnt++] = fd;
823   }
824
825   if (logfn != NULL) {
826     logf = fopen(logfn, "wb");
827     if (logf == NULL) {
828       fprintf(stderr, "fopen %s: ", logfn);
829       perror("");
830       return 1;
831     }
832   }
833
834   if (tasfn != NULL) {
835     const char *ext;
836     long size;
837     FILE *f;
838
839     f = fopen(tasfn, "rb");
840     if (f == NULL) {
841       fprintf(stderr, "fopen %s: ", tasfn);
842       perror("");
843       return 1;
844     }
845
846     fseek(f, 0, SEEK_END);
847     size = ftell(f);
848     fseek(f, 0, SEEK_SET);
849     if (size <= 0) {
850       fprintf(stderr, "bad size: %ld\n", size);
851       return 1;
852     }
853
854     ext = strrchr(tasfn, '.');
855     if (ext == NULL)
856       ext = tasfn;
857     else
858       ext++;
859
860     if (strcasecmp(ext, "gmv") == 0)
861       tas_data = import_gmv(f, size, &tas_data_size, logf);
862     else if (strcasecmp(ext, "bkm") == 0)
863       tas_data = import_bkm(f, &tas_data_size, logf);
864     else if (strcasecmp(ext, "txt") == 0)
865       tas_data = import_raw(f, &tas_data_size, logf);
866     else {
867       fprintf(stderr, "unknown movie type: '%s'\n", ext);
868       return 1;
869     }
870     fclose(f);
871
872     if (logf != NULL) {
873       rewind(logf);
874       logf = NULL;
875     }
876
877     if (tas_data == NULL) {
878       fprintf(stderr, "failed fo parse %s\n", tasfn);
879       return 1;
880     }
881   }
882
883   if (outfn != NULL) {
884     outf = fopen(outfn, "w");
885     if (outf == NULL) {
886       fprintf(stderr, "fopen %s: ", outfn);
887       perror("");
888       return 1;
889     }
890   }
891
892   enable_echo(0);
893   signal(SIGINT, signal_handler);
894
895   dev.fd = -1;
896
897   while (!g_exit || (pending_urbs & (1 << URB_DATA_OUT)))
898   {
899     if (dev.fd == -1) {
900       ret = find_device(&dev, 0x16C0, 0x0486);
901       if (ret < 0)
902         break;
903
904       if (ret == 0) {
905         if (!wait_device) {
906           printf("waiting for device..\n");
907           wait_device = 1;
908         }
909         usleep(250000);
910         continue;
911       }
912
913       wait_device = 0;
914       pending_urbs = 0;
915       enable_sent = 0;
916       bytes_sent = 0;
917
918       /* we wait first, then send commands, but if teensy
919        * is started already, it won't send anything */
920       tout.tv_sec = 1;
921       tout.tv_usec = 0;
922       timeout = &tout;
923     }
924
925     if (!(pending_urbs & (1 << URB_DATA_IN))) {
926       memset(&pkt_in, 0, sizeof(pkt_in));
927       ret = submit_urb(dev.fd, &urb[URB_DATA_IN], dev.ifaces[0].ep_in,
928                        &pkt_in, sizeof(pkt_in));
929       if (ret != 0) {
930         perror("USBDEVFS_SUBMITURB URB_DATA_IN");
931         break;
932       }
933
934       pending_urbs |= 1 << URB_DATA_IN;
935     }
936     if (!(pending_urbs & (1 << URB_DBG_IN))) {
937       ret = submit_urb(dev.fd, &urb[URB_DBG_IN], dev.ifaces[1].ep_in,
938                        buf_dbg, sizeof(buf_dbg) - 1);
939       if (ret != 0) {
940         perror("USBDEVFS_SUBMITURB URB_DBG_IN");
941         break;
942       }
943
944       pending_urbs |= 1 << URB_DBG_IN;
945     }
946
947     FD_ZERO(&rfds);
948     FD_SET(STDIN_FILENO, &rfds);
949     for (i = 0; i < evdev_fd_cnt; i++)
950       FD_SET(evdev_fds[i], &rfds);
951
952     FD_ZERO(&wfds);
953     FD_SET(dev.fd, &wfds);
954
955     ret = select(dev.fd + 1, &rfds, &wfds, NULL, timeout);
956     if (ret < 0) {
957       perror("select");
958       break;
959     }
960     timeout = NULL;
961
962     /* sometihng form stdin? */
963     if (FD_ISSET(STDIN_FILENO, &rfds)) {
964       char c = 0;
965       ret = read(STDIN_FILENO, &c, 1);
966       if (ret <= 0) {
967         perror("read stdin");
968         break;
969       }
970
971       switch (c) {
972       case 'r':
973         enable_sent = 0;
974         break;
975       }
976     }
977
978     /* something from input devices? */
979     for (i = 0; i < evdev_fd_cnt; i++) {
980       if (FD_ISSET(evdev_fds[i], &rfds)) {
981         fixed_input_changed |=
982           do_evdev_input(evdev_fds[i]);
983       }
984     }
985
986     /* something from USB? */
987     if (FD_ISSET(dev.fd, &wfds))
988     {
989       unsigned int which_urb;
990
991       reaped_urb = NULL;
992       ret = ioctl(dev.fd, USBDEVFS_REAPURB, &reaped_urb);
993       if (ret != 0) {
994         if (errno == ENODEV)
995           goto dev_close;
996         perror("USBDEVFS_REAPURB");
997         break;
998       }
999       which_urb = reaped_urb - urb;
1000       if (which_urb < ARRAY_SIZE(urb))
1001         pending_urbs &= ~(1 << which_urb);
1002       else {
1003         fprintf(stderr, "reaped unknown urb: %p #%u",
1004                 reaped_urb, which_urb);
1005       }
1006
1007       if (reaped_urb != NULL && reaped_urb->status != 0) {
1008         errno = -reaped_urb->status;
1009         fprintf(stderr, "urb #%u: ", which_urb);
1010         perror("");
1011         if (reaped_urb->status == -EILSEQ) {
1012           /* this is usually a sign of disconnect.. */
1013           usleep(250000);
1014           goto dev_close;
1015         }
1016       }
1017       else if (reaped_urb == &urb[URB_DATA_IN])
1018       {
1019         /* some request from teensy */
1020         switch (pkt_in.type) {
1021         case PKT_STREAM_REQ:
1022           printf("req: %d/%d/%d\n", pkt_in.req.frame * 2,
1023             bytes_sent, tas_data_size);
1024
1025           pkt_out.size = 0;
1026           if (bytes_sent < tas_data_size) {
1027             pkt_out.type = PKT_STREAM_DATA_TO;
1028
1029             i = tas_data_size - bytes_sent;
1030             if (i > sizeof(pkt_out.data))
1031               i = sizeof(pkt_out.data);
1032             memcpy(pkt_out.data, tas_data + bytes_sent, i);
1033             bytes_sent += i;
1034             pkt_out.size = i;
1035           }
1036           else {
1037             pkt_out.type = PKT_STREAM_END;
1038           }
1039
1040           ret = submit_urb(dev.fd, &urb[URB_DATA_OUT],
1041                   dev.ifaces[0].ep_out, &pkt_out, sizeof(pkt_out));
1042           if (ret != 0)
1043             perror("USBDEVFS_SUBMITURB PKT_STREAM_DATA_TO");
1044           break;
1045
1046         case PKT_STREAM_DATA_FROM:
1047           printf("f: %d\n", frame_count);
1048           if (pkt_in.size == 0 || pkt_in.size > sizeof(pkt_out.data)) {
1049             printf("host: got bad DATA_FROM size: %u\n", pkt_in.size);
1050             break;
1051           }
1052           for (i = 0; i < pkt_in.size; ) {
1053             i += write_bkm_frame(outf, pkt_in.data + i);
1054             frame_count++;
1055           }
1056           break;
1057
1058         default:
1059           printf("host: got unknown pkt type: %04x\n", pkt_in.type);
1060           break;
1061         }
1062       }
1063       else if (reaped_urb == &urb[URB_DATA_OUT])
1064       {
1065       }
1066       else if (reaped_urb == &urb[URB_DBG_IN])
1067       {
1068         /* debug text */
1069         buf_dbg[reaped_urb->actual_length] = 0;
1070         printf("%s", buf_dbg);
1071
1072         // continue receiving debug before sending out stuff
1073         tout.tv_sec = 0;
1074         tout.tv_usec = 1000;
1075         timeout = &tout;
1076         continue;
1077       }
1078       else {
1079         fprintf(stderr, "reaped unknown urb? %p #%zu\n",
1080           reaped_urb, reaped_urb - urb);
1081       }
1082     }
1083
1084     /* something to send? */
1085     if (pending_urbs & (1 << URB_DATA_OUT))
1086       // can't do that yet
1087       continue;
1088
1089     if ((tas_data != NULL || outf != NULL) && !enable_sent) {
1090       memset(&pkt_out, 0, sizeof(pkt_out));
1091       pkt_out.type = PKT_STREAM_ENABLE;
1092       pkt_out.enable.stream_to = (tas_data != NULL);
1093       pkt_out.enable.stream_from = (outf != NULL);
1094       pkt_out.enable.use_readinc = !use_vsync;
1095       pkt_out.enable.no_start_seq = no_start_seq;
1096
1097       ret = submit_urb(dev.fd, &urb[URB_DATA_OUT], dev.ifaces[0].ep_out,
1098                        &pkt_out, sizeof(pkt_out));
1099       if (ret != 0) {
1100         perror("USBDEVFS_SUBMITURB PKT_STREAM_ENABLE");
1101         continue;
1102       }
1103       pending_urbs |= 1 << URB_DATA_OUT;
1104       enable_sent = 1;
1105       bytes_sent = 0;
1106       continue;
1107     }
1108     if (tas_data == NULL && fixed_input_changed) {
1109       memset(&pkt_out, 0, sizeof(pkt_out));
1110       pkt_out.type = PKT_FIXED_STATE;
1111       memcpy(pkt_out.data, fixed_input_state, sizeof(fixed_input_state));
1112
1113       ret = submit_urb(dev.fd, &urb[URB_DATA_OUT], dev.ifaces[0].ep_out,
1114                        &pkt_out, sizeof(pkt_out));
1115       if (ret != 0) {
1116         perror("USBDEVFS_SUBMITURB PKT_FIXED_STATE");
1117         break;
1118       }
1119       fixed_input_changed = 0;
1120       pending_urbs |= 1 << URB_DATA_OUT;
1121       continue;
1122     }
1123     if (g_exit && !abort_sent) {
1124       memset(&pkt_out, 0, sizeof(pkt_out));
1125       pkt_out.type = PKT_STREAM_ABORT;
1126
1127       ret = submit_urb(dev.fd, &urb[URB_DATA_OUT], dev.ifaces[0].ep_out,
1128                        &pkt_out, sizeof(pkt_out));
1129       if (ret != 0) {
1130         perror("USBDEVFS_SUBMITURB PKT_STREAM_ABORT");
1131         break;
1132       }
1133       pending_urbs |= 1 << URB_DATA_OUT;
1134       abort_sent = 1;
1135       continue;
1136     }
1137
1138     continue;
1139
1140 dev_close:
1141     close(dev.fd);
1142     dev.fd = -1;
1143   }
1144
1145   enable_echo(1);
1146
1147   if (outf != NULL)
1148     fclose(outf);
1149
1150   if (dev.fd != -1) {
1151     /* deal with pending URBs */
1152     if (pending_urbs & (1 << URB_DATA_IN))
1153       ioctl(dev.fd, USBDEVFS_DISCARDURB, &urb[URB_DATA_IN]);
1154     if (pending_urbs & (1 << URB_DBG_IN))
1155       ioctl(dev.fd, USBDEVFS_DISCARDURB, &urb[URB_DBG_IN]);
1156     for (i = 0; i < URB_CNT; i++) {
1157       if (pending_urbs & (1 << i)) {
1158         ret = ioctl(dev.fd, USBDEVFS_REAPURB, &reaped_urb);
1159         if (ret != 0)
1160           perror("USBDEVFS_REAPURB");
1161       }
1162     }
1163
1164     close(dev.fd);
1165   }
1166
1167   return ret;
1168 }
1169
1170 // vim: ts=2:sw=2:expandtab