some movies fixed
[fceu.git] / movie.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4 #include <unistd.h>
5 #ifdef WIN32
6 #include <windows.h>
7 #endif
8
9 #include "types.h"
10 #include "endian.h"
11 #include "input.h"
12 #include "fce.h"
13 #include "svga.h"
14 //#include "palette.h"
15 #include "driver.h"
16 #include "state.h"
17 #include "general.h"
18 #include "video.h"
19 #include "file.h"
20 #include "movie.h"
21
22 #define MOVIE_MAGIC             0x1a4d4346      // FCM\x1a
23 #define MOVIE_VERSION           2 // still at 2 since the format itself is still compatible - to detect which version the movie was made with, check the fceu version stored in the movie header (e.g against FCEU_VERSION_NUMERIC)
24
25 #define MOVIE_FLAG_NOSYNCHACK          (1<<4) // set in newer version, used for old movie compatibility
26
27
28 #define read32le read32
29
30 typedef struct
31 {
32  int    movie_version;                                  // version of the movie format in the file
33  uint32 num_frames;
34  uint32 rerecord_count;
35  uint8  flags;
36  int    read_only;
37  uint32 emu_version_used;                               // 9813 = 0.98.13
38  char*  metadata;                                               // caller-supplied buffer to store metadata.  can be NULL.
39  int    metadata_size;                                  // size of the buffer pointed to by metadata
40  uint8  md5_of_rom_used[16];
41  int    md5_of_rom_used_present;                // v1 movies don't have md5 info available
42  char*  name_of_rom_used;                               // caller-supplied buffer to store metadata.  can be NULL.
43  int    name_of_rom_used_size;                  // size of the buffer pointer to by name_of_rom_used
44 } MOVIE_INFO;
45
46
47
48 // backwards compat
49 static void FCEUI_LoadMovie_v1(char *fname, int _read_only);
50 //static int FCEUI_MovieGetInfo_v1(const char* fname, MOVIE_INFO* info);
51
52 extern char FileBase[];
53
54 /*
55 struct MovieHeader
56 {
57  uint32 magic;                                          // +0
58  uint32 version=2;                                      // +4
59  uint8 flags[4];                                        // +8
60  uint32 length_frames;                          // +12
61  uint32 rerecord_count;                         // +16
62  uint32 movie_data_size;                        // +20
63  uint32 offset_to_savestate;            // +24, should be 4-byte-aligned
64  uint32 offset_to_movie_data;           // +28, should be 4-byte-aligned
65  uint8 md5_of_rom_used[16];                     // +32
66  uint32 version_of_emu_used                     // +48
67  char name_of_rom_used[]                        // +52, utf-8, null-terminated
68  char metadata[];                                       //      utf-8, null-terminated
69  uint8 padding[];
70  uint8 savestate[];                                     //      always present, even in a "from reset" recording
71  uint8 padding[];                                       //      used for byte-alignment
72  uint8 movie_data[];
73 }
74 */
75
76 //static
77 int current = 0;     // > 0 for recording, < 0 for playback
78 static FILE *slots[10]={0};
79 static uint8 joop[4];
80 static uint32 framets = 0;
81 static uint32 frameptr = 0;
82 static uint8* moviedata = NULL;
83 static uint32 moviedatasize = 0;
84 static uint32 firstframeoffset = 0;
85 static uint32 savestate_offset = 0;
86 /*static*/ uint32 framecount = 0;
87 static uint32 rerecord_count = 0;
88 /*static*/ int movie_readonly = 1;
89 int frame_display = 0;
90 //static uint32 last_frame_display = ~0;
91 int input_display = 0;
92 static uint32 cur_input_display = 0;
93 //static uint32 last_input_display = ~0;
94
95 int resetDMCacc=0;
96
97 /* Cache variables used for playback. */
98 static uint32 nextts = 0;
99 static int32 nextd = 0;
100
101 #define FCEUSTATE_RLSB            0x80000000
102
103 SFORMAT FCEUMOV_STATEINFO[]={
104  { joop, 4,"JOOP"},
105  { &framets, 4|FCEUSTATE_RLSB, "FTS "},
106  { &nextts, 4|FCEUSTATE_RLSB, "NXTS"},
107  { &nextd, 4|FCEUSTATE_RLSB, "NXTD"},
108  { &frameptr, 4|FCEUSTATE_RLSB, "FPTR"},
109  { &framecount, 4|FCEUSTATE_RLSB, "FCNT"},
110
111  { 0 }
112 };
113
114 static int CurrentMovie = 1;
115 //static int MovieShow = 0;
116
117 static int MovieStatus[10];
118
119 //static void DoEncode(int joy, int button, int);
120
121 int FCEUMOV_IsPlaying(void)
122 {
123  if(current < 0) return(1);
124  else return(0);
125 }
126
127 int FCEUMOV_IsRecording(void)
128 {
129  if(current > 0) return(1);
130  else return(0);
131 }
132
133 int suppressMovieStop=0;
134 int movieConvertOffset1=0, movieConvertOffset2=0,movieConvertOK=0,movieSyncHackOn=0;
135
136 static void StopPlayback(void)
137 {
138   if(suppressMovieStop)
139    return;
140   resetDMCacc=movieSyncHackOn=0;
141   fclose(slots[-1 - current]);
142   current=0;
143   FCEU_DispMessage("Movie playback stopped.");
144 }
145
146 #if 0
147 static void FlushHeader(void)
148 {
149         if(current <= 0)
150                 return;// only write header data if recording
151
152         FILE* fp = slots[current - 1];
153         if(fp == 0)
154                 return;
155
156         unsigned long loc = ftell(fp);
157         fseek(fp, 4, SEEK_SET);
158         write32le(MOVIE_VERSION, fp);
159         fseek(fp, 12, SEEK_SET);
160         write32le(framecount, fp);
161         write32le(rerecord_count, fp);
162         write32le(frameptr, fp);
163         fseek(fp, 32, SEEK_SET);
164         fwrite(FCEUGameInfo->MD5, 1, 16, fp);   // write ROM checksum
165         write32le(FCEU_VERSION_NUMERIC, fp);    // write emu version used
166
167         // write ROM name used
168         fseek(fp, 52, SEEK_SET);
169         char str[512];
170         fgets(str,512,fp);
171         str[511]='\0';
172         int strdiff=strlen(FileBase)-strlen(str);
173         if(strdiff)
174         {
175                 // resize the whole damn movie because the ROM name in the header is of variable length
176                 int off=52;
177                 fseek(fp, 52, SEEK_SET);
178                 do { off++;
179                 } while(fgetc(fp) && !feof(fp) && !ferror(fp));
180
181                 if(feof(fp) || ferror(fp))
182                 {
183                         fseek(fp, loc, SEEK_SET);
184                         return;
185                 }
186
187                 fseek(fp, 0, SEEK_END);
188                 uint32 fsize=ftell(fp)-off;
189                 char* ctemp=(char*)FCEU_malloc(fsize*sizeof(char)+4);
190                 if(!ctemp)
191                 {
192                         fseek(fp, loc, SEEK_SET);
193                         return;
194                 }
195                 fseek(fp, off, SEEK_SET);
196                 fread(ctemp, 1,fsize, fp);
197                 fseek(fp, 52+strlen(FileBase)+1, SEEK_SET);
198                 int wrote = fwrite(ctemp, fsize,1, fp);
199                 FCEU_free(ctemp);
200                 if(!wrote)
201                 {
202                         fseek(fp, loc, SEEK_SET);
203                         return;
204                 }
205
206                 if(loc >= firstframeoffset)
207                         loc += strdiff;
208                 savestate_offset += strdiff;
209                 firstframeoffset += strdiff;
210                 fseek(fp, 24, SEEK_SET);
211                 write32le(savestate_offset, fp);
212                 write32le(firstframeoffset, fp);
213         }
214         fseek(fp, 52, SEEK_SET);
215         fputs(FileBase, fp);
216         fputc('\0', fp);
217
218         fseek(fp, loc, SEEK_SET);
219 }
220
221 static void StopRecording(void)
222 {
223   if(suppressMovieStop)
224    return;
225   resetDMCacc=movieSyncHackOn=0;
226  DoEncode(0,0,1);   /* Write a dummy timestamp value so that the movie will keep
227                        "playing" after user input has stopped. */
228  // finish header
229  FlushHeader();
230
231  // FIXME:  truncate movie to length
232  // ftruncate();
233  fclose(slots[current - 1]);
234  MovieStatus[current - 1] = 1;
235  current=0;
236  FCEU_DispMessage("Movie recording stopped.");
237 }
238 #endif
239
240 void FCEUI_StopMovie(void)
241 {
242  if(current < 0) StopPlayback();
243 #if 0
244  if(current > 0) StopRecording();
245 #endif
246 }
247
248 #ifdef WIN32
249 #include "process.h"
250 void executeCommand(const char* cmd)
251 {
252         if(!cmd || !*cmd)
253                 return;
254
255         const char *argv[4];
256         argv[0] = getenv("COMSPEC");
257         argv[1] = "/c";
258         argv[2] = cmd;
259         argv[3] = NULL;
260         if(*argv && *(*argv))
261                 _spawnve(_P_WAIT, argv[0], argv, NULL);
262 }
263 #endif
264
265 int justAutoConverted=0;
266 static const char* convertToFCM(const char *fname, char *buffer)
267 {
268 #ifdef WIN32
269         justAutoConverted=0;
270
271         // convert to fcm if not already
272         const char* dot = strrchr(fname, '.');
273         if(dot)
274         {
275                 int fmv = !stricmp(dot, ".fmv");
276                 int nmv = !stricmp(dot, ".nmv");
277                 int vmv = !stricmp(dot, ".vmv");
278                 if(fmv || nmv || vmv)
279                 {
280                         strcpy(buffer, fname);
281                         buffer[dot-fname]='\0';
282                         strcat(buffer,"-autoconverted.fcm");
283
284                         int fceuver=0;
285                         if(fmv)
286                                 fceuver=1;
287                         else if(nmv)
288                                 fceuver=2;
289                         else if(vmv)
290                                 fceuver=3;
291
292                         extern char lastLoadedGameName [2048];
293                         char cmd [1024], offset[64], romInfo[1024];
294                         if(movieConvertOK)
295                                 sprintf(romInfo, "-smd5=\"%s\" -sromname=\"%s (MAYBE)\" -s", lastLoadedGameName, FileBase);
296                         else
297                                 sprintf(romInfo, "-sromname=\"(unknown)\" -s");
298                         if(movieConvertOffset2) sprintf(offset, "-o %d:%d", movieConvertOffset2,movieConvertOffset1);
299                         else sprintf(offset, "-o %d", movieConvertOffset1);
300                         sprintf(cmd, ".\\util\\nesmock\\nesmock.exe %s %s -spal=%c -sfceuver=%d \"%s\" \"%s\" ", offset, romInfo, FCEUI_GetCurrentVidSystem(0,0)?'1':'0', fceuver, fname, buffer);
301 //                              FCEU_PrintError(cmd);
302                         executeCommand(cmd);
303
304                         FILE* file = FCEUD_UTF8fopen(buffer,"rb");
305                         if(file)
306                         {
307                                 fseek(file, 12, SEEK_SET);
308                                 int frames=0;
309                                 read32le(&frames, file);
310                                 if(frames)
311                                 {
312                                         fname = buffer;
313                                         justAutoConverted=1;
314                                 }
315                                 else
316                                 {
317                                         static int errAlready=0;
318                                         if(!errAlready)
319                                         {
320                                                 errAlready=1;
321                                                 FCEU_PrintError("For some reason, nesmock was unable to create a valid FCM from the given file.\nThe command given was:\n%s\nPerhaps the file specified is not a movie file or contains no input data,\nor perhaps it is a movie file of a version unsupported by nesmock.\n\n(This error message will self-destruct until you restart FCEU.)", cmd);
322                                         }
323                                 }
324                                 fclose(file);
325                         }
326                         else
327                         {
328                                 char str [512];
329                                 str[0] = '\0';
330                                 GetCurrentDirectory(512,str);
331                                 strcat(str, "\\util\\nesmock\\nesmock.exe");
332                                 file = FCEUD_UTF8fopen(str, "rb");
333                                 if(file)
334                                 {
335                                         static int errAlready=0;
336                                         if(!errAlready)
337                                         {
338                                                 errAlready=1;
339                                                 FCEU_PrintError("For some reason, nesmock was unable to convert the movie to FCM format.\nThe command given was:\n%s\n\n(This error message will self-destruct until you restart FCEU.)", cmd);
340                                                 fclose(file);
341                                         }
342                                 }
343                                 else
344                                 {
345                                         static int errAlready=0;
346                                         if(!errAlready)
347                                         {
348                                                 errAlready=1;
349                                                 FCEU_PrintError("Nesmock not found, so the movie could not be converted to FCM format.\nYou must place nesmock.exe at this location so FCEU can find it:\n%s\n\n(This error message will self-destruct until you restart FCEU.)", str);
350                                         }
351                                 }
352                         }
353                 }
354         }
355 #endif
356         return fname;
357 }
358
359 static void ResetInputTypes()
360 {
361 #ifdef WIN32
362  extern int UsrInputType[3];
363  UsrInputType[0] = SI_GAMEPAD;
364  UsrInputType[1] = SI_GAMEPAD;
365  UsrInputType[2] = SIFC_NONE;
366
367  ParseGIInput(NULL/*FCEUGameInfo*/);
368  extern int cspec, gametype;
369  cspec=FCEUGameInfo->cspecial;
370  gametype=FCEUGameInfo->type;
371
372  InitOtherInput();
373 #endif
374 }
375
376 char curMovieFilename[512];
377
378
379 // PlayMovie / MoviePlay function
380 void FCEUI_LoadMovie(char *fname, int _read_only)
381 {
382  char buffer [512];
383  fname = (char*)convertToFCM(fname,buffer);
384
385  FILE *fp;
386  char *fn = NULL;
387
388  FCEUI_StopMovie();
389
390 #if 0
391  if(!fname)
392   fname = fn = FCEU_MakeFName(FCEUMKF_MOVIE,CurrentMovie,0);
393 #endif
394
395 #if 0
396 char origname[512];
397 strcpy(origname,fname);
398 #endif
399
400  // check movie_readonly
401  movie_readonly = _read_only;
402  if(access(fname, W_OK))
403   movie_readonly = 2;
404
405  fp = fopen(fname, (movie_readonly>=2) ? "rb" : "r+b");
406
407  if(fn)
408  {
409   free(fn);
410   fname = NULL;
411  }
412
413  if(!fp) return;
414
415  // read header
416  {
417   uint32 magic;
418   uint32 version;
419   uint8 flags[4];
420
421   read32le(&magic, fp);
422   if(magic != MOVIE_MAGIC)
423   {
424    fclose(fp);
425    return;
426   }
427 //DEBUG_COMPARE_RAM(__LINE__);
428
429   read32le(&version, fp);
430   if(version == 1)
431   {
432           // attempt to load previous version's format
433           fclose(fp);
434           printf("trying movie v1\n");
435           FCEUI_LoadMovie_v1(fname, _read_only);
436           return;
437   }
438   else if(version == MOVIE_VERSION)
439   {}
440   else
441   {
442           // unsupported version
443           fclose(fp);
444           return;
445   }
446
447   fread(flags, 1, 4, fp);
448   read32le(&framecount, fp);
449   read32le(&rerecord_count, fp);
450   read32le(&moviedatasize, fp);
451   read32le(&savestate_offset, fp);
452   read32le(&firstframeoffset, fp);
453   if(fseek(fp, savestate_offset, SEEK_SET))
454   {
455    fclose(fp);
456    return;
457   }
458
459 //  FCEU_PrintError("flags[0] & MOVIE_FLAG_NOSYNCHACK=%d",flags[0] & MOVIE_FLAG_NOSYNCHACK);
460   if(flags[0] & MOVIE_FLAG_NOSYNCHACK)
461           movieSyncHackOn=0;
462   else
463           movieSyncHackOn=1;
464  }
465
466  // fully reload the game to reinitialize everything before playing any movie
467  // to try fixing nondeterministic playback of some games
468 #if 0 // do we need this?
469  {
470         extern char lastLoadedGameName [2048];
471 #if 0 // TODO?
472         extern int disableBatteryLoading, suppressAddPowerCommand;
473         suppressAddPowerCommand=1;
474         suppressMovieStop=1;
475 #endif
476         {
477                 FCEUGI * gi = FCEUI_LoadGame(lastLoadedGameName);
478                 if(!gi)
479                         PowerNES();
480         }
481 #if 0 // TODO?
482         suppressMovieStop=0;
483         suppressAddPowerCommand=0;
484 #endif
485  }
486 #endif
487
488  if(!FCEUSS_LoadFP(fp,1)) return;
489
490  ResetInputTypes();
491
492  fseek(fp, firstframeoffset, SEEK_SET);
493  moviedata = (uint8*)realloc(moviedata, moviedatasize);
494  fread(moviedata, 1, moviedatasize, fp);
495
496  framecount = 0;                // movies start at frame 0!
497  frameptr = 0;
498  current = CurrentMovie;
499  slots[current] = fp;
500
501  memset(joop,0,sizeof(joop));
502  current = -1 - current;
503  framets=0;
504  nextts=0;
505  nextd = -1;
506
507  MovieStatus[CurrentMovie] = 1;
508 #if 0
509  if(!fname)
510   FCEUI_SelectMovie(CurrentMovie,1);       /* Quick hack to display status. */
511  else
512 #endif
513   FCEU_DispMessage("Movie playback started.");
514
515 #if 0
516  strcpy(curMovieFilename, origname);
517 #else
518  strcpy(curMovieFilename, fname);
519 #endif
520 }
521
522 #if 0
523 void FCEUI_SaveMovie(char *fname, uint8 flags, const char* metadata)
524 {
525  FILE *fp;
526  char *fn;
527  int poweron=0;
528  uint8 padding[4] = {0,0,0,0};
529  int n_padding;
530
531  FCEUI_StopMovie();
532
533  char origname[512];
534  if(fname)
535  {
536   fp = FCEUD_UTF8fopen(fname, "wb");
537   strcpy(origname,fname);
538  }
539  else
540  {
541   fp=FCEUD_UTF8fopen(fn=FCEU_MakeFName(FCEUMKF_MOVIE,CurrentMovie,0),"wb");
542   strcpy(origname,fn);
543   free(fn);
544  }
545
546  if(!fp) return;
547
548  // don't need the movieSyncHackOn sync hack for newly recorded movies
549  flags |= MOVIE_FLAG_NOSYNCHACK;
550  resetDMCacc=movieSyncHackOn=0;
551
552  // add PAL flag
553  if(FCEUI_GetCurrentVidSystem(0,0))
554   flags |= MOVIE_FLAG_PAL;
555
556  if(flags & MOVIE_FLAG_FROM_POWERON)
557  {
558          poweron=1;
559          flags &= ~MOVIE_FLAG_FROM_POWERON;
560          flags |= MOVIE_FLAG_FROM_RESET;
561  }
562
563  // write header
564  write32le(MOVIE_MAGIC, fp);
565  write32le(MOVIE_VERSION, fp);
566  fputc(flags, fp);
567  fputc(0, fp);                      // reserved
568  fputc(0, fp);                      // reserved
569  fputc(0, fp);                      // reserved
570  write32le(0, fp);                  // leave room for length frames
571  write32le(0, fp);                  // leave room for rerecord count
572  write32le(0, fp);                  // leave room for movie data size
573  write32le(0, fp);                  // leave room for savestate_offset
574  write32le(0, fp);                  // leave room for offset_to_controller_data
575  fwrite(FCEUGameInfo->MD5, 1, 16, fp);  // write ROM checksum
576  write32le(FCEU_VERSION_NUMERIC, fp);   // write emu version used
577  fputs(FileBase, fp);                                   // write ROM name used
578  fputc(0, fp);
579  if(metadata)
580  {
581   if(strlen(metadata) < MOVIE_MAX_METADATA)
582    fputs(metadata, fp);
583   else
584    fwrite(metadata, 1, MOVIE_MAX_METADATA-1, fp);
585  }
586  fputc(0, fp);
587
588  // add padding
589  n_padding = (4 - (ftell(fp) & 0x3)) & 0x3;
590  fwrite(padding, 1, n_padding, fp);
591
592  if(flags & MOVIE_FLAG_FROM_RESET)
593  {
594          if(poweron)
595          {
596                 // make a for-movie-recording power-on clear the game's save data, too
597                 // (note: FCEU makes a save state immediately after this and that loads that on movie playback)
598                 extern char lastLoadedGameName [2048];
599                 extern int disableBatteryLoading, suppressAddPowerCommand;
600                 suppressAddPowerCommand=1;
601                 disableBatteryLoading=1;
602                 suppressMovieStop=1;
603                 {
604                         // NOTE:  this will NOT write an FCEUNPCMD_POWER into the movie file
605                         FCEUGI * gi = FCEUI_LoadGame(lastLoadedGameName);
606                         if(!gi)
607                                 PowerNES(); // and neither will this, if it can even happen
608                 }
609                 suppressMovieStop=0;
610                 disableBatteryLoading=0;
611                 suppressAddPowerCommand=0;
612          }
613  }
614
615  savestate_offset = ftell(fp);
616  FCEUSS_SaveFP(fp);
617  fseek(fp, 0, SEEK_END);
618
619  ResetInputTypes();
620
621  // add padding
622  n_padding = (4 - (ftell(fp) & 0x3)) & 0x3;
623  fwrite(padding, 1, n_padding, fp);
624
625  firstframeoffset = ftell(fp);
626
627  // finish header
628  fseek(fp, 24, SEEK_SET);                       // offset_to_savestate offset
629  write32le(savestate_offset, fp);
630  write32le(firstframeoffset, fp);
631
632  fseek(fp, firstframeoffset, SEEK_SET);
633
634  // set recording flag
635  current=CurrentMovie;
636
637  movie_readonly = 0;
638  frameptr = 0;
639  framecount = 0;
640  rerecord_count = 0;
641  slots[current] = fp;
642  memset(joop,0,sizeof(joop));
643  current++;
644  framets=0;
645  nextd = -1;
646
647  // trigger a reset
648  if(flags & MOVIE_FLAG_FROM_RESET)
649  {
650          if(poweron)
651          {
652                 PowerNES();                                                     // NOTE:  this will write an FCEUNPCMD_POWER into the movie file
653          }
654          else
655                 ResetNES();                                                     // NOTE:  this will write an FCEUNPCMD_RESET into the movie file
656  }
657  if(!fname)
658   FCEUI_SelectMovie(CurrentMovie,1);       /* Quick hack to display status. */
659  else
660   FCEU_DispMessage("Movie recording started.");
661
662  strcpy(curMovieFilename, origname);
663 }
664
665 static void movie_writechar(int c)
666 {
667  if(frameptr == moviedatasize)
668  {
669   moviedatasize += 4096;
670   moviedata = (uint8*)realloc(moviedata, moviedatasize);
671  }
672  moviedata[frameptr++] = (uint8)(c & 0xff);
673  fputc(c, slots[current - 1]);
674 }
675 #endif
676
677 static int movie_readchar()
678 {
679  if(frameptr >= moviedatasize)
680  {
681   return -1;
682  }
683  return (int)(moviedata[frameptr++]);
684 }
685
686 #if 0
687 static void DoEncode(int joy, int button, int dummy)
688 {
689  uint8 d;
690
691  d = 0;
692
693  if(framets >= 65536)
694   d = 3 << 5;
695  else if(framets >= 256)
696   d = 2 << 5;
697  else if(framets > 0)
698   d = 1 << 5;
699
700  if(dummy) d|=0x80;
701
702  d |= joy << 3;
703  d |= button;
704
705  movie_writechar(d);
706  //printf("Wr: %02x, %d\n",d,slots[current-1]);
707  while(framets)
708  {
709   movie_writechar(framets & 0xff);
710   //printf("Wrts: %02x\n",framets & 0xff);
711   framets >>= 8;
712  }
713 }
714 #endif
715
716 // TODO: make this function legible! (what are all these magic numbers and weirdly named variables and crazy unexplained loops?)
717 void FCEUMOV_AddJoy(uint8 *js)
718 {
719 // int x,y;
720
721  if(!current) return;   // Not playback nor recording.
722
723  if(current < 0)    // Playback
724  {
725   while(nextts == framets || nextd == -1)
726   {
727    int tmp,ti;
728    uint8 d;
729
730    if(nextd != -1)
731    {
732     if(nextd&0x80)
733     {
734     //puts("Egads");
735      FCEU_DoSimpleCommand(nextd&0x1F);
736     }
737     else
738      joop[(nextd >> 3)&0x3] ^= 1 << (nextd&0x7);
739    }
740
741
742    tmp = movie_readchar();
743    d = tmp;
744
745    if(tmp < 0)
746    {
747     StopPlayback();
748     memcpy(&cur_input_display,js,4);
749     return;
750    }
751
752    nextts = 0;
753    tmp >>= 5;
754    tmp &= 0x3;
755    ti=0;
756
757    int tmpfix = tmp;
758    while(tmp--) { nextts |= movie_readchar() << (ti * 8); ti++; }
759
760    // This fixes a bug in movies recorded before version 0.98.11
761    // It's probably not necessary, but it may keep away CRAZY PEOPLE who recorded
762    // movies on <= 0.98.10 and don't work on playback.
763    if(tmpfix == 1 && !nextts)
764    {nextts |= movie_readchar()<<8; }
765    else if(tmpfix == 2 && !nextts) {nextts |= movie_readchar()<<16; }
766
767    if(nextd != -1)
768     framets = 0;
769    nextd = d;
770   }
771
772   memcpy(js,joop,4);
773  }
774 #if 0
775  else if(current > 0)                   // Recording
776  {
777     // flush header info every 300 frames in case of crash
778         {
779          static int fcounter=0;
780          fcounter++;
781          if(!(fcounter%300))
782                  FlushHeader();
783         }
784
785   for(x=0;x<4;x++)
786   {
787    if(js[x] != joop[x])
788    {
789     for(y=0;y<8;y++)
790      if((js[x] ^ joop[x]) & (1 << y))
791       DoEncode(x, y, 0);
792     joop[x] = js[x];
793    }
794    else if(framets == ((1<<24)-1)) DoEncode(0,0,1); // Overflow will happen, so do dummy update.
795   }
796  }
797 #endif
798
799  if(current)
800  {
801   framets++;
802   framecount++;
803  }
804
805  memcpy(&cur_input_display,js,4);
806 }
807
808 #if 0
809 void FCEUMOV_AddCommand(int cmd)
810 {
811  if(current <= 0) return;   // Return if not recording a movie
812  //printf("%d\n",cmd);
813  DoEncode((cmd>>3)&0x3,cmd&0x7,1);
814 }
815 #endif
816
817 #if 0
818 void FCEUMOV_CheckMovies(void)
819 {
820         FILE *st=NULL;
821         char *fn;
822         int ssel;
823
824         for(ssel=0;ssel<10;ssel++)
825         {
826          st=FCEUD_UTF8fopen(fn=FCEU_MakeFName(FCEUMKF_MOVIE,ssel,0),"rb");
827          free(fn);
828          if(st)
829          {
830           MovieStatus[ssel]=1;
831           fclose(st);
832          }
833          else
834           MovieStatus[ssel]=0;
835         }
836
837 }
838
839 void FCEUI_SelectMovieNext(int n)
840 {
841         if(n>0)
842                 CurrentMovie=(CurrentMovie+1)%10;
843         else
844                 CurrentMovie=(CurrentMovie+9)%10;
845         FCEUI_SelectMovie(CurrentMovie, 1);
846 }
847
848
849 int FCEUI_SelectMovie(int w, int show)
850 {
851  int oldslot=CurrentMovie;
852  if(w == -1) { MovieShow = 0; return; }
853  FCEUI_SelectState(-1,0);
854
855  CurrentMovie=w;
856  MovieShow=180;
857
858  if(show)
859  {
860   MovieShow=180;
861   if(current > 0)
862    FCEU_DispMessage("-recording movie %d-",current-1);
863   else if (current < 0)
864    FCEU_DispMessage("-playing movie %d-",-1 - current);
865   else
866    FCEU_DispMessage("-select movie-");
867  }
868 }
869
870 int movcounter=0;
871
872 void FCEU_DrawMovies(uint8 *XBuf)
873 {
874         int frameDisplayOn = current != 0 && frame_display;
875         extern int howlong;
876 #if WIN32
877         extern int32 fps_scale;
878 #else
879         int32 fps_scale=256;
880 #endif
881         int howl=(180-(FCEUI_EmulationPaused()?(60):(20*fps_scale/256)));
882         if(howl>176) howl=180;
883         if(howl<1) howl=1;
884         if((howlong<howl || movcounter)
885         && (frameDisplayOn && (!movcounter || last_frame_display!=framecount) || input_display && (!movcounter || last_input_display!=cur_input_display)))
886         {
887                 char inputstr [32];
888                 if(input_display)
889                 {
890                         uint32 c = cur_input_display;
891                         sprintf(inputstr, "%c%c%c%c%c%c%c%c %c%c%c%c%c%c%c%c",
892                                 (c&0x40)?'<':' ', (c&0x10)?'^':' ', (c&0x80)?'>':' ', (c&0x20)?'v':' ',
893                                 (c&0x01)?'A':' ', (c&0x02)?'B':' ', (c&0x08)?'S':' ', (c&0x04)?'s':' ',
894                                 (c&0x4000)?'<':' ', (c&0x1000)?'^':' ', (c&0x8000)?'>':' ', (c&0x2000)?'v':' ',
895                                 (c&0x0100)?'A':' ', (c&0x0200)?'B':' ', (c&0x0800)?'S':' ', (c&0x0400)?'s':' ');
896                         if(!(c&0xff00))
897                                 inputstr[8] = '\0';
898                 }
899                 if(frameDisplayOn && !input_display)
900                         FCEU_DispMessage("%s frame %u",current >= 0?"Recording":"Playing",framecount);
901                 else if(input_display && !frameDisplayOn)
902                         FCEU_DispMessage("Input: %s",inputstr);
903                 else //if(input_display && frame_display)
904                         FCEU_DispMessage("%s %u %s",current >= 0?"Recording":"Playing",framecount,inputstr);
905
906                 last_frame_display = framecount;
907                 last_input_display = cur_input_display;
908                 movcounter=180-1;
909                 return;
910         }
911
912         if(movcounter) movcounter--;
913
914         if(!MovieShow) return;
915
916         FCEU_DrawNumberRow(XBuf,MovieStatus, CurrentMovie);
917         MovieShow--;
918 }
919
920 int FCEUMOV_WriteState(FILE* st)
921 {
922  uint32 to_write = 0;
923  if(current < 0)
924   to_write = moviedatasize;
925  else if(current > 0)
926   to_write = frameptr;
927
928  if(!st)
929   return to_write;
930
931  if(to_write)
932   fwrite(moviedata, 1, to_write, st);
933  return to_write;
934 }
935
936 static int load_successful;
937
938 int FCEUMOV_ReadState(FILE* st, uint32 size)
939 {
940  // if this savestate was made while replaying,
941  // we need to "undo" nextd and nextts
942  if(nextd != -1)
943  {
944   int d = 1;
945   if(nextts > 65536)
946    d = 4;
947   else if(nextts > 256)
948    d = 3;
949   else if(nextts > 0)
950    d = 2;
951   frameptr -= d;
952   nextd = -1;
953  }
954
955 // if(current > 0 || (!movie_readonly && current < 0))            /* Recording or Playback (!read-only) */
956  if(current!=0 && !movie_readonly)
957  {
958   // copy movie data from savestate
959   moviedata = (uint8*)realloc(moviedata, size);
960   moviedatasize = size;
961   if(size && fread(moviedata, 1, size, st)<size)
962    return 0;
963   if(current < 0)                   // switch to recording
964    current = -current;
965   fseek(slots[current - 1], firstframeoffset, SEEK_SET);
966   fwrite(moviedata, 1, frameptr, slots[current - 1]);
967   rerecord_count++;
968  }
969 // else if(current < 0)       /* Playback (read-only) */
970  else if(current!=0 && movie_readonly)
971  {
972   if(current > 0)                   // switch to playback
973    current = -current;
974   // allow frameptr to be updated but keep movie data
975   fseek(st, size, SEEK_CUR);
976   // prevent seeking beyond the end of the movie
977   if(frameptr > moviedatasize)
978    frameptr = moviedatasize;
979  }
980  else                                           /* Neither recording or replaying */
981  {
982   // skip movie data
983   fseek(st, size, SEEK_CUR);
984  }
985
986  load_successful=1;
987  return 1;
988 }
989
990 void FCEUMOV_PreLoad(void)
991 {
992         load_successful=0;
993 }
994
995 int FCEUMOV_PostLoad(void)
996 {
997         if(!FCEUI_IsMovieActive())
998                 return 1;
999         else
1000                 return load_successful;
1001 }
1002
1003 char* FCEUI_MovieGetCurrentName(int addSlotNumber)
1004 {
1005  return FCEU_MakeFName(FCEUMKF_MOVIE,(addSlotNumber ? CurrentMovie : -1),0);
1006 }
1007 #endif
1008
1009 int FCEUI_IsMovieActive(void)
1010 {
1011   return current;
1012 }
1013
1014 #if 0
1015 void FCEUI_MovieToggleFrameDisplay(void)
1016 {
1017  frame_display=!frame_display;
1018  if(!(current != 0 && frame_display) && !input_display)
1019   FCEU_ResetMessages();
1020  else
1021  {
1022   last_frame_display = ~framecount;
1023   last_input_display = ~cur_input_display;
1024  }
1025 }
1026
1027 void FCEUI_ToggleInputDisplay(void)
1028 {
1029  input_display=!input_display;
1030  if(!input_display && !(current != 0 && frame_display))
1031   FCEU_ResetMessages();
1032  else
1033  {
1034   last_frame_display = ~framecount;
1035   last_input_display = ~cur_input_display;
1036  }
1037 }
1038
1039 void FCEUI_MovieToggleReadOnly(void)
1040 {
1041         if(movie_readonly < 2)
1042         {
1043                 movie_readonly = !movie_readonly;
1044                 if(movie_readonly)
1045                         FCEU_DispMessage("Movie is now Read-Only.");
1046                 else
1047                         FCEU_DispMessage("Movie is now Read+Write.");
1048         }
1049         else
1050         {
1051                 FCEU_DispMessage("Movie file is Read-Only.");
1052         }
1053 }
1054
1055 char lastMovieInfoFilename [512] = {'\0',};
1056
1057 int FCEUI_MovieGetInfo(const char* fname, MOVIE_INFO* info)
1058 {
1059         FlushHeader();
1060
1061         char buffer [512];
1062         fname = (const char*)convertToFCM(fname,buffer);
1063         strncpy(lastMovieInfoFilename, fname, 512);
1064
1065 // main get info part of function
1066 {
1067  uint32 magic;
1068  uint32 version;
1069  uint8 _flags[4];
1070
1071  FILE* fp = FCEUD_UTF8fopen(fname, "rb");
1072  if(!fp)
1073   return 0;
1074
1075  read32le(&magic, fp);
1076  if(magic != MOVIE_MAGIC)
1077  {
1078   fclose(fp);
1079   return 0;
1080  }
1081
1082  read32le(&version, fp);
1083  if(version != MOVIE_VERSION)
1084  {
1085   fclose(fp);
1086   if(version == 1)
1087    return FCEUI_MovieGetInfo_v1(fname, info);
1088   else
1089    return 0;
1090  }
1091
1092  info->movie_version = MOVIE_VERSION;
1093
1094  fread(_flags, 1, 4, fp);
1095
1096  info->flags = _flags[0];
1097  read32le(&info->num_frames, fp);
1098  read32le(&info->rerecord_count, fp);
1099
1100  if(access(fname, W_OK))
1101   info->read_only = 1;
1102  else
1103   info->read_only = 0;
1104
1105  fseek(fp, 12, SEEK_CUR);                       // skip movie_data_size, offset_to_savestate, and offset_to_movie_data
1106
1107  fread(info->md5_of_rom_used, 1, 16, fp);
1108  info->md5_of_rom_used_present = 1;
1109
1110  read32le(&info->emu_version_used, fp);
1111
1112  // I probably could have planned this better...
1113  {
1114   char str[256];
1115   size_t r;
1116   int p;
1117   int p2=0;
1118   char last_c=32;
1119
1120   if(info->name_of_rom_used && info->name_of_rom_used_size)
1121    info->name_of_rom_used[0]='\0';
1122
1123   r=fread(str, 1, 256, fp);
1124   while(r > 0)
1125   {
1126    for(p=0; p<r && last_c != '\0'; ++p)
1127    {
1128     if(info->name_of_rom_used && info->name_of_rom_used_size && (p2 < info->name_of_rom_used_size-1))
1129     {
1130      info->name_of_rom_used[p2]=str[p];
1131      p2++;
1132          last_c=str[p];
1133     }
1134    }
1135    if(p<r)
1136    {
1137     memmove(str, str+p, r-p);
1138     r -= p;
1139     break;
1140    }
1141    r=fread(str, 1, 256, fp);
1142   }
1143
1144   p2=0;
1145   last_c=32;
1146
1147   if(info->metadata && info->metadata_size)
1148    info->metadata[0]='\0';
1149
1150   while(r > 0)
1151   {
1152    for(p=0; p<r && last_c != '\0'; ++p)
1153    {
1154     if(info->metadata && info->metadata_size && (p2 < info->metadata_size-1))
1155     {
1156      info->metadata[p2]=str[p];
1157      p2++;
1158          last_c=str[p];
1159     }
1160    }
1161    if(p != r)
1162     break;
1163    r=fread(str, 1, 256, fp);
1164   }
1165
1166   if(r<=0)
1167   {
1168    // somehow failed to read romname and metadata
1169    fclose(fp);
1170    return 0;
1171   }
1172  }
1173
1174  // check what hacks are necessary
1175   fseek(fp, 24, SEEK_SET);                      // offset_to_savestate offset
1176   uint32 temp_savestate_offset;
1177   read32le(&temp_savestate_offset, fp);
1178   if(fseek(fp, temp_savestate_offset, SEEK_SET))
1179   {
1180    fclose(fp);
1181    return 0;
1182   }
1183   if(!FCEUSS_LoadFP(fp,2)) return 0; // 2 -> don't really load, just load to find what's there then load backup
1184
1185  fclose(fp);
1186  return 1;
1187 }
1188 }
1189 #endif
1190 /*
1191   Backwards compat
1192 */
1193
1194
1195 /*
1196 struct MovieHeader_v1
1197 {
1198  uint32 magic;
1199  uint32 version=1;
1200  uint8 flags[4];
1201  uint32 length_frames;
1202  uint32 rerecord_count;
1203  uint32 movie_data_size;
1204  uint32 offset_to_savestate;
1205  uint32 offset_to_movie_data;
1206  uint16 metadata_ucs2[];     // ucs-2, ick!  sizeof(metadata) = offset_to_savestate - MOVIE_HEADER_SIZE
1207 }
1208 */
1209
1210 #define MOVIE_V1_HEADER_SIZE    32
1211
1212 static void FCEUI_LoadMovie_v1(char *fname, int _read_only)
1213 {
1214  FILE *fp;
1215  char *fn = NULL;
1216
1217  FCEUI_StopMovie();
1218
1219 #if 0
1220  if(!fname)
1221   fname = fn = FCEU_MakeFName(FCEUMKF_MOVIE,CurrentMovie,0);
1222 #endif
1223
1224  // check movie_readonly
1225  movie_readonly = _read_only;
1226  if(access(fname, W_OK))
1227   movie_readonly = 2;
1228
1229 #if 0
1230  fp = FCEUD_UTF8fopen(fname, (movie_readonly>=2) ? "rb" : "r+b");
1231 #else
1232  fp = fopen(fname, (movie_readonly>=2) ? "rb" : "r+b");
1233 #endif
1234
1235  if(fn)
1236  {
1237   free(fn);
1238   fname = NULL;
1239  }
1240
1241  if(!fp) return;
1242
1243  // read header
1244  {
1245   uint32 magic;
1246   uint32 version;
1247   uint8 flags[4];
1248   uint32 fc;
1249
1250   read32le(&magic, fp);
1251   if(magic != MOVIE_MAGIC)
1252   {
1253    fclose(fp);
1254    return;
1255   }
1256
1257   read32le(&version, fp);
1258   if(version != 1)
1259   {
1260    fclose(fp);
1261    return;
1262   }
1263
1264   fread(flags, 1, 4, fp);
1265   read32le(&fc, fp);
1266   read32le(&rerecord_count, fp);
1267   read32le(&moviedatasize, fp);
1268   read32le(&savestate_offset, fp);
1269   read32le(&firstframeoffset, fp);
1270   if(fseek(fp, savestate_offset, SEEK_SET))
1271   {
1272    fclose(fp);
1273    return;
1274   }
1275
1276   if(flags[0] & MOVIE_FLAG_NOSYNCHACK)
1277           movieSyncHackOn=0;
1278   else
1279           movieSyncHackOn=1;
1280  }
1281
1282  // fully reload the game to reinitialize everything before playing any movie
1283  // to try fixing nondeterministic playback of some games
1284  {
1285         extern char lastLoadedGameName [2048];
1286 #if 0 // TODO?
1287         extern int disableBatteryLoading, suppressAddPowerCommand;
1288         suppressAddPowerCommand=1;
1289         suppressMovieStop=1;
1290 #endif
1291         {
1292                 FCEUGI * gi = FCEUI_LoadGame(lastLoadedGameName);
1293                 if(!gi)
1294                         PowerNES();
1295         }
1296 #if 0 // TODO?
1297         suppressMovieStop=0;
1298         suppressAddPowerCommand=0;
1299 #endif
1300  }
1301
1302  if(!FCEUSS_LoadFP(fp,1)) return;
1303
1304  ResetInputTypes();
1305
1306  fseek(fp, firstframeoffset, SEEK_SET);
1307  moviedata = (uint8*)realloc(moviedata, moviedatasize);
1308  fread(moviedata, 1, moviedatasize, fp);
1309
1310  framecount = 0;                // movies start at frame 0!
1311  frameptr = 0;
1312  current = CurrentMovie;
1313  slots[current] = fp;
1314
1315  memset(joop,0,sizeof(joop));
1316  current = -1 - current;
1317  framets=0;
1318  nextts=0;
1319  nextd = -1;
1320  MovieStatus[CurrentMovie] = 1;
1321 #if 0
1322  if(!fname)
1323   FCEUI_SelectMovie(CurrentMovie,1);       /* Quick hack to display status. */
1324  else
1325 #endif
1326   FCEU_DispMessage("Movie playback started.");
1327 }
1328
1329 #if 0
1330 static int FCEUI_MovieGetInfo_v1(const char* fname, MOVIE_INFO* info)
1331 {
1332  uint32 magic;
1333  uint32 version;
1334  uint8 _flags[4];
1335  uint32 savestateoffset;
1336  uint8 tmp[MOVIE_MAX_METADATA<<1];
1337  int metadata_length;
1338
1339  FILE* fp = FCEUD_UTF8fopen(fname, "rb");
1340  if(!fp)
1341   return 0;
1342
1343  read32le(&magic, fp);
1344  if(magic != MOVIE_MAGIC)
1345  {
1346   fclose(fp);
1347   return 0;
1348  }
1349
1350  read32le(&version, fp);
1351  if(version != 1)
1352  {
1353   fclose(fp);
1354   return 0;
1355  }
1356
1357  info->movie_version = 1;
1358  info->emu_version_used = 0;                    // unknown
1359
1360  fread(_flags, 1, 4, fp);
1361
1362  info->flags = _flags[0];
1363  read32le(&info->num_frames, fp);
1364  read32le(&info->rerecord_count, fp);
1365
1366  if(access(fname, W_OK))
1367   info->read_only = 1;
1368  else
1369   info->read_only = 0;
1370
1371  fseek(fp, 4, SEEK_CUR);
1372  read32le(&savestateoffset, fp);
1373
1374  metadata_length = (int)savestateoffset - MOVIE_V1_HEADER_SIZE;
1375  if(metadata_length > 0)
1376  {
1377   int i;
1378
1379   metadata_length >>= 1;
1380   if(metadata_length >= MOVIE_MAX_METADATA)
1381    metadata_length = MOVIE_MAX_METADATA-1;
1382
1383   fseek(fp, MOVIE_V1_HEADER_SIZE, SEEK_SET);
1384   fread(tmp, 1, metadata_length<<1, fp);
1385  }
1386
1387  // turn old ucs2 metadata into utf8
1388  if(info->metadata && info->metadata_size)
1389  {
1390          char* ptr=info->metadata;
1391          char* ptr_end=info->metadata+info->metadata_size-1;
1392          int c_ptr=0;
1393          while(ptr<ptr_end && c_ptr<metadata_length)
1394          {
1395                  uint16 c=(tmp[c_ptr<<1] | (tmp[(c_ptr<<1)+1] << 8));
1396                  switch(c)
1397                  {
1398                  case 0 ... 0x7f:
1399                          *ptr++ = (char)(c&0x7f);
1400                          break;
1401                  case 0x80 ... 0x7ff:
1402                          if(ptr+1>=ptr_end)
1403                                  ptr_end=ptr;
1404                          else
1405                          {
1406                                  *ptr++=(0xc0 | (c>>6));
1407                                  *ptr++=(0x80 | (c & 0x3f));
1408                          }
1409                          break;
1410                  case 0x800 ... 0xffff:
1411                          if(ptr+2>=ptr_end)
1412                                  ptr_end=ptr;
1413                          else
1414                          {
1415                                  *ptr++=(0xe0 | (c>>12));
1416                                  *ptr++=(0x80 | ((c>>6) & 0x3f));
1417                                  *ptr++=(0x80 | (c & 0x3f));
1418                          }
1419                          break;
1420                  }
1421                  c_ptr++;
1422          }
1423          *ptr='\0';
1424  }
1425
1426  // md5 info not available from v1
1427  info->md5_of_rom_used_present = 0;
1428  // rom name used for the movie not available from v1
1429  if(info->name_of_rom_used && info->name_of_rom_used_size)
1430   info->name_of_rom_used[0] = '\0';
1431
1432  // check what hacks are necessary
1433   fseek(fp, 24, SEEK_SET);                      // offset_to_savestate offset
1434   uint32 temp_savestate_offset;
1435   read32le(&temp_savestate_offset, fp);
1436   if(fseek(fp, temp_savestate_offset, SEEK_SET))
1437   {
1438    fclose(fp);
1439    return 0;
1440   }
1441   if(!FCEUSS_LoadFP(fp,2)) return 0; // 2 -> don't really load, just load to find what's there then load backup
1442
1443
1444  fclose(fp);
1445  return 1;
1446 }
1447 #endif
1448