race condition fix from 2007 (gpsp09-2xb_1)
[gpsp.git] / main.c
1 /* gameplaySP
2  *
3  * Copyright (C) 2006 Exophase <exophase@gmail.com>
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License as
7  * published by the Free Software Foundation; either version 2 of
8  * the License, or (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18  */
19
20 #include "common.h"
21
22 #ifdef PSP_BUILD
23
24 //PSP_MODULE_INFO("gpSP", 0x1000, 0, 6);
25 //PSP_MAIN_THREAD_ATTR(THREAD_ATTR_USER);
26
27 void vblank_interrupt_handler(u32 sub, u32 *parg);
28
29 #endif
30
31 timer_type timer[4];
32
33 //debug_state current_debug_state = COUNTDOWN_BREAKPOINT;
34 //debug_state current_debug_state = PC_BREAKPOINT;
35 u32 breakpoint_value = 0x7c5000;
36 debug_state current_debug_state = RUN;
37 //debug_state current_debug_state = STEP_RUN;
38
39 //u32 breakpoint_value = 0;
40
41 frameskip_type current_frameskip_type = auto_frameskip;
42 u32 global_cycles_per_instruction = 1;
43 u32 random_skip = 0;
44
45 #ifdef GP2X_BUILD
46 u32 frameskip_value = 2;
47
48 u64 frame_count_initial_timestamp = 0;
49 u64 last_frame_interval_timestamp;
50 u32 gp2x_fps_debug = 0;
51
52 void gp2x_quit(void);
53 #else
54
55 u32 frameskip_value = 4;
56 #endif
57 u32 skip_next_frame = 0;
58
59 u32 frameskip_counter = 0;
60
61 u32 cpu_ticks = 0;
62 u32 frame_ticks = 0;
63
64 u32 execute_cycles = 960;
65 s32 video_count = 960;
66 u32 ticks;
67
68 u32 arm_frame = 0;
69 u32 thumb_frame = 0;
70 u32 last_frame = 0;
71
72 u32 cycle_memory_access = 0;
73 u32 cycle_pc_relative_access = 0;
74 u32 cycle_sp_relative_access = 0;
75 u32 cycle_block_memory_access = 0;
76 u32 cycle_block_memory_sp_access = 0;
77 u32 cycle_block_memory_words = 0;
78 u32 cycle_dma16_words = 0;
79 u32 cycle_dma32_words = 0;
80 u32 flush_ram_count = 0;
81 u32 gbc_update_count = 0;
82 u32 oam_update_count = 0;
83
84 u32 synchronize_flag = 1;
85
86 u32 update_backup_flag = 1;
87 u32 clock_speed = 333;
88 u8 main_path[512];
89
90 void trigger_ext_event();
91
92 #define check_count(count_var)                                                \
93   if(count_var < execute_cycles)                                              \
94     execute_cycles = count_var;                                               \
95
96 #define check_timer(timer_number)                                             \
97   if(timer[timer_number].status == TIMER_PRESCALE)                            \
98     check_count(timer[timer_number].count);                                   \
99
100 #define update_timer(timer_number)                                            \
101   if(timer[timer_number].status != TIMER_INACTIVE)                            \
102   {                                                                           \
103     if(timer[timer_number].status != TIMER_CASCADE)                           \
104     {                                                                         \
105       timer[timer_number].count -= execute_cycles;                            \
106       io_registers[REG_TM##timer_number##D] =                                 \
107        -(timer[timer_number].count >> timer[timer_number].prescale);          \
108     }                                                                         \
109                                                                               \
110     if(timer[timer_number].count <= 0)                                        \
111     {                                                                         \
112       if(timer[timer_number].irq == TIMER_TRIGGER_IRQ)                        \
113         irq_raised |= IRQ_TIMER##timer_number;                                \
114                                                                               \
115       if((timer_number != 3) &&                                               \
116        (timer[timer_number + 1].status == TIMER_CASCADE))                     \
117       {                                                                       \
118         timer[timer_number + 1].count--;                                      \
119         io_registers[REG_TM0D + (timer_number + 1) * 2] =                     \
120          -(timer[timer_number + 1].count);                                    \
121       }                                                                       \
122                                                                               \
123       if(timer_number < 2)                                                    \
124       {                                                                       \
125         if(timer[timer_number].direct_sound_channels & 0x01)                  \
126           sound_timer(timer[timer_number].frequency_step, 0);                 \
127                                                                               \
128         if(timer[timer_number].direct_sound_channels & 0x02)                  \
129           sound_timer(timer[timer_number].frequency_step, 1);                 \
130       }                                                                       \
131                                                                               \
132       timer[timer_number].count +=                                            \
133        (timer[timer_number].reload << timer[timer_number].prescale);          \
134     }                                                                         \
135   }                                                                           \
136
137 u8 *file_ext[] = { ".gba", ".bin", ".zip", NULL };
138
139 #ifdef ARM_ARCH
140 void ChangeWorkingDirectory(char *exe)
141 {
142 #ifndef _WIN32_WCE
143   char *s = strrchr(exe, '/');
144   if (s != NULL) {
145     *s = '\0';
146     chdir(exe);
147     *s = '/';
148   }
149 #endif
150 }
151 #endif
152
153 void init_main()
154 {
155   u32 i;
156
157   skip_next_frame = 0;
158
159   for(i = 0; i < 4; i++)
160   {
161     dma[i].start_type = DMA_INACTIVE;
162     dma[i].direct_sound_channel = DMA_NO_DIRECT_SOUND;
163     timer[i].status = TIMER_INACTIVE;
164     timer[i].reload = 0x10000;
165     timer[i].stop_cpu_ticks = 0;
166   }
167
168   timer[0].direct_sound_channels = TIMER_DS_CHANNEL_BOTH;
169   timer[1].direct_sound_channels = TIMER_DS_CHANNEL_NONE;
170
171   cpu_ticks = 0;
172   frame_ticks = 0;
173
174   execute_cycles = 960;
175   video_count = 960;
176
177   flush_translation_cache_rom();
178   flush_translation_cache_ram();
179   flush_translation_cache_bios();
180 }
181
182 int main(int argc, char *argv[])
183 {
184   u32 i;
185   u32 vcount = 0;
186   u32 ticks;
187   u32 dispstat;
188   u8 load_filename[512];
189   u8 bios_filename[512];
190
191 #ifdef GP2X_BUILD
192   if(gp2x_load_mmuhack() == -1)
193     delay_us(2500000);
194 #endif
195
196 #ifdef PSP_BUILD
197   sceKernelRegisterSubIntrHandler(PSP_VBLANK_INT, 0,
198    vblank_interrupt_handler, NULL);
199   sceKernelEnableSubIntr(PSP_VBLANK_INT, 0);
200 #else
201   freopen("CON", "wb", stdout);
202 #endif
203
204   extern char *cpu_mode_names[];
205
206   init_gamepak_buffer();
207
208   // Copy the directory path of the executable into main_path
209
210 #ifdef ARM_ARCH
211   // ChangeWorkingDirectory will null out the filename out of the path
212   ChangeWorkingDirectory(argv[0]);
213 #endif
214
215   getcwd(main_path, 512);
216   load_config_file();
217
218   gamepak_filename[0] = 0;
219
220 #ifdef PSP_BUILD
221   delay_us(2500000);
222 #endif
223
224   init_video();
225
226 #ifdef GP2X_BUILD
227   // Overclocking GP2X and MMU patch goes here
228   gp2x_overclock();
229 #endif
230
231 #ifdef GP2X_BUILD
232   sprintf(bios_filename, "%s/%s", main_path, "gba_bios.bin");
233   if(load_bios(bios_filename) == -1)
234 #else
235   if(load_bios("gba_bios.bin") == -1)
236 #endif
237   {
238     gui_action_type gui_action = CURSOR_NONE;
239
240     debug_screen_start();
241     debug_screen_printl("Sorry, but gpSP requires a Gameboy Advance BIOS   ");
242     debug_screen_printl("image to run correctly. Make sure to get an       ");
243     debug_screen_printl("authentic one, it'll be exactly 16384 bytes large ");
244     debug_screen_printl("and should have the following md5sum value:       ");
245     debug_screen_printl("                                                  ");
246     debug_screen_printl("a860e8c0b6d573d191e4ec7db1b1e4f6                  ");
247     debug_screen_printl("                                                  ");
248     debug_screen_printl("When you do get it name it gba_bios.bin and put it");
249     debug_screen_printl("in the same directory as gpSP.                    ");
250     debug_screen_printl("                                                  ");
251     debug_screen_printl("Press any button to exit.                         ");
252
253     debug_screen_update();
254
255     while(gui_action == CURSOR_NONE)
256     {
257       gui_action = get_gui_input();
258       delay_us(15000);
259     }
260
261     debug_screen_end();
262
263     quit();
264   }
265
266   if(bios_rom[0] != 0x18)
267   {
268     gui_action_type gui_action = CURSOR_NONE;
269
270     debug_screen_start();
271     debug_screen_printl("You have an incorrect BIOS image.                 ");
272     debug_screen_printl("While many games will work fine, some will not. It");
273     debug_screen_printl("is strongly recommended that you obtain the       ");
274     debug_screen_printl("correct BIOS file. Do NOT report any bugs if you  ");
275     debug_screen_printl("are seeing this message.                          ");
276     debug_screen_printl("                                                  ");
277     debug_screen_printl("Press any button to resume, at your own risk.     ");
278
279     debug_screen_update();
280
281     while(gui_action == CURSOR_NONE)
282     {
283       gui_action = get_gui_input();
284       delay_us(15000);
285     }
286
287     debug_screen_end();
288   }
289
290   init_main();
291   init_sound();
292
293   init_input();
294
295   video_resolution_large();
296
297   if(argc > 1)
298   {
299     if(load_gamepak(argv[1]) == -1)
300     {
301 #ifdef PC_BUILD
302       printf("Failed to load gamepak %s, exiting.\n", load_filename);
303 #endif
304       exit(-1);
305     }
306
307     set_gba_resolution(screen_scale);
308     video_resolution_small();
309
310     init_cpu();
311     init_memory();
312   }
313   else
314   {
315     if(load_file(file_ext, load_filename) == -1)
316     {
317       menu(copy_screen());
318     }
319     else
320     {
321       if(load_gamepak(load_filename) == -1)
322       {
323 #ifdef PC_BUILD
324         printf("Failed to load gamepak %s, exiting.\n", load_filename);
325 #endif
326         exit(-1);
327       }
328
329       set_gba_resolution(screen_scale);
330       video_resolution_small();
331
332       init_cpu();
333       init_memory();
334     }
335   }
336
337   last_frame = 0;
338
339   // We'll never actually return from here.
340
341 #ifdef PSP_BUILD
342   execute_arm_translate(execute_cycles);
343 #else
344
345 #ifdef GP2X_BUILD
346   get_ticks_us(&frame_count_initial_timestamp);
347 #endif
348
349 /*  u8 current_savestate_filename[512];
350   get_savestate_filename_noshot(savestate_slot,
351    current_savestate_filename);
352   load_state(current_savestate_filename); */
353
354   debug_on();
355
356   if(argc > 2)
357   {
358     current_debug_state = COUNTDOWN_BREAKPOINT;
359     breakpoint_value = strtol(argv[2], NULL, 16);
360   }
361
362   trigger_ext_event();
363
364   execute_arm_translate(execute_cycles);
365   execute_arm(execute_cycles);
366 #endif
367   return 0;
368 }
369
370 void print_memory_stats(u32 *counter, u32 *region_stats, char *stats_str)
371 {
372   u32 other_region_counter = region_stats[0x1] + region_stats[0xE] +
373    region_stats[0xF];
374   u32 rom_region_counter = region_stats[0x8] + region_stats[0x9] +
375    region_stats[0xA] + region_stats[0xB] + region_stats[0xC] +
376    region_stats[0xD];
377   u32 _counter = *counter;
378
379   printf("memory access stats: %s (out of %d)\n", stats_str, _counter);
380   printf("bios: %f%%\tiwram: %f%%\tewram: %f%%\tvram: %f\n",
381    region_stats[0x0] * 100.0 / _counter, region_stats[0x3] * 100.0 /
382    _counter,
383    region_stats[0x2] * 100.0 / _counter, region_stats[0x6] * 100.0 /
384    _counter);
385
386   printf("oam: %f%%\tpalette: %f%%\trom: %f%%\tother: %f%%\n",
387    region_stats[0x7] * 100.0 / _counter, region_stats[0x5] * 100.0 /
388    _counter,
389    rom_region_counter * 100.0 / _counter, other_region_counter * 100.0 /
390    _counter);
391
392   *counter = 0;
393   memset(region_stats, 0, sizeof(u32) * 16);
394 }
395
396 u32 event_cycles = 0;
397 const u32 event_cycles_trigger = 60 * 5;
398 u32 no_alpha = 0;
399
400 void trigger_ext_event()
401 {
402   static u32 event_number = 0;
403   static u64 benchmark_ticks[16];
404   u64 new_ticks;
405   u8 current_savestate_filename[512];
406
407   return;
408
409   if(event_number)
410   {
411     get_ticks_us(&new_ticks);
412     benchmark_ticks[event_number - 1] =
413      new_ticks - benchmark_ticks[event_number - 1];
414   }
415
416   current_frameskip_type = no_frameskip;
417   no_alpha = 0;
418   synchronize_flag = 0;
419
420   get_savestate_filename_noshot(savestate_slot,
421    current_savestate_filename);
422   load_state(current_savestate_filename);
423
424   switch(event_number)
425   {
426     case 0:
427       // Full benchmark, run normally
428       break;
429
430     case 1:
431       // No alpha blending
432       no_alpha = 1;
433       break;
434
435     case 2:
436       // No video benchmark
437       // Set frameskip really high + manual
438       current_frameskip_type = manual_frameskip;
439       frameskip_value = 1000000;
440       break;
441
442     case 3:
443       // No CPU benchmark
444       // Put CPU in halt mode, put it in IRQ mode with interrupts off
445       reg[CPU_HALT_STATE] = CPU_HALT;
446       reg[REG_CPSR] = 0xD2;
447       break;
448
449     case 4:
450       // No CPU or video benchmark
451       reg[CPU_HALT_STATE] = CPU_HALT;
452       reg[REG_CPSR] = 0xD2;
453       current_frameskip_type = manual_frameskip;
454       frameskip_value = 1000000;
455       break;
456
457     case 5:
458     {
459       // Done
460       char *print_strings[] =
461       {
462         "Full test   ",
463         "No blending ",
464         "No video    ",
465         "No CPU      ",
466         "No CPU/video",
467         "CPU speed   ",
468         "Video speed ",
469         "Alpha cost  "
470       };
471       u32 i;
472
473       benchmark_ticks[6] = benchmark_ticks[0] - benchmark_ticks[2];
474       benchmark_ticks[5] = benchmark_ticks[0] - benchmark_ticks[4] -
475        benchmark_ticks[6];
476       benchmark_ticks[7] = benchmark_ticks[0] - benchmark_ticks[1];
477
478       printf("Benchmark results (%d frames): \n", event_cycles_trigger);
479       for(i = 0; i < 8; i++)
480       {
481         printf("   %s: %d ms (%f ms per frame)\n",
482          print_strings[i], (u32)benchmark_ticks[i] / 1000,
483          (float)(benchmark_ticks[i] / (1000.0 * event_cycles_trigger)));
484         if(i == 4)
485           printf("\n");
486       }
487       quit();
488     }
489   }
490
491   event_cycles = 0;
492
493   get_ticks_us(benchmark_ticks + event_number);
494   event_number++;
495 }
496
497 u32 update_gba()
498 {
499   irq_type irq_raised = IRQ_NONE;
500
501   do
502   {
503     cpu_ticks += execute_cycles;
504
505     reg[CHANGED_PC_STATUS] = 0;
506
507     if(gbc_sound_update)
508     {
509       gbc_update_count++;
510       update_gbc_sound(cpu_ticks);
511       gbc_sound_update = 0;
512     }
513
514     update_timer(0);
515     update_timer(1);
516     update_timer(2);
517     update_timer(3);
518
519     video_count -= execute_cycles;
520
521     if(video_count <= 0)
522     {
523       u32 vcount = io_registers[REG_VCOUNT];
524       u32 dispstat = io_registers[REG_DISPSTAT];
525
526       if((dispstat & 0x02) == 0)
527       {
528         // Transition from hrefresh to hblank
529         video_count += (272);
530         dispstat |= 0x02;
531
532         if((dispstat & 0x01) == 0)
533         {
534           u32 i;
535           if(oam_update)
536             oam_update_count++;
537
538           if(no_alpha)
539             io_registers[REG_BLDCNT] = 0;
540           update_scanline();
541
542           // If in visible area also fire HDMA
543           for(i = 0; i < 4; i++)
544           {
545             if(dma[i].start_type == DMA_START_HBLANK)
546               dma_transfer(dma + i);
547           }
548         }
549
550         if(dispstat & 0x10)
551           irq_raised |= IRQ_HBLANK;
552       }
553       else
554       {
555         // Transition from hblank to next line
556         video_count += 960;
557         dispstat &= ~0x02;
558
559         vcount++;
560
561         if(vcount == 160)
562         {
563           // Transition from vrefresh to vblank
564           u32 i;
565
566           dispstat |= 0x01;
567           if(dispstat & 0x8)
568           {
569             irq_raised |= IRQ_VBLANK;
570           }
571
572           affine_reference_x[0] =
573            (s32)(address32(io_registers, 0x28) << 4) >> 4;
574           affine_reference_y[0] =
575            (s32)(address32(io_registers, 0x2C) << 4) >> 4;
576           affine_reference_x[1] =
577            (s32)(address32(io_registers, 0x38) << 4) >> 4;
578           affine_reference_y[1] =
579            (s32)(address32(io_registers, 0x3C) << 4) >> 4;
580
581           for(i = 0; i < 4; i++)
582           {
583             if(dma[i].start_type == DMA_START_VBLANK)
584               dma_transfer(dma + i);
585           }
586         }
587         else
588
589         if(vcount == 228)
590         {
591           // Transition from vblank to next screen
592           dispstat &= ~0x01;
593           frame_ticks++;
594
595   #ifdef PC_BUILD
596         printf("frame update (%x), %d instructions total, %d RAM flushes\n",
597            reg[REG_PC], instruction_count - last_frame, flush_ram_count);
598           last_frame = instruction_count;
599
600 /*          printf("%d gbc audio updates\n", gbc_update_count);
601           printf("%d oam updates\n", oam_update_count); */
602           gbc_update_count = 0;
603           oam_update_count = 0;
604           flush_ram_count = 0;
605   #endif
606
607           if(update_input())
608             continue;
609
610           update_gbc_sound(cpu_ticks);
611           synchronize();
612
613           update_screen();
614
615           if(update_backup_flag)
616             update_backup();
617
618           process_cheats();
619
620           event_cycles++;
621           if(event_cycles == event_cycles_trigger)
622           {
623             trigger_ext_event();
624             continue;
625           }
626
627           vcount = 0;
628         }
629
630         if(vcount == (dispstat >> 8))
631         {
632           // vcount trigger
633           dispstat |= 0x04;
634           if(dispstat & 0x20)
635           {
636             irq_raised |= IRQ_VCOUNT;
637           }
638         }
639         else
640         {
641           dispstat &= ~0x04;
642         }
643
644         io_registers[REG_VCOUNT] = vcount;
645       }
646       io_registers[REG_DISPSTAT] = dispstat;
647     }
648
649     if(irq_raised)
650       raise_interrupt(irq_raised);
651
652     execute_cycles = video_count;
653
654     check_timer(0);
655     check_timer(1);
656     check_timer(2);
657     check_timer(3);
658   } while(reg[CPU_HALT_STATE] != CPU_ACTIVE);
659
660   return execute_cycles;
661 }
662
663 u64 last_screen_timestamp = 0;
664 u32 frame_speed = 15000;
665
666
667 #ifdef PSP_BUILD
668
669 u32 real_frame_count = 0;
670 u32 virtual_frame_count = 0;
671 u32 num_skipped_frames = 0;
672
673 void vblank_interrupt_handler(u32 sub, u32 *parg)
674 {
675   real_frame_count++;
676 }
677
678 void synchronize()
679 {
680   char char_buffer[64];
681   u64 new_ticks, time_delta;
682   s32 used_frameskip = frameskip_value;
683
684   if(!synchronize_flag)
685   {
686     print_string("--FF--", 0xFFFF, 0x000, 0, 0);
687     used_frameskip = 4;
688     virtual_frame_count = real_frame_count - 1;
689   }
690
691   skip_next_frame = 0;
692
693   virtual_frame_count++;
694
695   if(real_frame_count >= virtual_frame_count)
696   {
697     if((real_frame_count > virtual_frame_count) &&
698      (current_frameskip_type == auto_frameskip) &&
699      (num_skipped_frames < frameskip_value))
700     {
701       skip_next_frame = 1;
702       num_skipped_frames++;
703     }
704     else
705     {
706       virtual_frame_count = real_frame_count;
707       num_skipped_frames = 0;
708     }
709
710     // Here so that the home button return will eventually work.
711     // If it's not running fullspeed anyway this won't really hurt
712     // it much more.
713
714     delay_us(1);
715   }
716   else
717   {
718     if(synchronize_flag)
719       sceDisplayWaitVblankStart();
720   }
721
722   if(current_frameskip_type == manual_frameskip)
723   {
724     frameskip_counter = (frameskip_counter + 1) %
725      (used_frameskip + 1);
726     if(random_skip)
727     {
728       if(frameskip_counter != (rand() % (used_frameskip + 1)))
729         skip_next_frame = 1;
730     }
731     else
732     {
733       if(frameskip_counter)
734         skip_next_frame = 1;
735     }
736   }
737
738 /*  sprintf(char_buffer, "%08d %08d %d %d %d\n",
739    real_frame_count, virtual_frame_count, num_skipped_frames,
740    real_frame_count - virtual_frame_count, skip_next_frame);
741   print_string(char_buffer, 0xFFFF, 0x0000, 0, 10); */
742
743 /*
744     sprintf(char_buffer, "%02d %02d %06d %07d", frameskip, (u32)ms_needed,
745      ram_translation_ptr - ram_translation_cache, rom_translation_ptr -
746      rom_translation_cache);
747     print_string(char_buffer, 0xFFFF, 0x0000, 0, 0);
748 */
749 }
750
751 #endif
752
753 #ifdef GP2X_BUILD
754
755 u32 real_frame_count = 0;
756 u32 virtual_frame_count = 0;
757 u32 num_skipped_frames = 0;
758 u32 interval_skipped_frames;
759 u32 frames;
760
761 u32 skipped_frames = 0;
762 u32 ticks_needed_total = 0;
763 const u32 frame_interval = 60;
764
765 void synchronize()
766 {
767   u64 new_ticks;
768   u64 time_delta;
769   static u32 fps = 60;
770   static u32 frames_drawn = 60;
771
772   if(gp2x_fps_debug)
773   {
774     char print_buffer[128];
775     sprintf(print_buffer, "%d (%d)", fps, frames_drawn);
776     print_string(print_buffer, 0xFFFF, 0x000, 0, 0);
777   }
778
779   get_ticks_us(&new_ticks);
780   time_delta = new_ticks - last_screen_timestamp;
781   last_screen_timestamp = new_ticks;
782   ticks_needed_total += time_delta;
783
784   skip_next_frame = 0;
785   virtual_frame_count++;
786
787   real_frame_count = ((new_ticks -
788     frame_count_initial_timestamp) * 3) / 50000;
789
790   if(real_frame_count >= virtual_frame_count)
791   {
792     if((real_frame_count > virtual_frame_count) &&
793      (current_frameskip_type == auto_frameskip) &&
794      (num_skipped_frames < frameskip_value))
795     {
796       skip_next_frame = 1;
797       num_skipped_frames++;
798     }
799     else
800     {
801       virtual_frame_count = real_frame_count;
802       num_skipped_frames = 0;
803     }
804   }
805   else
806   {
807     if((synchronize_flag) &&
808      ((time_delta < frame_speed) && synchronize_flag))
809     {
810       delay_us(frame_speed - time_delta);
811     }
812   }
813
814   frames++;
815
816   if(frames == frame_interval)
817   {
818     u32 new_fps;
819     u32 new_frames_drawn;
820
821     time_delta = new_ticks - last_frame_interval_timestamp;
822     new_fps = (u64)((u64)1000000 * (u64)frame_interval) / time_delta;
823     new_frames_drawn =
824      (frame_interval - interval_skipped_frames) * (60 / frame_interval);
825
826     // Left open for rolling averages
827     fps = new_fps;
828     frames_drawn = new_frames_drawn;
829
830     last_frame_interval_timestamp = new_ticks;
831     interval_skipped_frames = 0;
832     ticks_needed_total = 0;
833     frames = 0;
834   }
835
836   if(current_frameskip_type == manual_frameskip)
837   {
838     frameskip_counter = (frameskip_counter + 1) %
839      (frameskip_value + 1);
840     if(random_skip)
841     {
842       if(frameskip_counter != (rand() % (frameskip_value + 1)))
843         skip_next_frame = 1;
844     }
845     else
846     {
847       if(frameskip_counter)
848         skip_next_frame = 1;
849     }
850   }
851
852   interval_skipped_frames += skip_next_frame;
853
854   if(!synchronize_flag)
855     print_string("--FF--", 0xFFFF, 0x000, 0, 0);
856 }
857
858 #endif
859
860
861 #ifdef PC_BUILD
862
863 u32 ticks_needed_total = 0;
864 float us_needed = 0.0;
865 u32 frames = 0;
866 const u32 frame_interval = 60;
867
868 void synchronize()
869 {
870   u64 new_ticks;
871   u64 time_delta;
872   char char_buffer[64];
873
874   get_ticks_us(&new_ticks);
875   time_delta = new_ticks - last_screen_timestamp;
876   last_screen_timestamp = new_ticks;
877   ticks_needed_total += time_delta;
878
879   skip_next_frame = 0;
880
881   if((time_delta < frame_speed) && synchronize_flag)
882   {
883     delay_us(frame_speed - time_delta);
884   }
885
886   frames++;
887
888   if(frames == frame_interval)
889   {
890     us_needed = (float)ticks_needed_total / frame_interval;
891     ticks_needed_total = 0;
892     frames = 0;
893   }
894
895   if(current_frameskip_type == manual_frameskip)
896   {
897     frameskip_counter = (frameskip_counter + 1) %
898      (frameskip_value + 1);
899     if(random_skip)
900     {
901       if(frameskip_counter != (rand() % (frameskip_value + 1)))
902         skip_next_frame = 1;
903     }
904     else
905     {
906       if(frameskip_counter)
907         skip_next_frame = 1;
908     }
909   }
910
911   if(synchronize_flag == 0)
912     print_string("--FF--", 0xFFFF, 0x000, 0, 0);
913
914   sprintf(char_buffer, "gpSP: %.1fms %.1ffps", us_needed / 1000.0,
915    1000000.0 / us_needed);
916   SDL_WM_SetCaption(char_buffer, "gpSP");
917
918 /*
919     sprintf(char_buffer, "%02d %02d %06d %07d", frameskip, (u32)ms_needed,
920      ram_translation_ptr - ram_translation_cache, rom_translation_ptr -
921      rom_translation_cache);
922     print_string(char_buffer, 0xFFFF, 0x0000, 0, 0);
923 */
924 }
925
926 #endif
927
928 void quit()
929 {
930   if(!update_backup_flag)
931     update_backup_force();
932
933   sound_exit();
934
935 #ifdef REGISTER_USAGE_ANALYZE
936   print_register_usage();
937 #endif
938
939 #ifdef PSP_BUILD
940   sceKernelExitGame();
941 #else
942   SDL_Quit();
943
944 #ifdef GP2X_BUILD
945   gp2x_quit();
946 #endif
947
948   exit(0);
949 #endif
950 }
951
952 void reset_gba()
953 {
954   init_main();
955   init_memory();
956   init_cpu();
957   reset_sound();
958 }
959
960 #ifdef PSP_BUILD
961
962 u32 file_length(u8 *filename, s32 dummy)
963 {
964   SceIoStat stats;
965   sceIoGetstat(filename, &stats);
966   return stats.st_size;
967 }
968
969 void delay_us(u32 us_count)
970 {
971   sceKernelDelayThread(us_count);
972 }
973
974 void get_ticks_us(u64 *tick_return)
975 {
976   u64 ticks;
977   sceRtcGetCurrentTick(&ticks);
978
979   *tick_return = (ticks * 1000000) / sceRtcGetTickResolution();
980 }
981
982 #else
983
984 u32 file_length(u8 *dummy, FILE *fp)
985 {
986   u32 length;
987
988   fseek(fp, 0, SEEK_END);
989   length = ftell(fp);
990   fseek(fp, 0, SEEK_SET);
991
992   return length;
993 }
994
995 #ifdef PC_BUILD
996
997 void delay_us(u32 us_count)
998 {
999   SDL_Delay(us_count / 1000);
1000 }
1001
1002 void get_ticks_us(u64 *ticks_return)
1003 {
1004   *ticks_return = (SDL_GetTicks() * 1000);
1005 }
1006
1007 #else
1008
1009 void delay_us(u32 us_count)
1010 {
1011   usleep(us_count);
1012 }
1013
1014 void get_ticks_us(u64 *ticks_return)
1015 {
1016   struct timeval current_time;
1017   gettimeofday(&current_time, NULL);
1018
1019   *ticks_return =
1020    (u64)current_time.tv_sec * 1000000 + current_time.tv_usec;
1021 }
1022
1023 #endif
1024
1025 #endif
1026
1027 void change_ext(u8 *src, u8 *buffer, u8 *extension)
1028 {
1029   u8 *dot_position;
1030   strcpy(buffer, src);
1031   dot_position = strrchr(buffer, '.');
1032
1033   if(dot_position)
1034     strcpy(dot_position, extension);
1035 }
1036
1037 #define main_savestate_builder(type)                                          \
1038 void main_##type##_savestate(file_tag_type savestate_file)                    \
1039 {                                                                             \
1040   file_##type##_variable(savestate_file, cpu_ticks);                          \
1041   file_##type##_variable(savestate_file, execute_cycles);                     \
1042   file_##type##_variable(savestate_file, video_count);                        \
1043   file_##type##_array(savestate_file, timer);                                 \
1044 }                                                                             \
1045
1046 main_savestate_builder(read);
1047 main_savestate_builder(write_mem);
1048
1049
1050 void printout(void *str, u32 val)
1051 {
1052   printf(str, val);
1053 }