Merge pull request #23 from tuluse/master
[picodrive.git] / platform / libretro / libretro.c
... / ...
CommitLineData
1/*
2 * libretro core glue for PicoDrive
3 * (C) notaz, 2013
4 *
5 * This work is licensed under the terms of MAME license.
6 * See COPYING file in the top-level directory.
7 */
8
9#define _GNU_SOURCE 1 // mremap
10#include <stdio.h>
11#include <stdarg.h>
12#include <string.h>
13#ifndef _WIN32
14#ifndef NO_MMAP
15#include <sys/mman.h>
16#endif
17#else
18#include <io.h>
19#include <windows.h>
20#include <sys/types.h>
21#endif
22#include <errno.h>
23#ifdef __MACH__
24#include <libkern/OSCacheControl.h>
25#endif
26
27#ifdef _3DS
28#include "3ds/3ds_utils.h"
29#define MEMOP_MAP 4
30#define MEMOP_UNMAP 5
31#define MEMOP_PROT 6
32
33int svcDuplicateHandle(unsigned int* out, unsigned int original);
34int svcCloseHandle(unsigned int handle);
35int svcControlProcessMemory(unsigned int process, void* addr0, void* addr1,
36 unsigned int size, unsigned int type, unsigned int perm);
37void* linearMemAlign(size_t size, size_t alignment);
38void linearFree(void* mem);
39
40static int ctr_svchack_successful = 0;
41#endif
42
43#include <pico/pico_int.h>
44#include <pico/state.h>
45#include "../common/input_pico.h"
46#include "../common/version.h"
47#include "libretro.h"
48
49static retro_log_printf_t log_cb;
50static retro_video_refresh_t video_cb;
51static retro_input_poll_t input_poll_cb;
52static retro_input_state_t input_state_cb;
53static retro_environment_t environ_cb;
54static retro_audio_sample_batch_t audio_batch_cb;
55
56#define VOUT_MAX_WIDTH 320
57#define VOUT_MAX_HEIGHT 240
58static void *vout_buf;
59static int vout_width, vout_height, vout_offset;
60
61#ifdef _MSC_VER
62static short sndBuffer[2*44100/50];
63#else
64static short __attribute__((aligned(4))) sndBuffer[2*44100/50];
65#endif
66
67static void snd_write(int len);
68
69#ifdef _WIN32
70#define SLASH '\\'
71#else
72#define SLASH '/'
73#endif
74
75/* functions called by the core */
76
77void cache_flush_d_inval_i(void *start, void *end)
78{
79#ifdef __arm__
80#if defined(__BLACKBERRY_QNX__)
81 msync(start, end - start, MS_SYNC | MS_CACHE_ONLY | MS_INVALIDATE_ICACHE);
82#elif defined(__MACH__)
83 size_t len = (char *)end - (char *)start;
84 sys_dcache_flush(start, len);
85 sys_icache_invalidate(start, len);
86#elif defined(_3DS)
87 ctr_flush_invalidate_cache();
88#else
89 __clear_cache(start, end);
90#endif
91#endif
92}
93
94#ifdef _WIN32
95/* mmap() replacement for Windows
96 *
97 * Author: Mike Frysinger <vapier@gentoo.org>
98 * Placed into the public domain
99 */
100
101/* References:
102 * CreateFileMapping: http://msdn.microsoft.com/en-us/library/aa366537(VS.85).aspx
103 * CloseHandle: http://msdn.microsoft.com/en-us/library/ms724211(VS.85).aspx
104 * MapViewOfFile: http://msdn.microsoft.com/en-us/library/aa366761(VS.85).aspx
105 * UnmapViewOfFile: http://msdn.microsoft.com/en-us/library/aa366882(VS.85).aspx
106 */
107
108#define PROT_READ 0x1
109#define PROT_WRITE 0x2
110/* This flag is only available in WinXP+ */
111#ifdef FILE_MAP_EXECUTE
112#define PROT_EXEC 0x4
113#else
114#define PROT_EXEC 0x0
115#define FILE_MAP_EXECUTE 0
116#endif
117
118#define MAP_SHARED 0x01
119#define MAP_PRIVATE 0x02
120#define MAP_ANONYMOUS 0x20
121#define MAP_ANON MAP_ANONYMOUS
122#define MAP_FAILED ((void *) -1)
123
124#ifdef __USE_FILE_OFFSET64
125# define DWORD_HI(x) (x >> 32)
126# define DWORD_LO(x) ((x) & 0xffffffff)
127#else
128# define DWORD_HI(x) (0)
129# define DWORD_LO(x) (x)
130#endif
131
132static void *mmap(void *start, size_t length, int prot, int flags, int fd, off_t offset)
133{
134 uint32_t flProtect, dwDesiredAccess;
135 off_t end;
136 HANDLE mmap_fd, h;
137 void *ret;
138
139 if (prot & ~(PROT_READ | PROT_WRITE | PROT_EXEC))
140 return MAP_FAILED;
141 if (fd == -1) {
142 if (!(flags & MAP_ANON) || offset)
143 return MAP_FAILED;
144 } else if (flags & MAP_ANON)
145 return MAP_FAILED;
146
147 if (prot & PROT_WRITE) {
148 if (prot & PROT_EXEC)
149 flProtect = PAGE_EXECUTE_READWRITE;
150 else
151 flProtect = PAGE_READWRITE;
152 } else if (prot & PROT_EXEC) {
153 if (prot & PROT_READ)
154 flProtect = PAGE_EXECUTE_READ;
155 else if (prot & PROT_EXEC)
156 flProtect = PAGE_EXECUTE;
157 } else
158 flProtect = PAGE_READONLY;
159
160 end = length + offset;
161
162 if (fd == -1)
163 mmap_fd = INVALID_HANDLE_VALUE;
164 else
165 mmap_fd = (HANDLE)_get_osfhandle(fd);
166 h = CreateFileMapping(mmap_fd, NULL, flProtect, DWORD_HI(end), DWORD_LO(end), NULL);
167 if (h == NULL)
168 return MAP_FAILED;
169
170 if (prot & PROT_WRITE)
171 dwDesiredAccess = FILE_MAP_WRITE;
172 else
173 dwDesiredAccess = FILE_MAP_READ;
174 if (prot & PROT_EXEC)
175 dwDesiredAccess |= FILE_MAP_EXECUTE;
176 if (flags & MAP_PRIVATE)
177 dwDesiredAccess |= FILE_MAP_COPY;
178 ret = MapViewOfFile(h, dwDesiredAccess, DWORD_HI(offset), DWORD_LO(offset), length);
179 if (ret == NULL) {
180 CloseHandle(h);
181 ret = MAP_FAILED;
182 }
183 return ret;
184}
185
186static void munmap(void *addr, size_t length)
187{
188 UnmapViewOfFile(addr);
189 /* ruh-ro, we leaked handle from CreateFileMapping() ... */
190}
191#elif defined(NO_MMAP)
192#define PROT_EXEC 0x04
193#define MAP_FAILED 0
194#define PROT_READ 0
195#define PROT_WRITE 0
196#define MAP_PRIVATE 0
197#define MAP_ANONYMOUS 0
198
199void* mmap(void *desired_addr, size_t len, int mmap_prot, int mmap_flags, int fildes, size_t off)
200{
201 return malloc(len);
202}
203
204void munmap(void *base_addr, size_t len)
205{
206 free(base_addr);
207}
208
209int mprotect(void *addr, size_t len, int prot)
210{
211 /* stub - not really needed at this point since this codepath has no dynarecs */
212 return 0;
213}
214
215#endif
216
217#ifndef MAP_ANONYMOUS
218#define MAP_ANONYMOUS MAP_ANON
219#endif
220
221#ifdef _3DS
222typedef struct
223{
224 unsigned int requested_map;
225 void* buffer;
226}pico_mmap_t;
227
228pico_mmap_t pico_mmaps[] = {
229 {0x02000000, 0},
230 {0x06000000, 0},
231 {NULL, 0}
232};
233
234void *plat_mmap(unsigned long addr, size_t size, int need_exec, int is_fixed)
235{
236 (void)is_fixed;
237
238 if (ctr_svchack_successful)
239 {
240 pico_mmap_t* pico_mmap;
241
242 for (pico_mmap = pico_mmaps; pico_mmap->requested_map; pico_mmap++)
243 {
244 if ((pico_mmap->requested_map == addr))
245 {
246 unsigned int ptr_aligned, tmp;
247 unsigned int currentHandle;
248 unsigned int perm = 0b011;
249
250 if (need_exec)
251 perm = 0b111;
252
253 size = (size + 0xFFF) & ~0xFFF;
254 pico_mmap->buffer = malloc(size + 0x1000);
255 ptr_aligned = (((unsigned int)pico_mmap->buffer) + 0xFFF) & ~0xFFF;
256
257 svcDuplicateHandle(&currentHandle, 0xFFFF8001);
258
259 if(svcControlProcessMemory(currentHandle, pico_mmap->requested_map, ptr_aligned, size, MEMOP_MAP, perm) < 0)
260 {
261 if (log_cb)
262 log_cb(RETRO_LOG_ERROR, "could not map memory @0x%08X\n", pico_mmap->requested_map);
263 exit(1);
264 }
265
266 svcCloseHandle(currentHandle);
267 return (void*)pico_mmap->requested_map;
268 }
269 }
270 }
271
272 return malloc(size);
273}
274
275void *plat_mremap(void *ptr, size_t oldsize, size_t newsize)
276{
277 if (ctr_svchack_successful)
278 {
279 pico_mmap_t* pico_mmap;
280
281 for (pico_mmap = pico_mmaps; pico_mmap->requested_map; pico_mmap++)
282 {
283 if ((pico_mmap->requested_map == (unsigned int)ptr))
284 {
285 unsigned int ptr_aligned;
286 unsigned int currentHandle;
287 void* tmp;
288
289 oldsize = (oldsize + 0xFFF) & ~0xFFF;
290 newsize = (newsize + 0xFFF) & ~0xFFF;
291 ptr_aligned = (((unsigned int)pico_mmap->buffer) + 0xFFF) & ~0xFFF;
292
293 svcDuplicateHandle(&currentHandle, 0xFFFF8001);
294
295 svcControlProcessMemory(currentHandle, pico_mmap->requested_map, ptr_aligned, oldsize, MEMOP_UNMAP, 0b011);
296
297 tmp = realloc(pico_mmap->buffer, newsize + 0x1000);
298 if(!tmp)
299 return NULL;
300
301 pico_mmap->buffer = tmp;
302 ptr_aligned = (((unsigned int)pico_mmap->buffer) + 0xFFF) & ~0xFFF;
303
304 svcControlProcessMemory(currentHandle, pico_mmap->requested_map, ptr_aligned, newsize, MEMOP_MAP, 0x3);
305
306 svcCloseHandle(currentHandle);
307
308 return ptr;
309 }
310 }
311 }
312
313 return realloc(ptr, newsize);
314
315}
316void plat_munmap(void *ptr, size_t size)
317{
318 if (ctr_svchack_successful)
319 {
320 pico_mmap_t* pico_mmap;
321
322 for (pico_mmap = pico_mmaps; pico_mmap->requested_map; pico_mmap++)
323 {
324 if ((pico_mmap->requested_map == (unsigned int)ptr))
325 {
326 unsigned int ptr_aligned;
327 unsigned int currentHandle;
328
329 size = (size + 0xFFF) & ~0xFFF;
330 ptr_aligned = (((unsigned int)pico_mmap->buffer) + 0xFFF) & ~0xFFF;
331
332 svcDuplicateHandle(&currentHandle, 0xFFFF8001);
333
334 svcControlProcessMemory(currentHandle, (void*)pico_mmap->requested_map, (void*)ptr_aligned, size, MEMOP_UNMAP, 0b011);
335
336 svcCloseHandle(currentHandle);
337
338 free(pico_mmap->buffer);
339 pico_mmap->buffer = NULL;
340 return;
341 }
342 }
343 }
344
345 free(ptr);
346}
347
348#else
349void *plat_mmap(unsigned long addr, size_t size, int need_exec, int is_fixed)
350{
351 int flags = MAP_PRIVATE | MAP_ANONYMOUS;
352 void *req, *ret;
353
354 req = (void *)addr;
355 ret = mmap(req, size, PROT_READ | PROT_WRITE, flags, -1, 0);
356 if (ret == MAP_FAILED) {
357 if (log_cb)
358 log_cb(RETRO_LOG_ERROR, "mmap(%08lx, %zd) failed: %d\n", addr, size, errno);
359 return NULL;
360 }
361
362 if (addr != 0 && ret != (void *)addr) {
363 if (log_cb)
364 log_cb(RETRO_LOG_WARN, "warning: wanted to map @%08lx, got %p\n",
365 addr, ret);
366
367 if (is_fixed) {
368 munmap(ret, size);
369 return NULL;
370 }
371 }
372
373 return ret;
374}
375
376void *plat_mremap(void *ptr, size_t oldsize, size_t newsize)
377{
378#ifdef __linux__
379 void *ret = mremap(ptr, oldsize, newsize, 0);
380 if (ret == MAP_FAILED)
381 return NULL;
382
383 return ret;
384#else
385 void *tmp, *ret;
386 size_t preserve_size;
387
388 preserve_size = oldsize;
389 if (preserve_size > newsize)
390 preserve_size = newsize;
391 tmp = malloc(preserve_size);
392 if (tmp == NULL)
393 return NULL;
394 memcpy(tmp, ptr, preserve_size);
395
396 munmap(ptr, oldsize);
397 ret = mmap(ptr, newsize, PROT_READ | PROT_WRITE,
398 MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
399 if (ret == MAP_FAILED) {
400 free(tmp);
401 return NULL;
402 }
403 memcpy(ret, tmp, preserve_size);
404 free(tmp);
405 return ret;
406#endif
407}
408
409void plat_munmap(void *ptr, size_t size)
410{
411 if (ptr != NULL)
412 munmap(ptr, size);
413}
414#endif
415
416int plat_mem_set_exec(void *ptr, size_t size)
417{
418#ifdef _WIN32
419 int ret = VirtualProtect(ptr,size,PAGE_EXECUTE_READWRITE,0);
420 if (ret == 0 && log_cb)
421 log_cb(RETRO_LOG_ERROR, "mprotect(%p, %zd) failed: %d\n", ptr, size, 0);
422#elif defined(_3DS)
423 int ret = -1;
424 if (ctr_svchack_successful)
425 {
426 unsigned int currentHandle;
427 svcDuplicateHandle(&currentHandle, 0xFFFF8001);
428 ret = svcControlProcessMemory(currentHandle, ptr, 0x0,
429 size, MEMOP_PROT, 0b111);
430 svcCloseHandle(currentHandle);
431 ctr_flush_invalidate_cache();
432
433 }
434 else
435 {
436 if (log_cb)
437 log_cb(RETRO_LOG_ERROR, "plat_mem_set_exec called with no svcControlProcessMemory access\n");
438 exit(1);
439 }
440
441
442#else
443 int ret = mprotect(ptr, size, PROT_READ | PROT_WRITE | PROT_EXEC);
444 if (ret != 0 && log_cb)
445 log_cb(RETRO_LOG_ERROR, "mprotect(%p, %zd) failed: %d\n", ptr, size, errno);
446#endif
447 return ret;
448}
449
450void emu_video_mode_change(int start_line, int line_count, int is_32cols)
451{
452 memset(vout_buf, 0, 320 * 240 * 2);
453 vout_width = is_32cols ? 256 : 320;
454 PicoDrawSetOutBuf(vout_buf, vout_width * 2);
455
456 vout_height = line_count;
457 vout_offset = vout_width * start_line;
458}
459
460void emu_32x_startup(void)
461{
462}
463
464void lprintf(const char *fmt, ...)
465{
466 char buffer[256];
467 va_list ap;
468 va_start(ap, fmt);
469 vsprintf(buffer, fmt, ap);
470 /* TODO - add 'level' param for warning/error messages? */
471 if (log_cb)
472 log_cb(RETRO_LOG_INFO, "%s", buffer);
473 va_end(ap);
474}
475
476/* libretro */
477void retro_set_environment(retro_environment_t cb)
478{
479 static const struct retro_variable vars[] = {
480 { "picodrive_input1", "Input device 1; 3 button pad|6 button pad|None" },
481 { "picodrive_input2", "Input device 2; 3 button pad|6 button pad|None" },
482 { "picodrive_sprlim", "No sprite limit; disabled|enabled" },
483 { "picodrive_ramcart", "MegaCD RAM cart; disabled|enabled" },
484 { "picodrive_region", "Region; Auto|Japan NTSC|Japan PAL|US|Europe" },
485 { "picodrive_region_fps", "Region FPS; Auto|NTSC|PAL" },
486#ifdef DRC_SH2
487 { "picodrive_drc", "Dynamic recompilers; enabled|disabled" },
488#endif
489 { NULL, NULL },
490 };
491
492 environ_cb = cb;
493
494 cb(RETRO_ENVIRONMENT_SET_VARIABLES, (void *)vars);
495}
496
497void retro_set_video_refresh(retro_video_refresh_t cb) { video_cb = cb; }
498void retro_set_audio_sample(retro_audio_sample_t cb) { (void)cb; }
499void retro_set_audio_sample_batch(retro_audio_sample_batch_t cb) { audio_batch_cb = cb; }
500void retro_set_input_poll(retro_input_poll_t cb) { input_poll_cb = cb; }
501void retro_set_input_state(retro_input_state_t cb) { input_state_cb = cb; }
502
503unsigned retro_api_version(void)
504{
505 return RETRO_API_VERSION;
506}
507
508void retro_set_controller_port_device(unsigned port, unsigned device)
509{
510}
511
512void retro_get_system_info(struct retro_system_info *info)
513{
514 memset(info, 0, sizeof(*info));
515 info->library_name = "PicoDrive";
516 info->library_version = VERSION;
517 info->valid_extensions = "bin|gen|smd|md|32x|cue|iso|sms";
518 info->need_fullpath = true;
519}
520
521void retro_get_system_av_info(struct retro_system_av_info *info)
522{
523 memset(info, 0, sizeof(*info));
524 info->timing.fps = Pico.m.pal ? 50 : 60;
525 info->timing.sample_rate = 44100;
526 info->geometry.base_width = 320;
527 info->geometry.base_height = vout_height;
528 info->geometry.max_width = VOUT_MAX_WIDTH;
529 info->geometry.max_height = VOUT_MAX_HEIGHT;
530 info->geometry.aspect_ratio = 4.0f / 3.0f;
531}
532
533/* savestates */
534struct savestate_state {
535 const char *load_buf;
536 char *save_buf;
537 size_t size;
538 size_t pos;
539};
540
541size_t state_read(void *p, size_t size, size_t nmemb, void *file)
542{
543 struct savestate_state *state = file;
544 size_t bsize = size * nmemb;
545
546 if (state->pos + bsize > state->size) {
547 if (log_cb)
548 log_cb(RETRO_LOG_ERROR, "savestate error: %u/%u\n",
549 state->pos + bsize, state->size);
550 bsize = state->size - state->pos;
551 if ((int)bsize <= 0)
552 return 0;
553 }
554
555 memcpy(p, state->load_buf + state->pos, bsize);
556 state->pos += bsize;
557 return bsize;
558}
559
560size_t state_write(void *p, size_t size, size_t nmemb, void *file)
561{
562 struct savestate_state *state = file;
563 size_t bsize = size * nmemb;
564
565 if (state->pos + bsize > state->size) {
566 if (log_cb)
567 log_cb(RETRO_LOG_ERROR, "savestate error: %u/%u\n",
568 state->pos + bsize, state->size);
569 bsize = state->size - state->pos;
570 if ((int)bsize <= 0)
571 return 0;
572 }
573
574 memcpy(state->save_buf + state->pos, p, bsize);
575 state->pos += bsize;
576 return bsize;
577}
578
579size_t state_skip(void *p, size_t size, size_t nmemb, void *file)
580{
581 struct savestate_state *state = file;
582 size_t bsize = size * nmemb;
583
584 state->pos += bsize;
585 return bsize;
586}
587
588size_t state_eof(void *file)
589{
590 struct savestate_state *state = file;
591
592 return state->pos >= state->size;
593}
594
595int state_fseek(void *file, long offset, int whence)
596{
597 struct savestate_state *state = file;
598
599 switch (whence) {
600 case SEEK_SET:
601 state->pos = offset;
602 break;
603 case SEEK_CUR:
604 state->pos += offset;
605 break;
606 case SEEK_END:
607 state->pos = state->size + offset;
608 break;
609 }
610 return (int)state->pos;
611}
612
613/* savestate sizes vary wildly depending if cd/32x or
614 * carthw is active, so run the whole thing to get size */
615size_t retro_serialize_size(void)
616{
617 struct savestate_state state = { 0, };
618 int ret;
619
620 ret = PicoStateFP(&state, 1, NULL, state_skip, NULL, state_fseek);
621 if (ret != 0)
622 return 0;
623
624 return state.pos;
625}
626
627bool retro_serialize(void *data, size_t size)
628{
629 struct savestate_state state = { 0, };
630 int ret;
631
632 state.save_buf = data;
633 state.size = size;
634 state.pos = 0;
635
636 ret = PicoStateFP(&state, 1, NULL, state_write,
637 NULL, state_fseek);
638 return ret == 0;
639}
640
641bool retro_unserialize(const void *data, size_t size)
642{
643 struct savestate_state state = { 0, };
644 int ret;
645
646 state.load_buf = data;
647 state.size = size;
648 state.pos = 0;
649
650 ret = PicoStateFP(&state, 0, state_read, NULL,
651 state_eof, state_fseek);
652 return ret == 0;
653}
654
655/* cheats - TODO */
656void retro_cheat_reset(void)
657{
658}
659
660void retro_cheat_set(unsigned index, bool enabled, const char *code)
661{
662}
663
664/* multidisk support */
665static bool disk_ejected;
666static unsigned int disk_current_index;
667static unsigned int disk_count;
668static struct disks_state {
669 char *fname;
670} disks[8];
671
672static bool disk_set_eject_state(bool ejected)
673{
674 // TODO?
675 disk_ejected = ejected;
676 return true;
677}
678
679static bool disk_get_eject_state(void)
680{
681 return disk_ejected;
682}
683
684static unsigned int disk_get_image_index(void)
685{
686 return disk_current_index;
687}
688
689static bool disk_set_image_index(unsigned int index)
690{
691 enum cd_img_type cd_type;
692 int ret;
693
694 if (index >= sizeof(disks) / sizeof(disks[0]))
695 return false;
696
697 if (disks[index].fname == NULL) {
698 if (log_cb)
699 log_cb(RETRO_LOG_ERROR, "missing disk #%u\n", index);
700
701 // RetroArch specifies "no disk" with index == count,
702 // so don't fail here..
703 disk_current_index = index;
704 return true;
705 }
706
707 if (log_cb)
708 log_cb(RETRO_LOG_INFO, "switching to disk %u: \"%s\"\n", index,
709 disks[index].fname);
710
711 ret = -1;
712 cd_type = PicoCdCheck(disks[index].fname, NULL);
713 if (cd_type != CIT_NOT_CD)
714 ret = cdd_load(disks[index].fname, cd_type);
715 if (ret != 0) {
716 if (log_cb)
717 log_cb(RETRO_LOG_ERROR, "Load failed, invalid CD image?\n");
718 return 0;
719 }
720
721 disk_current_index = index;
722 return true;
723}
724
725static unsigned int disk_get_num_images(void)
726{
727 return disk_count;
728}
729
730static bool disk_replace_image_index(unsigned index,
731 const struct retro_game_info *info)
732{
733 bool ret = true;
734
735 if (index >= sizeof(disks) / sizeof(disks[0]))
736 return false;
737
738 if (disks[index].fname != NULL)
739 free(disks[index].fname);
740 disks[index].fname = NULL;
741
742 if (info != NULL) {
743 disks[index].fname = strdup(info->path);
744 if (index == disk_current_index)
745 ret = disk_set_image_index(index);
746 }
747
748 return ret;
749}
750
751static bool disk_add_image_index(void)
752{
753 if (disk_count >= sizeof(disks) / sizeof(disks[0]))
754 return false;
755
756 disk_count++;
757 return true;
758}
759
760static struct retro_disk_control_callback disk_control = {
761 disk_set_eject_state,
762 disk_get_eject_state,
763 disk_get_image_index,
764 disk_set_image_index,
765 disk_get_num_images,
766 disk_replace_image_index,
767 disk_add_image_index,
768};
769
770static void disk_tray_open(void)
771{
772 if (log_cb)
773 log_cb(RETRO_LOG_INFO, "cd tray open\n");
774 disk_ejected = 1;
775}
776
777static void disk_tray_close(void)
778{
779 if (log_cb)
780 log_cb(RETRO_LOG_INFO, "cd tray close\n");
781 disk_ejected = 0;
782}
783
784
785static const char * const biosfiles_us[] = {
786 "us_scd2_9306", "SegaCDBIOS9303", "us_scd1_9210", "bios_CD_U"
787};
788static const char * const biosfiles_eu[] = {
789 "eu_mcd2_9306", "eu_mcd2_9303", "eu_mcd1_9210", "bios_CD_E"
790};
791static const char * const biosfiles_jp[] = {
792 "jp_mcd2_921222", "jp_mcd1_9112", "jp_mcd1_9111", "bios_CD_J"
793};
794
795static void make_system_path(char *buf, size_t buf_size,
796 const char *name, const char *ext)
797{
798 const char *dir = NULL;
799
800 if (environ_cb(RETRO_ENVIRONMENT_GET_SYSTEM_DIRECTORY, &dir) && dir) {
801 snprintf(buf, buf_size, "%s%c%s%s", dir, SLASH, name, ext);
802 }
803 else {
804 snprintf(buf, buf_size, "%s%s", name, ext);
805 }
806}
807
808static const char *find_bios(int *region, const char *cd_fname)
809{
810 const char * const *files;
811 static char path[256];
812 int i, count;
813 FILE *f = NULL;
814
815 if (*region == 4) { // US
816 files = biosfiles_us;
817 count = sizeof(biosfiles_us) / sizeof(char *);
818 } else if (*region == 8) { // EU
819 files = biosfiles_eu;
820 count = sizeof(biosfiles_eu) / sizeof(char *);
821 } else if (*region == 1 || *region == 2) {
822 files = biosfiles_jp;
823 count = sizeof(biosfiles_jp) / sizeof(char *);
824 } else {
825 return NULL;
826 }
827
828 for (i = 0; i < count; i++)
829 {
830 make_system_path(path, sizeof(path), files[i], ".bin");
831 f = fopen(path, "rb");
832 if (f != NULL)
833 break;
834
835 make_system_path(path, sizeof(path), files[i], ".zip");
836 f = fopen(path, "rb");
837 if (f != NULL)
838 break;
839 }
840
841 if (f != NULL) {
842 if (log_cb)
843 log_cb(RETRO_LOG_INFO, "using bios: %s\n", path);
844 fclose(f);
845 return path;
846 }
847
848 return NULL;
849}
850
851bool retro_load_game(const struct retro_game_info *info)
852{
853 enum media_type_e media_type;
854 static char carthw_path[256];
855 size_t i;
856
857 struct retro_input_descriptor desc[] = {
858 { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_LEFT, "D-Pad Left" },
859 { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_UP, "D-Pad Up" },
860 { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_DOWN, "D-Pad Down" },
861 { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_RIGHT, "D-Pad Right" },
862 { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_B, "B" },
863 { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_A, "C" },
864 { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_X, "Y" },
865 { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_Y, "A" },
866 { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_L, "X" },
867 { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_R, "Z" },
868 { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_SELECT,"Mode" },
869 { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_START, "Start" },
870
871 { 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_LEFT, "D-Pad Left" },
872 { 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_UP, "D-Pad Up" },
873 { 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_DOWN, "D-Pad Down" },
874 { 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_RIGHT, "D-Pad Right" },
875 { 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_B, "B" },
876 { 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_A, "C" },
877 { 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_X, "Y" },
878 { 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_Y, "A" },
879 { 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_L, "X" },
880 { 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_R, "Z" },
881 { 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_SELECT,"Mode" },
882 { 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_START, "Start" },
883
884 { 0 },
885 };
886
887 struct retro_input_descriptor desc_sms[] = {
888 { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_LEFT, "D-Pad Left" },
889 { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_UP, "D-Pad Up" },
890 { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_DOWN, "D-Pad Down" },
891 { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_RIGHT, "D-Pad Right" },
892 { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_B, "Button 1 Start" },
893 { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_A, "Button 2" },
894 { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_START, "Button Pause" },
895
896 { 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_LEFT, "D-Pad Left" },
897 { 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_UP, "D-Pad Up" },
898 { 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_DOWN, "D-Pad Down" },
899 { 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_RIGHT, "D-Pad Right" },
900 { 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_B, "Button 1 Start" },
901 { 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_A, "Button 2" },
902 { 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_START, "Button Pause" },
903
904 { 0 },
905 };
906
907 enum retro_pixel_format fmt = RETRO_PIXEL_FORMAT_RGB565;
908 if (!environ_cb(RETRO_ENVIRONMENT_SET_PIXEL_FORMAT, &fmt)) {
909 if (log_cb)
910 log_cb(RETRO_LOG_ERROR, "RGB565 support required, sorry\n");
911 return false;
912 }
913
914 if (info == NULL || info->path == NULL) {
915 if (log_cb)
916 log_cb(RETRO_LOG_ERROR, "info->path required\n");
917 return false;
918 }
919
920 for (i = 0; i < sizeof(disks) / sizeof(disks[0]); i++) {
921 if (disks[i].fname != NULL) {
922 free(disks[i].fname);
923 disks[i].fname = NULL;
924 }
925 }
926
927 disk_current_index = 0;
928 disk_count = 1;
929 disks[0].fname = strdup(info->path);
930
931 make_system_path(carthw_path, sizeof(carthw_path), "carthw", ".cfg");
932
933 media_type = PicoLoadMedia(info->path, carthw_path,
934 find_bios, NULL);
935
936 switch (media_type) {
937 case PM_BAD_DETECT:
938 if (log_cb)
939 log_cb(RETRO_LOG_ERROR, "Failed to detect ROM/CD image type.\n");
940 return false;
941 case PM_BAD_CD:
942 if (log_cb)
943 log_cb(RETRO_LOG_ERROR, "Invalid CD image\n");
944 return false;
945 case PM_BAD_CD_NO_BIOS:
946 if (log_cb)
947 log_cb(RETRO_LOG_ERROR, "Missing BIOS\n");
948 return false;
949 case PM_ERROR:
950 if (log_cb)
951 log_cb(RETRO_LOG_ERROR, "Load error\n");
952 return false;
953 default:
954 break;
955 }
956
957 if (media_type == PM_MARK3)
958 environ_cb(RETRO_ENVIRONMENT_SET_INPUT_DESCRIPTORS, desc_sms);
959 else
960 environ_cb(RETRO_ENVIRONMENT_SET_INPUT_DESCRIPTORS, desc);
961
962 PicoLoopPrepare();
963
964 PicoWriteSound = snd_write;
965 memset(sndBuffer, 0, sizeof(sndBuffer));
966 PsndOut = sndBuffer;
967 PsndRerate(0);
968
969 return true;
970}
971
972bool retro_load_game_special(unsigned game_type, const struct retro_game_info *info, size_t num_info)
973{
974 return false;
975}
976
977void retro_unload_game(void)
978{
979}
980
981unsigned retro_get_region(void)
982{
983 return Pico.m.pal ? RETRO_REGION_PAL : RETRO_REGION_NTSC;
984}
985
986void *retro_get_memory_data(unsigned type)
987{
988 uint8_t* data;
989
990 switch(type)
991 {
992 case RETRO_MEMORY_SAVE_RAM:
993 if (PicoAHW & PAHW_MCD)
994 data = Pico_mcd->bram;
995 else
996 data = SRam.data;
997 break;
998 case RETRO_MEMORY_SYSTEM_RAM:
999 if (PicoAHW & PAHW_SMS)
1000 data = Pico.vramb;
1001 else
1002 data = Pico.ram;
1003 break;
1004 default:
1005 data = NULL;
1006 break;
1007 }
1008
1009 return data;
1010}
1011
1012size_t retro_get_memory_size(unsigned type)
1013{
1014 unsigned int i;
1015 int sum;
1016
1017 switch(type)
1018 {
1019 case RETRO_MEMORY_SAVE_RAM:
1020 if (PicoAHW & PAHW_MCD)
1021 // bram
1022 return 0x2000;
1023
1024 if (Pico.m.frame_count == 0)
1025 return SRam.size;
1026
1027 // if game doesn't write to sram, don't report it to
1028 // libretro so that RA doesn't write out zeroed .srm
1029 for (i = 0, sum = 0; i < SRam.size; i++)
1030 sum |= SRam.data[i];
1031
1032 return (sum != 0) ? SRam.size : 0;
1033
1034 case RETRO_MEMORY_SYSTEM_RAM:
1035 if (PicoAHW & PAHW_SMS)
1036 return sizeof(Pico.vramb);
1037 else
1038 return sizeof(Pico.ram);
1039
1040 default:
1041 return 0;
1042 }
1043
1044}
1045
1046void retro_reset(void)
1047{
1048 PicoReset();
1049}
1050
1051static const unsigned short retro_pico_map[] = {
1052 1 << GBTN_B,
1053 1 << GBTN_A,
1054 1 << GBTN_MODE,
1055 1 << GBTN_START,
1056 1 << GBTN_UP,
1057 1 << GBTN_DOWN,
1058 1 << GBTN_LEFT,
1059 1 << GBTN_RIGHT,
1060 1 << GBTN_C,
1061 1 << GBTN_Y,
1062 1 << GBTN_X,
1063 1 << GBTN_Z,
1064};
1065#define RETRO_PICO_MAP_LEN (sizeof(retro_pico_map) / sizeof(retro_pico_map[0]))
1066
1067static void snd_write(int len)
1068{
1069 audio_batch_cb(PsndOut, len / 4);
1070}
1071
1072static enum input_device input_name_to_val(const char *name)
1073{
1074 if (strcmp(name, "3 button pad") == 0)
1075 return PICO_INPUT_PAD_3BTN;
1076 if (strcmp(name, "6 button pad") == 0)
1077 return PICO_INPUT_PAD_6BTN;
1078 if (strcmp(name, "None") == 0)
1079 return PICO_INPUT_NOTHING;
1080
1081 if (log_cb)
1082 log_cb(RETRO_LOG_WARN, "invalid picodrive_input: '%s'\n", name);
1083 return PICO_INPUT_PAD_3BTN;
1084}
1085
1086static void update_variables(void)
1087{
1088 struct retro_variable var;
1089
1090 var.value = NULL;
1091 var.key = "picodrive_input1";
1092 if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value)
1093 PicoSetInputDevice(0, input_name_to_val(var.value));
1094
1095 var.value = NULL;
1096 var.key = "picodrive_input2";
1097 if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value)
1098 PicoSetInputDevice(1, input_name_to_val(var.value));
1099
1100 var.value = NULL;
1101 var.key = "picodrive_sprlim";
1102 if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value) {
1103 if (strcmp(var.value, "enabled") == 0)
1104 PicoOpt |= POPT_DIS_SPRITE_LIM;
1105 else
1106 PicoOpt &= ~POPT_DIS_SPRITE_LIM;
1107 }
1108
1109 var.value = NULL;
1110 var.key = "picodrive_ramcart";
1111 if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value) {
1112 if (strcmp(var.value, "enabled") == 0)
1113 PicoOpt |= POPT_EN_MCD_RAMCART;
1114 else
1115 PicoOpt &= ~POPT_EN_MCD_RAMCART;
1116 }
1117
1118 int OldPicoRegionOverride = PicoRegionOverride;
1119 var.value = NULL;
1120 var.key = "picodrive_region";
1121 if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value) {
1122 if (strcmp(var.value, "Auto") == 0)
1123 PicoRegionOverride = 0;
1124 else if (strcmp(var.value, "Japan NTSC") == 0)
1125 PicoRegionOverride = 1;
1126 else if (strcmp(var.value, "Japan PAL") == 0)
1127 PicoRegionOverride = 2;
1128 else if (strcmp(var.value, "US") == 0)
1129 PicoRegionOverride = 4;
1130 else if (strcmp(var.value, "Europe") == 0)
1131 PicoRegionOverride = 8;
1132 }
1133
1134 int OldPicoRegionFPSOverride = PicoRegionFPSOverride;
1135 var.value = NULL;
1136 var.key = "picodrive_region_fps";
1137 if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value) {
1138 if (strcmp(var.value, "Auto") == 0)
1139 PicoRegionFPSOverride = 0;
1140 else if (strcmp(var.value, "NTSC") == 0)
1141 PicoRegionFPSOverride = 1;
1142 else if (strcmp(var.value, "PAL") == 0)
1143 PicoRegionFPSOverride = 2;
1144 }
1145
1146 // Update region, fps and sound flags if needed
1147 if (PicoRegionOverride != OldPicoRegionOverride ||
1148 PicoRegionFPSOverride != OldPicoRegionFPSOverride)
1149 {
1150 PicoDetectRegion();
1151 PicoLoopPrepare();
1152 PsndRerate(1);
1153 }
1154
1155#ifdef DRC_SH2
1156 var.value = NULL;
1157 var.key = "picodrive_drc";
1158 if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value) {
1159 if (strcmp(var.value, "enabled") == 0)
1160 PicoOpt |= POPT_EN_DRC;
1161 else
1162 PicoOpt &= ~POPT_EN_DRC;
1163 }
1164#endif
1165#ifdef _3DS
1166 if(!ctr_svchack_successful)
1167 PicoOpt &= ~POPT_EN_DRC;
1168#endif
1169}
1170
1171void retro_run(void)
1172{
1173 bool updated = false;
1174 int pad, i;
1175
1176 if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE_UPDATE, &updated) && updated)
1177 update_variables();
1178
1179 input_poll_cb();
1180
1181 PicoPad[0] = PicoPad[1] = 0;
1182 for (pad = 0; pad < 2; pad++)
1183 for (i = 0; i < RETRO_PICO_MAP_LEN; i++)
1184 if (input_state_cb(pad, RETRO_DEVICE_JOYPAD, 0, i))
1185 PicoPad[pad] |= retro_pico_map[i];
1186
1187 PicoFrame();
1188
1189 video_cb((short *)vout_buf + vout_offset,
1190 vout_width, vout_height, vout_width * 2);
1191}
1192
1193static void check_system_specs(void)
1194{
1195 /* TODO - set different performance level for 32X - 6 for ARM dynarec, higher for interpreter core */
1196 unsigned level = 5;
1197 environ_cb(RETRO_ENVIRONMENT_SET_PERFORMANCE_LEVEL, &level);
1198}
1199
1200void retro_init(void)
1201{
1202 struct retro_log_callback log;
1203 int level;
1204
1205 level = 0;
1206 environ_cb(RETRO_ENVIRONMENT_SET_PERFORMANCE_LEVEL, &level);
1207
1208 if (environ_cb(RETRO_ENVIRONMENT_GET_LOG_INTERFACE, &log))
1209 log_cb = log.log;
1210 else
1211 log_cb = NULL;
1212
1213 environ_cb(RETRO_ENVIRONMENT_SET_DISK_CONTROL_INTERFACE, &disk_control);
1214
1215#ifdef _3DS
1216 ctr_svchack_successful = ctr_svchack_init();
1217#endif
1218
1219 PicoOpt = POPT_EN_STEREO|POPT_EN_FM|POPT_EN_PSG|POPT_EN_Z80
1220 | POPT_EN_MCD_PCM|POPT_EN_MCD_CDDA|POPT_EN_MCD_GFX
1221 | POPT_EN_32X|POPT_EN_PWM
1222 | POPT_ACC_SPRITES|POPT_DIS_32C_BORDER;
1223#ifdef __arm__
1224#ifdef _3DS
1225 if (ctr_svchack_successful)
1226#endif
1227 PicoOpt |= POPT_EN_DRC;
1228#endif
1229 PsndRate = 44100;
1230 PicoAutoRgnOrder = 0x184; // US, EU, JP
1231
1232 vout_width = 320;
1233 vout_height = 240;
1234#ifdef _3DS
1235 vout_buf = linearMemAlign(VOUT_MAX_WIDTH * VOUT_MAX_HEIGHT * 2, 0x80);
1236#else
1237 vout_buf = malloc(VOUT_MAX_WIDTH * VOUT_MAX_HEIGHT * 2);
1238#endif
1239
1240 PicoInit();
1241 PicoDrawSetOutFormat(PDF_RGB555, 0);
1242 PicoDrawSetOutBuf(vout_buf, vout_width * 2);
1243
1244 //PicoMessage = plat_status_msg_busy_next;
1245 PicoMCDopenTray = disk_tray_open;
1246 PicoMCDcloseTray = disk_tray_close;
1247
1248 update_variables();
1249}
1250
1251void retro_deinit(void)
1252{
1253#ifdef _3DS
1254 linearFree(vout_buf);
1255#else
1256 free(vout_buf);
1257#endif
1258 vout_buf = NULL;
1259 PicoExit();
1260}