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