cdrom: change pause timing again
[pcsx_rearmed.git] / frontend / plugin_lib.c
1 /*
2  * (C) notaz, 2010-2011
3  *
4  * This work is licensed under the terms of the GNU GPLv2 or later.
5  * See the COPYING file in the top-level directory.
6  */
7
8 #include <stdio.h>
9 #include <stdlib.h>
10 #include <string.h>
11 #include <stdarg.h>
12 #include <stdint.h>
13 #include <sys/time.h>
14 #include <sys/types.h>
15 #include <sys/stat.h>
16 #include <fcntl.h>
17 #include <unistd.h>
18 #include <pthread.h>
19 #include <assert.h>
20
21 #include "libpicofe/fonts.h"
22 #include "libpicofe/input.h"
23 #include "libpicofe/plat.h"
24 #include "libpicofe/arm/neon_scale2x.h"
25 #include "libpicofe/arm/neon_eagle2x.h"
26 #include "plugin_lib.h"
27 #include "menu.h"
28 #include "main.h"
29 #include "plat.h"
30 #include "pcnt.h"
31 #include "pl_gun_ts.h"
32 #include "cspace.h"
33 #include "psemu_plugin_defs.h"
34 #include "../libpcsxcore/new_dynarec/new_dynarec.h"
35 #include "../libpcsxcore/psxmem_map.h"
36 #include "../libpcsxcore/gpu.h"
37 #include "../libpcsxcore/r3000a.h"
38 #include "../libpcsxcore/psxcounters.h"
39
40 #define HUD_HEIGHT 10
41
42 int in_type[8];
43 int multitap1;
44 int multitap2;
45 int in_analog_left[8][2] = {{ 127, 127 },{ 127, 127 },{ 127, 127 },{ 127, 127 },{ 127, 127 },{ 127, 127 },{ 127, 127 },{ 127, 127 }};
46 int in_analog_right[8][2] = {{ 127, 127 },{ 127, 127 },{ 127, 127 },{ 127, 127 },{ 127, 127 },{ 127, 127 },{ 127, 127 },{ 127, 127 }};
47 int in_adev[2] = { -1, -1 }, in_adev_axis[2][2] = {{ 0, 1 }, { 0, 1 }};
48 int in_adev_is_nublike[2];
49 unsigned short in_keystate[8];
50 int in_mouse[8][2];
51 int in_enable_vibration;
52 void *tsdev;
53 void *pl_vout_buf;
54 int g_layer_x, g_layer_y, g_layer_w, g_layer_h;
55 static int pl_vout_w, pl_vout_h, pl_vout_bpp; /* output display/layer */
56 static int pl_vout_scale_w, pl_vout_scale_h, pl_vout_yoffset;
57 static int psx_w, psx_h, psx_bpp;
58 static int vsync_cnt;
59 static int is_pal, frame_interval, frame_interval1024;
60 static int vsync_usec_time;
61
62 // platform hooks
63 void (*pl_plat_clear)(void);
64 void (*pl_plat_blit)(int doffs, const void *src, int w, int h,
65                      int sstride, int bgr24);
66 void (*pl_plat_hud_print)(int x, int y, const char *str, int bpp);
67
68
69 static __attribute__((noinline)) int get_cpu_ticks(void)
70 {
71         static unsigned long last_utime;
72         static int fd;
73         unsigned long utime, ret;
74         char buf[128];
75
76         if (fd == 0)
77                 fd = open("/proc/self/stat", O_RDONLY);
78         lseek(fd, 0, SEEK_SET);
79         buf[0] = 0;
80         read(fd, buf, sizeof(buf));
81         buf[sizeof(buf) - 1] = 0;
82
83         sscanf(buf, "%*d %*s %*c %*d %*d %*d %*d %*d %*u %*u %*u %*u %*u %lu", &utime);
84         ret = utime - last_utime;
85         if (ret > 200)
86                 ret = 0;
87         last_utime = utime;
88         return ret;
89 }
90
91 static void hud_print(void *fb, int w, int x, int y, const char *text)
92 {
93         if (pl_plat_hud_print)
94                 pl_plat_hud_print(x, y, text, pl_vout_bpp);
95         else if (pl_vout_bpp == 16)
96                 basic_text_out16_nf(fb, w, x, y, text);
97 }
98
99 static void hud_printf(void *fb, int w, int x, int y, const char *texto, ...)
100 {
101         va_list args;
102         char    buffer[256];
103
104         va_start(args, texto);
105         vsnprintf(buffer, sizeof(buffer), texto, args);
106         va_end(args);
107
108         hud_print(fb, w, x, y, buffer);
109 }
110
111 static void print_msg(int h, int border)
112 {
113         hud_print(pl_vout_buf, pl_vout_w, border + 2, h - HUD_HEIGHT, hud_msg);
114 }
115
116 static void print_fps(int h, int border)
117 {
118         hud_printf(pl_vout_buf, pl_vout_w, border + 2, h - HUD_HEIGHT,
119                 "%2d %4.1f", pl_rearmed_cbs.flips_per_sec,
120                 pl_rearmed_cbs.vsps_cur);
121 }
122
123 static void print_cpu_usage(int x, int h)
124 {
125         hud_printf(pl_vout_buf, pl_vout_w, x - 28,
126                 h - HUD_HEIGHT, "%3d", pl_rearmed_cbs.cpu_usage);
127 }
128
129 // draw 192x8 status of 24 sound channels
130 static __attribute__((noinline)) void draw_active_chans(int vout_w, int vout_h)
131 {
132         extern void spu_get_debug_info(int *chans_out, int *run_chans,
133                 int *fmod_chans_out, int *noise_chans_out); // hack
134         int live_chans, run_chans, fmod_chans, noise_chans;
135
136         static const unsigned short colors[2] = { 0x1fe3, 0x0700 };
137         unsigned short *dest = (unsigned short *)pl_vout_buf +
138                 pl_vout_w * (vout_h - HUD_HEIGHT) + pl_vout_w / 2 - 192/2;
139         unsigned short *d, p;
140         int c, x, y;
141
142         if (pl_vout_buf == NULL || pl_vout_bpp != 16)
143                 return;
144
145         spu_get_debug_info(&live_chans, &run_chans, &fmod_chans, &noise_chans);
146
147         for (c = 0; c < 24; c++) {
148                 d = dest + c * 8;
149                 p = !(live_chans & (1<<c)) ? (run_chans & (1<<c) ? 0x01c0 : 0) :
150                      (fmod_chans & (1<<c)) ? 0xf000 :
151                      (noise_chans & (1<<c)) ? 0x001f :
152                      colors[c & 1];
153                 for (y = 0; y < 8; y++, d += pl_vout_w)
154                         for (x = 0; x < 8; x++)
155                                 d[x] = p;
156         }
157 }
158
159 static void print_hud(int x, int w, int h)
160 {
161         if (h < 192)
162                 return;
163
164         if (h > pl_vout_h)
165                 h = pl_vout_h;
166
167         if (g_opts & OPT_SHOWSPU)
168                 draw_active_chans(w, h);
169
170         if (hud_msg[0] != 0)
171                 print_msg(h, x);
172         else if (g_opts & OPT_SHOWFPS)
173                 print_fps(h, x);
174
175         if (g_opts & OPT_SHOWCPU)
176                 print_cpu_usage(x + w, h);
177 }
178
179 /* update scaler target size according to user settings */
180 static void update_layer_size(int w, int h)
181 {
182         float mult;
183         int imult;
184
185         switch (g_scaler) {
186         case SCALE_1_1:
187                 g_layer_w = w; g_layer_h = h;
188                 break;
189
190         case SCALE_2_2:
191                 g_layer_w = w; g_layer_h = h;
192                 if (w * 2 <= g_menuscreen_w)
193                         g_layer_w = w * 2;
194                 if (h * 2 <= g_menuscreen_h)
195                         g_layer_h = h * 2;
196                 break;
197
198         case SCALE_4_3v2:
199                 if (h > g_menuscreen_h || (240 < h && h <= 360))
200                         goto fractional_4_3;
201
202                 // 4:3 that prefers integer scaling
203                 imult = g_menuscreen_h / h;
204                 g_layer_w = w * imult;
205                 g_layer_h = h * imult;
206                 mult = (float)g_layer_w / (float)g_layer_h;
207                 if (mult < 1.25f || mult > 1.666f)
208                         g_layer_w = 4.0f/3.0f * (float)g_layer_h;
209                 printf("  -> %dx%d %.1f\n", g_layer_w, g_layer_h, mult);
210                 break;
211
212         fractional_4_3:
213         case SCALE_4_3:
214                 mult = 240.0f / (float)h * 4.0f / 3.0f;
215                 if (h > 256)
216                         mult *= 2.0f;
217                 g_layer_w = mult * (float)g_menuscreen_h;
218                 g_layer_h = g_menuscreen_h;
219                 printf("  -> %dx%d %.1f\n", g_layer_w, g_layer_h, mult);
220                 break;
221
222         case SCALE_FULLSCREEN:
223                 g_layer_w = g_menuscreen_w;
224                 g_layer_h = g_menuscreen_h;
225                 break;
226
227         default:
228                 break;
229         }
230
231         if (g_scaler != SCALE_CUSTOM) {
232                 g_layer_x = g_menuscreen_w / 2 - g_layer_w / 2;
233                 g_layer_y = g_menuscreen_h / 2 - g_layer_h / 2;
234         }
235         if (g_layer_w > g_menuscreen_w * 2) g_layer_w = g_menuscreen_w * 2;
236         if (g_layer_h > g_menuscreen_h * 2) g_layer_h = g_menuscreen_h * 2;
237 }
238
239 // XXX: this is platform specific really
240 static inline int resolution_ok(int w, int h)
241 {
242         return w <= 1024 && h <= 512;
243 }
244
245 static void pl_vout_set_mode(int w, int h, int raw_w, int raw_h, int bpp)
246 {
247         int vout_w, vout_h, vout_bpp;
248         int buf_yoffset = 0;
249
250         // special h handling, Wipeout likes to change it by 1-6
251         static int vsync_cnt_ms_prev;
252         if ((unsigned int)(vsync_cnt - vsync_cnt_ms_prev) < 5*60)
253                 h = (h + 7) & ~7;
254         vsync_cnt_ms_prev = vsync_cnt;
255
256         psx_w = raw_w;
257         psx_h = raw_h;
258         psx_bpp = bpp;
259         vout_w = w;
260         vout_h = h;
261         vout_bpp = bpp;
262         if (pl_rearmed_cbs.only_16bpp)
263                 vout_bpp = 16;
264
265         assert(vout_h >= 192);
266
267         pl_vout_scale_w = pl_vout_scale_h = 1;
268 #ifdef __ARM_NEON__
269         if (soft_filter) {
270                 if (resolution_ok(w * 2, h * 2) && bpp == 16) {
271                         pl_vout_scale_w = 2;
272                         pl_vout_scale_h = 2;
273                 }
274                 else {
275                         // filter unavailable
276                         hud_msg[0] = 0;
277                 }
278         }
279         else if (scanlines != 0 && scanline_level != 100 && bpp == 16) {
280                 if (h <= 256)
281                         pl_vout_scale_h = 2;
282         }
283 #endif
284         vout_w *= pl_vout_scale_w;
285         vout_h *= pl_vout_scale_h;
286
287         update_layer_size(vout_w, vout_h);
288
289         pl_vout_buf = plat_gvideo_set_mode(&vout_w, &vout_h, &vout_bpp);
290         if (pl_vout_buf == NULL && pl_plat_blit == NULL)
291                 fprintf(stderr, "failed to set mode %dx%d@%d\n",
292                         vout_w, vout_h, vout_bpp);
293         else {
294                 pl_vout_w = vout_w;
295                 pl_vout_h = vout_h;
296                 pl_vout_bpp = vout_bpp;
297                 pl_vout_yoffset = buf_yoffset;
298         }
299         if (pl_vout_buf != NULL)
300                 pl_vout_buf = (char *)pl_vout_buf
301                         + pl_vout_yoffset * pl_vout_w * pl_vout_bpp / 8;
302
303         menu_notify_mode_change(pl_vout_w, pl_vout_h, pl_vout_bpp);
304 }
305
306 static int flip_clear_counter;
307
308 void pl_force_clear(void)
309 {
310         flip_clear_counter = 2;
311 }
312
313 static void pl_vout_flip(const void *vram, int stride, int bgr24,
314         int x, int y, int w, int h, int dims_changed)
315 {
316         unsigned char *dest = pl_vout_buf;
317         const unsigned short *src = vram;
318         int dstride = pl_vout_w, h1 = h;
319         int h_full = pl_vout_h - pl_vout_yoffset;
320         int xoffs = 0, doffs;
321
322         pcnt_start(PCNT_BLIT);
323
324         if (vram == NULL) {
325                 // blanking
326                 if (pl_plat_clear)
327                         pl_plat_clear();
328                 else
329                         memset(pl_vout_buf, 0,
330                                 dstride * h_full * pl_vout_bpp / 8);
331                 goto out_hud;
332         }
333
334         assert(x + w <= pl_vout_w);
335         assert(y + h <= pl_vout_h);
336
337         // offset
338         xoffs = x * pl_vout_scale_w;
339         doffs = xoffs + y * dstride;
340
341         if (dims_changed)
342                 flip_clear_counter = 3;
343
344         if (flip_clear_counter > 0) {
345                 if (pl_plat_clear)
346                         pl_plat_clear();
347                 else
348                         memset(pl_vout_buf, 0,
349                                 dstride * h_full * pl_vout_bpp / 8);
350                 flip_clear_counter--;
351         }
352
353         if (pl_plat_blit)
354         {
355                 pl_plat_blit(doffs, src, w, h, stride, bgr24);
356                 goto out_hud;
357         }
358
359         if (dest == NULL)
360                 goto out;
361
362         dest += doffs * 2;
363
364         if (bgr24)
365         {
366                 if (pl_rearmed_cbs.only_16bpp) {
367                         for (; h1-- > 0; dest += dstride * 2, src += stride)
368                         {
369                                 bgr888_to_rgb565(dest, src, w * 3);
370                         }
371                 }
372                 else {
373                         dest -= doffs * 2;
374                         dest += (doffs / 8) * 24;
375
376                         for (; h1-- > 0; dest += dstride * 3, src += stride)
377                         {
378                                 bgr888_to_rgb888(dest, src, w * 3);
379                         }
380                 }
381         }
382 #ifdef __ARM_NEON__
383         else if (soft_filter == SOFT_FILTER_SCALE2X && pl_vout_scale_w == 2)
384         {
385                 neon_scale2x_16_16(src, (void *)dest, w,
386                         stride * 2, dstride * 2, h);
387         }
388         else if (soft_filter == SOFT_FILTER_EAGLE2X && pl_vout_scale_w == 2)
389         {
390                 neon_eagle2x_16_16(src, (void *)dest, w,
391                         stride * 2, dstride * 2, h);
392         }
393         else if (scanlines != 0 && scanline_level != 100)
394         {
395                 int h2, l = scanline_level * 2048 / 100;
396                 int stride_0 = pl_vout_scale_h >= 2 ? 0 : stride;
397
398                 h1 *= pl_vout_scale_h;
399                 while (h1 > 0)
400                 {
401                         for (h2 = scanlines; h2 > 0 && h1 > 0; h2--, h1--) {
402                                 bgr555_to_rgb565(dest, src, w * 2);
403                                 dest += dstride * 2, src += stride_0;
404                         }
405
406                         for (h2 = scanlines; h2 > 0 && h1 > 0; h2--, h1--) {
407                                 bgr555_to_rgb565_b(dest, src, w * 2, l);
408                                 dest += dstride * 2, src += stride;
409                         }
410                 }
411         }
412 #endif
413         else
414         {
415                 for (; h1-- > 0; dest += dstride * 2, src += stride)
416                 {
417                         bgr555_to_rgb565(dest, src, w * 2);
418                 }
419         }
420
421 out_hud:
422         print_hud(xoffs, w * pl_vout_scale_w, (y + h) * pl_vout_scale_h);
423
424 out:
425         pcnt_end(PCNT_BLIT);
426
427         // let's flip now
428         pl_vout_buf = plat_gvideo_flip();
429         if (pl_vout_buf != NULL)
430                 pl_vout_buf = (char *)pl_vout_buf
431                         + pl_vout_yoffset * pl_vout_w * pl_vout_bpp / 8;
432
433         pl_rearmed_cbs.flip_cnt++;
434 }
435
436 static int pl_vout_open(void)
437 {
438         struct timeval now;
439
440         // force mode update on pl_vout_set_mode() call from gpulib/vout_pl
441         pl_vout_buf = NULL;
442
443         plat_gvideo_open(is_pal);
444
445         gettimeofday(&now, 0);
446         vsync_usec_time = now.tv_usec;
447         while (vsync_usec_time >= frame_interval)
448                 vsync_usec_time -= frame_interval;
449
450         return 0;
451 }
452
453 static void pl_vout_close(void)
454 {
455         plat_gvideo_close();
456 }
457
458 static void pl_set_gpu_caps(int caps)
459 {
460         pl_rearmed_cbs.gpu_caps = caps;
461 }
462
463 void *pl_prepare_screenshot(int *w, int *h, int *bpp)
464 {
465         void *ret = plat_prepare_screenshot(w, h, bpp);
466         if (ret != NULL)
467                 return ret;
468
469         *w = pl_vout_w;
470         *h = pl_vout_h;
471         *bpp = pl_vout_bpp;
472
473         return pl_vout_buf;
474 }
475
476 /* display/redering mode switcher */
477 static int dispmode_default(void)
478 {
479         pl_rearmed_cbs.gpu_neon.enhancement_enable = 0;
480         soft_filter = SOFT_FILTER_NONE;
481         snprintf(hud_msg, sizeof(hud_msg), "default mode");
482         return 1;
483 }
484
485 #ifdef BUILTIN_GPU_NEON
486 static int dispmode_doubleres(void)
487 {
488         if (!(pl_rearmed_cbs.gpu_caps & GPU_CAP_SUPPORTS_2X)
489             || !resolution_ok(psx_w * 2, psx_h * 2) || psx_bpp != 16)
490                 return 0;
491
492         dispmode_default();
493         pl_rearmed_cbs.gpu_neon.enhancement_enable = 1;
494         snprintf(hud_msg, sizeof(hud_msg), "double resolution");
495         return 1;
496 }
497 #endif
498
499 #ifdef __ARM_NEON__
500 static int dispmode_scale2x(void)
501 {
502         if (!resolution_ok(psx_w * 2, psx_h * 2) || psx_bpp != 16)
503                 return 0;
504
505         dispmode_default();
506         soft_filter = SOFT_FILTER_SCALE2X;
507         snprintf(hud_msg, sizeof(hud_msg), "scale2x");
508         return 1;
509 }
510
511 static int dispmode_eagle2x(void)
512 {
513         if (!resolution_ok(psx_w * 2, psx_h * 2) || psx_bpp != 16)
514                 return 0;
515
516         dispmode_default();
517         soft_filter = SOFT_FILTER_EAGLE2X;
518         snprintf(hud_msg, sizeof(hud_msg), "eagle2x");
519         return 1;
520 }
521 #endif
522
523 static int (*dispmode_switchers[])(void) = {
524         dispmode_default,
525 #ifdef BUILTIN_GPU_NEON
526         dispmode_doubleres,
527 #endif
528 #ifdef __ARM_NEON__
529         dispmode_scale2x,
530         dispmode_eagle2x,
531 #endif
532 };
533
534 static int dispmode_current;
535
536 void pl_switch_dispmode(void)
537 {
538         if (pl_rearmed_cbs.gpu_caps & GPU_CAP_OWNS_DISPLAY)
539                 return;
540
541         while (1) {
542                 dispmode_current++;
543                 if (dispmode_current >=
544                     sizeof(dispmode_switchers) / sizeof(dispmode_switchers[0]))
545                         dispmode_current = 0;
546                 if (dispmode_switchers[dispmode_current]())
547                         break;
548         }
549 }
550
551 #ifndef MAEMO
552 /* adjust circle-like analog inputs to better match
553  * more square-like analogs in PSX */
554 static void update_analog_nub_adjust(int *x_, int *y_)
555 {
556         #define d 16
557         static const int scale[] =
558                 { 0 - d*2,  0 - d*2,  0 - d*2, 12 - d*2,
559                  30 - d*2, 60 - d*2, 75 - d*2, 60 - d*2, 60 - d*2 };
560         int x = abs(*x_);
561         int y = abs(*y_);
562         int scale_x = scale[y / 16];
563         int scale_y = scale[x / 16];
564
565         if (x) {
566                 x += d + (x * scale_x >> 8);
567                 if (*x_ < 0)
568                         x = -x;
569         }
570         if (y) {
571                 y += d + (y * scale_y >> 8);
572                 if (*y_ < 0)
573                         y = -y;
574         }
575
576         *x_ = x;
577         *y_ = y;
578         #undef d
579 }
580
581 static void update_analogs(void)
582 {
583         int *nubp[2] = { in_analog_left[0], in_analog_right[0] };
584         int vals[2];
585         int i, a, v, ret;
586
587         for (i = 0; i < 2; i++)
588         {
589                 if (in_adev[i] < 0)
590                         continue;
591
592                 for (a = 0; a < 2; a++) {
593                         vals[a] = 0;
594
595                         ret = in_update_analog(in_adev[i], in_adev_axis[i][a], &v);
596                         if (ret == 0)
597                                 vals[a] = 128 * v / IN_ABS_RANGE;
598                 }
599
600                 if (in_adev_is_nublike[i])
601                         update_analog_nub_adjust(&vals[0], &vals[1]);
602
603                 for (a = 0; a < 2; a++) {
604                         v = vals[a] + 127;
605                         if (v < 0) v = 0;
606                         else if (v > 255) v = 255;
607                         nubp[i][a] = v;
608                 }
609
610         }
611 }
612
613 static void update_input(void)
614 {
615         int actions[IN_BINDTYPE_COUNT] = { 0, };
616         unsigned int emu_act;
617         int in_state_gun;
618         int i;
619
620         in_update(actions);
621         if (in_type[0] == PSE_PAD_TYPE_ANALOGJOY || in_type[0] == PSE_PAD_TYPE_ANALOGPAD)
622                 update_analogs();
623         emu_act = actions[IN_BINDTYPE_EMU];
624         in_state_gun = emu_act & SACTION_GUN_MASK;
625
626         emu_act &= ~SACTION_GUN_MASK;
627         if (emu_act) {
628                 int which = 0;
629                 for (; !(emu_act & 1); emu_act >>= 1, which++)
630                         ;
631                 emu_act = which;
632         }
633         emu_set_action(emu_act);
634
635         in_keystate[0] = actions[IN_BINDTYPE_PLAYER12] & 0xffff;
636         in_keystate[1] = (actions[IN_BINDTYPE_PLAYER12] >> 16) & 0xffff;
637
638         if (tsdev) for (i = 0; i < 2; i++) {
639                 int in = 0, x = 0, y = 0, trigger;;
640                 if (in_type[i] != PSE_PAD_TYPE_GUN
641                     && in_type[i] != PSE_PAD_TYPE_GUNCON)
642                         continue;
643                 trigger = in_type[i] == PSE_PAD_TYPE_GUN
644                         ? (1 << DKEY_SQUARE) : (1 << DKEY_CIRCLE);
645
646                 pl_gun_ts_update(tsdev, &x, &y, &in);
647                 in_analog_left[i][0] = 65536;
648                 in_analog_left[i][1] = 65536;
649                 if (in && !(in_state_gun & (1 << SACTION_GUN_TRIGGER2))) {
650                         in_analog_left[i][0] = x;
651                         in_analog_left[i][1] = y;
652                         if (!(g_opts & OPT_TSGUN_NOTRIGGER))
653                                 in_state_gun |= (1 << SACTION_GUN_TRIGGER);
654                 }
655                 in_keystate[i] = 0;
656                 if (in_state_gun & ((1 << SACTION_GUN_TRIGGER)
657                                         | (1 << SACTION_GUN_TRIGGER2)))
658                         in_keystate[i] |= trigger;
659                 if (in_state_gun & (1 << SACTION_GUN_A))
660                         in_keystate[i] |= (1 << DKEY_START);
661                 if (in_state_gun & (1 << SACTION_GUN_B))
662                         in_keystate[i] |= (1 << DKEY_CROSS);
663         }
664 }
665 #else /* MAEMO */
666 extern void update_input(void);
667 #endif
668
669 void pl_gun_byte2(int port, unsigned char byte)
670 {
671         if (!tsdev || in_type[port] != PSE_PAD_TYPE_GUN || !(byte & 0x10))
672                 return;
673         if (in_analog_left[port][0] == 65536)
674                 return;
675
676         psxScheduleIrq10(4, in_analog_left[port][0] * 1629 / 1024,
677                 in_analog_left[port][1] * psx_h / 1024);
678 }
679
680 #define MAX_LAG_FRAMES 3
681
682 #define tvdiff(tv, tv_old) \
683         ((tv.tv_sec - tv_old.tv_sec) * 1000000 + tv.tv_usec - tv_old.tv_usec)
684
685 /* called on every vsync */
686 void pl_frame_limit(void)
687 {
688         static struct timeval tv_old, tv_expect;
689         static int vsync_cnt_prev, drc_active_vsyncs;
690         struct timeval now;
691         int diff, usadj;
692
693         if (g_emu_resetting)
694                 return;
695
696         vsync_cnt++;
697
698         /* doing input here because the pad is polled
699          * thousands of times per frame for some reason */
700         update_input();
701
702         pcnt_end(PCNT_ALL);
703         gettimeofday(&now, 0);
704
705         if (now.tv_sec != tv_old.tv_sec) {
706                 diff = tvdiff(now, tv_old);
707                 pl_rearmed_cbs.vsps_cur = 0.0f;
708                 if (0 < diff && diff < 2000000)
709                         pl_rearmed_cbs.vsps_cur = 1000000.0f * (vsync_cnt - vsync_cnt_prev) / diff;
710                 vsync_cnt_prev = vsync_cnt;
711
712                 if (g_opts & OPT_SHOWFPS)
713                         pl_rearmed_cbs.flips_per_sec = pl_rearmed_cbs.flip_cnt;
714                 pl_rearmed_cbs.flip_cnt = 0;
715                 if (g_opts & OPT_SHOWCPU)
716                         pl_rearmed_cbs.cpu_usage = get_cpu_ticks();
717
718                 if (hud_new_msg > 0) {
719                         hud_new_msg--;
720                         if (hud_new_msg == 0)
721                                 hud_msg[0] = 0;
722                 }
723                 tv_old = now;
724                 //new_dynarec_print_stats();
725         }
726 #ifdef PCNT
727         static int ya_vsync_count;
728         if (++ya_vsync_count == PCNT_FRAMES) {
729                 pcnt_print(pl_rearmed_cbs.vsps_cur);
730                 ya_vsync_count = 0;
731         }
732 #endif
733
734         // tv_expect uses usec*1024 units instead of usecs for better accuracy
735         tv_expect.tv_usec += frame_interval1024;
736         if (tv_expect.tv_usec >= (1000000 << 10)) {
737                 tv_expect.tv_usec -= (1000000 << 10);
738                 tv_expect.tv_sec++;
739         }
740         diff = (tv_expect.tv_sec - now.tv_sec) * 1000000 + (tv_expect.tv_usec >> 10) - now.tv_usec;
741
742         if (diff > MAX_LAG_FRAMES * frame_interval || diff < -MAX_LAG_FRAMES * frame_interval) {
743                 //printf("pl_frame_limit reset, diff=%d, iv %d\n", diff, frame_interval);
744                 tv_expect = now;
745                 diff = 0;
746                 // try to align with vsync
747                 usadj = vsync_usec_time;
748                 while (usadj < tv_expect.tv_usec - frame_interval)
749                         usadj += frame_interval;
750                 tv_expect.tv_usec = usadj << 10;
751         }
752
753         if (!(g_opts & OPT_NO_FRAMELIM) && diff > frame_interval) {
754                 // yay for working usleep on pandora!
755                 //printf("usleep %d\n", diff - frame_interval / 2);
756                 usleep(diff - frame_interval);
757         }
758
759         if (pl_rearmed_cbs.frameskip) {
760                 if (diff < -frame_interval)
761                         pl_rearmed_cbs.fskip_advice = 1;
762                 else if (diff >= 0)
763                         pl_rearmed_cbs.fskip_advice = 0;
764
765                 // recompilation is not that fast and may cause frame skip on
766                 // loading screens and such, resulting in flicker or glitches
767                 if (new_dynarec_did_compile) {
768                         if (drc_active_vsyncs < 32)
769                                 pl_rearmed_cbs.fskip_advice = 0;
770                         drc_active_vsyncs++;
771                 }
772                 else
773                         drc_active_vsyncs = 0;
774                 new_dynarec_did_compile = 0;
775         }
776
777         pcnt_start(PCNT_ALL);
778 }
779
780 void pl_timing_prepare(int is_pal_)
781 {
782         double fps;
783         pl_rearmed_cbs.fskip_advice = 0;
784         pl_rearmed_cbs.flips_per_sec = 0;
785         pl_rearmed_cbs.cpu_usage = 0;
786
787         is_pal = is_pal_;
788         fps = psxGetFps();
789         frame_interval = (int)(1000000.0 / fps);
790         frame_interval1024 = (int)(1000000.0 * 1024.0 / fps);
791
792         // used by P.E.Op.S. frameskip code
793         pl_rearmed_cbs.gpu_peops.fFrameRateHz = (float)fps;
794         pl_rearmed_cbs.gpu_peops.dwFrameRateTicks =
795                 (100000*100 / (int)(pl_rearmed_cbs.gpu_peops.fFrameRateHz*100));
796 }
797
798 static void pl_get_layer_pos(int *x, int *y, int *w, int *h)
799 {
800         *x = g_layer_x;
801         *y = g_layer_y;
802         *w = g_layer_w;
803         *h = g_layer_h;
804 }
805
806 static void *pl_mmap(unsigned int size);
807 static void pl_munmap(void *ptr, unsigned int size);
808
809 struct rearmed_cbs pl_rearmed_cbs = {
810         pl_get_layer_pos,
811         pl_vout_open,
812         pl_vout_set_mode,
813         pl_vout_flip,
814         pl_vout_close,
815
816         .mmap = pl_mmap,
817         .munmap = pl_munmap,
818         .pl_set_gpu_caps = pl_set_gpu_caps,
819         .gpu_state_change = gpu_state_change,
820 };
821
822 /* watchdog */
823 static void *watchdog_thread(void *unused)
824 {
825         int vsync_cnt_old = 0;
826         int seen_dead = 0;
827         int sleep_time = 5;
828
829 #if !defined(NDEBUG) || defined(DRC_DBG)
830         // don't interfere with debug
831         return NULL;
832 #endif
833         while (1)
834         {
835                 sleep(sleep_time);
836
837                 if (stop) {
838                         seen_dead = 0;
839                         sleep_time = 5;
840                         continue;
841                 }
842                 if (vsync_cnt != vsync_cnt_old) {
843                         vsync_cnt_old = vsync_cnt;
844                         seen_dead = 0;
845                         sleep_time = 2;
846                         continue;
847                 }
848
849                 seen_dead++;
850                 sleep_time = 1;
851                 if (seen_dead > 1)
852                         fprintf(stderr, "watchdog: seen_dead %d\n", seen_dead);
853                 if (seen_dead > 4) {
854                         fprintf(stderr, "watchdog: lockup detected, aborting\n");
855                         // we can't do any cleanup here really, the main thread is
856                         // likely touching resources and would crash anyway
857                         abort();
858                 }
859         }
860 }
861
862 void pl_start_watchdog(void)
863 {
864         pthread_attr_t attr;
865         pthread_t tid;
866         int ret;
867         
868         pthread_attr_init(&attr);
869         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
870
871         ret = pthread_create(&tid, &attr, watchdog_thread, NULL);
872         if (ret != 0)
873                 fprintf(stderr, "could not start watchdog: %d\n", ret);
874 }
875
876 static void *pl_emu_mmap(unsigned long addr, size_t size, int is_fixed,
877         enum psxMapTag tag)
878 {
879         return plat_mmap(addr, size, 0, is_fixed);
880 }
881
882 static void pl_emu_munmap(void *ptr, size_t size, enum psxMapTag tag)
883 {
884         plat_munmap(ptr, size);
885 }
886
887 static void *pl_mmap(unsigned int size)
888 {
889         return psxMapHook(0, size, 0, MAP_TAG_VRAM);
890 }
891
892 static void pl_munmap(void *ptr, unsigned int size)
893 {
894         psxUnmapHook(ptr, size, MAP_TAG_VRAM);
895 }
896
897 void pl_init(void)
898 {
899         extern unsigned int hSyncCount; // from psxcounters
900         extern unsigned int frame_counter;
901
902         psx_w = psx_h = pl_vout_w = pl_vout_h = 256;
903         psx_bpp = pl_vout_bpp = 16;
904
905         tsdev = pl_gun_ts_init();
906
907         pl_rearmed_cbs.gpu_hcnt = &hSyncCount;
908         pl_rearmed_cbs.gpu_frame_count = &frame_counter;
909
910         psxMapHook = pl_emu_mmap;
911         psxUnmapHook = pl_emu_munmap;
912 }