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