broken movie support
[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      // TODO?
736 #if 0
737      FCEU_DoSimpleCommand(nextd&0x1F);
738 #endif
739     }
740     else
741      joop[(nextd >> 3)&0x3] ^= 1 << (nextd&0x7);
742    }
743
744
745    tmp = movie_readchar();
746    d = tmp;
747
748    if(tmp < 0)
749    {
750     StopPlayback();
751     memcpy(&cur_input_display,js,4);
752     return;
753    }
754
755    nextts = 0;
756    tmp >>= 5;
757    tmp &= 0x3;
758    ti=0;
759
760    int tmpfix = tmp;
761    while(tmp--) { nextts |= movie_readchar() << (ti * 8); ti++; }
762
763    // This fixes a bug in movies recorded before version 0.98.11
764    // It's probably not necessary, but it may keep away CRAZY PEOPLE who recorded
765    // movies on <= 0.98.10 and don't work on playback.
766    if(tmpfix == 1 && !nextts)
767    {nextts |= movie_readchar()<<8; }
768    else if(tmpfix == 2 && !nextts) {nextts |= movie_readchar()<<16; }
769
770    if(nextd != -1)
771     framets = 0;
772    nextd = d;
773   }
774
775   memcpy(js,joop,4);
776  }
777 #if 0
778  else if(current > 0)                   // Recording
779  {
780     // flush header info every 300 frames in case of crash
781         {
782          static int fcounter=0;
783          fcounter++;
784          if(!(fcounter%300))
785                  FlushHeader();
786         }
787
788   for(x=0;x<4;x++)
789   {
790    if(js[x] != joop[x])
791    {
792     for(y=0;y<8;y++)
793      if((js[x] ^ joop[x]) & (1 << y))
794       DoEncode(x, y, 0);
795     joop[x] = js[x];
796    }
797    else if(framets == ((1<<24)-1)) DoEncode(0,0,1); // Overflow will happen, so do dummy update.
798   }
799  }
800 #endif
801
802  if(current)
803  {
804   framets++;
805   framecount++;
806  }
807
808  memcpy(&cur_input_display,js,4);
809 }
810
811 #if 0
812 void FCEUMOV_AddCommand(int cmd)
813 {
814  if(current <= 0) return;   // Return if not recording a movie
815  //printf("%d\n",cmd);
816  DoEncode((cmd>>3)&0x3,cmd&0x7,1);
817 }
818 #endif
819
820 #if 0
821 void FCEUMOV_CheckMovies(void)
822 {
823         FILE *st=NULL;
824         char *fn;
825         int ssel;
826
827         for(ssel=0;ssel<10;ssel++)
828         {
829          st=FCEUD_UTF8fopen(fn=FCEU_MakeFName(FCEUMKF_MOVIE,ssel,0),"rb");
830          free(fn);
831          if(st)
832          {
833           MovieStatus[ssel]=1;
834           fclose(st);
835          }
836          else
837           MovieStatus[ssel]=0;
838         }
839
840 }
841
842 void FCEUI_SelectMovieNext(int n)
843 {
844         if(n>0)
845                 CurrentMovie=(CurrentMovie+1)%10;
846         else
847                 CurrentMovie=(CurrentMovie+9)%10;
848         FCEUI_SelectMovie(CurrentMovie, 1);
849 }
850
851
852 int FCEUI_SelectMovie(int w, int show)
853 {
854  int oldslot=CurrentMovie;
855  if(w == -1) { MovieShow = 0; return; }
856  FCEUI_SelectState(-1,0);
857
858  CurrentMovie=w;
859  MovieShow=180;
860
861  if(show)
862  {
863   MovieShow=180;
864   if(current > 0)
865    FCEU_DispMessage("-recording movie %d-",current-1);
866   else if (current < 0)
867    FCEU_DispMessage("-playing movie %d-",-1 - current);
868   else
869    FCEU_DispMessage("-select movie-");
870  }
871 }
872
873 int movcounter=0;
874
875 void FCEU_DrawMovies(uint8 *XBuf)
876 {
877         int frameDisplayOn = current != 0 && frame_display;
878         extern int howlong;
879 #if WIN32
880         extern int32 fps_scale;
881 #else
882         int32 fps_scale=256;
883 #endif
884         int howl=(180-(FCEUI_EmulationPaused()?(60):(20*fps_scale/256)));
885         if(howl>176) howl=180;
886         if(howl<1) howl=1;
887         if((howlong<howl || movcounter)
888         && (frameDisplayOn && (!movcounter || last_frame_display!=framecount) || input_display && (!movcounter || last_input_display!=cur_input_display)))
889         {
890                 char inputstr [32];
891                 if(input_display)
892                 {
893                         uint32 c = cur_input_display;
894                         sprintf(inputstr, "%c%c%c%c%c%c%c%c %c%c%c%c%c%c%c%c",
895                                 (c&0x40)?'<':' ', (c&0x10)?'^':' ', (c&0x80)?'>':' ', (c&0x20)?'v':' ',
896                                 (c&0x01)?'A':' ', (c&0x02)?'B':' ', (c&0x08)?'S':' ', (c&0x04)?'s':' ',
897                                 (c&0x4000)?'<':' ', (c&0x1000)?'^':' ', (c&0x8000)?'>':' ', (c&0x2000)?'v':' ',
898                                 (c&0x0100)?'A':' ', (c&0x0200)?'B':' ', (c&0x0800)?'S':' ', (c&0x0400)?'s':' ');
899                         if(!(c&0xff00))
900                                 inputstr[8] = '\0';
901                 }
902                 if(frameDisplayOn && !input_display)
903                         FCEU_DispMessage("%s frame %u",current >= 0?"Recording":"Playing",framecount);
904                 else if(input_display && !frameDisplayOn)
905                         FCEU_DispMessage("Input: %s",inputstr);
906                 else //if(input_display && frame_display)
907                         FCEU_DispMessage("%s %u %s",current >= 0?"Recording":"Playing",framecount,inputstr);
908
909                 last_frame_display = framecount;
910                 last_input_display = cur_input_display;
911                 movcounter=180-1;
912                 return;
913         }
914
915         if(movcounter) movcounter--;
916
917         if(!MovieShow) return;
918
919         FCEU_DrawNumberRow(XBuf,MovieStatus, CurrentMovie);
920         MovieShow--;
921 }
922
923 int FCEUMOV_WriteState(FILE* st)
924 {
925  uint32 to_write = 0;
926  if(current < 0)
927   to_write = moviedatasize;
928  else if(current > 0)
929   to_write = frameptr;
930
931  if(!st)
932   return to_write;
933
934  if(to_write)
935   fwrite(moviedata, 1, to_write, st);
936  return to_write;
937 }
938
939 static int load_successful;
940
941 int FCEUMOV_ReadState(FILE* st, uint32 size)
942 {
943  // if this savestate was made while replaying,
944  // we need to "undo" nextd and nextts
945  if(nextd != -1)
946  {
947   int d = 1;
948   if(nextts > 65536)
949    d = 4;
950   else if(nextts > 256)
951    d = 3;
952   else if(nextts > 0)
953    d = 2;
954   frameptr -= d;
955   nextd = -1;
956  }
957
958 // if(current > 0 || (!movie_readonly && current < 0))            /* Recording or Playback (!read-only) */
959  if(current!=0 && !movie_readonly)
960  {
961   // copy movie data from savestate
962   moviedata = (uint8*)realloc(moviedata, size);
963   moviedatasize = size;
964   if(size && fread(moviedata, 1, size, st)<size)
965    return 0;
966   if(current < 0)                   // switch to recording
967    current = -current;
968   fseek(slots[current - 1], firstframeoffset, SEEK_SET);
969   fwrite(moviedata, 1, frameptr, slots[current - 1]);
970   rerecord_count++;
971  }
972 // else if(current < 0)       /* Playback (read-only) */
973  else if(current!=0 && movie_readonly)
974  {
975   if(current > 0)                   // switch to playback
976    current = -current;
977   // allow frameptr to be updated but keep movie data
978   fseek(st, size, SEEK_CUR);
979   // prevent seeking beyond the end of the movie
980   if(frameptr > moviedatasize)
981    frameptr = moviedatasize;
982  }
983  else                                           /* Neither recording or replaying */
984  {
985   // skip movie data
986   fseek(st, size, SEEK_CUR);
987  }
988
989  load_successful=1;
990  return 1;
991 }
992
993 void FCEUMOV_PreLoad(void)
994 {
995         load_successful=0;
996 }
997
998 int FCEUMOV_PostLoad(void)
999 {
1000         if(!FCEUI_IsMovieActive())
1001                 return 1;
1002         else
1003                 return load_successful;
1004 }
1005
1006 char* FCEUI_MovieGetCurrentName(int addSlotNumber)
1007 {
1008  return FCEU_MakeFName(FCEUMKF_MOVIE,(addSlotNumber ? CurrentMovie : -1),0);
1009 }
1010 #endif
1011
1012 int FCEUI_IsMovieActive(void)
1013 {
1014   return current;
1015 }
1016
1017 #if 0
1018 void FCEUI_MovieToggleFrameDisplay(void)
1019 {
1020  frame_display=!frame_display;
1021  if(!(current != 0 && frame_display) && !input_display)
1022   FCEU_ResetMessages();
1023  else
1024  {
1025   last_frame_display = ~framecount;
1026   last_input_display = ~cur_input_display;
1027  }
1028 }
1029
1030 void FCEUI_ToggleInputDisplay(void)
1031 {
1032  input_display=!input_display;
1033  if(!input_display && !(current != 0 && frame_display))
1034   FCEU_ResetMessages();
1035  else
1036  {
1037   last_frame_display = ~framecount;
1038   last_input_display = ~cur_input_display;
1039  }
1040 }
1041
1042 void FCEUI_MovieToggleReadOnly(void)
1043 {
1044         if(movie_readonly < 2)
1045         {
1046                 movie_readonly = !movie_readonly;
1047                 if(movie_readonly)
1048                         FCEU_DispMessage("Movie is now Read-Only.");
1049                 else
1050                         FCEU_DispMessage("Movie is now Read+Write.");
1051         }
1052         else
1053         {
1054                 FCEU_DispMessage("Movie file is Read-Only.");
1055         }
1056 }
1057
1058 char lastMovieInfoFilename [512] = {'\0',};
1059
1060 int FCEUI_MovieGetInfo(const char* fname, MOVIE_INFO* info)
1061 {
1062         FlushHeader();
1063
1064         char buffer [512];
1065         fname = (const char*)convertToFCM(fname,buffer);
1066         strncpy(lastMovieInfoFilename, fname, 512);
1067
1068 // main get info part of function
1069 {
1070  uint32 magic;
1071  uint32 version;
1072  uint8 _flags[4];
1073
1074  FILE* fp = FCEUD_UTF8fopen(fname, "rb");
1075  if(!fp)
1076   return 0;
1077
1078  read32le(&magic, fp);
1079  if(magic != MOVIE_MAGIC)
1080  {
1081   fclose(fp);
1082   return 0;
1083  }
1084
1085  read32le(&version, fp);
1086  if(version != MOVIE_VERSION)
1087  {
1088   fclose(fp);
1089   if(version == 1)
1090    return FCEUI_MovieGetInfo_v1(fname, info);
1091   else
1092    return 0;
1093  }
1094
1095  info->movie_version = MOVIE_VERSION;
1096
1097  fread(_flags, 1, 4, fp);
1098
1099  info->flags = _flags[0];
1100  read32le(&info->num_frames, fp);
1101  read32le(&info->rerecord_count, fp);
1102
1103  if(access(fname, W_OK))
1104   info->read_only = 1;
1105  else
1106   info->read_only = 0;
1107
1108  fseek(fp, 12, SEEK_CUR);                       // skip movie_data_size, offset_to_savestate, and offset_to_movie_data
1109
1110  fread(info->md5_of_rom_used, 1, 16, fp);
1111  info->md5_of_rom_used_present = 1;
1112
1113  read32le(&info->emu_version_used, fp);
1114
1115  // I probably could have planned this better...
1116  {
1117   char str[256];
1118   size_t r;
1119   int p;
1120   int p2=0;
1121   char last_c=32;
1122
1123   if(info->name_of_rom_used && info->name_of_rom_used_size)
1124    info->name_of_rom_used[0]='\0';
1125
1126   r=fread(str, 1, 256, fp);
1127   while(r > 0)
1128   {
1129    for(p=0; p<r && last_c != '\0'; ++p)
1130    {
1131     if(info->name_of_rom_used && info->name_of_rom_used_size && (p2 < info->name_of_rom_used_size-1))
1132     {
1133      info->name_of_rom_used[p2]=str[p];
1134      p2++;
1135          last_c=str[p];
1136     }
1137    }
1138    if(p<r)
1139    {
1140     memmove(str, str+p, r-p);
1141     r -= p;
1142     break;
1143    }
1144    r=fread(str, 1, 256, fp);
1145   }
1146
1147   p2=0;
1148   last_c=32;
1149
1150   if(info->metadata && info->metadata_size)
1151    info->metadata[0]='\0';
1152
1153   while(r > 0)
1154   {
1155    for(p=0; p<r && last_c != '\0'; ++p)
1156    {
1157     if(info->metadata && info->metadata_size && (p2 < info->metadata_size-1))
1158     {
1159      info->metadata[p2]=str[p];
1160      p2++;
1161          last_c=str[p];
1162     }
1163    }
1164    if(p != r)
1165     break;
1166    r=fread(str, 1, 256, fp);
1167   }
1168
1169   if(r<=0)
1170   {
1171    // somehow failed to read romname and metadata
1172    fclose(fp);
1173    return 0;
1174   }
1175  }
1176
1177  // check what hacks are necessary
1178   fseek(fp, 24, SEEK_SET);                      // offset_to_savestate offset
1179   uint32 temp_savestate_offset;
1180   read32le(&temp_savestate_offset, fp);
1181   if(fseek(fp, temp_savestate_offset, SEEK_SET))
1182   {
1183    fclose(fp);
1184    return 0;
1185   }
1186   if(!FCEUSS_LoadFP(fp,2)) return 0; // 2 -> don't really load, just load to find what's there then load backup
1187
1188  fclose(fp);
1189  return 1;
1190 }
1191 }
1192 #endif
1193 /*
1194   Backwards compat
1195 */
1196
1197
1198 /*
1199 struct MovieHeader_v1
1200 {
1201  uint32 magic;
1202  uint32 version=1;
1203  uint8 flags[4];
1204  uint32 length_frames;
1205  uint32 rerecord_count;
1206  uint32 movie_data_size;
1207  uint32 offset_to_savestate;
1208  uint32 offset_to_movie_data;
1209  uint16 metadata_ucs2[];     // ucs-2, ick!  sizeof(metadata) = offset_to_savestate - MOVIE_HEADER_SIZE
1210 }
1211 */
1212
1213 #define MOVIE_V1_HEADER_SIZE    32
1214
1215 static void FCEUI_LoadMovie_v1(char *fname, int _read_only)
1216 {
1217  FILE *fp;
1218  char *fn = NULL;
1219
1220  FCEUI_StopMovie();
1221
1222 #if 0
1223  if(!fname)
1224   fname = fn = FCEU_MakeFName(FCEUMKF_MOVIE,CurrentMovie,0);
1225 #endif
1226
1227  // check movie_readonly
1228  movie_readonly = _read_only;
1229  if(access(fname, W_OK))
1230   movie_readonly = 2;
1231
1232 #if 0
1233  fp = FCEUD_UTF8fopen(fname, (movie_readonly>=2) ? "rb" : "r+b");
1234 #else
1235  fp = fopen(fname, (movie_readonly>=2) ? "rb" : "r+b");
1236 #endif
1237
1238  if(fn)
1239  {
1240   free(fn);
1241   fname = NULL;
1242  }
1243
1244  if(!fp) return;
1245
1246  // read header
1247  {
1248   uint32 magic;
1249   uint32 version;
1250   uint8 flags[4];
1251   uint32 fc;
1252
1253   read32le(&magic, fp);
1254   if(magic != MOVIE_MAGIC)
1255   {
1256    fclose(fp);
1257    return;
1258   }
1259
1260   read32le(&version, fp);
1261   if(version != 1)
1262   {
1263    fclose(fp);
1264    return;
1265   }
1266
1267   fread(flags, 1, 4, fp);
1268   read32le(&fc, fp);
1269   read32le(&rerecord_count, fp);
1270   read32le(&moviedatasize, fp);
1271   read32le(&savestate_offset, fp);
1272   read32le(&firstframeoffset, fp);
1273   if(fseek(fp, savestate_offset, SEEK_SET))
1274   {
1275    fclose(fp);
1276    return;
1277   }
1278
1279   if(flags[0] & MOVIE_FLAG_NOSYNCHACK)
1280           movieSyncHackOn=0;
1281   else
1282           movieSyncHackOn=1;
1283  }
1284
1285  // fully reload the game to reinitialize everything before playing any movie
1286  // to try fixing nondeterministic playback of some games
1287  {
1288         extern char lastLoadedGameName [2048];
1289 #if 0 // TODO?
1290         extern int disableBatteryLoading, suppressAddPowerCommand;
1291         suppressAddPowerCommand=1;
1292         suppressMovieStop=1;
1293 #endif
1294         {
1295                 FCEUGI * gi = FCEUI_LoadGame(lastLoadedGameName);
1296                 if(!gi)
1297                         PowerNES();
1298         }
1299 #if 0 // TODO?
1300         suppressMovieStop=0;
1301         suppressAddPowerCommand=0;
1302 #endif
1303  }
1304
1305  if(!FCEUSS_LoadFP(fp,1)) return;
1306
1307  ResetInputTypes();
1308
1309  fseek(fp, firstframeoffset, SEEK_SET);
1310  moviedata = (uint8*)realloc(moviedata, moviedatasize);
1311  fread(moviedata, 1, moviedatasize, fp);
1312
1313  framecount = 0;                // movies start at frame 0!
1314  frameptr = 0;
1315  current = CurrentMovie;
1316  slots[current] = fp;
1317
1318  memset(joop,0,sizeof(joop));
1319  current = -1 - current;
1320  framets=0;
1321  nextts=0;
1322  nextd = -1;
1323  MovieStatus[CurrentMovie] = 1;
1324 #if 0
1325  if(!fname)
1326   FCEUI_SelectMovie(CurrentMovie,1);       /* Quick hack to display status. */
1327  else
1328 #endif
1329   FCEU_DispMessage("Movie playback started.");
1330 }
1331
1332 #if 0
1333 static int FCEUI_MovieGetInfo_v1(const char* fname, MOVIE_INFO* info)
1334 {
1335  uint32 magic;
1336  uint32 version;
1337  uint8 _flags[4];
1338  uint32 savestateoffset;
1339  uint8 tmp[MOVIE_MAX_METADATA<<1];
1340  int metadata_length;
1341
1342  FILE* fp = FCEUD_UTF8fopen(fname, "rb");
1343  if(!fp)
1344   return 0;
1345
1346  read32le(&magic, fp);
1347  if(magic != MOVIE_MAGIC)
1348  {
1349   fclose(fp);
1350   return 0;
1351  }
1352
1353  read32le(&version, fp);
1354  if(version != 1)
1355  {
1356   fclose(fp);
1357   return 0;
1358  }
1359
1360  info->movie_version = 1;
1361  info->emu_version_used = 0;                    // unknown
1362
1363  fread(_flags, 1, 4, fp);
1364
1365  info->flags = _flags[0];
1366  read32le(&info->num_frames, fp);
1367  read32le(&info->rerecord_count, fp);
1368
1369  if(access(fname, W_OK))
1370   info->read_only = 1;
1371  else
1372   info->read_only = 0;
1373
1374  fseek(fp, 4, SEEK_CUR);
1375  read32le(&savestateoffset, fp);
1376
1377  metadata_length = (int)savestateoffset - MOVIE_V1_HEADER_SIZE;
1378  if(metadata_length > 0)
1379  {
1380   int i;
1381
1382   metadata_length >>= 1;
1383   if(metadata_length >= MOVIE_MAX_METADATA)
1384    metadata_length = MOVIE_MAX_METADATA-1;
1385
1386   fseek(fp, MOVIE_V1_HEADER_SIZE, SEEK_SET);
1387   fread(tmp, 1, metadata_length<<1, fp);
1388  }
1389
1390  // turn old ucs2 metadata into utf8
1391  if(info->metadata && info->metadata_size)
1392  {
1393          char* ptr=info->metadata;
1394          char* ptr_end=info->metadata+info->metadata_size-1;
1395          int c_ptr=0;
1396          while(ptr<ptr_end && c_ptr<metadata_length)
1397          {
1398                  uint16 c=(tmp[c_ptr<<1] | (tmp[(c_ptr<<1)+1] << 8));
1399                  switch(c)
1400                  {
1401                  case 0 ... 0x7f:
1402                          *ptr++ = (char)(c&0x7f);
1403                          break;
1404                  case 0x80 ... 0x7ff:
1405                          if(ptr+1>=ptr_end)
1406                                  ptr_end=ptr;
1407                          else
1408                          {
1409                                  *ptr++=(0xc0 | (c>>6));
1410                                  *ptr++=(0x80 | (c & 0x3f));
1411                          }
1412                          break;
1413                  case 0x800 ... 0xffff:
1414                          if(ptr+2>=ptr_end)
1415                                  ptr_end=ptr;
1416                          else
1417                          {
1418                                  *ptr++=(0xe0 | (c>>12));
1419                                  *ptr++=(0x80 | ((c>>6) & 0x3f));
1420                                  *ptr++=(0x80 | (c & 0x3f));
1421                          }
1422                          break;
1423                  }
1424                  c_ptr++;
1425          }
1426          *ptr='\0';
1427  }
1428
1429  // md5 info not available from v1
1430  info->md5_of_rom_used_present = 0;
1431  // rom name used for the movie not available from v1
1432  if(info->name_of_rom_used && info->name_of_rom_used_size)
1433   info->name_of_rom_used[0] = '\0';
1434
1435  // check what hacks are necessary
1436   fseek(fp, 24, SEEK_SET);                      // offset_to_savestate offset
1437   uint32 temp_savestate_offset;
1438   read32le(&temp_savestate_offset, fp);
1439   if(fseek(fp, temp_savestate_offset, SEEK_SET))
1440   {
1441    fclose(fp);
1442    return 0;
1443   }
1444   if(!FCEUSS_LoadFP(fp,2)) return 0; // 2 -> don't really load, just load to find what's there then load backup
1445
1446
1447  fclose(fp);
1448  return 1;
1449 }
1450 #endif
1451