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