frontend: update libpicofe, fix missed callbacks
[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 // XXX: this is platform specific really
253 static inline int resolution_ok(int w, int h)
254 {
255         return w <= 1024 && h <= 512;
256 }
257
258 static void pl_vout_set_mode(int w, int h, int raw_w, int raw_h, int bpp)
259 {
260         int vout_w, vout_h, vout_bpp;
261
262         // special h handling, Wipeout likes to change it by 1-6
263         static int vsync_cnt_ms_prev;
264         if ((unsigned int)(vsync_cnt - vsync_cnt_ms_prev) < 5*60)
265                 h = (h + 7) & ~7;
266         vsync_cnt_ms_prev = vsync_cnt;
267
268         psx_w = raw_w;
269         psx_h = raw_h;
270         psx_bpp = bpp;
271         vout_w = w;
272         vout_h = h;
273         vout_bpp = bpp;
274         if (pl_rearmed_cbs.only_16bpp)
275                 vout_bpp = 16;
276
277         assert(vout_h >= 192);
278
279         pl_vout_scale_w = pl_vout_scale_h = 1;
280 #ifdef HAVE_NEON32
281         if (soft_filter) {
282                 if (resolution_ok(w * 2, h * 2) && bpp == 16) {
283                         pl_vout_scale_w = 2;
284                         pl_vout_scale_h = 2;
285                 }
286                 else {
287                         // filter unavailable
288                         hud_msg[0] = 0;
289                 }
290         }
291         else if (scanlines != 0 && scanline_level != 100 && bpp == 16) {
292                 if (h <= 256)
293                         pl_vout_scale_h = 2;
294         }
295 #endif
296         vout_w *= pl_vout_scale_w;
297         vout_h *= pl_vout_scale_h;
298
299         pl_update_layer_size(vout_w, vout_h, g_menuscreen_w, g_menuscreen_h);
300
301         pl_vout_buf = plat_gvideo_set_mode(&vout_w, &vout_h, &vout_bpp);
302         if (pl_vout_buf == NULL && pl_plat_blit == NULL)
303                 fprintf(stderr, "failed to set mode %dx%d@%d\n",
304                         vout_w, vout_h, vout_bpp);
305         else {
306                 pl_vout_w = vout_w;
307                 pl_vout_h = vout_h;
308                 pl_vout_bpp = vout_bpp;
309         }
310
311         menu_notify_mode_change(pl_vout_w, pl_vout_h, pl_vout_bpp);
312 }
313
314 static int flip_clear_counter;
315
316 void pl_force_clear(void)
317 {
318         flip_clear_counter = 2;
319 }
320
321 static void pl_vout_flip(const void *vram_, int vram_ofs, int bgr24,
322         int x, int y, int w, int h, int dims_changed)
323 {
324         unsigned char *dest = pl_vout_buf;
325         const unsigned char *vram = vram_;
326         int dstride = pl_vout_w, h1 = h;
327         int h_full = pl_vout_h;
328         int enhres = w > psx_w;
329         int xoffs = 0, doffs;
330         int hwrapped;
331
332         pcnt_start(PCNT_BLIT);
333
334         if (vram == NULL) {
335                 // blanking
336                 if (pl_plat_clear)
337                         pl_plat_clear();
338                 else
339                         memset(pl_vout_buf, 0,
340                                 dstride * h_full * pl_vout_bpp / 8);
341                 goto out_hud;
342         }
343
344         assert(x + w <= pl_vout_w);
345         assert(y + h <= pl_vout_h);
346
347         // offset
348         xoffs = x * pl_vout_scale_w;
349         doffs = xoffs + y * pl_vout_scale_h * dstride;
350
351         if (dims_changed)
352                 flip_clear_counter = 3;
353
354         if (flip_clear_counter > 0) {
355                 if (pl_plat_clear)
356                         pl_plat_clear();
357                 else
358                         memset(pl_vout_buf, 0,
359                                 dstride * h_full * pl_vout_bpp / 8);
360                 flip_clear_counter--;
361         }
362
363         if (pl_plat_blit)
364         {
365                 pl_plat_blit(doffs, vram + vram_ofs, w, h, 1024, bgr24);
366                 goto out_hud;
367         }
368
369         if (dest == NULL)
370                 goto out;
371
372         dest += doffs * 2;
373
374         if (bgr24)
375         {
376                 hwrapped = (vram_ofs & 2047) + w * 3 - 2048;
377                 if (pl_rearmed_cbs.only_16bpp) {
378                         for (; h1-- > 0; dest += dstride * 2) {
379                                 bgr888_to_rgb565(dest, vram + vram_ofs, w * 3);
380                                 vram_ofs = (vram_ofs + 2048) & 0xfffff;
381                         }
382
383                         if (hwrapped > 0) {
384                                 // this is super-rare so just fix-up
385                                 vram_ofs = (vram_ofs - h * 2048) & 0xff800;
386                                 dest -= dstride * 2 * h;
387                                 dest += (w - hwrapped / 3) * 2;
388                                 for (h1 = h; h1-- > 0; dest += dstride * 2) {
389                                         bgr888_to_rgb565(dest, vram + vram_ofs, hwrapped);
390                                         vram_ofs = (vram_ofs + 2048) & 0xfffff;
391                                 }
392                         }
393                 }
394                 else {
395                         dest -= doffs * 2;
396                         dest += (doffs / 8) * 24;
397
398                         for (; h1-- > 0; dest += dstride * 3) {
399                                 bgr888_to_rgb888(dest, vram + vram_ofs, w * 3);
400                                 vram_ofs = (vram_ofs + 2048) & 0xfffff;
401                         }
402
403                         if (hwrapped > 0) {
404                                 vram_ofs = (vram_ofs - h * 2048) & 0xff800;
405                                 dest -= dstride * 3 * h;
406                                 dest += w * 3 - hwrapped;
407                                 for (h1 = h; h1-- > 0; dest += dstride * 3) {
408                                         bgr888_to_rgb888(dest, vram + vram_ofs, hwrapped);
409                                         vram_ofs = (vram_ofs + 2048) & 0xfffff;
410                                 }
411                         }
412                 }
413         }
414 #ifdef HAVE_NEON32
415         else if (soft_filter == SOFT_FILTER_SCALE2X && pl_vout_scale_w == 2)
416         {
417                 neon_scale2x_16_16((const void *)(vram + vram_ofs), (void *)dest, w,
418                         2048, dstride * 2, h);
419         }
420         else if (soft_filter == SOFT_FILTER_EAGLE2X && pl_vout_scale_w == 2)
421         {
422                 neon_eagle2x_16_16((const void *)(vram + vram_ofs), (void *)dest, w,
423                         2048, dstride * 2, h);
424         }
425         else if (scanlines != 0 && scanline_level != 100)
426         {
427                 int h2, l = scanline_level * 2048 / 100;
428                 int stride_0 = pl_vout_scale_h >= 2 ? 0 : 2048;
429
430                 h1 *= pl_vout_scale_h;
431                 while (h1 > 0)
432                 {
433                         for (h2 = scanlines; h2 > 0 && h1 > 0; h2--, h1--) {
434                                 bgr555_to_rgb565(dest, vram + vram_ofs, w * 2);
435                                 vram_ofs = (vram_ofs + stride_0) & 0xfffff;
436                                 dest += dstride * 2;
437                         }
438
439                         for (h2 = scanlines; h2 > 0 && h1 > 0; h2--, h1--) {
440                                 bgr555_to_rgb565_b(dest, vram + vram_ofs, w * 2, l);
441                                 vram_ofs = (vram_ofs + 2048) & 0xfffff;
442                                 dest += dstride * 2;
443                         }
444                 }
445         }
446 #endif
447         else
448         {
449                 unsigned int vram_mask = enhres ? ~0 : 0xfffff;
450                 for (; h1-- > 0; dest += dstride * 2) {
451                         bgr555_to_rgb565(dest, vram + vram_ofs, w * 2);
452                         vram_ofs = (vram_ofs + 2048) & vram_mask;
453                 }
454
455                 hwrapped = (vram_ofs & 2047) + w * 2 - 2048;
456                 if (!enhres && hwrapped > 0) {
457                         vram_ofs = (vram_ofs - h * 2048) & 0xff800;
458                         dest -= dstride * 2 * h;
459                         dest += w * 2 - hwrapped;
460                         for (h1 = h; h1-- > 0; dest += dstride * 2) {
461                                 bgr555_to_rgb565(dest, vram + vram_ofs, hwrapped);
462                                 vram_ofs = (vram_ofs + 2048) & 0xfffff;
463                         }
464                 }
465         }
466
467 out_hud:
468         print_hud(xoffs, w * pl_vout_scale_w, (y + h) * pl_vout_scale_h);
469
470 out:
471         pcnt_end(PCNT_BLIT);
472
473         // let's flip now
474         pl_vout_buf = plat_gvideo_flip();
475
476         pl_rearmed_cbs.flip_cnt++;
477 }
478
479 static int pl_vout_open(void)
480 {
481         struct timeval now;
482
483         // force mode update on pl_vout_set_mode() call from gpulib/vout_pl
484         pl_vout_buf = NULL;
485
486         plat_gvideo_open(is_pal);
487
488         gettimeofday(&now, 0);
489         vsync_usec_time = now.tv_usec;
490         while (vsync_usec_time >= frame_interval)
491                 vsync_usec_time -= frame_interval;
492
493         return 0;
494 }
495
496 static void pl_vout_close(void)
497 {
498         plat_gvideo_close();
499 }
500
501 static void pl_set_gpu_caps(int caps)
502 {
503         pl_rearmed_cbs.gpu_caps = caps;
504 }
505
506 void *pl_prepare_screenshot(int *w, int *h, int *bpp)
507 {
508         void *ret = plat_prepare_screenshot(w, h, bpp);
509         if (ret != NULL)
510                 return ret;
511
512         *w = pl_vout_w;
513         *h = pl_vout_h;
514         *bpp = pl_vout_bpp;
515
516         return pl_vout_buf;
517 }
518
519 /* display/redering mode switcher */
520 static int dispmode_default(void)
521 {
522         pl_rearmed_cbs.gpu_neon.enhancement_enable = 0;
523         soft_filter = SOFT_FILTER_NONE;
524         snprintf(hud_msg, sizeof(hud_msg), "default mode");
525         return 1;
526 }
527
528 static int dispmode_doubleres(void)
529 {
530         if (!(pl_rearmed_cbs.gpu_caps & GPU_CAP_SUPPORTS_2X)
531             || !resolution_ok(psx_w * 2, psx_h * 2) || psx_bpp != 16)
532                 return 0;
533
534         dispmode_default();
535         pl_rearmed_cbs.gpu_neon.enhancement_enable = 1;
536         snprintf(hud_msg, sizeof(hud_msg), "double resolution");
537         return 1;
538 }
539
540 #ifdef HAVE_NEON32
541 static int dispmode_scale2x(void)
542 {
543         if (!resolution_ok(psx_w * 2, psx_h * 2) || psx_bpp != 16)
544                 return 0;
545
546         dispmode_default();
547         soft_filter = SOFT_FILTER_SCALE2X;
548         snprintf(hud_msg, sizeof(hud_msg), "scale2x");
549         return 1;
550 }
551
552 static int dispmode_eagle2x(void)
553 {
554         if (!resolution_ok(psx_w * 2, psx_h * 2) || psx_bpp != 16)
555                 return 0;
556
557         dispmode_default();
558         soft_filter = SOFT_FILTER_EAGLE2X;
559         snprintf(hud_msg, sizeof(hud_msg), "eagle2x");
560         return 1;
561 }
562 #endif
563
564 static int (*dispmode_switchers[])(void) = {
565         dispmode_default,
566         dispmode_doubleres,
567 #ifdef HAVE_NEON32
568         dispmode_scale2x,
569         dispmode_eagle2x,
570 #endif
571 };
572
573 static int dispmode_current;
574
575 void pl_switch_dispmode(void)
576 {
577         if (pl_rearmed_cbs.gpu_caps & GPU_CAP_OWNS_DISPLAY)
578                 return;
579
580         while (1) {
581                 dispmode_current++;
582                 if (dispmode_current >=
583                     sizeof(dispmode_switchers) / sizeof(dispmode_switchers[0]))
584                         dispmode_current = 0;
585                 if (dispmode_switchers[dispmode_current]())
586                         break;
587         }
588 }
589
590 #ifndef MAEMO
591 /* adjust circle-like analog inputs to better match
592  * more square-like analogs in PSX */
593 static void update_analog_nub_adjust(int *x_, int *y_)
594 {
595         #define d 16
596         static const int scale[] =
597                 { 0 - d*2,  0 - d*2,  0 - d*2, 12 - d*2,
598                  30 - d*2, 60 - d*2, 75 - d*2, 60 - d*2, 60 - d*2 };
599         int x = abs(*x_);
600         int y = abs(*y_);
601         int scale_x = scale[y / 16];
602         int scale_y = scale[x / 16];
603
604         if (x) {
605                 x += d + (x * scale_x >> 8);
606                 if (*x_ < 0)
607                         x = -x;
608         }
609         if (y) {
610                 y += d + (y * scale_y >> 8);
611                 if (*y_ < 0)
612                         y = -y;
613         }
614
615         *x_ = x;
616         *y_ = y;
617         #undef d
618 }
619
620 static void update_analogs(void)
621 {
622         int *nubp[2] = { in_analog_left[0], in_analog_right[0] };
623         int vals[2];
624         int i, a, v, ret;
625
626         for (i = 0; i < 2; i++)
627         {
628                 if (in_adev[i] < 0)
629                         continue;
630
631                 for (a = 0; a < 2; a++) {
632                         vals[a] = 0;
633
634                         ret = in_update_analog(in_adev[i], in_adev_axis[i][a], &v);
635                         if (ret == 0)
636                                 vals[a] = 128 * v / IN_ABS_RANGE;
637                 }
638
639                 if (in_adev_is_nublike[i])
640                         update_analog_nub_adjust(&vals[0], &vals[1]);
641
642                 for (a = 0; a < 2; a++) {
643                         v = vals[a] + 127;
644                         if (v < 0) v = 0;
645                         else if (v > 255) v = 255;
646                         nubp[i][a] = v;
647                 }
648
649         }
650 }
651
652 static void emu_set_action(enum sched_action action_)
653 {
654         extern enum sched_action emu_action, emu_action_old;
655
656         if (action_ == SACTION_NONE)
657                 emu_action_old = 0;
658         else if (action_ != emu_action_old)
659                 psxRegs.stop++;
660         emu_action = action_;
661 }
662
663 static void update_input(void)
664 {
665         int actions[IN_BINDTYPE_COUNT] = { 0, };
666         unsigned int emu_act;
667         int in_state_gun;
668         int i;
669
670         in_update(actions);
671         if (in_type[0] == PSE_PAD_TYPE_ANALOGJOY || in_type[0] == PSE_PAD_TYPE_ANALOGPAD)
672                 update_analogs();
673         emu_act = actions[IN_BINDTYPE_EMU];
674         in_state_gun = emu_act & SACTION_GUN_MASK;
675
676         emu_act &= ~SACTION_GUN_MASK;
677         if (emu_act) {
678                 int which = 0;
679                 for (; !(emu_act & 1); emu_act >>= 1, which++)
680                         ;
681                 emu_act = which;
682         }
683         emu_set_action(emu_act);
684
685         in_keystate[0] = actions[IN_BINDTYPE_PLAYER12] & 0xffff;
686         in_keystate[1] = (actions[IN_BINDTYPE_PLAYER12] >> 16) & 0xffff;
687
688         if (tsdev) for (i = 0; i < 2; i++) {
689                 int in = 0, x = 0, y = 0, trigger;;
690                 if (in_type[i] != PSE_PAD_TYPE_GUN
691                     && in_type[i] != PSE_PAD_TYPE_GUNCON)
692                         continue;
693                 trigger = in_type[i] == PSE_PAD_TYPE_GUN
694                         ? (1 << DKEY_SQUARE) : (1 << DKEY_CIRCLE);
695
696                 pl_gun_ts_update(tsdev, &x, &y, &in);
697                 in_analog_left[i][0] = 65536;
698                 in_analog_left[i][1] = 65536;
699                 if (in && !(in_state_gun & (1 << SACTION_GUN_TRIGGER2))) {
700                         in_analog_left[i][0] = x;
701                         in_analog_left[i][1] = y;
702                         if (!(g_opts & OPT_TSGUN_NOTRIGGER))
703                                 in_state_gun |= (1 << SACTION_GUN_TRIGGER);
704                 }
705                 in_keystate[i] = 0;
706                 if (in_state_gun & ((1 << SACTION_GUN_TRIGGER)
707                                         | (1 << SACTION_GUN_TRIGGER2)))
708                         in_keystate[i] |= trigger;
709                 if (in_state_gun & (1 << SACTION_GUN_A))
710                         in_keystate[i] |= (1 << DKEY_START);
711                 if (in_state_gun & (1 << SACTION_GUN_B))
712                         in_keystate[i] |= (1 << DKEY_CROSS);
713         }
714 }
715 #else /* MAEMO */
716 extern void update_input(void);
717 #endif
718
719 void pl_gun_byte2(int port, unsigned char byte)
720 {
721         if (!tsdev || in_type[port] != PSE_PAD_TYPE_GUN || !(byte & 0x10))
722                 return;
723         if (in_analog_left[port][0] == 65536)
724                 return;
725
726         psxScheduleIrq10(4, in_analog_left[port][0] * 1629 / 1024,
727                 in_analog_left[port][1] * psx_h / 1024);
728 }
729
730 #define MAX_LAG_FRAMES 3
731
732 #define tvdiff(tv, tv_old) \
733         ((tv.tv_sec - tv_old.tv_sec) * 1000000 + tv.tv_usec - tv_old.tv_usec)
734
735 /* called on every vsync */
736 void pl_frame_limit(void)
737 {
738         static struct timeval tv_old, tv_expect;
739         static int vsync_cnt_prev, drc_active_vsyncs;
740         struct timeval now;
741         int diff, usadj;
742
743         if (g_emu_resetting)
744                 return;
745
746         vsync_cnt++;
747
748         /* doing input here because the pad is polled
749          * thousands of times per frame for some reason */
750         update_input();
751
752         pcnt_end(PCNT_ALL);
753         gettimeofday(&now, 0);
754
755         if (now.tv_sec != tv_old.tv_sec) {
756                 diff = tvdiff(now, tv_old);
757                 pl_rearmed_cbs.vsps_cur = 0.0f;
758                 if (0 < diff && diff < 2000000)
759                         pl_rearmed_cbs.vsps_cur = 1000000.0f * (vsync_cnt - vsync_cnt_prev) / diff;
760                 vsync_cnt_prev = vsync_cnt;
761
762                 if (g_opts & OPT_SHOWFPS)
763                         pl_rearmed_cbs.flips_per_sec = pl_rearmed_cbs.flip_cnt;
764                 pl_rearmed_cbs.flip_cnt = 0;
765                 if (g_opts & OPT_SHOWCPU)
766                         pl_rearmed_cbs.cpu_usage = get_cpu_ticks();
767
768                 if (hud_new_msg > 0) {
769                         hud_new_msg--;
770                         if (hud_new_msg == 0)
771                                 hud_msg[0] = 0;
772                 }
773                 tv_old = now;
774                 //new_dynarec_print_stats();
775         }
776 #ifdef PCNT
777         static int ya_vsync_count;
778         if (++ya_vsync_count == PCNT_FRAMES) {
779                 pcnt_print(pl_rearmed_cbs.vsps_cur);
780                 ya_vsync_count = 0;
781         }
782 #endif
783
784         // tv_expect uses usec*1024 units instead of usecs for better accuracy
785         tv_expect.tv_usec += frame_interval1024;
786         if (tv_expect.tv_usec >= (1000000 << 10)) {
787                 tv_expect.tv_usec -= (1000000 << 10);
788                 tv_expect.tv_sec++;
789         }
790         diff = (tv_expect.tv_sec - now.tv_sec) * 1000000 + (tv_expect.tv_usec >> 10) - now.tv_usec;
791
792         if (diff > MAX_LAG_FRAMES * frame_interval || diff < -MAX_LAG_FRAMES * frame_interval) {
793                 //printf("pl_frame_limit reset, diff=%d, iv %d\n", diff, frame_interval);
794                 tv_expect = now;
795                 diff = 0;
796                 // try to align with vsync
797                 usadj = vsync_usec_time;
798                 while (usadj < tv_expect.tv_usec - frame_interval)
799                         usadj += frame_interval;
800                 tv_expect.tv_usec = usadj << 10;
801         }
802
803         if (!(g_opts & OPT_NO_FRAMELIM) && diff > frame_interval) {
804                 // yay for working usleep on pandora!
805                 //printf("usleep %d\n", diff - frame_interval / 2);
806                 usleep(diff - frame_interval);
807         }
808
809         if (pl_rearmed_cbs.frameskip) {
810                 if (diff < -frame_interval)
811                         pl_rearmed_cbs.fskip_advice = 1;
812                 else if (diff >= 0)
813                         pl_rearmed_cbs.fskip_advice = 0;
814
815                 // recompilation is not that fast and may cause frame skip on
816                 // loading screens and such, resulting in flicker or glitches
817                 if (ndrc_g.did_compile) {
818                         if (drc_active_vsyncs < 32)
819                                 pl_rearmed_cbs.fskip_advice = 0;
820                         drc_active_vsyncs++;
821                 }
822                 else
823                         drc_active_vsyncs = 0;
824                 ndrc_g.did_compile = 0;
825         }
826
827         pcnt_start(PCNT_ALL);
828 }
829
830 void pl_timing_prepare(int is_pal_)
831 {
832         double fps;
833         pl_rearmed_cbs.fskip_advice = 0;
834         pl_rearmed_cbs.flips_per_sec = 0;
835         pl_rearmed_cbs.cpu_usage = 0;
836
837         is_pal = is_pal_;
838         fps = psxGetFps();
839         frame_interval = (int)(1000000.0 / fps);
840         frame_interval1024 = (int)(1000000.0 * 1024.0 / fps);
841
842         // used by P.E.Op.S. frameskip code
843         pl_rearmed_cbs.gpu_peops.fFrameRateHz = (float)fps;
844         pl_rearmed_cbs.gpu_peops.dwFrameRateTicks =
845                 (100000*100 / (int)(pl_rearmed_cbs.gpu_peops.fFrameRateHz*100));
846 }
847
848 static void pl_get_layer_pos(int *x, int *y, int *w, int *h)
849 {
850         *x = g_layer_x;
851         *y = g_layer_y;
852         *w = g_layer_w;
853         *h = g_layer_h;
854 }
855
856 static void *pl_mmap(unsigned int size);
857 static void pl_munmap(void *ptr, unsigned int size);
858
859 struct rearmed_cbs pl_rearmed_cbs = {
860         pl_get_layer_pos,
861         pl_vout_open,
862         pl_vout_set_mode,
863         pl_vout_flip,
864         pl_vout_close,
865
866         .mmap = pl_mmap,
867         .munmap = pl_munmap,
868         .pl_set_gpu_caps = pl_set_gpu_caps,
869         .gpu_state_change = gpu_state_change,
870 };
871
872 /* watchdog */
873 static void *watchdog_thread(void *unused)
874 {
875         int vsync_cnt_old = 0;
876         int seen_dead = 0;
877         int sleep_time = 5;
878
879         while (1)
880         {
881                 sleep(sleep_time);
882
883                 if (psxRegs.stop) {
884                         seen_dead = 0;
885                         sleep_time = 5;
886                         continue;
887                 }
888                 if (vsync_cnt != vsync_cnt_old) {
889                         vsync_cnt_old = vsync_cnt;
890                         seen_dead = 0;
891                         sleep_time = 2;
892                         continue;
893                 }
894
895                 seen_dead++;
896                 sleep_time = 1;
897                 if (seen_dead > 1)
898                         fprintf(stderr, "watchdog: seen_dead %d\n", seen_dead);
899                 if (seen_dead > 4) {
900                         fprintf(stderr, "watchdog: lockup detected, aborting\n");
901                         fflush(stderr);
902                         // we can't do any cleanup here really, the main thread is
903                         // likely touching resources and would crash anyway
904                         abort();
905                 }
906         }
907 }
908
909 void pl_start_watchdog(void)
910 {
911 #if defined(NDEBUG) && !defined(DRC_DBG)
912         pthread_attr_t attr;
913         pthread_t tid;
914         int ret;
915 #ifdef __linux__
916         int tpid = 0;
917         char buf[256];
918         FILE *f = fopen("/proc/self/status", "r");
919         if (f) {
920                 while (fgets(buf, sizeof(buf), f))
921                         if (buf[0] == 'T' && sscanf(buf, "TracerPid: %d", &tpid) == 1)
922                                 break;
923                 fclose(f);
924         }
925         if (tpid) {
926                 printf("no watchdog to tracer %d\n", tpid);
927                 return;
928         }
929 #endif
930         
931         pthread_attr_init(&attr);
932         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
933
934         ret = pthread_create(&tid, &attr, watchdog_thread, NULL);
935         if (ret != 0)
936                 fprintf(stderr, "could not start watchdog: %d\n", ret);
937 #endif
938         (void)watchdog_thread;
939 }
940
941 static void *pl_emu_mmap(unsigned long addr, size_t size,
942         enum psxMapTag tag, int *can_retry_addr)
943 {
944         *can_retry_addr = 1;
945         return plat_mmap(addr, size, 0, 0);
946 }
947
948 static void pl_emu_munmap(void *ptr, size_t size, enum psxMapTag tag)
949 {
950         plat_munmap(ptr, size);
951 }
952
953 static void *pl_mmap(unsigned int size)
954 {
955         int can_retry_addr;
956         return psxMapHook(0, size, MAP_TAG_VRAM, &can_retry_addr);
957 }
958
959 static void pl_munmap(void *ptr, unsigned int size)
960 {
961         psxUnmapHook(ptr, size, MAP_TAG_VRAM);
962 }
963
964 void pl_init(void)
965 {
966         extern unsigned int hSyncCount; // from psxcounters
967         extern unsigned int frame_counter;
968
969         psx_w = psx_h = pl_vout_w = pl_vout_h = 256;
970         psx_bpp = pl_vout_bpp = 16;
971
972         tsdev = pl_gun_ts_init();
973
974         pl_rearmed_cbs.gpu_hcnt = &hSyncCount;
975         pl_rearmed_cbs.gpu_frame_count = &frame_counter;
976
977         psxMapHook = pl_emu_mmap;
978         psxUnmapHook = pl_emu_munmap;
979 }