support 2nd player streaming from separate raw file
[teensytas.git] / host / main.c
index f8f74c9..bf6966d 100644 (file)
@@ -1,3 +1,28 @@
+/*
+ * TeensyTAS, TAS input player for MegaDrive
+ * Copyright (c) 2014 notaz
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
+ * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
+ * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
@@ -397,6 +422,28 @@ int do_evdev_input(int fd)
   return memcmp(old_state, fixed_input_state, STATE_BYTES) ? 1 : 0;
 }
 
+#define MAX_INPUT_BYTES 2
+
+// TODO: 6btn
+static int tas_data_to_teensy(uint16_t b, uint8_t *data, FILE *logf)
+{
+  uint8_t t;
+
+  /* SCBA RLDU */
+  /*     v     */
+  /* ?0SA 00DU, ?1CB RLDU */
+  data[0] = (b & 0x13) | ((b >> 2) & 0x20);
+  data[1] = (b & 0x0f) | ((b >> 1) & 0x30);
+
+  if (logf != NULL) {
+    fwrite(&data[0], 1, 1, logf);
+    t = data[1] | 0x40; // expected TH
+    fwrite(&t, 1, 1, logf);
+  }
+
+  return 2;
+}
+
 struct gmv_tas {
   char sig[15];
   char ver;
@@ -408,54 +455,59 @@ struct gmv_tas {
   uint8_t data[0][3];
 };
 
-static uint8_t *import_gmv(FILE *f, long size, int *frame_count)
+static int import_gmv(FILE *f, long size,
+  uint8_t *out[2], int out_byte_count[2], FILE *logf)
 {
   struct gmv_tas *gmv;
-  uint8_t *out;
+  int frame_count;
+  int count = 0;
+  uint16_t val;
   int ret;
   int i;
 
+  out_byte_count[0] = out_byte_count[1] = 0;
+
   if (size < (long)sizeof(*gmv)) {
     fprintf(stderr, "bad gmv size: %ld\n", size);
-    return NULL;
+    return -1;
   }
 
   gmv = malloc(size);
   if (gmv == NULL) {
     fprintf(stderr, "OOM?\n");
-    return NULL;
+    return -1;
   }
   ret = fread(gmv, 1, size, f);
   if (ret != size) {
     fprintf(stderr, "fread %d/%ld: ", ret, size);
     perror("");
-    return NULL;
+    return -1;
   }
 
-  *frame_count = (size - sizeof(*gmv)) / sizeof(gmv->data[0]);
+  frame_count = (size - sizeof(*gmv)) / sizeof(gmv->data[0]);
 
   /* check the GMV.. */
-  if (*frame_count <= 0 || size != sizeof(*gmv) + *frame_count * 3) {
-    fprintf(stderr, "broken gmv? frames=%d\n", *frame_count);
-    return NULL;
+  if (frame_count <= 0 || size != sizeof(*gmv) + frame_count * 3) {
+    fprintf(stderr, "broken gmv? frames=%d\n", frame_count);
+    return -1;
   }
 
   if (strncmp(gmv->sig, "Gens Movie TEST", 15) != 0) {
     fprintf(stderr, "bad GMV sig\n");
-    return NULL;
+    return -1;
   }
   if (gmv->ctrl1 != '3') {
     fprintf(stderr, "unhandled controlled config: '%c'\n", gmv->ctrl1);
-    //return NULL;
+    //return -1;
   }
   if (gmv->ver >= 'A') {
     if (gmv->flags & 0x40) {
       fprintf(stderr, "unhandled flag: movie requires a savestate\n");
-      return NULL;
+      return -1;
     }
     if (gmv->flags & 0x20) {
       fprintf(stderr, "unhandled flag: 3-player movie\n");
-      return NULL;
+      return -1;
     }
     if (gmv->flags & ~0x80) {
       //fprintf(stderr, "unhandled flag(s): %04x\n", gmv->flags);
@@ -465,16 +517,17 @@ static uint8_t *import_gmv(FILE *f, long size, int *frame_count)
   gmv->name[39] = 0;
   printf("loaded GMV: %s\n", gmv->name);
   printf("%d frames, %u rerecords\n",
-         *frame_count, gmv->rerecord_count);
+         frame_count, gmv->rerecord_count);
 
-  out = malloc(*frame_count * sizeof(out[0]));
-  if (out == NULL) {
+  out[0] = malloc(frame_count * MAX_INPUT_BYTES);
+  if (out[0] == NULL) {
     fprintf(stderr, "OOM?\n");
-    return NULL;
+    return -1;
   }
 
-  for (i = 0; i < *frame_count; i++) {
-    out[i] = gmv->data[i][0];
+  for (i = 0; i < frame_count; i++) {
+    val = gmv->data[i][0] | ((gmv->data[i][2] & 0x0f) << 8);
+    count += tas_data_to_teensy(val, out[0] + count, logf);
 
     if (gmv->data[i][1] != 0xff || gmv->data[i][2] != 0xff)
     {
@@ -483,10 +536,11 @@ static uint8_t *import_gmv(FILE *f, long size, int *frame_count)
     }
   }
 
-  return out;
+  out_byte_count[0] = count;
+  return 0;
 }
 
-static int do_bkm_char(char c, char expect, uint8_t *val, int bit)
+static int do_bkm_char(char c, char expect, uint16_t *val, int bit)
 {
   if (c == expect) {
     *val &= ~(1 << bit);
@@ -500,18 +554,24 @@ static int do_bkm_char(char c, char expect, uint8_t *val, int bit)
   return 1;
 }
 
-static uint8_t *import_bkm(FILE *f, int *frame_count)
+static int import_bkm(FILE *f, uint8_t *out[2], int out_byte_count[2],
+  FILE *logf)
 {
-  uint8_t *out = NULL, val;
+  int teensy_bytes = 0;
+  int have_pl2 = 0;
+  int have_xyz = 0;
+  int frames = 0;
   int count = 0;
   int alloc = 0;
   int line = 0;
   char buf[256];
   const char *r;
+  uint16_t val;
   char *p;
-  int i;
+  int pl, i;
 
-  while ((p = fgets(buf, sizeof(buf), f)) != NULL) {
+  while ((p = fgets(buf, sizeof(buf), f)) != NULL)
+  {
     line++;
     if (p[0] != '|')
       continue;
@@ -522,41 +582,128 @@ static uint8_t *import_bkm(FILE *f, int *frame_count)
       goto unhandled_line;
     p[30] = 0;
 
-    if (count >= alloc) {
+    if (count >= alloc - MAX_INPUT_BYTES) {
       alloc = alloc * 2 + 64;
-      out = realloc(out, alloc * sizeof(out[0]));
-      if (out == NULL) {
-        fprintf(stderr, "OOM?\n");
-        return NULL;
+      for (pl = 0; pl < 2; pl++) {
+        out[pl] = realloc(out[pl], alloc * sizeof(out[0][0]));
+        if (out[pl] == NULL) {
+          fprintf(stderr, "OOM?\n");
+          return -1;
+        }
       }
     }
 
-    val = 0xff;
-
     if (strncmp(p, "|.|", 3) != 0)
       goto unhandled_line;
     p += 3;
 
-    const char ref[] = "UDLRABCS";
-    for (r = ref, i = 0; *r != 0; p++, r++, i++) {
-      if (do_bkm_char(*p, *r, &val, i))
+    for (pl = 0; pl < 2; pl++) {
+      static const char ref[] = "UDLRABCSXYZM";
+
+      val = 0xfff;
+      for (r = ref, i = 0; *r != 0; p++, r++, i++) {
+        if (do_bkm_char(*p, *r, &val, i))
+          goto unhandled_line;
+      }
+
+      if (*p++ != '|')
         goto unhandled_line;
+
+      teensy_bytes = tas_data_to_teensy(val, out[pl] + count, logf);
+
+      if ((val & 0xf00) != 0xf00)
+        have_xyz = 1;
+      if (pl == 1)
+        have_pl2 |= (val != 0xfff);
     }
+    count += teensy_bytes;
 
-    if (strcmp(p, "....|............||") != 0)
+    if (strcmp(p, "|") != 0)
       goto unhandled_line;
 
-    out[count++] = val;
+    frames++;
     continue;
 
 unhandled_line:
     fprintf(stderr, "unhandled bkm line %d: '%s'\n", line, buf);
-    return NULL;
+    return -1;
+  }
+
+  printf("loaded bkm, %d players, %d frames, %d bytes, have_xyz=%d\n",
+    have_pl2 ? 2 : 1, frames, count, have_xyz);
+  out_byte_count[0] = count;
+  if (have_pl2)
+    out_byte_count[1] = count;
+  else {
+    free(out[1]);
+    out[1] = NULL;
   }
 
-  printf("loaded bkm, %d frames\n", count);
-  *frame_count = count;
-  return out;
+  return 0;
+}
+
+static int import_raw(FILE *f, uint8_t **out, int *out_byte_count,
+  FILE *logf)
+{
+  int count = 0;
+  int alloc = 0;
+  int line = 0;
+  int first = 1;
+  char buf[256];
+  uint8_t val;
+  char *p;
+  int i;
+
+  *out_byte_count = 0;
+
+  while ((p = fgets(buf, sizeof(buf), f)) != NULL)
+  {
+    line++;
+    if (p[0] == '#')
+      continue;
+    if (p[0] != 'e') {
+      printf("skipping: %s", p);
+      continue;
+    }
+
+    val = 0;
+    p++;
+    for (i = 6; i >= 0; i--, p++) {
+      if (*p != '0' && *p != '1')
+        goto bad;
+      if (*p == '1')
+        val |= 1 << i;
+    }
+    if (*p != ' ')
+      goto bad;
+
+    if (first && (val & 0x40))
+      continue; // XXX..
+    first = 0;
+
+    if (count >= alloc) {
+      alloc = alloc * 2 + 64;
+      *out = realloc(*out, alloc * sizeof((*out)[0]));
+      if (*out == NULL) {
+        fprintf(stderr, "OOM?\n");
+        return -1;
+      }
+    }
+
+    if (logf)
+      fwrite(&val, 1, 1, logf);
+
+    (*out)[count++] = val & 0x3f;
+    continue;
+
+bad:
+    fprintf(stderr, "bad raw line %d: '%s'\n", line, buf);
+    return -1;
+  }
+
+  printf("loaded raw, %d bytes\n", count);
+  *out_byte_count = count;
+  return 0;
 }
 
 static int write_bkm_frame(FILE *f, const uint8_t *data)
@@ -587,25 +734,6 @@ out:
   return 2;
 }
 
-static int tas_data_to_teensy(uint8_t b, uint8_t *data, FILE *logf)
-{
-  uint8_t t;
-
-  /* SCBA RLDU */
-  /*     v     */
-  /* ?0SA 00DU, ?1CB RLDU */
-  data[0] = (b & 0x13) | ((b >> 2) & 0x20);
-  data[1] = (b & 0x0f) | ((b >> 1) & 0x30);
-
-  if (logf != NULL) {
-    fwrite(&data[0], 1, 1, logf);
-    t = data[1] | 0x40; // expected TH
-    fwrite(&t, 1, 1, logf);
-  }
-
-  return 2;
-}
-
 static int submit_urb(int fd, struct usbdevfs_urb *urb, int ep,
   void *buf, size_t buf_size)
 {
@@ -636,7 +764,7 @@ int main(int argc, char *argv[])
   struct teensy_dev dev;
   struct usbdevfs_urb urb[URB_CNT];
   struct usbdevfs_urb *reaped_urb;
-  int fixed_input_changed;
+  int fixed_input_changed = 0;
   int evdev_fds[16];
   int evdev_fd_cnt = 0;
   int evdev_support;
@@ -644,15 +772,18 @@ int main(int argc, char *argv[])
   int pending_urbs = 0;
   fd_set rfds, wfds;
   const char *tasfn = NULL;
+  const char *tasfn_p2 = NULL;
   const char *outfn = NULL;
   const char *logfn = NULL;
-  uint8_t *tas_data = NULL;
+  uint8_t *tas_data[2] = { NULL, NULL };
+  int tas_data_size[2] = { 0, 0 };
+  int bytes_sent[2] = { 0, 0 };
   int use_vsync = 0; // frame increment on vsync
-  int tas_skip = 0;
+  int separate_2p = 0;
+  int no_start_seq = 0;
   int enable_sent = 0;
   int abort_sent = 0;
   int frame_count = 0;
-  int frames_sent = 0;
   char buf_dbg[64 + 1];
   struct tas_pkt pkt_in;
   struct tas_pkt pkt_out;
@@ -672,27 +803,30 @@ int main(int argc, char *argv[])
           missing_arg(i);
         tasfn = argv[i];
         continue;
-      case 'w':
+      case '2':
         i++;
         if (argv[i] == NULL)
           missing_arg(i);
-        outfn = argv[i];
+        tasfn_p2 = argv[i];
         continue;
-      case 'l':
+      case 'w':
         i++;
         if (argv[i] == NULL)
           missing_arg(i);
-        logfn = argv[i];
+        outfn = argv[i];
         continue;
-      case 's':
+      case 'l':
         i++;
         if (argv[i] == NULL)
           missing_arg(i);
-        tas_skip = atoi(argv[i]);
+        logfn = argv[i];
         continue;
       case 'v':
         use_vsync = 1;
         continue;
+      case 'n':
+        no_start_seq = 1;
+        continue;
       default:
         fprintf(stderr, "bad arg: %s\n", argv[i]);
         return 1;
@@ -723,10 +857,19 @@ int main(int argc, char *argv[])
     evdev_fds[evdev_fd_cnt++] = fd;
   }
 
+  if (logfn != NULL) {
+    logf = fopen(logfn, "wb");
+    if (logf == NULL) {
+      fprintf(stderr, "fopen %s: ", logfn);
+      perror("");
+      return 1;
+    }
+  }
+
   if (tasfn != NULL) {
+    FILE *f, *f_p2 = NULL;
     const char *ext;
     long size;
-    FILE *f;
 
     f = fopen(tasfn, "rb");
     if (f == NULL) {
@@ -735,6 +878,15 @@ int main(int argc, char *argv[])
       return 1;
     }
 
+    if (tasfn_p2 != NULL) {
+      f_p2 = fopen(tasfn_p2, "rb");
+      if (f_p2 == NULL) {
+        fprintf(stderr, "fopen %s: ", tasfn_p2);
+        perror("");
+        return 1;
+      }
+    }
+
     fseek(f, 0, SEEK_END);
     size = ftell(f);
     fseek(f, 0, SEEK_SET);
@@ -750,42 +902,41 @@ int main(int argc, char *argv[])
       ext++;
 
     if (strcasecmp(ext, "gmv") == 0)
-      tas_data = import_gmv(f, size, &frame_count);
+      ret = import_gmv(f, size, tas_data, tas_data_size, logf);
     else if (strcasecmp(ext, "bkm") == 0)
-      tas_data = import_bkm(f, &frame_count);
+      ret = import_bkm(f, tas_data, tas_data_size, logf);
+    else if (strcasecmp(ext, "txt") == 0)
+      ret = import_raw(f, &tas_data[0], &tas_data_size[0], logf);
     else {
       fprintf(stderr, "unknown movie type: '%s'\n", ext);
       return 1;
     }
     fclose(f);
 
-    if (tas_data == NULL) {
+    if (ret != 0 || tas_data[0] == NULL || tas_data_size[0] <= 0) {
       fprintf(stderr, "failed fo parse %s\n", tasfn);
       return 1;
     }
 
-    if (tas_skip != 0) {
-      if (tas_skip >= frame_count || tas_skip <= -frame_count) {
-        printf("skip out of range: %d/%d\n", tas_skip, frame_count);
+    // separate file with p2 input?
+    if (f_p2 != NULL) {
+      ret = import_raw(f_p2, &tas_data[1], &tas_data_size[1], NULL);
+      if (ret != 0 || tas_data[1] == NULL || tas_data_size[1] <= 0) {
+        fprintf(stderr, "failed fo parse %s\n", tasfn_p2);
         return 1;
       }
-      if (tas_skip > 0) {
-        frame_count -= tas_skip;
-        memmove(&tas_data[0], &tas_data[tas_skip],
-          sizeof(tas_data[0]) * frame_count);
-      }
-      else {
-        tas_data = realloc(tas_data,
-                     (frame_count - tas_skip) * sizeof(tas_data[0]));
-        if (tas_data == NULL) {
-          fprintf(stderr, "OOM?\n");
-          return 1;
-        }
-        memmove(&tas_data[-tas_skip], &tas_data[0],
-          sizeof(tas_data[0]) * frame_count);
-        memset(&tas_data[0], 0xff, sizeof(tas_data[0]) * -tas_skip);
-        frame_count -= tas_skip;
-      }
+      fclose(f_p2);
+      separate_2p = 1;
+    }
+
+    if (logf != NULL) {
+      fclose(logf);
+      logf = NULL;
+    }
+
+    if (tas_data_size[1] != 0 && tas_data[1] == NULL) {
+      fprintf(stderr, "missing tas_data[1]\n");
+      return 1;
     }
   }
 
@@ -798,15 +949,6 @@ int main(int argc, char *argv[])
     }
   }
 
-  if (logfn != NULL) {
-    logf = fopen(logfn, "wb");
-    if (logf == NULL) {
-      fprintf(stderr, "fopen %s: ", logfn);
-      perror("");
-      return 1;
-    }
-  }
-
   enable_echo(0);
   signal(SIGINT, signal_handler);
 
@@ -831,7 +973,8 @@ int main(int argc, char *argv[])
       wait_device = 0;
       pending_urbs = 0;
       enable_sent = 0;
-      frames_sent = 0;
+      bytes_sent[0] = 0;
+      bytes_sent[1] = 0;
 
       /* we wait first, then send commands, but if teensy
        * is started already, it won't send anything */
@@ -889,14 +1032,11 @@ int main(int argc, char *argv[])
       switch (c) {
       case 'r':
         enable_sent = 0;
-        if (logf != NULL)
-          rewind(logf);
         break;
       }
     }
 
     /* something from input devices? */
-    fixed_input_changed = 0;
     for (i = 0; i < evdev_fd_cnt; i++) {
       if (FD_ISSET(evdev_fds[i], &rfds)) {
         fixed_input_changed |=
@@ -937,30 +1077,29 @@ int main(int argc, char *argv[])
       }
       else if (reaped_urb == &urb[URB_DATA_IN])
       {
+        int p;
+
         /* some request from teensy */
         switch (pkt_in.type) {
         case PKT_STREAM_REQ:
-          printf("req: %d/%d/%d\n", pkt_in.req.frame,
-            frames_sent, frame_count);
+          p = pkt_in.req.is_p2 ? 1 : 0;
+          printf("req%d: %d/%d/%d\n", pkt_in.req.is_p2,
+            pkt_in.req.frame * 2, bytes_sent[p], tas_data_size[p]);
 
           pkt_out.size = 0;
-          if (frames_sent < frame_count) {
-            pkt_out.type = PKT_STREAM_DATA_TO;
-
-            for (i = 0; i < sizeof(pkt_out.data); ) {
-              i += tas_data_to_teensy(tas_data[frames_sent],
-                     pkt_out.data + i, logf);
-
-              frames_sent++;
-              if (frames_sent >= frame_count)
-                break;
-            }
+          if (bytes_sent[p] < tas_data_size[p]) {
+            pkt_out.type = p ? PKT_STREAM_DATA_TO_P2
+                             : PKT_STREAM_DATA_TO_P1;
+
+            i = tas_data_size[p] - bytes_sent[p];
+            if (i > sizeof(pkt_out.data))
+              i = sizeof(pkt_out.data);
+            memcpy(pkt_out.data, tas_data[p] + bytes_sent[p], i);
+            bytes_sent[p] += i;
             pkt_out.size = i;
           }
           else {
             pkt_out.type = PKT_STREAM_END;
-            if (logf != NULL)
-              fflush(logf);
           }
 
           ret = submit_urb(dev.fd, &urb[URB_DATA_OUT],
@@ -1012,12 +1151,20 @@ int main(int argc, char *argv[])
       // can't do that yet
       continue;
 
-    if ((tas_data != NULL || outf != NULL) && !enable_sent) {
+    if ((tas_data[0] != NULL || outf != NULL) && !enable_sent) {
       memset(&pkt_out, 0, sizeof(pkt_out));
       pkt_out.type = PKT_STREAM_ENABLE;
-      pkt_out.enable.stream_to = (tas_data != NULL);
+      pkt_out.enable.stream_to = (tas_data[0] != NULL);
       pkt_out.enable.stream_from = (outf != NULL);
-      pkt_out.enable.use_readinc = !use_vsync;
+      pkt_out.enable.no_start_seq = no_start_seq;
+      if (use_vsync)
+        pkt_out.enable.inc_mode = INC_MODE_VSYNC;
+      else if (tas_data_size[1] != 0 && separate_2p)
+        pkt_out.enable.inc_mode = INC_MODE_SEPARATE;
+      else if (tas_data_size[1] != 0)
+        pkt_out.enable.inc_mode = INC_MODE_SHARED_PL2;
+      else
+        pkt_out.enable.inc_mode = INC_MODE_SHARED_PL1;
 
       ret = submit_urb(dev.fd, &urb[URB_DATA_OUT], dev.ifaces[0].ep_out,
                        &pkt_out, sizeof(pkt_out));
@@ -1027,10 +1174,11 @@ int main(int argc, char *argv[])
       }
       pending_urbs |= 1 << URB_DATA_OUT;
       enable_sent = 1;
-      frames_sent = 0;
+      bytes_sent[0] = 0;
+      bytes_sent[1] = 0;
       continue;
     }
-    if (tas_data == NULL && fixed_input_changed) {
+    if (tas_data[0] == NULL && fixed_input_changed) {
       memset(&pkt_out, 0, sizeof(pkt_out));
       pkt_out.type = PKT_FIXED_STATE;
       memcpy(pkt_out.data, fixed_input_state, sizeof(fixed_input_state));
@@ -1041,6 +1189,7 @@ int main(int argc, char *argv[])
         perror("USBDEVFS_SUBMITURB PKT_FIXED_STATE");
         break;
       }
+      fixed_input_changed = 0;
       pending_urbs |= 1 << URB_DATA_OUT;
       continue;
     }
@@ -1070,8 +1219,6 @@ dev_close:
 
   if (outf != NULL)
     fclose(outf);
-  if (logf != NULL)
-    fclose(logf);
 
   if (dev.fd != -1) {
     /* deal with pending URBs */