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