1 /*
2  * libretro core glue for PicoDrive
3  * (C) notaz, 2013
4  * (C) aliaspider, 2016
5  * (C) Daniel De Matteis, 2013
6  *
7  * This work is licensed under the terms of MAME license.
8  * See COPYING file in the top-level directory.
9  */
10 
11 #define _GNU_SOURCE 1 // mremap
12 #include <stdio.h>
13 #include <stdlib.h>
14 #include <stdarg.h>
15 #include <string.h>
16 #ifndef _WIN32
17 #ifndef NO_MMAP
18 #ifdef __SWITCH__
19 #include "../switch/mman.h"
20 #else
21 #include <sys/mman.h>
22 #endif
23 #endif
24 #else
25 #include <io.h>
26 #include <windows.h>
27 #include <sys/types.h>
28 #endif
29 #include <errno.h>
30 #ifdef __MACH__
31 #include <libkern/OSCacheControl.h>
32 #endif
33 
34 #ifdef USE_LIBRETRO_VFS
35 #include "file_stream_transforms.h"
36 #endif
37 
38 #if defined(RENDER_GSKIT_PS2)
39 #include "libretro-common/include/libretro_gskit_ps2.h"
40 #include "../ps2/asm.h"
41 #endif
42 
43 #ifdef _3DS
44 #include "3ds/3ds_utils.h"
45 #define MEMOP_MAP     4
46 #define MEMOP_UNMAP   5
47 #define MEMOP_PROT    6
48 
49 int svcDuplicateHandle(unsigned int* out, unsigned int original);
50 int svcCloseHandle(unsigned int handle);
51 int svcControlProcessMemory(unsigned int process, void* addr0, void* addr1,
52                             unsigned int size, unsigned int type, unsigned int perm);
53 void* linearMemAlign(size_t size, size_t alignment);
54 void linearFree(void* mem);
55 
56 static int ctr_svchack_successful = 0;
57 
58 #elif defined(VITA)
59 #define TARGET_SIZE_2 24 // 2^24 = 16 megabytes
60 
61 #include <psp2/kernel/sysmem.h>
62 static int sceBlock;
63 int getVMBlock();
64 int _newlib_vm_size_user = 1 << TARGET_SIZE_2;
65 
66 #endif
67 
68 #include "libretro_core_options.h"
69 
70 #include <pico/pico_int.h>
71 #include <pico/state.h>
72 #include <pico/patch.h>
73 #include "../common/input_pico.h"
74 #include "../common/version.h"
75 #include <libretro.h>
76 
77 static retro_log_printf_t log_cb;
78 static retro_video_refresh_t video_cb;
79 static retro_input_poll_t input_poll_cb;
80 static retro_input_state_t input_state_cb;
81 static retro_environment_t environ_cb;
82 static retro_audio_sample_batch_t audio_batch_cb;
83 
84 #if defined(RENDER_GSKIT_PS2)
85 #define VOUT_MAX_WIDTH 328
86 #else
87 #define VOUT_MAX_WIDTH 320
88 #define VOUT_32BIT_WIDTH 256
89 #endif
90 #define VOUT_MAX_HEIGHT 240
91 #define INITIAL_SND_RATE 44100
92 
93 static const float VOUT_PAR = 0.0;
94 static const float VOUT_4_3 = (224.0f * (4.0f / 3.0f));
95 static const float VOUT_CRT = (224.0f * 1.29911f);
96 
97 static bool show_overscan = false;
98 static bool old_show_overscan = false;
99 
100 /* Required to allow on the fly changes to 'show overscan' */
101 static int vm_current_start_line = -1;
102 static int vm_current_line_count = -1;
103 static int vm_current_is_32cols = -1;
104 
105 static void *vout_buf;
106 static int vout_width, vout_height, vout_offset;
107 static float user_vout_width = 0.0;
108 
109 #if defined(RENDER_GSKIT_PS2)
110 RETRO_HW_RENDER_INTEFACE_GSKIT_PS2 *ps2 = NULL;
111 static void *retro_palette;
112 static struct retro_hw_ps2_insets padding;
113 #endif
114 
115 static short ALIGNED(4) sndBuffer[2*INITIAL_SND_RATE/50];
116 
117 static void snd_write(int len);
118 
119 #ifdef _WIN32
120 #define SLASH '\\'
121 #else
122 #define SLASH '/'
123 #endif
124 
125 /* functions called by the core */
126 
cache_flush_d_inval_i(void * start,void * end)127 void cache_flush_d_inval_i(void *start, void *end)
128 {
129 #ifdef __arm__
130    size_t len = (char *)end - (char *)start;
131    (void)len;
132 #if defined(__BLACKBERRY_QNX__)
133    msync(start, end - start, MS_SYNC | MS_CACHE_ONLY | MS_INVALIDATE_ICACHE);
134 #elif defined(__MACH__)
135    sys_dcache_flush(start, len);
136    sys_icache_invalidate(start, len);
137 #elif defined(_3DS)
138    ctr_flush_invalidate_cache();
139 #elif defined(VITA)
140    sceKernelSyncVMDomain(sceBlock, start, len);
141 #else
142    __clear_cache(start, end);
143 #endif
144 #endif
145 }
146 
147 #ifdef _WIN32
148 /* mmap() replacement for Windows
149  *
150  * Author: Mike Frysinger <vapier@gentoo.org>
151  * Placed into the public domain
152  */
153 
154 /* References:
155  * CreateFileMapping: http://msdn.microsoft.com/en-us/library/aa366537(VS.85).aspx
156  * CloseHandle:       http://msdn.microsoft.com/en-us/library/ms724211(VS.85).aspx
157  * MapViewOfFile:     http://msdn.microsoft.com/en-us/library/aa366761(VS.85).aspx
158  * UnmapViewOfFile:   http://msdn.microsoft.com/en-us/library/aa366882(VS.85).aspx
159  */
160 
161 #define PROT_READ     0x1
162 #define PROT_WRITE    0x2
163 /* This flag is only available in WinXP+ */
164 #ifdef FILE_MAP_EXECUTE
165 #define PROT_EXEC     0x4
166 #else
167 #define PROT_EXEC        0x0
168 #define FILE_MAP_EXECUTE 0
169 #endif
170 
171 #define MAP_SHARED    0x01
172 #define MAP_PRIVATE   0x02
173 #define MAP_ANONYMOUS 0x20
174 #define MAP_ANON      MAP_ANONYMOUS
175 #define MAP_FAILED    ((void *) -1)
176 
177 #ifdef __USE_FILE_OFFSET64
178 # define DWORD_HI(x) (x >> 32)
179 # define DWORD_LO(x) ((x) & 0xffffffff)
180 #else
181 # define DWORD_HI(x) (0)
182 # define DWORD_LO(x) (x)
183 #endif
184 
mmap(void * start,size_t length,int prot,int flags,int fd,off_t offset)185 static void *mmap(void *start, size_t length, int prot, int flags, int fd, off_t offset)
186 {
187    uint32_t flProtect, dwDesiredAccess;
188    off_t end;
189    HANDLE mmap_fd, h;
190    void *ret;
191 
192    if (prot & ~(PROT_READ | PROT_WRITE | PROT_EXEC))
193       return MAP_FAILED;
194    if (fd == -1) {
195       if (!(flags & MAP_ANON) || offset)
196          return MAP_FAILED;
197    } else if (flags & MAP_ANON)
198       return MAP_FAILED;
199 
200    if (prot & PROT_WRITE) {
201       if (prot & PROT_EXEC)
202          flProtect = PAGE_EXECUTE_READWRITE;
203       else
204          flProtect = PAGE_READWRITE;
205    } else if (prot & PROT_EXEC) {
206       if (prot & PROT_READ)
207          flProtect = PAGE_EXECUTE_READ;
208       else if (prot & PROT_EXEC)
209          flProtect = PAGE_EXECUTE;
210    } else
211       flProtect = PAGE_READONLY;
212 
213    end = length + offset;
214 
215    if (fd == -1)
216       mmap_fd = INVALID_HANDLE_VALUE;
217    else
218       mmap_fd = (HANDLE)_get_osfhandle(fd);
219    h = CreateFileMapping(mmap_fd, NULL, flProtect, DWORD_HI(end), DWORD_LO(end), NULL);
220    if (h == NULL)
221       return MAP_FAILED;
222 
223    if (prot & PROT_WRITE)
224       dwDesiredAccess = FILE_MAP_WRITE;
225    else
226       dwDesiredAccess = FILE_MAP_READ;
227    if (prot & PROT_EXEC)
228       dwDesiredAccess |= FILE_MAP_EXECUTE;
229    if (flags & MAP_PRIVATE)
230       dwDesiredAccess |= FILE_MAP_COPY;
231    ret = MapViewOfFile(h, dwDesiredAccess, DWORD_HI(offset), DWORD_LO(offset), length);
232    if (ret == NULL) {
233       CloseHandle(h);
234       ret = MAP_FAILED;
235    }
236    return ret;
237 }
238 
munmap(void * addr,size_t length)239 static void munmap(void *addr, size_t length)
240 {
241    UnmapViewOfFile(addr);
242    /* ruh-ro, we leaked handle from CreateFileMapping() ... */
243 }
244 #elif defined(NO_MMAP)
245 #define PROT_EXEC   0x04
246 #define MAP_FAILED 0
247 #define PROT_READ 0
248 #define PROT_WRITE 0
249 #define MAP_PRIVATE 0
250 #define MAP_ANONYMOUS 0
251 
mmap(void * desired_addr,size_t len,int mmap_prot,int mmap_flags,int fildes,size_t off)252 void* mmap(void *desired_addr, size_t len, int mmap_prot, int mmap_flags, int fildes, size_t off)
253 {
254    return malloc(len);
255 }
256 
munmap(void * base_addr,size_t len)257 void munmap(void *base_addr, size_t len)
258 {
259    free(base_addr);
260 }
261 
mprotect(void * addr,size_t len,int prot)262 int mprotect(void *addr, size_t len, int prot)
263 {
264    /* stub - not really needed at this point since this codepath has no dynarecs */
265    return 0;
266 }
267 
268 #endif
269 
270 #ifndef MAP_ANONYMOUS
271 #define MAP_ANONYMOUS MAP_ANON
272 #endif
273 
274 #ifdef _3DS
275 typedef struct
276 {
277    unsigned int requested_map;
278    void* buffer;
279 }pico_mmap_t;
280 
281 pico_mmap_t pico_mmaps[] = {
282    {0x02000000, 0},
283    {0x06000000, 0},
284    {NULL,       0}
285 };
286 
plat_mmap(unsigned long addr,size_t size,int need_exec,int is_fixed)287 void *plat_mmap(unsigned long addr, size_t size, int need_exec, int is_fixed)
288 {
289    (void)is_fixed;
290 
291    if (ctr_svchack_successful)
292    {
293       pico_mmap_t* pico_mmap;
294 
295       for (pico_mmap = pico_mmaps; pico_mmap->requested_map; pico_mmap++)
296       {
297          if ((pico_mmap->requested_map == addr))
298          {
299             unsigned int ptr_aligned, tmp;
300             unsigned int currentHandle;
301             unsigned int perm = 0b011;
302 
303             if (need_exec)
304                perm = 0b111;
305 
306             size = (size + 0xFFF) & ~0xFFF;
307             pico_mmap->buffer = malloc(size + 0x1000);
308             ptr_aligned = (((unsigned int)pico_mmap->buffer) + 0xFFF) & ~0xFFF;
309 
310             svcDuplicateHandle(&currentHandle, 0xFFFF8001);
311 
312             if(svcControlProcessMemory(currentHandle, pico_mmap->requested_map, ptr_aligned, size, MEMOP_MAP, perm) < 0)
313             {
314                if (log_cb)
315                   log_cb(RETRO_LOG_ERROR, "could not map memory @0x%08X\n", pico_mmap->requested_map);
316                exit(1);
317             }
318 
319             svcCloseHandle(currentHandle);
320             return (void*)pico_mmap->requested_map;
321          }
322       }
323    }
324 
325    return malloc(size);
326 }
327 
plat_mremap(void * ptr,size_t oldsize,size_t newsize)328 void *plat_mremap(void *ptr, size_t oldsize, size_t newsize)
329 {
330    if (ctr_svchack_successful)
331    {
332       pico_mmap_t* pico_mmap;
333 
334       for (pico_mmap = pico_mmaps; pico_mmap->requested_map; pico_mmap++)
335       {
336          if ((pico_mmap->requested_map == (unsigned int)ptr))
337          {
338             unsigned int ptr_aligned;
339             unsigned int currentHandle;
340             void* tmp;
341 
342             oldsize = (oldsize + 0xFFF) & ~0xFFF;
343             newsize = (newsize + 0xFFF) & ~0xFFF;
344             ptr_aligned = (((unsigned int)pico_mmap->buffer) + 0xFFF) & ~0xFFF;
345 
346             svcDuplicateHandle(&currentHandle, 0xFFFF8001);
347 
348             svcControlProcessMemory(currentHandle, pico_mmap->requested_map, ptr_aligned, oldsize, MEMOP_UNMAP, 0b011);
349 
350             tmp = realloc(pico_mmap->buffer, newsize + 0x1000);
351             if(!tmp)
352                return NULL;
353 
354             pico_mmap->buffer = tmp;
355             ptr_aligned = (((unsigned int)pico_mmap->buffer) + 0xFFF) & ~0xFFF;
356 
357             svcControlProcessMemory(currentHandle, pico_mmap->requested_map, ptr_aligned, newsize, MEMOP_MAP, 0x3);
358 
359             svcCloseHandle(currentHandle);
360 
361             return ptr;
362          }
363       }
364    }
365 
366    return realloc(ptr, newsize);
367 
368 }
plat_munmap(void * ptr,size_t size)369 void plat_munmap(void *ptr, size_t size)
370 {
371    if (ctr_svchack_successful)
372    {
373       pico_mmap_t* pico_mmap;
374 
375       for (pico_mmap = pico_mmaps; pico_mmap->requested_map; pico_mmap++)
376       {
377          if ((pico_mmap->requested_map == (unsigned int)ptr))
378          {
379             unsigned int ptr_aligned;
380             unsigned int currentHandle;
381 
382             size = (size + 0xFFF) & ~0xFFF;
383             ptr_aligned = (((unsigned int)pico_mmap->buffer) + 0xFFF) & ~0xFFF;
384 
385             svcDuplicateHandle(&currentHandle, 0xFFFF8001);
386 
387             svcControlProcessMemory(currentHandle, (void*)pico_mmap->requested_map, (void*)ptr_aligned, size, MEMOP_UNMAP, 0b011);
388 
389             svcCloseHandle(currentHandle);
390 
391             free(pico_mmap->buffer);
392             pico_mmap->buffer = NULL;
393             return;
394          }
395       }
396    }
397 
398    free(ptr);
399 }
400 
401 #else
plat_mmap(unsigned long addr,size_t size,int need_exec,int is_fixed)402 void *plat_mmap(unsigned long addr, size_t size, int need_exec, int is_fixed)
403 {
404    int flags = MAP_PRIVATE | MAP_ANONYMOUS;
405    void *req, *ret;
406 
407    req = (void *)(uintptr_t)addr;
408    ret = mmap(req, size, PROT_READ | PROT_WRITE, flags, -1, 0);
409    if (ret == MAP_FAILED) {
410       if (log_cb)
411          log_cb(RETRO_LOG_ERROR, "mmap(%08lx, %zd) failed: %d\n", addr, size, errno);
412       return NULL;
413    }
414 
415    if (addr != 0 && ret != (void *)(uintptr_t)addr) {
416       if (log_cb)
417          log_cb(RETRO_LOG_WARN, "warning: wanted to map @%08lx, got %p\n",
418                addr, ret);
419 
420       if (is_fixed) {
421          munmap(ret, size);
422          return NULL;
423       }
424    }
425 
426    return ret;
427 }
428 
plat_mremap(void * ptr,size_t oldsize,size_t newsize)429 void *plat_mremap(void *ptr, size_t oldsize, size_t newsize)
430 {
431 #if defined(__linux__) && !defined(__SWITCH__)
432    void *ret = mremap(ptr, oldsize, newsize, 0);
433    if (ret == MAP_FAILED)
434       return NULL;
435 
436    return ret;
437 #else
438    void *tmp, *ret;
439    size_t preserve_size;
440 
441    preserve_size = oldsize;
442    if (preserve_size > newsize)
443       preserve_size = newsize;
444    tmp = malloc(preserve_size);
445    if (tmp == NULL)
446       return NULL;
447    memcpy(tmp, ptr, preserve_size);
448 
449    munmap(ptr, oldsize);
450    ret = mmap(ptr, newsize, PROT_READ | PROT_WRITE,
451          MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
452    if (ret == MAP_FAILED) {
453       free(tmp);
454       return NULL;
455    }
456    memcpy(ret, tmp, preserve_size);
457    free(tmp);
458    return ret;
459 #endif
460 }
461 
plat_munmap(void * ptr,size_t size)462 void plat_munmap(void *ptr, size_t size)
463 {
464    if (ptr != NULL)
465       munmap(ptr, size);
466 }
467 #endif
468 
469 // if NULL is returned, static buffer is used
plat_mem_get_for_drc(size_t size)470 void *plat_mem_get_for_drc(size_t size)
471 {
472    void *mem = NULL;
473 #ifdef VITA
474    sceKernelGetMemBlockBase(sceBlock, &mem);
475 #endif
476    return mem;
477 }
478 
plat_mem_set_exec(void * ptr,size_t size)479 int plat_mem_set_exec(void *ptr, size_t size)
480 {
481    int ret = -1;
482 #ifdef _WIN32
483    DWORD oldProtect = 0;
484    ret = VirtualProtect(ptr, size, PAGE_EXECUTE_READWRITE, &oldProtect);
485    if (ret == 0 && log_cb)
486       log_cb(RETRO_LOG_ERROR, "VirtualProtect(%p, %d) failed: %d\n", ptr, (int)size,
487              GetLastError());
488 #elif defined(_3DS)
489    if (ctr_svchack_successful)
490    {
491       unsigned int currentHandle;
492       svcDuplicateHandle(&currentHandle, 0xFFFF8001);
493       ret = svcControlProcessMemory(currentHandle, ptr, 0x0,
494                               size, MEMOP_PROT, 0b111);
495       svcCloseHandle(currentHandle);
496       ctr_flush_invalidate_cache();
497 
498    }
499    else
500    {
501       if (log_cb)
502          log_cb(RETRO_LOG_ERROR, "plat_mem_set_exec called with no svcControlProcessMemory access\n");
503       exit(1);
504    }
505 
506 #elif defined(VITA)
507    ret = sceKernelOpenVMDomain();
508 #else
509    ret = mprotect(ptr, size, PROT_READ | PROT_WRITE | PROT_EXEC);
510    if (ret != 0 && log_cb)
511       log_cb(RETRO_LOG_ERROR, "mprotect(%p, %zd) failed: %d\n", ptr, size, errno);
512 #endif
513    return ret;
514 }
515 
emu_video_mode_change(int start_line,int line_count,int is_32cols)516 void emu_video_mode_change(int start_line, int line_count, int is_32cols)
517 {
518    struct retro_system_av_info av_info;
519 
520    vm_current_start_line = start_line;
521    vm_current_line_count = line_count;
522    vm_current_is_32cols = is_32cols;
523 
524 #if defined(RENDER_GSKIT_PS2)
525    if (is_32cols) {
526       padding = (struct retro_hw_ps2_insets){start_line, 16.0f, VOUT_MAX_HEIGHT - line_count - start_line, 64.0f};
527    } else {
528       padding = (struct retro_hw_ps2_insets){start_line, 16.0f, VOUT_MAX_HEIGHT - line_count - start_line, 0.0f};
529    }
530 
531    vout_width = VOUT_MAX_WIDTH;
532    vout_height = VOUT_MAX_HEIGHT;
533    memset(vout_buf, 0, vout_width * VOUT_MAX_HEIGHT);
534    memset(retro_palette, 0, gsKit_texture_size_ee(16, 16, GS_PSM_CT16));
535    PicoDrawSetOutBuf(vout_buf, vout_width);
536 
537    if (ps2) {
538       ps2->clearTexture = true;
539    }
540 #else
541    vout_width = is_32cols ? VOUT_32BIT_WIDTH : VOUT_MAX_WIDTH;
542    memset(vout_buf, 0, VOUT_MAX_WIDTH * VOUT_MAX_HEIGHT * 2);
543    PicoDrawSetOutBuf(vout_buf, vout_width * 2);
544 
545    if (show_overscan)
546    {
547       vout_height = line_count + (start_line * 2);
548       vout_offset = 0;
549    }
550    else
551    {
552       vout_height = line_count;
553       /* Note: We multiply by 2 here to account for pitch */
554       vout_offset = vout_width * start_line * 2;
555    }
556 
557    /* Redundant sanity check... */
558    vout_height = (vout_height > VOUT_MAX_HEIGHT) ?
559          VOUT_MAX_HEIGHT : vout_height;
560    vout_offset = (vout_offset > vout_width * (VOUT_MAX_HEIGHT - 1) * 2) ?
561          vout_width * (VOUT_MAX_HEIGHT - 1) * 2 : vout_offset;
562 
563 #endif
564 
565    // Update the geometry
566    retro_get_system_av_info(&av_info);
567    environ_cb(RETRO_ENVIRONMENT_SET_GEOMETRY, &av_info);
568 }
569 
emu_32x_startup(void)570 void emu_32x_startup(void)
571 {
572 }
573 
lprintf(const char * fmt,...)574 void lprintf(const char *fmt, ...)
575 {
576    char buffer[256];
577    va_list ap;
578    va_start(ap, fmt);
579    vsprintf(buffer, fmt, ap);
580    /* TODO - add 'level' param for warning/error messages? */
581    if (log_cb)
582       log_cb(RETRO_LOG_INFO, "%s", buffer);
583    va_end(ap);
584 }
585 
586 /* libretro */
retro_set_environment(retro_environment_t cb)587 void retro_set_environment(retro_environment_t cb)
588 {
589 #ifdef USE_LIBRETRO_VFS
590    struct retro_vfs_interface_info vfs_iface_info;
591 #endif
592 
593    environ_cb = cb;
594 
595    libretro_set_core_options(environ_cb);
596 
597 #ifdef USE_LIBRETRO_VFS
598    vfs_iface_info.required_interface_version = 1;
599    vfs_iface_info.iface = NULL;
600    if (environ_cb(RETRO_ENVIRONMENT_GET_VFS_INTERFACE, &vfs_iface_info))
601       filestream_vfs_init(&vfs_iface_info);
602 #endif
603 }
604 
retro_set_video_refresh(retro_video_refresh_t cb)605 void retro_set_video_refresh(retro_video_refresh_t cb) { video_cb = cb; }
retro_set_audio_sample(retro_audio_sample_t cb)606 void retro_set_audio_sample(retro_audio_sample_t cb) { (void)cb; }
retro_set_audio_sample_batch(retro_audio_sample_batch_t cb)607 void retro_set_audio_sample_batch(retro_audio_sample_batch_t cb) { audio_batch_cb = cb; }
retro_set_input_poll(retro_input_poll_t cb)608 void retro_set_input_poll(retro_input_poll_t cb) { input_poll_cb = cb; }
retro_set_input_state(retro_input_state_t cb)609 void retro_set_input_state(retro_input_state_t cb) { input_state_cb = cb; }
610 
retro_api_version(void)611 unsigned retro_api_version(void)
612 {
613    return RETRO_API_VERSION;
614 }
615 
retro_set_controller_port_device(unsigned port,unsigned device)616 void retro_set_controller_port_device(unsigned port, unsigned device)
617 {
618 }
619 
retro_get_system_info(struct retro_system_info * info)620 void retro_get_system_info(struct retro_system_info *info)
621 {
622    memset(info, 0, sizeof(*info));
623    info->library_name = "PicoDrive";
624 #ifndef GIT_VERSION
625 #define GIT_VERSION ""
626 #endif
627    info->library_version = VERSION GIT_VERSION;
628    info->valid_extensions = "bin|gen|smd|md|32x|cue|iso|sms";
629    info->need_fullpath = true;
630 }
631 
retro_get_system_av_info(struct retro_system_av_info * info)632 void retro_get_system_av_info(struct retro_system_av_info *info)
633 {
634    float common_width;
635 
636    memset(info, 0, sizeof(*info));
637    info->timing.fps            = Pico.m.pal ? 50 : 60;
638    info->timing.sample_rate    = PicoIn.sndRate;
639    info->geometry.base_width   = vout_width;
640    info->geometry.base_height  = vout_height;
641    info->geometry.max_width    = vout_width;
642    info->geometry.max_height   = vout_height;
643 
644    common_width = vout_width;
645    if (user_vout_width != 0)
646       common_width = user_vout_width;
647 
648    info->geometry.aspect_ratio = common_width / vout_height;
649 }
650 
651 /* savestates */
652 struct savestate_state {
653    const char *load_buf;
654    char *save_buf;
655    size_t size;
656    size_t pos;
657 };
658 
state_read(void * p,size_t size,size_t nmemb,void * file)659 size_t state_read(void *p, size_t size, size_t nmemb, void *file)
660 {
661    struct savestate_state *state = file;
662    size_t bsize = size * nmemb;
663 
664    if (state->pos + bsize > state->size) {
665       if (log_cb)
666          log_cb(RETRO_LOG_ERROR, "savestate error: %u/%u\n",
667                state->pos + bsize, state->size);
668       bsize = state->size - state->pos;
669       if ((int)bsize <= 0)
670          return 0;
671    }
672 
673    memcpy(p, state->load_buf + state->pos, bsize);
674    state->pos += bsize;
675    return bsize;
676 }
677 
state_write(void * p,size_t size,size_t nmemb,void * file)678 size_t state_write(void *p, size_t size, size_t nmemb, void *file)
679 {
680    struct savestate_state *state = file;
681    size_t bsize = size * nmemb;
682 
683    if (state->pos + bsize > state->size) {
684       if (log_cb)
685          log_cb(RETRO_LOG_ERROR, "savestate error: %u/%u\n",
686                state->pos + bsize, state->size);
687       bsize = state->size - state->pos;
688       if ((int)bsize <= 0)
689          return 0;
690    }
691 
692    memcpy(state->save_buf + state->pos, p, bsize);
693    state->pos += bsize;
694    return bsize;
695 }
696 
state_skip(void * p,size_t size,size_t nmemb,void * file)697 size_t state_skip(void *p, size_t size, size_t nmemb, void *file)
698 {
699    struct savestate_state *state = file;
700    size_t bsize = size * nmemb;
701 
702    state->pos += bsize;
703    return bsize;
704 }
705 
state_eof(void * file)706 size_t state_eof(void *file)
707 {
708    struct savestate_state *state = file;
709 
710    return state->pos >= state->size;
711 }
712 
state_fseek(void * file,long offset,int whence)713 int state_fseek(void *file, long offset, int whence)
714 {
715    struct savestate_state *state = file;
716 
717    switch (whence) {
718    case SEEK_SET:
719       state->pos = offset;
720       break;
721    case SEEK_CUR:
722       state->pos += offset;
723       break;
724    case SEEK_END:
725       state->pos = state->size + offset;
726       break;
727    }
728    return (int)state->pos;
729 }
730 
731 /* savestate sizes vary wildly depending if cd/32x or
732  * carthw is active, so run the whole thing to get size */
retro_serialize_size(void)733 size_t retro_serialize_size(void)
734 {
735    struct savestate_state state = { 0, };
736    int ret;
737 
738    ret = PicoStateFP(&state, 1, NULL, state_skip, NULL, state_fseek);
739    if (ret != 0)
740       return 0;
741 
742    return state.pos;
743 }
744 
retro_serialize(void * data,size_t size)745 bool retro_serialize(void *data, size_t size)
746 {
747    struct savestate_state state = { 0, };
748    int ret;
749 
750    state.save_buf = data;
751    state.size = size;
752    state.pos = 0;
753 
754    ret = PicoStateFP(&state, 1, NULL, state_write,
755       NULL, state_fseek);
756    return ret == 0;
757 }
758 
retro_unserialize(const void * data,size_t size)759 bool retro_unserialize(const void *data, size_t size)
760 {
761    struct savestate_state state = { 0, };
762    int ret;
763 
764    state.load_buf = data;
765    state.size = size;
766    state.pos = 0;
767 
768    ret = PicoStateFP(&state, 0, state_read, NULL,
769       state_eof, state_fseek);
770    return ret == 0;
771 }
772 
773 typedef struct patch
774 {
775 	unsigned int addr;
776 	unsigned short data;
777 	unsigned char comp;
778 } patch;
779 
780 extern void decode(char *buff, patch *dest);
781 extern uint16_t m68k_read16(uint32_t a);
782 extern void m68k_write16(uint32_t a, uint16_t d);
783 
retro_cheat_reset(void)784 void retro_cheat_reset(void)
785 {
786 	int i=0;
787 	unsigned int addr;
788 
789 	for (i = 0; i < PicoPatchCount; i++)
790 	{
791 		addr = PicoPatches[i].addr;
792 		if (addr < Pico.romsize) {
793 			if (PicoPatches[i].active)
794 				*(unsigned short *)(Pico.rom + addr) = PicoPatches[i].data_old;
795 		} else {
796 			if (PicoPatches[i].active)
797 				m68k_write16(PicoPatches[i].addr,PicoPatches[i].data_old);
798 		}
799 	}
800 
801 	PicoPatchUnload();
802 }
803 
retro_cheat_set(unsigned index,bool enabled,const char * code)804 void retro_cheat_set(unsigned index, bool enabled, const char *code)
805 {
806 	patch pt;
807 	int array_len = PicoPatchCount;
808 	char codeCopy[256];
809 	char *buff;
810 
811 	if (*code == '\0')
812       return;
813 	strcpy(codeCopy, code);
814 	buff = strtok(codeCopy,"+");
815 
816 	while (buff != NULL)
817 	{
818 		decode(buff, &pt);
819 		if (pt.addr == (uint32_t) -1 || pt.data == (uint16_t) -1)
820 		{
821 			log_cb(RETRO_LOG_ERROR,"CHEATS: Invalid code: %s\n",buff);
822 			return;
823 		}
824 
825 		/* code was good, add it */
826 		if (array_len < PicoPatchCount + 1)
827 		{
828 			void *ptr;
829 			array_len *= 2;
830 			array_len++;
831 			ptr = realloc(PicoPatches, array_len * sizeof(PicoPatches[0]));
832 			if (ptr == NULL) {
833 				log_cb(RETRO_LOG_ERROR,"CHEATS: Failed to allocate memory for: %s\n",buff);
834 				return;
835 			}
836 			PicoPatches = ptr;
837 		}
838 		strcpy(PicoPatches[PicoPatchCount].code, buff);
839 
840 		PicoPatches[PicoPatchCount].active = enabled;
841 		PicoPatches[PicoPatchCount].addr = pt.addr;
842 		PicoPatches[PicoPatchCount].data = pt.data;
843 		PicoPatches[PicoPatchCount].comp = pt.comp;
844 		if (PicoPatches[PicoPatchCount].addr < Pico.romsize)
845 			PicoPatches[PicoPatchCount].data_old = *(uint16_t *)(Pico.rom + PicoPatches[PicoPatchCount].addr);
846 		else
847 			PicoPatches[PicoPatchCount].data_old = (uint16_t) m68k_read16(PicoPatches[PicoPatchCount].addr);
848 		PicoPatchCount++;
849 
850 		buff = strtok(NULL,"+");
851 	}
852 }
853 
854 /* multidisk support */
855 static bool disk_ejected;
856 static unsigned int disk_current_index;
857 static unsigned int disk_count;
858 static struct disks_state {
859    char *fname;
860 } disks[8];
861 
disk_set_eject_state(bool ejected)862 static bool disk_set_eject_state(bool ejected)
863 {
864    // TODO?
865    disk_ejected = ejected;
866    return true;
867 }
868 
disk_get_eject_state(void)869 static bool disk_get_eject_state(void)
870 {
871    return disk_ejected;
872 }
873 
disk_get_image_index(void)874 static unsigned int disk_get_image_index(void)
875 {
876    return disk_current_index;
877 }
878 
disk_set_image_index(unsigned int index)879 static bool disk_set_image_index(unsigned int index)
880 {
881    enum cd_img_type cd_type;
882    int ret;
883 
884    if (index >= sizeof(disks) / sizeof(disks[0]))
885       return false;
886 
887    if (disks[index].fname == NULL) {
888       if (log_cb)
889          log_cb(RETRO_LOG_ERROR, "missing disk #%u\n", index);
890 
891       // RetroArch specifies "no disk" with index == count,
892       // so don't fail here..
893       disk_current_index = index;
894       return true;
895    }
896 
897    if (log_cb)
898       log_cb(RETRO_LOG_INFO, "switching to disk %u: \"%s\"\n", index,
899             disks[index].fname);
900 
901    ret = -1;
902    cd_type = PicoCdCheck(disks[index].fname, NULL);
903    if (cd_type != CIT_NOT_CD)
904       ret = cdd_load(disks[index].fname, cd_type);
905    if (ret != 0) {
906       if (log_cb)
907          log_cb(RETRO_LOG_ERROR, "Load failed, invalid CD image?\n");
908       return 0;
909    }
910 
911    disk_current_index = index;
912    return true;
913 }
914 
disk_get_num_images(void)915 static unsigned int disk_get_num_images(void)
916 {
917    return disk_count;
918 }
919 
disk_replace_image_index(unsigned index,const struct retro_game_info * info)920 static bool disk_replace_image_index(unsigned index,
921    const struct retro_game_info *info)
922 {
923    bool ret = true;
924 
925    if (index >= sizeof(disks) / sizeof(disks[0]))
926       return false;
927 
928    if (disks[index].fname != NULL)
929       free(disks[index].fname);
930    disks[index].fname = NULL;
931 
932    if (info != NULL) {
933       disks[index].fname = strdup(info->path);
934       if (index == disk_current_index)
935          ret = disk_set_image_index(index);
936    }
937 
938    return ret;
939 }
940 
disk_add_image_index(void)941 static bool disk_add_image_index(void)
942 {
943    if (disk_count >= sizeof(disks) / sizeof(disks[0]))
944       return false;
945 
946    disk_count++;
947    return true;
948 }
949 
950 static struct retro_disk_control_callback disk_control = {
951    disk_set_eject_state,
952    disk_get_eject_state,
953    disk_get_image_index,
954    disk_set_image_index,
955    disk_get_num_images,
956    disk_replace_image_index,
957    disk_add_image_index,
958 };
959 
disk_tray_open(void)960 static void disk_tray_open(void)
961 {
962    if (log_cb)
963       log_cb(RETRO_LOG_INFO, "cd tray open\n");
964    disk_ejected = 1;
965 }
966 
disk_tray_close(void)967 static void disk_tray_close(void)
968 {
969    if (log_cb)
970       log_cb(RETRO_LOG_INFO, "cd tray close\n");
971    disk_ejected = 0;
972 }
973 
974 
975 static const char * const biosfiles_us[] = {
976    "us_scd2_9306", "SegaCDBIOS9303", "us_scd1_9210", "bios_CD_U"
977 };
978 static const char * const biosfiles_eu[] = {
979    "eu_mcd2_9306", "eu_mcd2_9303", "eu_mcd1_9210", "bios_CD_E"
980 };
981 static const char * const biosfiles_jp[] = {
982    "jp_mcd2_921222", "jp_mcd1_9112", "jp_mcd1_9111", "bios_CD_J"
983 };
984 
make_system_path(char * buf,size_t buf_size,const char * name,const char * ext)985 static void make_system_path(char *buf, size_t buf_size,
986    const char *name, const char *ext)
987 {
988    const char *dir = NULL;
989 
990    if (environ_cb(RETRO_ENVIRONMENT_GET_SYSTEM_DIRECTORY, &dir) && dir) {
991       snprintf(buf, buf_size, "%s%c%s%s", dir, SLASH, name, ext);
992    }
993    else {
994       snprintf(buf, buf_size, "%s%s", name, ext);
995    }
996 }
997 
find_bios(int * region,const char * cd_fname)998 static const char *find_bios(int *region, const char *cd_fname)
999 {
1000    const char * const *files;
1001    static char path[256];
1002    int i, count;
1003    FILE *f = NULL;
1004 
1005    if (*region == 4) { // US
1006       files = biosfiles_us;
1007       count = sizeof(biosfiles_us) / sizeof(char *);
1008    } else if (*region == 8) { // EU
1009       files = biosfiles_eu;
1010       count = sizeof(biosfiles_eu) / sizeof(char *);
1011    } else if (*region == 1 || *region == 2) {
1012       files = biosfiles_jp;
1013       count = sizeof(biosfiles_jp) / sizeof(char *);
1014    } else {
1015       return NULL;
1016    }
1017 
1018    for (i = 0; i < count; i++)
1019    {
1020       make_system_path(path, sizeof(path), files[i], ".bin");
1021       f = fopen(path, "rb");
1022       if (f != NULL)
1023          break;
1024 
1025       make_system_path(path, sizeof(path), files[i], ".zip");
1026       f = fopen(path, "rb");
1027       if (f != NULL)
1028          break;
1029    }
1030 
1031    if (f != NULL) {
1032       if (log_cb)
1033          log_cb(RETRO_LOG_INFO, "using bios: %s\n", path);
1034       fclose(f);
1035       return path;
1036    }
1037 
1038    return NULL;
1039 }
1040 
set_memory_maps(void)1041 static void set_memory_maps(void)
1042 {
1043    if (PicoIn.AHW & PAHW_MCD)
1044    {
1045       const size_t SCD_BIT = 1ULL << 31ULL;
1046       const uint64_t mem = RETRO_MEMDESC_SYSTEM_RAM;
1047       struct retro_memory_map mmaps;
1048       struct retro_memory_descriptor descs[] = {
1049          { mem, PicoMem.ram,        0,           0xFF0000, 0, 0, 0x10000, "68KRAM" },
1050          /* virtual address using SCD_BIT so all 512M of prg_ram can be accessed */
1051          /* at address $80020000 */
1052          { mem, Pico_mcd->prg_ram,  0, SCD_BIT | 0x020000, 0, 0, 0x80000, "PRGRAM" },
1053       };
1054 
1055       mmaps.descriptors = descs;
1056       mmaps.num_descriptors = sizeof(descs) / sizeof(descs[0]);
1057       environ_cb(RETRO_ENVIRONMENT_SET_MEMORY_MAPS, &mmaps);
1058    }
1059 }
1060 
retro_load_game(const struct retro_game_info * info)1061 bool retro_load_game(const struct retro_game_info *info)
1062 {
1063    enum media_type_e media_type;
1064    static char carthw_path[256];
1065    size_t i;
1066 
1067    struct retro_input_descriptor desc[] = {
1068       { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_LEFT,  "D-Pad Left" },
1069       { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_UP,    "D-Pad Up" },
1070       { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_DOWN,  "D-Pad Down" },
1071       { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_RIGHT, "D-Pad Right" },
1072       { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_B,     "B" },
1073       { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_A,     "C" },
1074       { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_X,     "Y" },
1075       { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_Y,     "A" },
1076       { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_L,     "X" },
1077       { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_R,     "Z" },
1078       { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_SELECT,"Mode" },
1079       { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_START, "Start" },
1080 
1081       { 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_LEFT,  "D-Pad Left" },
1082       { 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_UP,    "D-Pad Up" },
1083       { 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_DOWN,  "D-Pad Down" },
1084       { 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_RIGHT, "D-Pad Right" },
1085       { 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_B,     "B" },
1086       { 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_A,     "C" },
1087       { 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_X,     "Y" },
1088       { 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_Y,     "A" },
1089       { 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_L,     "X" },
1090       { 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_R,     "Z" },
1091       { 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_SELECT,"Mode" },
1092       { 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_START, "Start" },
1093 
1094       { 0 },
1095    };
1096 
1097    struct retro_input_descriptor desc_sms[] = {
1098       { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_LEFT,  "D-Pad Left" },
1099       { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_UP,    "D-Pad Up" },
1100       { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_DOWN,  "D-Pad Down" },
1101       { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_RIGHT, "D-Pad Right" },
1102       { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_B,     "Button 1 Start" },
1103       { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_A,     "Button 2" },
1104       { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_START, "Button Pause" },
1105 
1106       { 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_LEFT,  "D-Pad Left" },
1107       { 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_UP,    "D-Pad Up" },
1108       { 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_DOWN,  "D-Pad Down" },
1109       { 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_RIGHT, "D-Pad Right" },
1110       { 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_B,     "Button 1 Start" },
1111       { 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_A,     "Button 2" },
1112       { 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_START, "Button Pause" },
1113 
1114       { 0 },
1115    };
1116 
1117    enum retro_pixel_format fmt = RETRO_PIXEL_FORMAT_RGB565;
1118    if (!environ_cb(RETRO_ENVIRONMENT_SET_PIXEL_FORMAT, &fmt)) {
1119       if (log_cb)
1120          log_cb(RETRO_LOG_ERROR, "RGB565 support required, sorry\n");
1121       return false;
1122    }
1123 
1124    if (info == NULL || info->path == NULL) {
1125       if (log_cb)
1126          log_cb(RETRO_LOG_ERROR, "info->path required\n");
1127       return false;
1128    }
1129 
1130    for (i = 0; i < sizeof(disks) / sizeof(disks[0]); i++) {
1131       if (disks[i].fname != NULL) {
1132          free(disks[i].fname);
1133          disks[i].fname = NULL;
1134       }
1135    }
1136 
1137    disk_current_index = 0;
1138    disk_count = 1;
1139    disks[0].fname = strdup(info->path);
1140 
1141    make_system_path(carthw_path, sizeof(carthw_path), "carthw", ".cfg");
1142 
1143    media_type = PicoLoadMedia(info->path, carthw_path,
1144          find_bios, NULL);
1145 
1146    switch (media_type) {
1147    case PM_BAD_DETECT:
1148       if (log_cb)
1149          log_cb(RETRO_LOG_ERROR, "Failed to detect ROM/CD image type.\n");
1150       return false;
1151    case PM_BAD_CD:
1152       if (log_cb)
1153          log_cb(RETRO_LOG_ERROR, "Invalid CD image\n");
1154       return false;
1155    case PM_BAD_CD_NO_BIOS:
1156       if (log_cb)
1157          log_cb(RETRO_LOG_ERROR, "Missing BIOS\n");
1158       return false;
1159    case PM_ERROR:
1160       if (log_cb)
1161          log_cb(RETRO_LOG_ERROR, "Load error\n");
1162       return false;
1163    default:
1164       break;
1165    }
1166 
1167    if (media_type == PM_MARK3)
1168       environ_cb(RETRO_ENVIRONMENT_SET_INPUT_DESCRIPTORS, desc_sms);
1169    else
1170       environ_cb(RETRO_ENVIRONMENT_SET_INPUT_DESCRIPTORS, desc);
1171 
1172    PicoLoopPrepare();
1173 
1174    PicoIn.writeSound = snd_write;
1175    memset(sndBuffer, 0, sizeof(sndBuffer));
1176    PicoIn.sndOut = sndBuffer;
1177    PsndRerate(0);
1178 
1179    /* Setup retro memory maps */
1180    set_memory_maps();
1181 
1182    return true;
1183 }
1184 
retro_load_game_special(unsigned game_type,const struct retro_game_info * info,size_t num_info)1185 bool retro_load_game_special(unsigned game_type, const struct retro_game_info *info, size_t num_info)
1186 {
1187    return false;
1188 }
1189 
retro_unload_game(void)1190 void retro_unload_game(void)
1191 {
1192 }
1193 
retro_get_region(void)1194 unsigned retro_get_region(void)
1195 {
1196    return Pico.m.pal ? RETRO_REGION_PAL : RETRO_REGION_NTSC;
1197 }
1198 
retro_get_memory_data(unsigned type)1199 void *retro_get_memory_data(unsigned type)
1200 {
1201    uint8_t* data;
1202 
1203    switch(type)
1204    {
1205       case RETRO_MEMORY_SAVE_RAM:
1206          if (PicoIn.AHW & PAHW_MCD)
1207             data = Pico_mcd->bram;
1208          else
1209             data = Pico.sv.data;
1210          break;
1211       case RETRO_MEMORY_SYSTEM_RAM:
1212          if (PicoIn.AHW & PAHW_SMS)
1213             data = PicoMem.zram;
1214          else
1215             data = PicoMem.ram;
1216          break;
1217       default:
1218          data = NULL;
1219          break;
1220    }
1221 
1222    return data;
1223 }
1224 
retro_get_memory_size(unsigned type)1225 size_t retro_get_memory_size(unsigned type)
1226 {
1227    unsigned int i;
1228    int sum;
1229 
1230    switch(type)
1231    {
1232       case RETRO_MEMORY_SAVE_RAM:
1233          if (PicoIn.AHW & PAHW_MCD)
1234             // bram
1235             return 0x2000;
1236 
1237          if (Pico.m.frame_count == 0)
1238             return Pico.sv.size;
1239 
1240          // if game doesn't write to sram, don't report it to
1241          // libretro so that RA doesn't write out zeroed .srm
1242          for (i = 0, sum = 0; i < Pico.sv.size; i++)
1243             sum |= Pico.sv.data[i];
1244 
1245          return (sum != 0) ? Pico.sv.size : 0;
1246 
1247       case RETRO_MEMORY_SYSTEM_RAM:
1248          if (PicoIn.AHW & PAHW_SMS)
1249             return 0x2000;
1250          else
1251             return sizeof(PicoMem.ram);
1252 
1253       default:
1254          return 0;
1255    }
1256 
1257 }
1258 
retro_reset(void)1259 void retro_reset(void)
1260 {
1261    PicoReset();
1262 }
1263 
1264 static const unsigned short retro_pico_map[] = {
1265    1 << GBTN_B,
1266    1 << GBTN_A,
1267    1 << GBTN_MODE,
1268    1 << GBTN_START,
1269    1 << GBTN_UP,
1270    1 << GBTN_DOWN,
1271    1 << GBTN_LEFT,
1272    1 << GBTN_RIGHT,
1273    1 << GBTN_C,
1274    1 << GBTN_Y,
1275    1 << GBTN_X,
1276    1 << GBTN_Z,
1277 };
1278 #define RETRO_PICO_MAP_LEN (sizeof(retro_pico_map) / sizeof(retro_pico_map[0]))
1279 
snd_write(int len)1280 static void snd_write(int len)
1281 {
1282    audio_batch_cb(PicoIn.sndOut, len / 4);
1283 }
1284 
input_name_to_val(const char * name)1285 static enum input_device input_name_to_val(const char *name)
1286 {
1287    if (strcmp(name, "3 button pad") == 0)
1288       return PICO_INPUT_PAD_3BTN;
1289    if (strcmp(name, "6 button pad") == 0)
1290       return PICO_INPUT_PAD_6BTN;
1291    if (strcmp(name, "None") == 0)
1292       return PICO_INPUT_NOTHING;
1293 
1294    if (log_cb)
1295       log_cb(RETRO_LOG_WARN, "invalid picodrive_input: '%s'\n", name);
1296    return PICO_INPUT_PAD_3BTN;
1297 }
1298 
update_variables(void)1299 static void update_variables(void)
1300 {
1301    struct retro_variable var;
1302    int OldPicoRegionOverride;
1303    float old_user_vout_width;
1304    double new_sound_rate;
1305 
1306    var.value = NULL;
1307    var.key = "picodrive_input1";
1308    if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value)
1309       PicoSetInputDevice(0, input_name_to_val(var.value));
1310 
1311    var.value = NULL;
1312    var.key = "picodrive_input2";
1313    if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value)
1314       PicoSetInputDevice(1, input_name_to_val(var.value));
1315 
1316    var.value = NULL;
1317    var.key = "picodrive_sprlim";
1318    if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value) {
1319       if (strcmp(var.value, "enabled") == 0)
1320          PicoIn.opt |= POPT_DIS_SPRITE_LIM;
1321       else
1322          PicoIn.opt &= ~POPT_DIS_SPRITE_LIM;
1323    }
1324 
1325    var.value = NULL;
1326    var.key = "picodrive_ramcart";
1327    if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value) {
1328       if (strcmp(var.value, "enabled") == 0)
1329          PicoIn.opt |= POPT_EN_MCD_RAMCART;
1330       else
1331          PicoIn.opt &= ~POPT_EN_MCD_RAMCART;
1332    }
1333 
1334    OldPicoRegionOverride = PicoIn.regionOverride;
1335    var.value = NULL;
1336    var.key = "picodrive_region";
1337    if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value) {
1338       if (strcmp(var.value, "Auto") == 0)
1339          PicoIn.regionOverride = 0;
1340       else if (strcmp(var.value, "Japan NTSC") == 0)
1341          PicoIn.regionOverride = 1;
1342       else if (strcmp(var.value, "Japan PAL") == 0)
1343          PicoIn.regionOverride = 2;
1344       else if (strcmp(var.value, "US") == 0)
1345          PicoIn.regionOverride = 4;
1346       else if (strcmp(var.value, "Europe") == 0)
1347          PicoIn.regionOverride = 8;
1348    }
1349 
1350    // Update region, fps and sound flags if needed
1351    if (Pico.rom && PicoIn.regionOverride != OldPicoRegionOverride)
1352    {
1353       PicoDetectRegion();
1354       PicoLoopPrepare();
1355       PsndRerate(1);
1356    }
1357 
1358    old_user_vout_width = user_vout_width;
1359    var.value = NULL;
1360    var.key = "picodrive_aspect";
1361    if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value) {
1362       if (strcmp(var.value, "4/3") == 0)
1363          user_vout_width = VOUT_4_3;
1364       else if (strcmp(var.value, "CRT") == 0)
1365          user_vout_width = VOUT_CRT;
1366       else
1367          user_vout_width = VOUT_PAR;
1368    }
1369 
1370    if (user_vout_width != old_user_vout_width)
1371    {
1372       // Update the geometry
1373       struct retro_system_av_info av_info;
1374       retro_get_system_av_info(&av_info);
1375       environ_cb(RETRO_ENVIRONMENT_SET_GEOMETRY, &av_info);
1376    }
1377 
1378    old_show_overscan = show_overscan;
1379    var.value = NULL;
1380    var.key = "picodrive_overscan";
1381    show_overscan = false;
1382    if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value) {
1383       if (strcmp(var.value, "enabled") == 0)
1384          show_overscan = true;
1385    }
1386 
1387    if (show_overscan != old_show_overscan)
1388    {
1389       if ((vm_current_start_line != -1) &&
1390           (vm_current_line_count != -1) &&
1391           (vm_current_is_32cols != -1))
1392          emu_video_mode_change(
1393                vm_current_start_line,
1394                vm_current_line_count,
1395                vm_current_is_32cols);
1396    }
1397 
1398    var.value = NULL;
1399    var.key = "picodrive_overclk68k";
1400    if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value) {
1401       PicoIn.overclockM68k = 0;
1402       if (var.value[0] == '+')
1403          PicoIn.overclockM68k = atoi(var.value + 1);
1404    }
1405 
1406 #ifdef DRC_SH2
1407    var.value = NULL;
1408    var.key = "picodrive_drc";
1409    if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value) {
1410       if (strcmp(var.value, "enabled") == 0)
1411          PicoIn.opt |= POPT_EN_DRC;
1412       else
1413          PicoIn.opt &= ~POPT_EN_DRC;
1414    }
1415 #endif
1416 #ifdef _3DS
1417    if(!ctr_svchack_successful)
1418       PicoIn.opt &= ~POPT_EN_DRC;
1419 #endif
1420 
1421    var.value = NULL;
1422    var.key = "picodrive_audio_filter";
1423    PicoIn.sndFilter = 0;
1424    if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value) {
1425       if (strcmp(var.value, "low-pass") == 0)
1426          PicoIn.sndFilter = 1;
1427    }
1428 
1429    var.value = NULL;
1430    var.key = "picodrive_lowpass_range";
1431    PicoIn.sndFilterRange = (60 * 65536) / 100;
1432    if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value) {
1433       PicoIn.sndFilterRange = (atoi(var.value) * 65536) / 100;
1434    }
1435 
1436    var.value = NULL;
1437    var.key = "picodrive_renderer";
1438    if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value) {
1439       if (strcmp(var.value, "fast") == 0)
1440          PicoIn.opt |= POPT_ALT_RENDERER;
1441       else
1442          PicoIn.opt &= ~POPT_ALT_RENDERER;
1443    }
1444 
1445    var.value = NULL;
1446    var.key = "picodrive_sound_rate";
1447    if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value) {
1448       new_sound_rate = atoi(var.value);
1449       if (new_sound_rate != PicoIn.sndRate) {
1450          /* Update the sound rate */
1451          PicoIn.sndRate = new_sound_rate;
1452          PsndRerate(1);
1453          struct retro_system_av_info av_info;
1454          retro_get_system_av_info(&av_info);
1455          environ_cb(RETRO_ENVIRONMENT_SET_SYSTEM_AV_INFO, &av_info);
1456       }
1457    }
1458 }
1459 
retro_run(void)1460 void retro_run(void)
1461 {
1462    bool updated = false;
1463    int pad, i;
1464    static void *buff;
1465 
1466    if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE_UPDATE, &updated) && updated)
1467       update_variables();
1468 
1469    input_poll_cb();
1470 
1471    PicoIn.pad[0] = PicoIn.pad[1] = 0;
1472    for (pad = 0; pad < 2; pad++)
1473       for (i = 0; i < RETRO_PICO_MAP_LEN; i++)
1474          if (input_state_cb(pad, RETRO_DEVICE_JOYPAD, 0, i))
1475             PicoIn.pad[pad] |= retro_pico_map[i];
1476 
1477    PicoPatchApply();
1478    PicoFrame();
1479 
1480 #if defined(RENDER_GSKIT_PS2)
1481    buff = (uint32_t *)RETRO_HW_FRAME_BUFFER_VALID;
1482 
1483    if (!ps2) {
1484       if (!environ_cb(RETRO_ENVIRONMENT_GET_HW_RENDER_INTERFACE, (void **)&ps2) || !ps2) {
1485          printf("Failed to get HW rendering interface!\n");
1486          return;
1487 	   }
1488 
1489       if (ps2->interface_version != RETRO_HW_RENDER_INTERFACE_GSKIT_PS2_VERSION) {
1490          printf("HW render interface mismatch, expected %u, got %u!\n",
1491                   RETRO_HW_RENDER_INTERFACE_GSKIT_PS2_VERSION, ps2->interface_version);
1492          return;
1493       }
1494 
1495       ps2->coreTexture->Width = vout_width;
1496       ps2->coreTexture->Height = vout_height;
1497       ps2->coreTexture->PSM = GS_PSM_T8;
1498       ps2->coreTexture->ClutPSM = GS_PSM_CT16;
1499       ps2->coreTexture->Filter = GS_FILTER_LINEAR;
1500       ps2->coreTexture->Clut = retro_palette;
1501    }
1502 
1503    if (Pico.m.dirtyPal) {
1504       int i;
1505       unsigned short int *pal=(void *)ps2->coreTexture->Clut;
1506 
1507       if (PicoIn.AHW & PAHW_SMS) {
1508          // SMS
1509          unsigned int *spal=(void *)PicoMem.cram;
1510          unsigned int *dpal=(void *)pal;
1511          unsigned int t;
1512 
1513          /* cram is always stored as shorts, even though real hardware probably uses bytes */
1514          for (i = 0x20/2; i > 0; i--, spal++, dpal++) {
1515             t = *spal;
1516             t = ((t & 0x00030003)<< 3) | ((t & 0x000c000c)<<6) | ((t & 0x00300030)<<9);
1517             t |= t >> 2;
1518             t |= (t >> 4) & 0x08610861;
1519             *dpal = t;
1520          }
1521          pal[0xe0] = 0;
1522 
1523 
1524       } else if (PicoIn.AHW & PAHW_32X) {
1525          // MCD+32X
1526       } else if (PicoIn.AHW & PAHW_MCD) {
1527          // MCD
1528       } else {
1529          // MD
1530          if(Pico.video.reg[0xC]&8){
1531             do_pal_convert_with_shadows(pal, PicoMem.cram);
1532          } else {
1533             do_pal_convert(pal, PicoMem.cram);
1534             if (Pico.est.rendstatus & PDRAW_SONIC_MODE) {
1535                memcpy(&pal[0x80], pal, 0x40*2);
1536             }
1537          }
1538       }
1539 
1540 
1541   	   //Rotate CLUT.
1542       for (i = 0; i < 256; i++) {
1543          if ((i&0x18) == 8) {
1544             unsigned short int tmp = pal[i];
1545             pal[i] = pal[i+8];
1546             pal[i+8] = tmp;
1547          }
1548       }
1549 
1550       Pico.m.dirtyPal = 0;
1551       ps2->updatedPalette = true;
1552    }
1553 
1554    if (PicoIn.AHW & PAHW_SMS) {
1555       ps2->coreTexture->Mem = vout_buf;
1556    } else {
1557       ps2->coreTexture->Mem = Pico.est.Draw2FB;
1558    }
1559 
1560    ps2->padding = padding;
1561 
1562 #else
1563    if (PicoIn.opt & POPT_ALT_RENDERER) {
1564       /* In retro_init, PicoDrawSetOutBuf is called to make sure the output gets written to vout_buf, but this only
1565        * applies to the line renderer (pico/draw.c). The faster tile-based renderer (pico/draw2.c) enabled by
1566        * POPT_ALT_RENDERER writes to Pico.est.Draw2FB, so we need to manually copy that to vout_buf.
1567        */
1568       /* This section is mostly copied from pemu_finalize_frame in platform/linux/emu.c */
1569       unsigned short *pd = (unsigned short *)vout_buf;
1570       /* Skip the leftmost 8 columns (it seems to be used as some sort of caching or overscan area) */
1571       unsigned char *ps = Pico.est.Draw2FB + 8;
1572       unsigned short *pal = Pico.est.HighPal;
1573       int x;
1574       if (Pico.m.dirtyPal)
1575          PicoDrawUpdateHighPal();
1576       /* Copy up to the max height to include the overscan area, and skip the leftmost 8 columns again */
1577       for (i = 0; i < VOUT_MAX_HEIGHT; i++, ps += 8)
1578          for (x = 0; x < vout_width; x++)
1579             *pd++ = pal[*ps++];
1580    }
1581 
1582    buff = (char*)vout_buf + vout_offset;
1583 #endif
1584 
1585    video_cb((short *)buff,
1586       vout_width, vout_height, vout_width * 2);
1587 }
1588 
retro_init(void)1589 void retro_init(void)
1590 {
1591    struct retro_log_callback log;
1592    int level;
1593 
1594    level = 0;
1595    environ_cb(RETRO_ENVIRONMENT_SET_PERFORMANCE_LEVEL, &level);
1596 
1597    if (environ_cb(RETRO_ENVIRONMENT_GET_LOG_INTERFACE, &log))
1598       log_cb = log.log;
1599    else
1600       log_cb = NULL;
1601 
1602    environ_cb(RETRO_ENVIRONMENT_SET_DISK_CONTROL_INTERFACE, &disk_control);
1603 
1604 #ifdef _3DS
1605    ctr_svchack_successful = ctr_svchack_init();
1606 #elif defined(VITA)
1607    sceBlock = getVMBlock();
1608 #endif
1609 
1610    PicoIn.opt = POPT_EN_STEREO|POPT_EN_FM|POPT_EN_PSG|POPT_EN_Z80
1611       | POPT_EN_MCD_PCM|POPT_EN_MCD_CDDA|POPT_EN_MCD_GFX
1612       | POPT_EN_32X|POPT_EN_PWM
1613       | POPT_ACC_SPRITES|POPT_DIS_32C_BORDER;
1614 #ifdef __arm__
1615 #ifdef _3DS
1616    if (ctr_svchack_successful)
1617 #endif
1618       PicoIn.opt |= POPT_EN_DRC;
1619 #endif
1620 
1621    struct retro_variable var = { .key = "picodrive_sound_rate" };
1622    if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value)
1623       PicoIn.sndRate = atoi(var.value);
1624    else
1625       PicoIn.sndRate = INITIAL_SND_RATE;
1626 
1627    PicoIn.autoRgnOrder = 0x184; // US, EU, JP
1628 
1629    vout_width = VOUT_MAX_WIDTH;
1630    vout_height = VOUT_MAX_HEIGHT;
1631 #ifdef _3DS
1632    vout_buf = linearMemAlign(VOUT_MAX_WIDTH * VOUT_MAX_HEIGHT * 2, 0x80);
1633 #elif defined(RENDER_GSKIT_PS2)
1634    vout_buf = memalign(128, VOUT_MAX_WIDTH * VOUT_MAX_HEIGHT);
1635    retro_palette = memalign(128, gsKit_texture_size_ee(16, 16, GS_PSM_CT16));
1636 #else
1637    vout_buf = malloc(VOUT_MAX_WIDTH * VOUT_MAX_HEIGHT * 2);
1638 #endif
1639 
1640    PicoInit();
1641 #if defined(RENDER_GSKIT_PS2)
1642    PicoDrawSetOutFormat(PDF_NONE, 0);
1643 	PicoDrawSetOutBuf(vout_buf, vout_width);
1644    PicoDrawSetOutputMode4(PDF_8BIT);
1645 #else
1646    PicoDrawSetOutFormat(PDF_RGB555, 0);
1647    PicoDrawSetOutBuf(vout_buf, vout_width * 2);
1648 #endif
1649 
1650    //PicoIn.osdMessage = plat_status_msg_busy_next;
1651    PicoIn.mcdTrayOpen = disk_tray_open;
1652    PicoIn.mcdTrayClose = disk_tray_close;
1653 
1654    update_variables();
1655 }
1656 
retro_deinit(void)1657 void retro_deinit(void)
1658 {
1659 #ifdef _3DS
1660    linearFree(vout_buf);
1661 #elif defined(RENDER_GSKIT_PS2)
1662    free(vout_buf);
1663    free(retro_palette);
1664    ps2 = NULL;
1665 #else
1666    free(vout_buf);
1667 #endif
1668    vout_buf = NULL;
1669    PicoExit();
1670 }
1671