add license
[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 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;
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 tas_skip = 0;
677   int enable_sent = 0;
678   int abort_sent = 0;
679   int frame_count = 0;
680   int frames_sent = 0;
681   char buf_dbg[64 + 1];
682   struct tas_pkt pkt_in;
683   struct tas_pkt pkt_out;
684   struct timeval *timeout = NULL;
685   struct timeval tout;
686   FILE *outf = NULL;
687   FILE *logf = NULL;
688   int i, ret = -1;
689   int fd;
690
691   for (i = 1; i < argc; i++) {
692     if (argv[i][0] == '-') {
693       switch (argv[i][1] | (argv[i][2] << 8)) {
694       case 'm':
695         i++;
696         if (argv[i] == NULL)
697           missing_arg(i);
698         tasfn = argv[i];
699         continue;
700       case 'w':
701         i++;
702         if (argv[i] == NULL)
703           missing_arg(i);
704         outfn = argv[i];
705         continue;
706       case 'l':
707         i++;
708         if (argv[i] == NULL)
709           missing_arg(i);
710         logfn = argv[i];
711         continue;
712       case 's':
713         i++;
714         if (argv[i] == NULL)
715           missing_arg(i);
716         tas_skip = atoi(argv[i]);
717         continue;
718       case 'v':
719         use_vsync = 1;
720         continue;
721       default:
722         fprintf(stderr, "bad arg: %s\n", argv[i]);
723         return 1;
724       }
725     }
726
727     /* remaining args are evdev filenames */
728     if (evdev_fd_cnt >= ARRAY_SIZE(evdev_fds)) {
729       fprintf(stderr, "too many evdevs\n");
730       break;
731     }
732     fd = open(argv[i], O_RDONLY);
733     if (fd == -1) {
734       fprintf(stderr, "open %s: ", argv[i]);
735       perror("");
736       continue;
737     }
738     evdev_support = 0;
739     ret = ioctl(fd, EVIOCGBIT(0, sizeof(evdev_support)),
740                 &evdev_support);
741     if (ret < 0)
742       perror("EVIOCGBIT");
743     if (!(evdev_support & (1 << EV_KEY))) {
744       fprintf(stderr, "%s doesn't have keys\n", argv[i]);
745       close(fd);
746       continue;
747     }
748     evdev_fds[evdev_fd_cnt++] = fd;
749   }
750
751   if (tasfn != NULL) {
752     const char *ext;
753     long size;
754     FILE *f;
755
756     f = fopen(tasfn, "rb");
757     if (f == NULL) {
758       fprintf(stderr, "fopen %s: ", tasfn);
759       perror("");
760       return 1;
761     }
762
763     fseek(f, 0, SEEK_END);
764     size = ftell(f);
765     fseek(f, 0, SEEK_SET);
766     if (size <= 0) {
767       fprintf(stderr, "bad size: %ld\n", size);
768       return 1;
769     }
770
771     ext = strrchr(tasfn, '.');
772     if (ext == NULL)
773       ext = tasfn;
774     else
775       ext++;
776
777     if (strcasecmp(ext, "gmv") == 0)
778       tas_data = import_gmv(f, size, &frame_count);
779     else if (strcasecmp(ext, "bkm") == 0)
780       tas_data = import_bkm(f, &frame_count);
781     else {
782       fprintf(stderr, "unknown movie type: '%s'\n", ext);
783       return 1;
784     }
785     fclose(f);
786
787     if (tas_data == NULL) {
788       fprintf(stderr, "failed fo parse %s\n", tasfn);
789       return 1;
790     }
791
792     if (tas_skip != 0) {
793       if (tas_skip >= frame_count || tas_skip <= -frame_count) {
794         printf("skip out of range: %d/%d\n", tas_skip, frame_count);
795         return 1;
796       }
797       if (tas_skip > 0) {
798         frame_count -= tas_skip;
799         memmove(&tas_data[0], &tas_data[tas_skip],
800           sizeof(tas_data[0]) * frame_count);
801       }
802       else {
803         tas_data = realloc(tas_data,
804                      (frame_count - tas_skip) * sizeof(tas_data[0]));
805         if (tas_data == NULL) {
806           fprintf(stderr, "OOM?\n");
807           return 1;
808         }
809         memmove(&tas_data[-tas_skip], &tas_data[0],
810           sizeof(tas_data[0]) * frame_count);
811         memset(&tas_data[0], 0xff, sizeof(tas_data[0]) * -tas_skip);
812         frame_count -= tas_skip;
813       }
814     }
815   }
816
817   if (outfn != NULL) {
818     outf = fopen(outfn, "w");
819     if (outf == NULL) {
820       fprintf(stderr, "fopen %s: ", outfn);
821       perror("");
822       return 1;
823     }
824   }
825
826   if (logfn != NULL) {
827     logf = fopen(logfn, "wb");
828     if (logf == NULL) {
829       fprintf(stderr, "fopen %s: ", logfn);
830       perror("");
831       return 1;
832     }
833   }
834
835   enable_echo(0);
836   signal(SIGINT, signal_handler);
837
838   dev.fd = -1;
839
840   while (!g_exit || (pending_urbs & (1 << URB_DATA_OUT)))
841   {
842     if (dev.fd == -1) {
843       ret = find_device(&dev, 0x16C0, 0x0486);
844       if (ret < 0)
845         break;
846
847       if (ret == 0) {
848         if (!wait_device) {
849           printf("waiting for device..\n");
850           wait_device = 1;
851         }
852         usleep(250000);
853         continue;
854       }
855
856       wait_device = 0;
857       pending_urbs = 0;
858       enable_sent = 0;
859       frames_sent = 0;
860
861       /* we wait first, then send commands, but if teensy
862        * is started already, it won't send anything */
863       tout.tv_sec = 1;
864       tout.tv_usec = 0;
865       timeout = &tout;
866     }
867
868     if (!(pending_urbs & (1 << URB_DATA_IN))) {
869       memset(&pkt_in, 0, sizeof(pkt_in));
870       ret = submit_urb(dev.fd, &urb[URB_DATA_IN], dev.ifaces[0].ep_in,
871                        &pkt_in, sizeof(pkt_in));
872       if (ret != 0) {
873         perror("USBDEVFS_SUBMITURB URB_DATA_IN");
874         break;
875       }
876
877       pending_urbs |= 1 << URB_DATA_IN;
878     }
879     if (!(pending_urbs & (1 << URB_DBG_IN))) {
880       ret = submit_urb(dev.fd, &urb[URB_DBG_IN], dev.ifaces[1].ep_in,
881                        buf_dbg, sizeof(buf_dbg) - 1);
882       if (ret != 0) {
883         perror("USBDEVFS_SUBMITURB URB_DBG_IN");
884         break;
885       }
886
887       pending_urbs |= 1 << URB_DBG_IN;
888     }
889
890     FD_ZERO(&rfds);
891     FD_SET(STDIN_FILENO, &rfds);
892     for (i = 0; i < evdev_fd_cnt; i++)
893       FD_SET(evdev_fds[i], &rfds);
894
895     FD_ZERO(&wfds);
896     FD_SET(dev.fd, &wfds);
897
898     ret = select(dev.fd + 1, &rfds, &wfds, NULL, timeout);
899     if (ret < 0) {
900       perror("select");
901       break;
902     }
903     timeout = NULL;
904
905     /* sometihng form stdin? */
906     if (FD_ISSET(STDIN_FILENO, &rfds)) {
907       char c = 0;
908       ret = read(STDIN_FILENO, &c, 1);
909       if (ret <= 0) {
910         perror("read stdin");
911         break;
912       }
913
914       switch (c) {
915       case 'r':
916         enable_sent = 0;
917         if (logf != NULL)
918           rewind(logf);
919         break;
920       }
921     }
922
923     /* something from input devices? */
924     fixed_input_changed = 0;
925     for (i = 0; i < evdev_fd_cnt; i++) {
926       if (FD_ISSET(evdev_fds[i], &rfds)) {
927         fixed_input_changed |=
928           do_evdev_input(evdev_fds[i]);
929       }
930     }
931
932     /* something from USB? */
933     if (FD_ISSET(dev.fd, &wfds))
934     {
935       unsigned int which_urb;
936
937       reaped_urb = NULL;
938       ret = ioctl(dev.fd, USBDEVFS_REAPURB, &reaped_urb);
939       if (ret != 0) {
940         if (errno == ENODEV)
941           goto dev_close;
942         perror("USBDEVFS_REAPURB");
943         break;
944       }
945       which_urb = reaped_urb - urb;
946       if (which_urb < ARRAY_SIZE(urb))
947         pending_urbs &= ~(1 << which_urb);
948       else {
949         fprintf(stderr, "reaped unknown urb: %p #%u",
950                 reaped_urb, which_urb);
951       }
952
953       if (reaped_urb != NULL && reaped_urb->status != 0) {
954         errno = -reaped_urb->status;
955         fprintf(stderr, "urb #%u: ", which_urb);
956         perror("");
957         if (reaped_urb->status == -EILSEQ) {
958           /* this is usually a sign of disconnect.. */
959           usleep(250000);
960           goto dev_close;
961         }
962       }
963       else if (reaped_urb == &urb[URB_DATA_IN])
964       {
965         /* some request from teensy */
966         switch (pkt_in.type) {
967         case PKT_STREAM_REQ:
968           printf("req: %d/%d/%d\n", pkt_in.req.frame,
969             frames_sent, frame_count);
970
971           pkt_out.size = 0;
972           if (frames_sent < frame_count) {
973             pkt_out.type = PKT_STREAM_DATA_TO;
974
975             for (i = 0; i < sizeof(pkt_out.data); ) {
976               i += tas_data_to_teensy(tas_data[frames_sent],
977                      pkt_out.data + i, logf);
978
979               frames_sent++;
980               if (frames_sent >= frame_count)
981                 break;
982             }
983             pkt_out.size = i;
984           }
985           else {
986             pkt_out.type = PKT_STREAM_END;
987             if (logf != NULL)
988               fflush(logf);
989           }
990
991           ret = submit_urb(dev.fd, &urb[URB_DATA_OUT],
992                   dev.ifaces[0].ep_out, &pkt_out, sizeof(pkt_out));
993           if (ret != 0)
994             perror("USBDEVFS_SUBMITURB PKT_STREAM_DATA_TO");
995           break;
996
997         case PKT_STREAM_DATA_FROM:
998           printf("f: %d\n", frame_count);
999           if (pkt_in.size == 0 || pkt_in.size > sizeof(pkt_out.data)) {
1000             printf("host: got bad DATA_FROM size: %u\n", pkt_in.size);
1001             break;
1002           }
1003           for (i = 0; i < pkt_in.size; ) {
1004             i += write_bkm_frame(outf, pkt_in.data + i);
1005             frame_count++;
1006           }
1007           break;
1008
1009         default:
1010           printf("host: got unknown pkt type: %04x\n", pkt_in.type);
1011           break;
1012         }
1013       }
1014       else if (reaped_urb == &urb[URB_DATA_OUT])
1015       {
1016       }
1017       else if (reaped_urb == &urb[URB_DBG_IN])
1018       {
1019         /* debug text */
1020         buf_dbg[reaped_urb->actual_length] = 0;
1021         printf("%s", buf_dbg);
1022
1023         // continue receiving debug before sending out stuff
1024         tout.tv_sec = 0;
1025         tout.tv_usec = 1000;
1026         timeout = &tout;
1027         continue;
1028       }
1029       else {
1030         fprintf(stderr, "reaped unknown urb? %p #%zu\n",
1031           reaped_urb, reaped_urb - urb);
1032       }
1033     }
1034
1035     /* something to send? */
1036     if (pending_urbs & (1 << URB_DATA_OUT))
1037       // can't do that yet
1038       continue;
1039
1040     if ((tas_data != NULL || outf != NULL) && !enable_sent) {
1041       memset(&pkt_out, 0, sizeof(pkt_out));
1042       pkt_out.type = PKT_STREAM_ENABLE;
1043       pkt_out.enable.stream_to = (tas_data != NULL);
1044       pkt_out.enable.stream_from = (outf != NULL);
1045       pkt_out.enable.use_readinc = !use_vsync;
1046
1047       ret = submit_urb(dev.fd, &urb[URB_DATA_OUT], dev.ifaces[0].ep_out,
1048                        &pkt_out, sizeof(pkt_out));
1049       if (ret != 0) {
1050         perror("USBDEVFS_SUBMITURB PKT_STREAM_ENABLE");
1051         continue;
1052       }
1053       pending_urbs |= 1 << URB_DATA_OUT;
1054       enable_sent = 1;
1055       frames_sent = 0;
1056       continue;
1057     }
1058     if (tas_data == NULL && fixed_input_changed) {
1059       memset(&pkt_out, 0, sizeof(pkt_out));
1060       pkt_out.type = PKT_FIXED_STATE;
1061       memcpy(pkt_out.data, fixed_input_state, sizeof(fixed_input_state));
1062
1063       ret = submit_urb(dev.fd, &urb[URB_DATA_OUT], dev.ifaces[0].ep_out,
1064                        &pkt_out, sizeof(pkt_out));
1065       if (ret != 0) {
1066         perror("USBDEVFS_SUBMITURB PKT_FIXED_STATE");
1067         break;
1068       }
1069       pending_urbs |= 1 << URB_DATA_OUT;
1070       continue;
1071     }
1072     if (g_exit && !abort_sent) {
1073       memset(&pkt_out, 0, sizeof(pkt_out));
1074       pkt_out.type = PKT_STREAM_ABORT;
1075
1076       ret = submit_urb(dev.fd, &urb[URB_DATA_OUT], dev.ifaces[0].ep_out,
1077                        &pkt_out, sizeof(pkt_out));
1078       if (ret != 0) {
1079         perror("USBDEVFS_SUBMITURB PKT_STREAM_ABORT");
1080         break;
1081       }
1082       pending_urbs |= 1 << URB_DATA_OUT;
1083       abort_sent = 1;
1084       continue;
1085     }
1086
1087     continue;
1088
1089 dev_close:
1090     close(dev.fd);
1091     dev.fd = -1;
1092   }
1093
1094   enable_echo(1);
1095
1096   if (outf != NULL)
1097     fclose(outf);
1098   if (logf != NULL)
1099     fclose(logf);
1100
1101   if (dev.fd != -1) {
1102     /* deal with pending URBs */
1103     if (pending_urbs & (1 << URB_DATA_IN))
1104       ioctl(dev.fd, USBDEVFS_DISCARDURB, &urb[URB_DATA_IN]);
1105     if (pending_urbs & (1 << URB_DBG_IN))
1106       ioctl(dev.fd, USBDEVFS_DISCARDURB, &urb[URB_DBG_IN]);
1107     for (i = 0; i < URB_CNT; i++) {
1108       if (pending_urbs & (1 << i)) {
1109         ret = ioctl(dev.fd, USBDEVFS_REAPURB, &reaped_urb);
1110         if (ret != 0)
1111           perror("USBDEVFS_REAPURB");
1112       }
1113     }
1114
1115     close(dev.fd);
1116   }
1117
1118   return ret;
1119 }
1120
1121 // vim: ts=2:sw=2:expandtab