support 2nd player streaming from separate raw file
[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 #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 int import_gmv(FILE *f, long size,
459   uint8_t *out[2], int out_byte_count[2], FILE *logf)
460 {
461   struct gmv_tas *gmv;
462   int frame_count;
463   int count = 0;
464   uint16_t val;
465   int ret;
466   int i;
467
468   out_byte_count[0] = out_byte_count[1] = 0;
469
470   if (size < (long)sizeof(*gmv)) {
471     fprintf(stderr, "bad gmv size: %ld\n", size);
472     return -1;
473   }
474
475   gmv = malloc(size);
476   if (gmv == NULL) {
477     fprintf(stderr, "OOM?\n");
478     return -1;
479   }
480   ret = fread(gmv, 1, size, f);
481   if (ret != size) {
482     fprintf(stderr, "fread %d/%ld: ", ret, size);
483     perror("");
484     return -1;
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 -1;
493   }
494
495   if (strncmp(gmv->sig, "Gens Movie TEST", 15) != 0) {
496     fprintf(stderr, "bad GMV sig\n");
497     return -1;
498   }
499   if (gmv->ctrl1 != '3') {
500     fprintf(stderr, "unhandled controlled config: '%c'\n", gmv->ctrl1);
501     //return -1;
502   }
503   if (gmv->ver >= 'A') {
504     if (gmv->flags & 0x40) {
505       fprintf(stderr, "unhandled flag: movie requires a savestate\n");
506       return -1;
507     }
508     if (gmv->flags & 0x20) {
509       fprintf(stderr, "unhandled flag: 3-player movie\n");
510       return -1;
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[0] = malloc(frame_count * MAX_INPUT_BYTES);
523   if (out[0] == NULL) {
524     fprintf(stderr, "OOM?\n");
525     return -1;
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[0] + 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   out_byte_count[0] = count;
540   return 0;
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 int import_bkm(FILE *f, uint8_t *out[2], int out_byte_count[2],
558   FILE *logf)
559 {
560   int teensy_bytes = 0;
561   int have_pl2 = 0;
562   int have_xyz = 0;
563   int frames = 0;
564   int count = 0;
565   int alloc = 0;
566   int line = 0;
567   char buf[256];
568   const char *r;
569   uint16_t val;
570   char *p;
571   int pl, i;
572
573   while ((p = fgets(buf, sizeof(buf), f)) != NULL)
574   {
575     line++;
576     if (p[0] != '|')
577       continue;
578
579     if (strlen(p) < 30)
580       goto unhandled_line;
581     if (p[30] != '\r' && p[30] != '\n')
582       goto unhandled_line;
583     p[30] = 0;
584
585     if (count >= alloc - MAX_INPUT_BYTES) {
586       alloc = alloc * 2 + 64;
587       for (pl = 0; pl < 2; pl++) {
588         out[pl] = realloc(out[pl], alloc * sizeof(out[0][0]));
589         if (out[pl] == NULL) {
590           fprintf(stderr, "OOM?\n");
591           return -1;
592         }
593       }
594     }
595
596     if (strncmp(p, "|.|", 3) != 0)
597       goto unhandled_line;
598     p += 3;
599
600     for (pl = 0; pl < 2; pl++) {
601       static const char ref[] = "UDLRABCSXYZM";
602
603       val = 0xfff;
604       for (r = ref, i = 0; *r != 0; p++, r++, i++) {
605         if (do_bkm_char(*p, *r, &val, i))
606           goto unhandled_line;
607       }
608
609       if (*p++ != '|')
610         goto unhandled_line;
611
612       teensy_bytes = tas_data_to_teensy(val, out[pl] + count, logf);
613
614       if ((val & 0xf00) != 0xf00)
615         have_xyz = 1;
616       if (pl == 1)
617         have_pl2 |= (val != 0xfff);
618     }
619     count += teensy_bytes;
620
621     if (strcmp(p, "|") != 0)
622       goto unhandled_line;
623
624     frames++;
625     continue;
626
627 unhandled_line:
628     fprintf(stderr, "unhandled bkm line %d: '%s'\n", line, buf);
629     return -1;
630   }
631
632   printf("loaded bkm, %d players, %d frames, %d bytes, have_xyz=%d\n",
633     have_pl2 ? 2 : 1, frames, count, have_xyz);
634   out_byte_count[0] = count;
635   if (have_pl2)
636     out_byte_count[1] = count;
637   else {
638     free(out[1]);
639     out[1] = NULL;
640   }
641
642   return 0;
643 }
644
645 static int import_raw(FILE *f, uint8_t **out, int *out_byte_count,
646   FILE *logf)
647 {
648   int count = 0;
649   int alloc = 0;
650   int line = 0;
651   int first = 1;
652   char buf[256];
653   uint8_t val;
654   char *p;
655   int i;
656
657   *out_byte_count = 0;
658
659   while ((p = fgets(buf, sizeof(buf), f)) != NULL)
660   {
661     line++;
662     if (p[0] == '#')
663       continue;
664     if (p[0] != 'e') {
665       printf("skipping: %s", p);
666       continue;
667     }
668
669     val = 0;
670     p++;
671     for (i = 6; i >= 0; i--, p++) {
672       if (*p != '0' && *p != '1')
673         goto bad;
674       if (*p == '1')
675         val |= 1 << i;
676     }
677     if (*p != ' ')
678       goto bad;
679
680     if (first && (val & 0x40))
681       continue; // XXX..
682     first = 0;
683
684     if (count >= alloc) {
685       alloc = alloc * 2 + 64;
686       *out = realloc(*out, alloc * sizeof((*out)[0]));
687       if (*out == NULL) {
688         fprintf(stderr, "OOM?\n");
689         return -1;
690       }
691     }
692
693     if (logf)
694       fwrite(&val, 1, 1, logf);
695
696     (*out)[count++] = val & 0x3f;
697     continue;
698
699 bad:
700     fprintf(stderr, "bad raw line %d: '%s'\n", line, buf);
701     return -1;
702   }
703
704   printf("loaded raw, %d bytes\n", count);
705   *out_byte_count = count;
706   return 0;
707 }
708
709 static int write_bkm_frame(FILE *f, const uint8_t *data)
710 {
711   /* ?0SA 00DU, ?1CB RLDU */
712   static const char ref[]  = "UDLRABCSXYZM";
713   static const char bits[] = { 0,1,2,3, 12,4,5,13, 16,16,16,16 };
714   uint32_t idata[2];
715   int p, i;
716
717   if (f == NULL) {
718     fprintf(stderr, "%s called without outfile\n", __func__);
719     goto out;
720   }
721
722   idata[0] = 0x10000 | (data[0] << 8) | data[1];
723   idata[1] = ~0;
724
725   fprintf(f, "|.|");
726   for (p = 0; p < 2; p++) {
727     for (i = 0; i < 12; i++)
728       fprintf(f, "%c", (idata[p] & (1 << bits[i])) ? '.' : ref[i]);
729     fprintf(f, "|");
730   }
731   fprintf(f, "|\n");
732
733 out:
734   return 2;
735 }
736
737 static int submit_urb(int fd, struct usbdevfs_urb *urb, int ep,
738   void *buf, size_t buf_size)
739 {
740   memset(urb, 0, sizeof(*urb));
741   urb->type = USBDEVFS_URB_TYPE_INTERRUPT;
742   urb->endpoint = ep;
743   urb->buffer = buf;
744   urb->buffer_length = buf_size;
745
746   return ioctl(fd, USBDEVFS_SUBMITURB, urb);
747 }
748
749 enum my_urbs {
750   URB_DATA_IN,
751   URB_DATA_OUT,
752   URB_DBG_IN,
753   URB_CNT
754 };
755
756 static void missing_arg(int a)
757 {
758   fprintf(stderr, "missing arg: %d\n", a);
759   exit(1);
760 }
761
762 int main(int argc, char *argv[])
763 {
764   struct teensy_dev dev;
765   struct usbdevfs_urb urb[URB_CNT];
766   struct usbdevfs_urb *reaped_urb;
767   int fixed_input_changed = 0;
768   int evdev_fds[16];
769   int evdev_fd_cnt = 0;
770   int evdev_support;
771   int wait_device = 0;
772   int pending_urbs = 0;
773   fd_set rfds, wfds;
774   const char *tasfn = NULL;
775   const char *tasfn_p2 = NULL;
776   const char *outfn = NULL;
777   const char *logfn = NULL;
778   uint8_t *tas_data[2] = { NULL, NULL };
779   int tas_data_size[2] = { 0, 0 };
780   int bytes_sent[2] = { 0, 0 };
781   int use_vsync = 0; // frame increment on vsync
782   int separate_2p = 0;
783   int no_start_seq = 0;
784   int enable_sent = 0;
785   int abort_sent = 0;
786   int frame_count = 0;
787   char buf_dbg[64 + 1];
788   struct tas_pkt pkt_in;
789   struct tas_pkt pkt_out;
790   struct timeval *timeout = NULL;
791   struct timeval tout;
792   FILE *outf = NULL;
793   FILE *logf = NULL;
794   int i, ret = -1;
795   int fd;
796
797   for (i = 1; i < argc; i++) {
798     if (argv[i][0] == '-') {
799       switch (argv[i][1] | (argv[i][2] << 8)) {
800       case 'm':
801         i++;
802         if (argv[i] == NULL)
803           missing_arg(i);
804         tasfn = argv[i];
805         continue;
806       case '2':
807         i++;
808         if (argv[i] == NULL)
809           missing_arg(i);
810         tasfn_p2 = argv[i];
811         continue;
812       case 'w':
813         i++;
814         if (argv[i] == NULL)
815           missing_arg(i);
816         outfn = argv[i];
817         continue;
818       case 'l':
819         i++;
820         if (argv[i] == NULL)
821           missing_arg(i);
822         logfn = argv[i];
823         continue;
824       case 'v':
825         use_vsync = 1;
826         continue;
827       case 'n':
828         no_start_seq = 1;
829         continue;
830       default:
831         fprintf(stderr, "bad arg: %s\n", argv[i]);
832         return 1;
833       }
834     }
835
836     /* remaining args are evdev filenames */
837     if (evdev_fd_cnt >= ARRAY_SIZE(evdev_fds)) {
838       fprintf(stderr, "too many evdevs\n");
839       break;
840     }
841     fd = open(argv[i], O_RDONLY);
842     if (fd == -1) {
843       fprintf(stderr, "open %s: ", argv[i]);
844       perror("");
845       continue;
846     }
847     evdev_support = 0;
848     ret = ioctl(fd, EVIOCGBIT(0, sizeof(evdev_support)),
849                 &evdev_support);
850     if (ret < 0)
851       perror("EVIOCGBIT");
852     if (!(evdev_support & (1 << EV_KEY))) {
853       fprintf(stderr, "%s doesn't have keys\n", argv[i]);
854       close(fd);
855       continue;
856     }
857     evdev_fds[evdev_fd_cnt++] = fd;
858   }
859
860   if (logfn != NULL) {
861     logf = fopen(logfn, "wb");
862     if (logf == NULL) {
863       fprintf(stderr, "fopen %s: ", logfn);
864       perror("");
865       return 1;
866     }
867   }
868
869   if (tasfn != NULL) {
870     FILE *f, *f_p2 = NULL;
871     const char *ext;
872     long size;
873
874     f = fopen(tasfn, "rb");
875     if (f == NULL) {
876       fprintf(stderr, "fopen %s: ", tasfn);
877       perror("");
878       return 1;
879     }
880
881     if (tasfn_p2 != NULL) {
882       f_p2 = fopen(tasfn_p2, "rb");
883       if (f_p2 == NULL) {
884         fprintf(stderr, "fopen %s: ", tasfn_p2);
885         perror("");
886         return 1;
887       }
888     }
889
890     fseek(f, 0, SEEK_END);
891     size = ftell(f);
892     fseek(f, 0, SEEK_SET);
893     if (size <= 0) {
894       fprintf(stderr, "bad size: %ld\n", size);
895       return 1;
896     }
897
898     ext = strrchr(tasfn, '.');
899     if (ext == NULL)
900       ext = tasfn;
901     else
902       ext++;
903
904     if (strcasecmp(ext, "gmv") == 0)
905       ret = import_gmv(f, size, tas_data, tas_data_size, logf);
906     else if (strcasecmp(ext, "bkm") == 0)
907       ret = import_bkm(f, tas_data, tas_data_size, logf);
908     else if (strcasecmp(ext, "txt") == 0)
909       ret = import_raw(f, &tas_data[0], &tas_data_size[0], logf);
910     else {
911       fprintf(stderr, "unknown movie type: '%s'\n", ext);
912       return 1;
913     }
914     fclose(f);
915
916     if (ret != 0 || tas_data[0] == NULL || tas_data_size[0] <= 0) {
917       fprintf(stderr, "failed fo parse %s\n", tasfn);
918       return 1;
919     }
920
921     // separate file with p2 input?
922     if (f_p2 != NULL) {
923       ret = import_raw(f_p2, &tas_data[1], &tas_data_size[1], NULL);
924       if (ret != 0 || tas_data[1] == NULL || tas_data_size[1] <= 0) {
925         fprintf(stderr, "failed fo parse %s\n", tasfn_p2);
926         return 1;
927       }
928       fclose(f_p2);
929       separate_2p = 1;
930     }
931
932     if (logf != NULL) {
933       fclose(logf);
934       logf = NULL;
935     }
936
937     if (tas_data_size[1] != 0 && tas_data[1] == NULL) {
938       fprintf(stderr, "missing tas_data[1]\n");
939       return 1;
940     }
941   }
942
943   if (outfn != NULL) {
944     outf = fopen(outfn, "w");
945     if (outf == NULL) {
946       fprintf(stderr, "fopen %s: ", outfn);
947       perror("");
948       return 1;
949     }
950   }
951
952   enable_echo(0);
953   signal(SIGINT, signal_handler);
954
955   dev.fd = -1;
956
957   while (!g_exit || (pending_urbs & (1 << URB_DATA_OUT)))
958   {
959     if (dev.fd == -1) {
960       ret = find_device(&dev, 0x16C0, 0x0486);
961       if (ret < 0)
962         break;
963
964       if (ret == 0) {
965         if (!wait_device) {
966           printf("waiting for device..\n");
967           wait_device = 1;
968         }
969         usleep(250000);
970         continue;
971       }
972
973       wait_device = 0;
974       pending_urbs = 0;
975       enable_sent = 0;
976       bytes_sent[0] = 0;
977       bytes_sent[1] = 0;
978
979       /* we wait first, then send commands, but if teensy
980        * is started already, it won't send anything */
981       tout.tv_sec = 1;
982       tout.tv_usec = 0;
983       timeout = &tout;
984     }
985
986     if (!(pending_urbs & (1 << URB_DATA_IN))) {
987       memset(&pkt_in, 0, sizeof(pkt_in));
988       ret = submit_urb(dev.fd, &urb[URB_DATA_IN], dev.ifaces[0].ep_in,
989                        &pkt_in, sizeof(pkt_in));
990       if (ret != 0) {
991         perror("USBDEVFS_SUBMITURB URB_DATA_IN");
992         break;
993       }
994
995       pending_urbs |= 1 << URB_DATA_IN;
996     }
997     if (!(pending_urbs & (1 << URB_DBG_IN))) {
998       ret = submit_urb(dev.fd, &urb[URB_DBG_IN], dev.ifaces[1].ep_in,
999                        buf_dbg, sizeof(buf_dbg) - 1);
1000       if (ret != 0) {
1001         perror("USBDEVFS_SUBMITURB URB_DBG_IN");
1002         break;
1003       }
1004
1005       pending_urbs |= 1 << URB_DBG_IN;
1006     }
1007
1008     FD_ZERO(&rfds);
1009     FD_SET(STDIN_FILENO, &rfds);
1010     for (i = 0; i < evdev_fd_cnt; i++)
1011       FD_SET(evdev_fds[i], &rfds);
1012
1013     FD_ZERO(&wfds);
1014     FD_SET(dev.fd, &wfds);
1015
1016     ret = select(dev.fd + 1, &rfds, &wfds, NULL, timeout);
1017     if (ret < 0) {
1018       perror("select");
1019       break;
1020     }
1021     timeout = NULL;
1022
1023     /* sometihng form stdin? */
1024     if (FD_ISSET(STDIN_FILENO, &rfds)) {
1025       char c = 0;
1026       ret = read(STDIN_FILENO, &c, 1);
1027       if (ret <= 0) {
1028         perror("read stdin");
1029         break;
1030       }
1031
1032       switch (c) {
1033       case 'r':
1034         enable_sent = 0;
1035         break;
1036       }
1037     }
1038
1039     /* something from input devices? */
1040     for (i = 0; i < evdev_fd_cnt; i++) {
1041       if (FD_ISSET(evdev_fds[i], &rfds)) {
1042         fixed_input_changed |=
1043           do_evdev_input(evdev_fds[i]);
1044       }
1045     }
1046
1047     /* something from USB? */
1048     if (FD_ISSET(dev.fd, &wfds))
1049     {
1050       unsigned int which_urb;
1051
1052       reaped_urb = NULL;
1053       ret = ioctl(dev.fd, USBDEVFS_REAPURB, &reaped_urb);
1054       if (ret != 0) {
1055         if (errno == ENODEV)
1056           goto dev_close;
1057         perror("USBDEVFS_REAPURB");
1058         break;
1059       }
1060       which_urb = reaped_urb - urb;
1061       if (which_urb < ARRAY_SIZE(urb))
1062         pending_urbs &= ~(1 << which_urb);
1063       else {
1064         fprintf(stderr, "reaped unknown urb: %p #%u",
1065                 reaped_urb, which_urb);
1066       }
1067
1068       if (reaped_urb != NULL && reaped_urb->status != 0) {
1069         errno = -reaped_urb->status;
1070         fprintf(stderr, "urb #%u: ", which_urb);
1071         perror("");
1072         if (reaped_urb->status == -EILSEQ) {
1073           /* this is usually a sign of disconnect.. */
1074           usleep(250000);
1075           goto dev_close;
1076         }
1077       }
1078       else if (reaped_urb == &urb[URB_DATA_IN])
1079       {
1080         int p;
1081
1082         /* some request from teensy */
1083         switch (pkt_in.type) {
1084         case PKT_STREAM_REQ:
1085           p = pkt_in.req.is_p2 ? 1 : 0;
1086           printf("req%d: %d/%d/%d\n", pkt_in.req.is_p2,
1087             pkt_in.req.frame * 2, bytes_sent[p], tas_data_size[p]);
1088
1089           pkt_out.size = 0;
1090           if (bytes_sent[p] < tas_data_size[p]) {
1091             pkt_out.type = p ? PKT_STREAM_DATA_TO_P2
1092                              : PKT_STREAM_DATA_TO_P1;
1093
1094             i = tas_data_size[p] - bytes_sent[p];
1095             if (i > sizeof(pkt_out.data))
1096               i = sizeof(pkt_out.data);
1097             memcpy(pkt_out.data, tas_data[p] + bytes_sent[p], i);
1098             bytes_sent[p] += i;
1099             pkt_out.size = i;
1100           }
1101           else {
1102             pkt_out.type = PKT_STREAM_END;
1103           }
1104
1105           ret = submit_urb(dev.fd, &urb[URB_DATA_OUT],
1106                   dev.ifaces[0].ep_out, &pkt_out, sizeof(pkt_out));
1107           if (ret != 0)
1108             perror("USBDEVFS_SUBMITURB PKT_STREAM_DATA_TO");
1109           break;
1110
1111         case PKT_STREAM_DATA_FROM:
1112           printf("f: %d\n", frame_count);
1113           if (pkt_in.size == 0 || pkt_in.size > sizeof(pkt_out.data)) {
1114             printf("host: got bad DATA_FROM size: %u\n", pkt_in.size);
1115             break;
1116           }
1117           for (i = 0; i < pkt_in.size; ) {
1118             i += write_bkm_frame(outf, pkt_in.data + i);
1119             frame_count++;
1120           }
1121           break;
1122
1123         default:
1124           printf("host: got unknown pkt type: %04x\n", pkt_in.type);
1125           break;
1126         }
1127       }
1128       else if (reaped_urb == &urb[URB_DATA_OUT])
1129       {
1130       }
1131       else if (reaped_urb == &urb[URB_DBG_IN])
1132       {
1133         /* debug text */
1134         buf_dbg[reaped_urb->actual_length] = 0;
1135         printf("%s", buf_dbg);
1136
1137         // continue receiving debug before sending out stuff
1138         tout.tv_sec = 0;
1139         tout.tv_usec = 1000;
1140         timeout = &tout;
1141         continue;
1142       }
1143       else {
1144         fprintf(stderr, "reaped unknown urb? %p #%zu\n",
1145           reaped_urb, reaped_urb - urb);
1146       }
1147     }
1148
1149     /* something to send? */
1150     if (pending_urbs & (1 << URB_DATA_OUT))
1151       // can't do that yet
1152       continue;
1153
1154     if ((tas_data[0] != NULL || outf != NULL) && !enable_sent) {
1155       memset(&pkt_out, 0, sizeof(pkt_out));
1156       pkt_out.type = PKT_STREAM_ENABLE;
1157       pkt_out.enable.stream_to = (tas_data[0] != NULL);
1158       pkt_out.enable.stream_from = (outf != NULL);
1159       pkt_out.enable.no_start_seq = no_start_seq;
1160       if (use_vsync)
1161         pkt_out.enable.inc_mode = INC_MODE_VSYNC;
1162       else if (tas_data_size[1] != 0 && separate_2p)
1163         pkt_out.enable.inc_mode = INC_MODE_SEPARATE;
1164       else if (tas_data_size[1] != 0)
1165         pkt_out.enable.inc_mode = INC_MODE_SHARED_PL2;
1166       else
1167         pkt_out.enable.inc_mode = INC_MODE_SHARED_PL1;
1168
1169       ret = submit_urb(dev.fd, &urb[URB_DATA_OUT], dev.ifaces[0].ep_out,
1170                        &pkt_out, sizeof(pkt_out));
1171       if (ret != 0) {
1172         perror("USBDEVFS_SUBMITURB PKT_STREAM_ENABLE");
1173         continue;
1174       }
1175       pending_urbs |= 1 << URB_DATA_OUT;
1176       enable_sent = 1;
1177       bytes_sent[0] = 0;
1178       bytes_sent[1] = 0;
1179       continue;
1180     }
1181     if (tas_data[0] == NULL && fixed_input_changed) {
1182       memset(&pkt_out, 0, sizeof(pkt_out));
1183       pkt_out.type = PKT_FIXED_STATE;
1184       memcpy(pkt_out.data, fixed_input_state, sizeof(fixed_input_state));
1185
1186       ret = submit_urb(dev.fd, &urb[URB_DATA_OUT], dev.ifaces[0].ep_out,
1187                        &pkt_out, sizeof(pkt_out));
1188       if (ret != 0) {
1189         perror("USBDEVFS_SUBMITURB PKT_FIXED_STATE");
1190         break;
1191       }
1192       fixed_input_changed = 0;
1193       pending_urbs |= 1 << URB_DATA_OUT;
1194       continue;
1195     }
1196     if (g_exit && !abort_sent) {
1197       memset(&pkt_out, 0, sizeof(pkt_out));
1198       pkt_out.type = PKT_STREAM_ABORT;
1199
1200       ret = submit_urb(dev.fd, &urb[URB_DATA_OUT], dev.ifaces[0].ep_out,
1201                        &pkt_out, sizeof(pkt_out));
1202       if (ret != 0) {
1203         perror("USBDEVFS_SUBMITURB PKT_STREAM_ABORT");
1204         break;
1205       }
1206       pending_urbs |= 1 << URB_DATA_OUT;
1207       abort_sent = 1;
1208       continue;
1209     }
1210
1211     continue;
1212
1213 dev_close:
1214     close(dev.fd);
1215     dev.fd = -1;
1216   }
1217
1218   enable_echo(1);
1219
1220   if (outf != NULL)
1221     fclose(outf);
1222
1223   if (dev.fd != -1) {
1224     /* deal with pending URBs */
1225     if (pending_urbs & (1 << URB_DATA_IN))
1226       ioctl(dev.fd, USBDEVFS_DISCARDURB, &urb[URB_DATA_IN]);
1227     if (pending_urbs & (1 << URB_DBG_IN))
1228       ioctl(dev.fd, USBDEVFS_DISCARDURB, &urb[URB_DBG_IN]);
1229     for (i = 0; i < URB_CNT; i++) {
1230       if (pending_urbs & (1 << i)) {
1231         ret = ioctl(dev.fd, USBDEVFS_REAPURB, &reaped_urb);
1232         if (ret != 0)
1233           perror("USBDEVFS_REAPURB");
1234       }
1235     }
1236
1237     close(dev.fd);
1238   }
1239
1240   return ret;
1241 }
1242
1243 // vim: ts=2:sw=2:expandtab