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