platform ps2, handle audio similar to psp
[picodrive.git] / platform / libretro / libretro.c
... / ...
CommitLineData
1/*
2 * libretro core glue for PicoDrive
3 * (C) notaz, 2013
4 * (C) aliaspider, 2016
5 * (C) Daniel De Matteis, 2013
6 * (C) irixxxx, 2020-2024
7 *
8 * This work is licensed under the terms of MAME license.
9 * See COPYING file in the top-level directory.
10 */
11
12#define _GNU_SOURCE 1 // mremap
13#include <stdio.h>
14#include <stdlib.h>
15#include <stdarg.h>
16#include <string.h>
17#include <errno.h>
18#ifdef __MACH__
19#include <libkern/OSCacheControl.h>
20#endif
21
22#include "libretro-common/include/formats/image.h" // really, for IMAGE_PROCESS_NEXT?!?
23#include "libretro-common/include/formats/rpng.h"
24#include "libretro-common/include/file/file_path.h"
25
26#include "libretro-common/include/memmap.h"
27/* Ouf, libretro-common defines replacement functions, but not the flags :-| */
28#ifndef PROT_READ
29#define PROT_READ 0x1
30#define PROT_WRITE 0x2
31#define PROT_READWRITE 0x3
32#define PROT_EXEC 0x4
33#define MAP_FAILED ((void *) -1)
34#define MAP_ANONYMOUS 0x1
35#define MAP_PRIVATE 0x2
36#endif
37
38#if defined(RENDER_GSKIT_PS2)
39#include <malloc.h>
40#include "libretro-common/include/libretro_gskit_ps2.h"
41#include "ps2/asm.h"
42#else
43#include <platform/common/upscale.h>
44#endif
45#include <platform/common/emu.h>
46#include <platform/libpicofe/plat.h> // need this for PXMAKE in readpng :-/
47
48#ifdef _3DS
49#include "3ds/3ds_utils.h"
50#define MEMOP_MAP 4
51#define MEMOP_UNMAP 5
52#define MEMOP_PROT 6
53
54int svcDuplicateHandle(unsigned int* out, unsigned int original);
55int svcCloseHandle(unsigned int handle);
56int svcControlProcessMemory(unsigned int process, void* addr0, void* addr1,
57 unsigned int size, unsigned int type, unsigned int perm);
58void* linearMemAlign(size_t size, size_t alignment);
59void linearFree(void* mem);
60
61static int ctr_svchack_successful = 0;
62
63#elif defined(VITA)
64#define TARGET_SIZE_2 24 // 2^24 = 16 megabytes
65
66#include <psp2/kernel/sysmem.h>
67static int sceBlock;
68int getVMBlock();
69int _newlib_vm_size_user = 1 << TARGET_SIZE_2;
70
71#elif defined(__PS3__)
72#include <sys/process.h>
73#include <ps3mapi_ps3_lib.h>
74
75static uint64_t page_table[2] = {0, 0};
76#endif
77
78#include "libretro_core_options.h"
79
80#include <pico/pico_int.h>
81#include <pico/state.h>
82#include <pico/patch.h>
83#include <pico/sound/mix.h>
84#include "../common/input_pico.h"
85#include "../common/version.h"
86#include <libretro.h>
87#include <compat/strcasestr.h>
88
89static retro_log_printf_t log_cb;
90static retro_video_refresh_t video_cb;
91static retro_input_poll_t input_poll_cb;
92static retro_input_state_t input_state_cb;
93static retro_environment_t environ_cb;
94static retro_audio_sample_batch_t audio_batch_cb;
95
96#define VOUT_MAX_WIDTH 320
97#define VOUT_MAX_HEIGHT 240
98
99#define SND_RATE_DEFAULT 44100
100#define SND_RATE_MAX 53267
101
102#ifndef PATH_MAX
103#define PATH_MAX 4096
104#endif
105
106static const float VOUT_PAR = 0.0;
107static const float VOUT_4_3 = (4.0f / 3.0f);
108static const float VOUT_CRT = (1.29911f);
109
110/* Required to allow on the fly changes to 'renderer' */
111static int vm_current_start_line = -1;
112static int vm_current_line_count = -1;
113static int vm_current_start_col = -1;
114static int vm_current_col_count = -1;
115
116static int vout_16bit = 1;
117static int vout_format = PDF_RGB555;
118static void *vout_buf, *vout_ghosting_buf;
119static int vout_width, vout_height, vout_offset;
120static float vout_aspect = 0.0;
121static int vout_ghosting = 0;
122
123static bool libretro_update_av_info = false;
124static bool libretro_update_geometry = false;
125
126#if defined(RENDER_GSKIT_PS2)
127#define VOUT_8BIT_WIDTH 328
128#define VOUT_8BIT_HEIGHT 256
129RETRO_HW_RENDER_INTEFACE_GSKIT_PS2 *ps2 = NULL;
130static void *retro_palette;
131static struct retro_hw_ps2_insets padding;
132#endif
133
134static short ALIGNED(4) sndBuffer[2*SND_RATE_MAX/50];
135
136static void snd_write(int len);
137
138char **g_argv;
139
140#ifdef _WIN32
141#define SLASH '\\'
142#else
143#define SLASH '/'
144#endif
145
146/* Frameskipping Support */
147
148static unsigned frameskip_type = 0;
149static unsigned frameskip_threshold = 0;
150static uint16_t frameskip_counter = 0;
151
152static bool retro_audio_buff_active = false;
153static unsigned retro_audio_buff_occupancy = 0;
154static bool retro_audio_buff_underrun = false;
155/* Maximum number of consecutive frames that
156 * can be skipped */
157#define FRAMESKIP_MAX 60
158
159static unsigned audio_latency = 0;
160static bool update_audio_latency = false;
161static uint16_t pico_events;
162// Sega Pico stuff
163int pico_inp_mode;
164int pico_pen_x = 320/2, pico_pen_y = 240/2;
165static int pico_page;
166static int pico_w, pico_h;
167static char pico_overlay_path[PATH_MAX];
168static unsigned short *pico_overlay;
169
170
171static void retro_audio_buff_status_cb(
172 bool active, unsigned occupancy, bool underrun_likely)
173{
174 retro_audio_buff_active = active;
175 retro_audio_buff_occupancy = occupancy;
176 retro_audio_buff_underrun = underrun_likely;
177}
178
179static void init_frameskip(void)
180{
181 if (frameskip_type > 0)
182 {
183 struct retro_audio_buffer_status_callback buf_status_cb;
184
185 buf_status_cb.callback = retro_audio_buff_status_cb;
186 if (!environ_cb(RETRO_ENVIRONMENT_SET_AUDIO_BUFFER_STATUS_CALLBACK,
187 &buf_status_cb))
188 {
189 if (log_cb)
190 log_cb(RETRO_LOG_WARN, "Frameskip disabled - frontend does not support audio buffer status monitoring.\n");
191
192 retro_audio_buff_active = false;
193 retro_audio_buff_occupancy = 0;
194 retro_audio_buff_underrun = false;
195 audio_latency = 0;
196 }
197 else
198 {
199 /* Frameskip is enabled - increase frontend
200 * audio latency to minimise potential
201 * buffer underruns */
202 float frame_time_msec = 1000.0f / (Pico.m.pal ? 50.0f : 60.0f);
203
204 /* Set latency to 6x current frame time... */
205 audio_latency = (unsigned)((6.0f * frame_time_msec) + 0.5f);
206
207 /* ...then round up to nearest multiple of 32 */
208 audio_latency = (audio_latency + 0x1F) & ~0x1F;
209 }
210 }
211 else
212 {
213 environ_cb(RETRO_ENVIRONMENT_SET_AUDIO_BUFFER_STATUS_CALLBACK, NULL);
214 audio_latency = 0;
215 }
216
217 update_audio_latency = true;
218}
219
220/* functions called by the core */
221
222void cache_flush_d_inval_i(void *start, void *end)
223{
224#ifdef __arm__
225 size_t len = (char *)end - (char *)start;
226#if defined(__BLACKBERRY_QNX__)
227 msync(start, len, MS_SYNC | MS_CACHE_ONLY | MS_INVALIDATE_ICACHE);
228#elif defined(__MACH__)
229 sys_dcache_flush(start, len);
230 sys_icache_invalidate(start, len);
231#elif defined(_3DS)
232 (void)len;
233 ctr_flush_invalidate_cache();
234#elif defined(VITA)
235 sceKernelSyncVMDomain(sceBlock, start, len);
236#else
237 (void)len;
238 __clear_cache(start, end);
239#endif
240#endif
241}
242
243#ifdef RENDER_GSKIT_PS2
244/* In PS2 toolchain these aren't yet defined */
245void _flush_cache(void *b, void *e)
246{
247#if 0 /* which of these is overall faster for lots of small cache updates? */
248 SyncDCache(b, e);
249#else
250 FlushCache(0); /* WRITEBACK_DCACHE */
251#endif
252 FlushCache(2); /* INVALIDATE_ICACHE */
253}
254
255int __builtin_parity(unsigned v)
256{
257 /* credits to bit twiddling hacks, https://graphics.stanford.edu/~seander/bithacks.html */
258 v ^= v >> 16;
259 v ^= v >> 8;
260 v ^= v >> 4;
261 return (0x6996 >> (v&0xf)) & 1;
262}
263#elif defined(PSP)
264int _flush_cache(char *addr, const int size, const int op)
265{
266 //sceKernelDcacheWritebackAll();
267 sceKernelDcacheWritebackRange(addr, size);
268 sceKernelIcacheInvalidateRange(addr, size);
269 return 0;
270}
271#endif
272
273#ifdef __MACH__
274/* calls to this may be generated by the compiler, but it's missing in libc? */
275void __clear_cache(void *start, void *end)
276{
277 size_t len = (char *)end - (char *)start;
278 sys_dcache_flush(start, len);
279 sys_icache_invalidate(start, len);
280}
281#endif
282
283#ifndef MAP_ANONYMOUS
284#define MAP_ANONYMOUS MAP_ANON
285#endif
286
287#ifdef _3DS
288typedef struct
289{
290 unsigned int requested_map;
291 void* buffer;
292}pico_mmap_t;
293
294pico_mmap_t pico_mmaps[] = {
295 {0x02000000, 0},
296 {0x06000000, 0},
297 {NULL, 0}
298};
299
300void *plat_mmap(unsigned long addr, size_t size, int need_exec, int is_fixed)
301{
302 (void)is_fixed;
303
304 if (ctr_svchack_successful)
305 {
306 pico_mmap_t* pico_mmap;
307
308 for (pico_mmap = pico_mmaps; pico_mmap->requested_map; pico_mmap++)
309 {
310 if ((pico_mmap->requested_map == addr))
311 {
312 unsigned int ptr_aligned, tmp;
313 unsigned int currentHandle;
314 unsigned int perm = 0b011;
315
316 if (need_exec)
317 perm = 0b111;
318
319 size = (size + 0xFFF) & ~0xFFF;
320 pico_mmap->buffer = malloc(size + 0x1000);
321 ptr_aligned = (((unsigned int)pico_mmap->buffer) + 0xFFF) & ~0xFFF;
322
323 svcDuplicateHandle(&currentHandle, 0xFFFF8001);
324
325 if(svcControlProcessMemory(currentHandle, pico_mmap->requested_map, ptr_aligned, size, MEMOP_MAP, perm) < 0)
326 {
327 if (log_cb)
328 log_cb(RETRO_LOG_ERROR, "could not map memory @0x%08X\n", pico_mmap->requested_map);
329 exit(1);
330 }
331
332 svcCloseHandle(currentHandle);
333 return (void*)pico_mmap->requested_map;
334 }
335 }
336 }
337
338 return malloc(size);
339}
340
341void *plat_mremap(void *ptr, size_t oldsize, size_t newsize)
342{
343 if (ctr_svchack_successful)
344 {
345 pico_mmap_t* pico_mmap;
346
347 for (pico_mmap = pico_mmaps; pico_mmap->requested_map; pico_mmap++)
348 {
349 if ((pico_mmap->requested_map == (unsigned int)ptr))
350 {
351 unsigned int ptr_aligned;
352 unsigned int currentHandle;
353 void* tmp;
354
355 oldsize = (oldsize + 0xFFF) & ~0xFFF;
356 newsize = (newsize + 0xFFF) & ~0xFFF;
357 ptr_aligned = (((unsigned int)pico_mmap->buffer) + 0xFFF) & ~0xFFF;
358
359 svcDuplicateHandle(&currentHandle, 0xFFFF8001);
360
361 svcControlProcessMemory(currentHandle, pico_mmap->requested_map, ptr_aligned, oldsize, MEMOP_UNMAP, 0b011);
362
363 tmp = realloc(pico_mmap->buffer, newsize + 0x1000);
364 if(!tmp)
365 return NULL;
366
367 pico_mmap->buffer = tmp;
368 ptr_aligned = (((unsigned int)pico_mmap->buffer) + 0xFFF) & ~0xFFF;
369
370 svcControlProcessMemory(currentHandle, pico_mmap->requested_map, ptr_aligned, newsize, MEMOP_MAP, 0x3);
371
372 svcCloseHandle(currentHandle);
373
374 return ptr;
375 }
376 }
377 }
378
379 return realloc(ptr, newsize);
380
381}
382void plat_munmap(void *ptr, size_t size)
383{
384 if (ctr_svchack_successful)
385 {
386 pico_mmap_t* pico_mmap;
387
388 for (pico_mmap = pico_mmaps; pico_mmap->requested_map; pico_mmap++)
389 {
390 if ((pico_mmap->requested_map == (unsigned int)ptr))
391 {
392 unsigned int ptr_aligned;
393 unsigned int currentHandle;
394
395 size = (size + 0xFFF) & ~0xFFF;
396 ptr_aligned = (((unsigned int)pico_mmap->buffer) + 0xFFF) & ~0xFFF;
397
398 svcDuplicateHandle(&currentHandle, 0xFFFF8001);
399
400 svcControlProcessMemory(currentHandle, (void*)pico_mmap->requested_map, (void*)ptr_aligned, size, MEMOP_UNMAP, 0b011);
401
402 svcCloseHandle(currentHandle);
403
404 free(pico_mmap->buffer);
405 pico_mmap->buffer = NULL;
406 return;
407 }
408 }
409 }
410
411 free(ptr);
412}
413
414#else
415void *plat_mmap(unsigned long addr, size_t size, int need_exec, int is_fixed)
416{
417 int flags = MAP_PRIVATE | MAP_ANONYMOUS;
418 void *req, *ret;
419
420 req = (void *)(uintptr_t)addr;
421 ret = mmap(req, size, PROT_READ | PROT_WRITE, flags, -1, 0);
422 if (ret == MAP_FAILED) {
423 if (log_cb)
424 log_cb(RETRO_LOG_ERROR, "mmap(%08lx, %zd) failed: %d\n", addr, size, errno);
425 return NULL;
426 }
427
428 if (addr != 0 && ret != (void *)(uintptr_t)addr) {
429 if (log_cb)
430 log_cb(RETRO_LOG_WARN, "warning: wanted to map @%08lx, got %p\n",
431 addr, ret);
432
433 if (is_fixed) {
434 munmap(ret, size);
435 return NULL;
436 }
437 }
438
439 return ret;
440}
441
442void *plat_mremap(void *ptr, size_t oldsize, size_t newsize)
443{
444#if defined(__linux__) && !defined(__SWITCH__)
445 void *ret = mremap(ptr, oldsize, newsize, 0);
446 if (ret == MAP_FAILED)
447 return NULL;
448
449 return ret;
450#else
451 void *tmp, *ret;
452 size_t preserve_size;
453
454 preserve_size = oldsize;
455 if (preserve_size > newsize)
456 preserve_size = newsize;
457 tmp = malloc(preserve_size);
458 if (tmp == NULL)
459 return NULL;
460 memcpy(tmp, ptr, preserve_size);
461
462 munmap(ptr, oldsize);
463 ret = mmap(ptr, newsize, PROT_READ | PROT_WRITE,
464 MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
465 if (ret == MAP_FAILED) {
466 free(tmp);
467 return NULL;
468 }
469 memcpy(ret, tmp, preserve_size);
470 free(tmp);
471 return ret;
472#endif
473}
474
475void plat_munmap(void *ptr, size_t size)
476{
477 if (ptr != NULL)
478 munmap(ptr, size);
479}
480#endif
481
482// if NULL is returned, static buffer is used
483void *plat_mem_get_for_drc(size_t size)
484{
485 void *mem = NULL;
486#if defined VITA
487 sceKernelGetMemBlockBase(sceBlock, &mem);
488#elif defined HW_WUP
489 // For WiiU, a slice of RWX memory left from the exploit is used, see:
490 // https://github.com/embercold/pcsx_rearmed/commit/af0453223
491 mem = (void *)(0x01000000 - size);
492#elif defined __PS3__
493 ps3mapi_process_page_allocate(sysProcessGetPid(), size, PAGE_SIZE_AUTO, 0x2F, 1, page_table);
494 mem = (void *)page_table[0];
495#endif
496 return mem;
497}
498
499int plat_mem_set_exec(void *ptr, size_t size)
500{
501 int ret = -1;
502#ifdef _WIN32
503 DWORD oldProtect = 0;
504 ret = VirtualProtect(ptr, size, PAGE_EXECUTE_READWRITE, &oldProtect);
505 if (ret == 0 && log_cb)
506 log_cb(RETRO_LOG_ERROR, "VirtualProtect(%p, %d) failed: %d\n", ptr, (int)size,
507 GetLastError());
508#elif defined(_3DS)
509 if (ctr_svchack_successful)
510 {
511 unsigned int currentHandle;
512 svcDuplicateHandle(&currentHandle, 0xFFFF8001);
513 ret = svcControlProcessMemory(currentHandle, ptr, 0x0,
514 size, MEMOP_PROT, 0b111);
515 svcCloseHandle(currentHandle);
516 ctr_flush_invalidate_cache();
517
518 }
519 else
520 {
521 if (log_cb)
522 log_cb(RETRO_LOG_ERROR, "plat_mem_set_exec called with no svcControlProcessMemory access\n");
523 exit(1);
524 }
525
526#elif defined(VITA)
527 ret = sceKernelOpenVMDomain();
528#else
529 ret = mprotect(ptr, size, PROT_READ | PROT_WRITE | PROT_EXEC);
530 if (ret != 0 && log_cb)
531 log_cb(RETRO_LOG_ERROR, "mprotect(%p, %zd) failed: %d\n", ptr, size, errno);
532#endif
533 return ret;
534}
535
536static void apply_renderer()
537{
538 PicoIn.opt &= ~(POPT_ALT_RENDERER|POPT_EN_SOFTSCALE);
539 PicoIn.opt |= POPT_DIS_32C_BORDER;
540 if (vout_format == PDF_NONE)
541 PicoIn.opt |= POPT_ALT_RENDERER;
542 PicoDrawSetOutFormat(vout_format, 0);
543 if (!vout_16bit && vout_format == PDF_8BIT)
544 PicoDrawSetOutBuf(Pico.est.Draw2FB, 328);
545}
546
547void emu_video_mode_change(int start_line, int line_count, int start_col, int col_count)
548{
549 vm_current_start_line = start_line;
550 vm_current_line_count = line_count;
551 vm_current_start_col = start_col;
552 vm_current_col_count = col_count;
553
554 // 8bit renderers create a 328x256 CLUT image, 16bit creates 320x240 RGB
555#if defined(RENDER_GSKIT_PS2)
556 // calculate the borders of the real image inside the picodrive image
557 vout_width = (vout_16bit ? VOUT_MAX_WIDTH : VOUT_8BIT_WIDTH);
558 vout_height = (vout_16bit ? VOUT_MAX_HEIGHT : VOUT_8BIT_HEIGHT);
559 vout_offset = (vout_16bit ? 0 : col_count == 248 ? 16 : 8); // 8bit has overlap area on the left
560 padding = (struct retro_hw_ps2_insets){start_line, vout_offset, vout_height - line_count - start_line, vout_width - col_count - vout_offset};
561
562 int pxsz = (vout_16bit ? 2 : 1); // pixel size: RGB = 16 bits, CLUT = 8 bits
563 memset(vout_buf, 0, pxsz * vout_width * vout_height);
564 memset(retro_palette, 0, gsKit_texture_size_ee(16, 16, GS_PSM_CT16));
565 PicoDrawSetOutBuf(vout_buf, pxsz * vout_width);
566 if (ps2) {
567 // prepare image as texture for rendering
568 ps2->coreTexture->Width = vout_width;
569 ps2->coreTexture->Height = vout_height;
570 ps2->coreTexture->PSM = (vout_16bit ? GS_PSM_CT16 : GS_PSM_T8);
571 ps2->padding = padding;
572 }
573#else
574 vout_width = col_count;
575 memset(vout_buf, 0, VOUT_MAX_WIDTH * VOUT_MAX_HEIGHT * 2);
576 if (vout_16bit)
577 PicoDrawSetOutBuf(vout_buf, vout_width * 2);
578
579 vout_height = line_count;
580 /* Note: We multiply by 2 here to account for pitch */
581 vout_offset = vout_width * start_line * 2;
582
583 /* Redundant sanity check... */
584 vout_height = (vout_height > VOUT_MAX_HEIGHT) ?
585 VOUT_MAX_HEIGHT : vout_height;
586 vout_offset = (vout_offset > vout_width * (VOUT_MAX_HEIGHT - 1) * 2) ?
587 vout_width * (VOUT_MAX_HEIGHT - 1) * 2 : vout_offset;
588
589 /* LCD ghosting */
590 if (vout_ghosting && vout_height == 144) {
591 vout_ghosting_buf = realloc(vout_ghosting_buf, VOUT_MAX_HEIGHT*vout_width*2);
592 memset(vout_ghosting_buf, 0, vout_width*vout_height*2);
593 }
594#endif
595 Pico.m.dirtyPal = 1;
596
597 /* Notify frontend of geometry update */
598 libretro_update_geometry = true;
599}
600
601void emu_32x_startup(void)
602{
603 PicoIn.filter = EOPT_FILTER_SMOOTHER; // for H32 upscaling
604 PicoDrawSetOutFormat(vout_format, 0);
605 vout_16bit = 1;
606
607 if (vout_buf &&
608 (vm_current_start_line != -1) && (vm_current_line_count != -1) &&
609 (vm_current_start_col != -1) && (vm_current_col_count != -1))
610 emu_video_mode_change(
611 vm_current_start_line, vm_current_line_count,
612 vm_current_start_col, vm_current_col_count);
613}
614
615void lprintf(const char *fmt, ...)
616{
617 char buffer[256];
618 va_list ap;
619 va_start(ap, fmt);
620 vsprintf(buffer, fmt, ap);
621 /* TODO - add 'level' param for warning/error messages? */
622 if (log_cb)
623 log_cb(RETRO_LOG_INFO, "%s", buffer);
624 va_end(ap);
625}
626
627/* libretro */
628bool libretro_supports_bitmasks = false;
629
630void retro_set_environment(retro_environment_t cb)
631{
632 bool option_categories_supported;
633#ifdef USE_LIBRETRO_VFS
634 struct retro_vfs_interface_info vfs_iface_info;
635#endif
636
637 static const struct retro_system_content_info_override content_overrides[] = {
638 {
639 "bin|gen|smd|md|32x|sms|gg|sg|sc|68k|sgd|pco", /* extensions */
640#if defined(LOW_MEMORY)
641 true, /* need_fullpath */
642#else
643 false, /* need_fullpath */
644#endif
645 false /* persistent_data */
646 },
647 { NULL, false, false }
648 };
649
650 environ_cb = cb;
651
652 libretro_set_core_options(environ_cb,
653 &option_categories_supported);
654 environ_cb(RETRO_ENVIRONMENT_SET_CONTENT_INFO_OVERRIDE,
655 (void*)content_overrides);
656
657#ifdef USE_LIBRETRO_VFS
658 vfs_iface_info.required_interface_version = 1;
659 vfs_iface_info.iface = NULL;
660 if (environ_cb(RETRO_ENVIRONMENT_GET_VFS_INTERFACE, &vfs_iface_info))
661 filestream_vfs_init(&vfs_iface_info);
662#endif
663}
664
665void retro_set_video_refresh(retro_video_refresh_t cb) { video_cb = cb; }
666void retro_set_audio_sample(retro_audio_sample_t cb) { (void)cb; }
667void retro_set_audio_sample_batch(retro_audio_sample_batch_t cb) { audio_batch_cb = cb; }
668void retro_set_input_poll(retro_input_poll_t cb) { input_poll_cb = cb; }
669void retro_set_input_state(retro_input_state_t cb) { input_state_cb = cb; }
670
671unsigned retro_api_version(void)
672{
673 return RETRO_API_VERSION;
674}
675
676void retro_set_controller_port_device(unsigned port, unsigned device)
677{
678}
679
680void retro_get_system_info(struct retro_system_info *info)
681{
682 memset(info, 0, sizeof(*info));
683 info->library_name = "PicoDrive";
684 info->library_version = VERSION;
685 info->valid_extensions = "bin|gen|smd|md|32x|cue|iso|chd|sms|gg|sg|sc|m3u|68k|sgd|pco";
686 info->need_fullpath = true;
687}
688
689void retro_get_system_av_info(struct retro_system_av_info *info)
690{
691 float tv_height = (vout_height > 144 ? Pico.m.pal ? 240 : 224 : 144);
692 float common_width;
693
694 memset(info, 0, sizeof(*info));
695 info->timing.fps = Pico.m.pal ? 50 : 60;
696 info->timing.sample_rate = PicoIn.sndRate;
697 info->geometry.base_width = vout_width;
698 info->geometry.base_height = vout_height;
699 info->geometry.max_width = vout_width;
700 info->geometry.max_height = vout_height;
701
702 common_width = vout_width;
703 if (vout_aspect != 0)
704 common_width = vout_aspect * tv_height;
705
706 info->geometry.aspect_ratio = common_width / vout_height;
707}
708
709/* savestates */
710struct savestate_state {
711 const char *load_buf;
712 char *save_buf;
713 size_t size;
714 size_t pos;
715};
716
717size_t state_read(void *p, size_t size, size_t nmemb, void *file)
718{
719 struct savestate_state *state = file;
720 size_t bsize = size * nmemb;
721
722 if (state->pos + bsize > state->size) {
723 if (log_cb)
724 log_cb(RETRO_LOG_ERROR, "savestate error: %u/%u\n",
725 state->pos + bsize, state->size);
726 bsize = state->size - state->pos;
727 if ((int)bsize <= 0)
728 return 0;
729 }
730
731 memcpy(p, state->load_buf + state->pos, bsize);
732 state->pos += bsize;
733 return bsize;
734}
735
736size_t state_write(void *p, size_t size, size_t nmemb, void *file)
737{
738 struct savestate_state *state = file;
739 size_t bsize = size * nmemb;
740
741 if (state->pos + bsize > state->size) {
742 if (log_cb)
743 log_cb(RETRO_LOG_ERROR, "savestate error: %u/%u\n",
744 state->pos + bsize, state->size);
745 bsize = state->size - state->pos;
746 if ((int)bsize <= 0)
747 return 0;
748 }
749
750 memcpy(state->save_buf + state->pos, p, bsize);
751 state->pos += bsize;
752 return bsize;
753}
754
755size_t state_skip(void *p, size_t size, size_t nmemb, void *file)
756{
757 struct savestate_state *state = file;
758 size_t bsize = size * nmemb;
759
760 state->pos += bsize;
761 return bsize;
762}
763
764size_t state_eof(void *file)
765{
766 struct savestate_state *state = file;
767
768 return state->pos >= state->size;
769}
770
771int state_fseek(void *file, long offset, int whence)
772{
773 struct savestate_state *state = file;
774
775 switch (whence) {
776 case SEEK_SET:
777 state->pos = offset;
778 break;
779 case SEEK_CUR:
780 state->pos += offset;
781 break;
782 case SEEK_END:
783 state->pos = state->size + offset;
784 break;
785 }
786 return (int)state->pos;
787}
788
789/* savestate sizes vary wildly depending if cd/32x or
790 * carthw is active, so run the whole thing to get size */
791size_t retro_serialize_size(void)
792{
793 struct savestate_state state = { 0, };
794 unsigned AHW = PicoIn.AHW;
795 int ret;
796
797 /* we need the max possible size here, so include 32X for MD and MCD */
798 if (!(AHW & (PAHW_SMS|PAHW_PICO|PAHW_SVP)))
799 PicoIn.AHW |= PAHW_32X;
800 ret = PicoStateFP(&state, 1, NULL, state_skip, NULL, state_fseek);
801 PicoIn.AHW = AHW;
802 if (ret != 0)
803 return 0;
804
805 return state.pos;
806}
807
808bool retro_serialize(void *data, size_t size)
809{
810 struct savestate_state state = { 0, };
811 int ret;
812
813 state.save_buf = data;
814 state.size = size;
815 state.pos = 0;
816
817 ret = PicoStateFP(&state, 1, NULL, state_write,
818 NULL, state_fseek);
819 return ret == 0;
820}
821
822bool retro_unserialize(const void *data, size_t size)
823{
824 struct savestate_state state = { 0, };
825 int ret;
826
827 state.load_buf = data;
828 state.size = size;
829 state.pos = 0;
830
831 ret = PicoStateFP(&state, 0, state_read, NULL,
832 state_eof, state_fseek);
833 return ret == 0;
834}
835
836typedef struct patch
837{
838 unsigned int addr;
839 unsigned short data;
840 unsigned char comp;
841} patch;
842
843extern void decode(char *buff, patch *dest);
844extern uint32_t m68k_read16(uint32_t a);
845extern void m68k_write16(uint32_t a, uint16_t d);
846
847void retro_cheat_reset(void)
848{
849 int i=0;
850 unsigned int addr;
851
852 for (i = 0; i < PicoPatchCount; i++)
853 {
854 addr = PicoPatches[i].addr;
855 if (addr < Pico.romsize) {
856 if (PicoPatches[i].active)
857 *(unsigned short *)(Pico.rom + addr) = PicoPatches[i].data_old;
858 } else {
859 if (PicoPatches[i].active)
860 m68k_write16(PicoPatches[i].addr,PicoPatches[i].data_old);
861 }
862 }
863
864 PicoPatchUnload();
865}
866
867void retro_cheat_set(unsigned index, bool enabled, const char *code)
868{
869 patch pt;
870 int array_len = PicoPatchCount;
871 char codeCopy[256];
872 char *buff;
873
874 if (*code == '\0')
875 return;
876 strcpy(codeCopy, code);
877 buff = strtok(codeCopy,"+");
878
879 while (buff != NULL)
880 {
881 decode(buff, &pt);
882 if (pt.addr == (uint32_t) -1 || pt.data == (uint16_t) -1)
883 {
884 log_cb(RETRO_LOG_ERROR,"CHEATS: Invalid code: %s\n",buff);
885 return;
886 }
887
888 /* code was good, add it */
889 if (array_len < PicoPatchCount + 1)
890 {
891 void *ptr;
892 array_len *= 2;
893 array_len++;
894 ptr = realloc(PicoPatches, array_len * sizeof(PicoPatches[0]));
895 if (ptr == NULL) {
896 log_cb(RETRO_LOG_ERROR,"CHEATS: Failed to allocate memory for: %s\n",buff);
897 return;
898 }
899 PicoPatches = ptr;
900 }
901 strcpy(PicoPatches[PicoPatchCount].code, buff);
902
903 PicoPatches[PicoPatchCount].active = enabled;
904 PicoPatches[PicoPatchCount].addr = pt.addr;
905 PicoPatches[PicoPatchCount].data = pt.data;
906 PicoPatches[PicoPatchCount].comp = pt.comp;
907 if (PicoPatches[PicoPatchCount].addr < Pico.romsize)
908 PicoPatches[PicoPatchCount].data_old = *(uint16_t *)(Pico.rom + PicoPatches[PicoPatchCount].addr);
909 else
910 PicoPatches[PicoPatchCount].data_old = (uint16_t) m68k_read16(PicoPatches[PicoPatchCount].addr);
911 PicoPatchCount++;
912
913 buff = strtok(NULL,"+");
914 }
915}
916
917/* multidisk support */
918static unsigned int disk_initial_index;
919static bool disk_ejected;
920static unsigned int disk_current_index;
921static unsigned int disk_count;
922static char disk_initial_path[PATH_MAX];
923static struct disks_state {
924 char *fname;
925 char *flabel;
926} disks[8];
927
928static void get_disk_label(char *disk_label, const char *disk_path, size_t len)
929{
930 const char *base = NULL;
931
932 if (!disk_path || (*disk_path == '\0'))
933 return;
934
935 base = strrchr(disk_path, SLASH);
936 if (!base)
937 base = disk_path;
938
939 if (*base == SLASH)
940 base++;
941
942 strncpy(disk_label, base, len - 1);
943 disk_label[len - 1] = '\0';
944
945 char *ext = strrchr(disk_label, '.');
946 if (ext)
947 *ext = '\0';
948}
949
950static void disk_init(void)
951{
952 size_t i;
953
954 disk_ejected = false;
955 disk_current_index = 0;
956 disk_count = 0;
957
958 for (i = 0; i < sizeof(disks) / sizeof(disks[0]); i++)
959 {
960 if (disks[i].fname != NULL)
961 {
962 free(disks[i].fname);
963 disks[i].fname = NULL;
964 }
965 if (disks[i].flabel != NULL)
966 {
967 free(disks[i].flabel);
968 disks[i].flabel = NULL;
969 }
970 }
971}
972
973static bool disk_set_eject_state(bool ejected)
974{
975 // TODO?
976 disk_ejected = ejected;
977 return true;
978}
979
980static bool disk_get_eject_state(void)
981{
982 return disk_ejected;
983}
984
985static unsigned int disk_get_image_index(void)
986{
987 return disk_current_index;
988}
989
990static bool disk_set_image_index(unsigned int index)
991{
992 enum cd_track_type cd_type;
993 int ret;
994
995 if (index >= sizeof(disks) / sizeof(disks[0]))
996 return false;
997
998 if (disks[index].fname == NULL) {
999 if (log_cb)
1000 log_cb(RETRO_LOG_ERROR, "missing disk #%u\n", index);
1001
1002 // RetroArch specifies "no disk" with index == count,
1003 // so don't fail here..
1004 disk_current_index = index;
1005 return true;
1006 }
1007
1008 if (log_cb)
1009 log_cb(RETRO_LOG_INFO, "switching to disk %u: \"%s\"\n", index,
1010 disks[index].fname);
1011
1012 ret = -1;
1013 cd_type = PicoCdCheck(disks[index].fname, NULL);
1014 if (cd_type >= 0 && cd_type != CT_UNKNOWN)
1015 ret = cdd_load(disks[index].fname, cd_type);
1016 if (ret != 0) {
1017 if (log_cb)
1018 log_cb(RETRO_LOG_ERROR, "Load failed, invalid CD image?\n");
1019 return 0;
1020 }
1021
1022 disk_current_index = index;
1023 return true;
1024}
1025
1026static unsigned int disk_get_num_images(void)
1027{
1028 return disk_count;
1029}
1030
1031static bool disk_replace_image_index(unsigned index,
1032 const struct retro_game_info *info)
1033{
1034 char *old_fname = NULL;
1035 char *old_flabel = NULL;
1036 bool ret = true;
1037
1038 if (index >= sizeof(disks) / sizeof(disks[0]))
1039 return false;
1040
1041 old_fname = disks[index].fname;
1042 old_flabel = disks[index].flabel;
1043
1044 if (disks[index].fname != NULL)
1045 free(disks[index].fname);
1046 disks[index].fname = NULL;
1047
1048 if (disks[index].flabel != NULL)
1049 free(disks[index].flabel);
1050 disks[index].flabel = NULL;
1051
1052 if (info != NULL) {
1053 char disk_label[PATH_MAX];
1054 disk_label[0] = '\0';
1055
1056 disks[index].fname = strdup(info->path);
1057
1058 get_disk_label(disk_label, info->path, PATH_MAX);
1059 disks[index].flabel = strdup(disk_label);
1060
1061 if (index == disk_current_index)
1062 ret = disk_set_image_index(index);
1063 }
1064
1065 if (old_fname != NULL)
1066 free(old_fname);
1067
1068 if (old_flabel != NULL)
1069 free(old_flabel);
1070
1071 return ret;
1072}
1073
1074static bool disk_add_image_index(void)
1075{
1076 if (disk_count >= sizeof(disks) / sizeof(disks[0]))
1077 return false;
1078
1079 disk_count++;
1080 return true;
1081}
1082
1083static bool disk_set_initial_image(unsigned index, const char *path)
1084{
1085 if (index >= sizeof(disks) / sizeof(disks[0]))
1086 return false;
1087
1088 if (!path || (*path == '\0'))
1089 return false;
1090
1091 disk_initial_index = index;
1092
1093 strncpy(disk_initial_path, path, sizeof(disk_initial_path) - 1);
1094 disk_initial_path[sizeof(disk_initial_path) - 1] = '\0';
1095
1096 return true;
1097}
1098
1099static bool disk_get_image_path(unsigned index, char *path, size_t len)
1100{
1101 const char *fname = NULL;
1102
1103 if (len < 1)
1104 return false;
1105
1106 if (index >= sizeof(disks) / sizeof(disks[0]))
1107 return false;
1108
1109 fname = disks[index].fname;
1110
1111 if (!fname || (*fname == '\0'))
1112 return false;
1113
1114 strncpy(path, fname, len - 1);
1115 path[len - 1] = '\0';
1116
1117 return true;
1118}
1119
1120static bool disk_get_image_label(unsigned index, char *label, size_t len)
1121{
1122 const char *flabel = NULL;
1123
1124 if (len < 1)
1125 return false;
1126
1127 if (index >= sizeof(disks) / sizeof(disks[0]))
1128 return false;
1129
1130 flabel = disks[index].flabel;
1131
1132 if (!flabel || (*flabel == '\0'))
1133 return false;
1134
1135 strncpy(label, flabel, len - 1);
1136 label[len - 1] = '\0';
1137
1138 return true;
1139}
1140
1141static struct retro_disk_control_callback disk_control = {
1142 disk_set_eject_state,
1143 disk_get_eject_state,
1144 disk_get_image_index,
1145 disk_set_image_index,
1146 disk_get_num_images,
1147 disk_replace_image_index,
1148 disk_add_image_index,
1149};
1150
1151static struct retro_disk_control_ext_callback disk_control_ext = {
1152 .set_eject_state = disk_set_eject_state,
1153 .get_eject_state = disk_get_eject_state,
1154 .get_image_index = disk_get_image_index,
1155 .set_image_index = disk_set_image_index,
1156 .get_num_images = disk_get_num_images,
1157 .replace_image_index = disk_replace_image_index,
1158 .add_image_index = disk_add_image_index,
1159 .set_initial_image = disk_set_initial_image,
1160 .get_image_path = disk_get_image_path,
1161 .get_image_label = disk_get_image_label,
1162};
1163
1164static void disk_tray_open(void)
1165{
1166 if (log_cb)
1167 log_cb(RETRO_LOG_INFO, "cd tray open\n");
1168 disk_ejected = 1;
1169}
1170
1171static void disk_tray_close(void)
1172{
1173 if (log_cb)
1174 log_cb(RETRO_LOG_INFO, "cd tray close\n");
1175 disk_ejected = 0;
1176}
1177
1178static char base_dir[1024];
1179
1180static void extract_directory(char *buf, const char *path, size_t size)
1181{
1182 char *base;
1183 strncpy(buf, path, size - 1);
1184 buf[size - 1] = '\0';
1185
1186 base = strrchr(buf, '/');
1187 if (!base)
1188 base = strrchr(buf, '\\');
1189
1190 if (base)
1191 *base = '\0';
1192 else
1193 {
1194 buf[0] = '.';
1195 buf[1] = '\0';
1196 }
1197}
1198
1199static void extract_basename(char *buf, const char *path, size_t size)
1200{
1201 const char *base = strrchr(path, '/');
1202 if (!base)
1203 base = strrchr(path, '\\');
1204 if (!base)
1205 base = path;
1206
1207 if (*base == '\\' || *base == '/')
1208 base++;
1209
1210 strncpy(buf, base, size - 1);
1211 buf[size - 1] = '\0';
1212
1213 char *ext = strrchr(buf, '.');
1214 if (ext)
1215 *ext = '\0';
1216}
1217
1218static bool read_m3u(const char *file)
1219{
1220 char line[1024];
1221 char name[PATH_MAX];
1222 FILE *f = fopen(file, "r");
1223 if (!f)
1224 return false;
1225
1226 while (fgets(line, sizeof(line), f) && disk_count < sizeof(disks) / sizeof(disks[0]))
1227 {
1228 if (line[0] == '#')
1229 continue;
1230 char *carrige_return = strchr(line, '\r');
1231 if (carrige_return)
1232 *carrige_return = '\0';
1233 char *newline = strchr(line, '\n');
1234 if (newline)
1235 *newline = '\0';
1236
1237 if (line[0] != '\0')
1238 {
1239 char disk_label[PATH_MAX];
1240 disk_label[0] = '\0';
1241
1242 snprintf(name, sizeof(name), "%s%c%s", base_dir, SLASH, line);
1243 disks[disk_count].fname = strdup(name);
1244
1245 get_disk_label(disk_label, name, PATH_MAX);
1246 disks[disk_count].flabel = strdup(disk_label);
1247
1248 disk_count++;
1249 }
1250 }
1251
1252 fclose(f);
1253 return (disk_count != 0);
1254}
1255
1256/* end of multi disk support */
1257
1258static const char * const biosfiles_us[] = {
1259 "us_scd2_9306", "SegaCDBIOS9303", "us_scd1_9210", "bios_CD_U"
1260};
1261static const char * const biosfiles_eu[] = {
1262 "eu_mcd2_9306", "eu_mcd2_9303", "eu_mcd1_9210", "bios_CD_E"
1263};
1264static const char * const biosfiles_jp[] = {
1265 "jp_mcd2_921222", "jp_mcd1_9112", "jp_mcd1_9111", "bios_CD_J"
1266};
1267
1268static void make_system_path(char *buf, size_t buf_size,
1269 const char *name, const char *ext)
1270{
1271 const char *dir = NULL;
1272
1273 if (environ_cb(RETRO_ENVIRONMENT_GET_SYSTEM_DIRECTORY, &dir) && dir) {
1274 snprintf(buf, buf_size, "%s%c%s%s", dir, SLASH, name, ext);
1275 }
1276 else {
1277 snprintf(buf, buf_size, "%s%s", name, ext);
1278 }
1279}
1280
1281static const char *find_bios(int *region, const char *cd_fname)
1282{
1283 const char * const *files;
1284 static char path[256];
1285 int i, count;
1286 FILE *f = NULL;
1287
1288 // look for MSU.MD rom file. XXX another extension list? ugh...
1289 static const char *md_exts[] = { "gen", "smd", "md", "32x" };
1290 char *ext = strrchr(cd_fname, '.');
1291 int extpos = ext ? ext-cd_fname : strlen(cd_fname);
1292 strcpy(path, cd_fname);
1293 path[extpos++] = '.';
1294 for (i = 0; i < ARRAY_SIZE(md_exts); i++) {
1295 strcpy(path+extpos, md_exts[i]);
1296 f = fopen(path, "rb");
1297 if (f != NULL) {
1298 log_cb(RETRO_LOG_INFO, "found MSU rom: %s\n", path);
1299 fclose(f);
1300 return path;
1301 }
1302 }
1303
1304 if (*region == 4) { // US
1305 files = biosfiles_us;
1306 count = sizeof(biosfiles_us) / sizeof(char *);
1307 } else if (*region == 8) { // EU
1308 files = biosfiles_eu;
1309 count = sizeof(biosfiles_eu) / sizeof(char *);
1310 } else if (*region == 1 || *region == 2) {
1311 files = biosfiles_jp;
1312 count = sizeof(biosfiles_jp) / sizeof(char *);
1313 } else {
1314 return NULL;
1315 }
1316
1317 for (i = 0; i < count; i++)
1318 {
1319 make_system_path(path, sizeof(path), files[i], ".bin");
1320 f = fopen(path, "rb");
1321 if (f != NULL)
1322 break;
1323
1324 make_system_path(path, sizeof(path), files[i], ".zip");
1325 f = fopen(path, "rb");
1326 if (f != NULL)
1327 break;
1328 }
1329
1330 if (f != NULL) {
1331 if (log_cb)
1332 log_cb(RETRO_LOG_INFO, "using bios: %s\n", path);
1333 fclose(f);
1334 return path;
1335 }
1336
1337 return NULL;
1338}
1339
1340static void set_memory_maps(void)
1341{
1342 if (PicoIn.AHW & PAHW_MCD)
1343 {
1344 const size_t SCD_BIT = 1ULL << 31ULL;
1345 const uint64_t mem = RETRO_MEMDESC_SYSTEM_RAM;
1346 struct retro_memory_map mmaps;
1347 struct retro_memory_descriptor descs[] = {
1348 { mem, PicoMem.ram, 0, 0xFF0000, 0, 0, 0x10000, "68KRAM" },
1349 /* virtual address using SCD_BIT so all 512M of prg_ram can be accessed */
1350 /* at address $80020000 */
1351 { mem, Pico_mcd->prg_ram, 0, SCD_BIT | 0x020000, 0, 0, 0x80000, "PRGRAM" },
1352 };
1353
1354 mmaps.descriptors = descs;
1355 mmaps.num_descriptors = sizeof(descs) / sizeof(descs[0]);
1356 environ_cb(RETRO_ENVIRONMENT_SET_MEMORY_MAPS, &mmaps);
1357 }
1358}
1359
1360bool retro_load_game(const struct retro_game_info *info)
1361{
1362 const struct retro_game_info_ext *info_ext = NULL;
1363 const unsigned char *content_data = NULL;
1364 size_t content_size = 0;
1365 char content_path[PATH_MAX];
1366 char content_ext[8];
1367 char carthw_path[PATH_MAX];
1368 enum media_type_e media_type;
1369 size_t i;
1370
1371#if defined(_WIN32)
1372 char slash = '\\';
1373#else
1374 char slash = '/';
1375#endif
1376
1377 content_path[0] = '\0';
1378 content_ext[0] = '\0';
1379 carthw_path[0] = '\0';
1380
1381 unsigned int cd_index = 0;
1382 bool is_m3u = false;
1383
1384 struct retro_input_descriptor desc[] = {
1385 { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_LEFT, "D-Pad Left" },
1386 { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_UP, "D-Pad Up" },
1387 { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_DOWN, "D-Pad Down" },
1388 { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_RIGHT, "D-Pad Right" },
1389 { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_B, "B" },
1390 { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_A, "C" },
1391 { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_X, "Y" },
1392 { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_Y, "A" },
1393 { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_L, "X" },
1394 { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_R, "Z" },
1395 { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_SELECT,"Mode" },
1396 { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_START, "Start" },
1397
1398 { 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_LEFT, "D-Pad Left" },
1399 { 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_UP, "D-Pad Up" },
1400 { 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_DOWN, "D-Pad Down" },
1401 { 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_RIGHT, "D-Pad Right" },
1402 { 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_B, "B" },
1403 { 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_A, "C" },
1404 { 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_X, "Y" },
1405 { 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_Y, "A" },
1406 { 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_L, "X" },
1407 { 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_R, "Z" },
1408 { 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_SELECT,"Mode" },
1409 { 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_START, "Start" },
1410
1411
1412 { 2, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_LEFT, "D-Pad Left" },
1413 { 2, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_UP, "D-Pad Up" },
1414 { 2, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_DOWN, "D-Pad Down" },
1415 { 2, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_RIGHT, "D-Pad Right" },
1416 { 2, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_B, "B" },
1417 { 2, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_A, "C" },
1418 { 2, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_X, "Y" },
1419 { 2, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_Y, "A" },
1420 { 2, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_L, "X" },
1421 { 2, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_R, "Z" },
1422 { 2, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_SELECT,"Mode" },
1423 { 2, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_START, "Start" },
1424
1425
1426 { 3, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_LEFT, "D-Pad Left" },
1427 { 3, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_UP, "D-Pad Up" },
1428 { 3, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_DOWN, "D-Pad Down" },
1429 { 3, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_RIGHT, "D-Pad Right" },
1430 { 3, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_B, "B" },
1431 { 3, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_A, "C" },
1432 { 3, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_X, "Y" },
1433 { 3, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_Y, "A" },
1434 { 3, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_L, "X" },
1435 { 3, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_R, "Z" },
1436 { 3, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_SELECT,"Mode" },
1437 { 3, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_START, "Start" },
1438
1439 { 0 },
1440 };
1441
1442 struct retro_input_descriptor desc_sms[] = {
1443 { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_LEFT, "D-Pad Left" },
1444 { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_UP, "D-Pad Up" },
1445 { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_DOWN, "D-Pad Down" },
1446 { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_RIGHT, "D-Pad Right" },
1447 { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_B, "Button 1 Start" },
1448 { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_A, "Button 2" },
1449 { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_START, "Button Pause" },
1450
1451 { 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_LEFT, "D-Pad Left" },
1452 { 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_UP, "D-Pad Up" },
1453 { 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_DOWN, "D-Pad Down" },
1454 { 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_RIGHT, "D-Pad Right" },
1455 { 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_B, "Button 1 Start" },
1456 { 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_A, "Button 2" },
1457 { 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_START, "Button Pause" },
1458
1459 { 0 },
1460 };
1461
1462 struct retro_input_descriptor desc_pico[] = {
1463 { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_LEFT, "D-Pad Left (violet)" },
1464 { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_UP, "D-Pad Up (white)" },
1465 { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_DOWN, "D-Pad Down (orange)" },
1466 { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_RIGHT, "D-Pad Right (green)" },
1467 { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_B, "Red Button" },
1468 { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_A, "Pen Button" },
1469 { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_START, "Pen State" },
1470 { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_Y, "Pen on Storyware" },
1471 { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_X, "Pen on Pad" },
1472 { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_L, "Previous Page" },
1473 { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_R, "Next Page" },
1474
1475 { 0 },
1476 };
1477
1478 /* Attempt to fetch extended game info */
1479 if (environ_cb(RETRO_ENVIRONMENT_GET_GAME_INFO_EXT, &info_ext))
1480 {
1481#if !defined(LOW_MEMORY)
1482 content_data = (const unsigned char *)info_ext->data;
1483 content_size = info_ext->size;
1484#endif
1485 strncpy(base_dir, info_ext->dir, sizeof(base_dir));
1486 base_dir[sizeof(base_dir) - 1] = '\0';
1487
1488 strncpy(content_ext, info_ext->ext, sizeof(content_ext));
1489 content_ext[sizeof(content_ext) - 1] = '\0';
1490
1491 if (info_ext->file_in_archive)
1492 {
1493 /* We don't have a 'physical' file in this
1494 * case, but the core still needs a filename
1495 * in order to detect media type. We therefore
1496 * fake it, using the content directory,
1497 * canonical content name, and content file
1498 * extension */
1499 snprintf(content_path, sizeof(content_path), "%s%c%s.%s",
1500 base_dir, slash, info_ext->name, content_ext);
1501 }
1502 else
1503 {
1504 strncpy(content_path, info_ext->full_path, sizeof(content_path));
1505 content_path[sizeof(content_path) - 1] = '\0';
1506 }
1507 }
1508 else
1509 {
1510 const char *ext = NULL;
1511
1512 if (!info || !info->path)
1513 {
1514 if (log_cb)
1515 log_cb(RETRO_LOG_ERROR, "info->path required\n");
1516 return false;
1517 }
1518
1519 extract_directory(base_dir, info->path, sizeof(base_dir));
1520
1521 strncpy(content_path, info->path, sizeof(content_path));
1522 content_path[sizeof(content_path) - 1] = '\0';
1523
1524 if ((ext = strrchr(info->path, '.')))
1525 {
1526 strncpy(content_ext, ext + 1, sizeof(content_ext));
1527 content_ext[sizeof(content_ext) - 1] = '\0';
1528 }
1529 }
1530
1531 enum retro_pixel_format fmt = RETRO_PIXEL_FORMAT_RGB565;
1532 if (!environ_cb(RETRO_ENVIRONMENT_SET_PIXEL_FORMAT, &fmt)) {
1533 if (log_cb)
1534 log_cb(RETRO_LOG_ERROR, "RGB565 support required, sorry\n");
1535 return false;
1536 }
1537
1538 disk_init();
1539
1540 is_m3u = (strcasestr(content_ext, "m3u") != NULL);
1541 if (is_m3u)
1542 {
1543 if (!read_m3u(content_path))
1544 {
1545 log_cb(RETRO_LOG_INFO, "failed to read m3u file\n");
1546 return false;
1547 }
1548
1549 strncpy(content_path, disks[0].fname, sizeof(content_path));
1550 content_path[sizeof(content_path) - 1] = '\0';
1551 }
1552 else
1553 {
1554 char disk_label[PATH_MAX];
1555 disk_label[0] = '\0';
1556
1557 disk_current_index = 0;
1558 disk_count = 1;
1559 disks[0].fname = strdup(content_path);
1560
1561 get_disk_label(disk_label, content_path, PATH_MAX);
1562 disks[0].flabel = strdup(disk_label);
1563 }
1564
1565 /* If this is an M3U file, attempt to set the
1566 * initial disk image */
1567 if (is_m3u && (disk_initial_index > 0) && (disk_initial_index < disk_count))
1568 {
1569 const char *fname = disks[disk_initial_index].fname;
1570
1571 if (fname && (*fname != '\0'))
1572 if (strcmp(disk_initial_path, fname) == 0)
1573 cd_index = disk_initial_index;
1574
1575 /* If we are not loading the first disk in the
1576 * M3U list, update the content_path string
1577 * that will be passed to PicoLoadMedia() */
1578 if (cd_index != 0)
1579 {
1580 strncpy(content_path, disks[cd_index].fname, sizeof(content_path));
1581 content_path[sizeof(content_path) - 1] = '\0';
1582 }
1583 }
1584
1585 make_system_path(carthw_path, sizeof(carthw_path), "carthw", ".cfg");
1586
1587 media_type = PicoLoadMedia(content_path, content_data, content_size,
1588 carthw_path, find_bios, NULL);
1589
1590 disk_current_index = cd_index;
1591
1592 switch (media_type) {
1593 case PM_BAD_DETECT:
1594 if (log_cb)
1595 log_cb(RETRO_LOG_ERROR, "Failed to detect ROM/CD image type.\n");
1596 return false;
1597 case PM_BAD_CD:
1598 if (log_cb)
1599 log_cb(RETRO_LOG_ERROR, "Invalid CD image\n");
1600 return false;
1601 case PM_BAD_CD_NO_BIOS:
1602 if (log_cb)
1603 log_cb(RETRO_LOG_ERROR, "Missing BIOS\n");
1604 return false;
1605 case PM_ERROR:
1606 if (log_cb)
1607 log_cb(RETRO_LOG_ERROR, "Load error\n");
1608 return false;
1609 default:
1610 break;
1611 }
1612
1613 strncpy(pico_overlay_path, content_path, sizeof(pico_overlay_path)-4);
1614 if (PicoIn.AHW & PAHW_PICO)
1615 environ_cb(RETRO_ENVIRONMENT_SET_INPUT_DESCRIPTORS, desc_pico);
1616 else if (PicoIn.AHW & PAHW_SMS)
1617 environ_cb(RETRO_ENVIRONMENT_SET_INPUT_DESCRIPTORS, desc_sms);
1618 else
1619 environ_cb(RETRO_ENVIRONMENT_SET_INPUT_DESCRIPTORS, desc);
1620
1621 PicoLoopPrepare();
1622
1623 PicoIn.writeSound = snd_write;
1624 memset(sndBuffer, 0, sizeof(sndBuffer));
1625 PicoIn.sndOut = sndBuffer;
1626 if (PicoIn.sndRate > 52000 && PicoIn.sndRate < 54000)
1627 PicoIn.sndRate = YM2612_NATIVE_RATE();
1628 PsndRerate(0);
1629
1630 apply_renderer();
1631
1632 /* Setup retro memory maps */
1633 set_memory_maps();
1634
1635 init_frameskip();
1636
1637 /* Initialisation routines may have 'triggered'
1638 * a libretro AV info or geometry update; this
1639 * happens automatically after retro_load_game(),
1640 * so disable the relevant flags here to avoid
1641 * redundant updates on the first call of
1642 * retro_run() */
1643 libretro_update_av_info = false;
1644 libretro_update_geometry = false;
1645
1646 return true;
1647}
1648
1649bool retro_load_game_special(unsigned game_type, const struct retro_game_info *info, size_t num_info)
1650{
1651 return false;
1652}
1653
1654void retro_unload_game(void)
1655{
1656}
1657
1658unsigned retro_get_region(void)
1659{
1660 return Pico.m.pal ? RETRO_REGION_PAL : RETRO_REGION_NTSC;
1661}
1662
1663void *retro_get_memory_data(unsigned type)
1664{
1665 void *data;
1666
1667 switch(type)
1668 {
1669 case RETRO_MEMORY_SAVE_RAM:
1670 /* Note: MCD RAM cart uses Pico.sv.data */
1671 if ((PicoIn.AHW & PAHW_MCD) &&
1672 !(PicoIn.opt & POPT_EN_MCD_RAMCART))
1673 data = Pico_mcd->bram;
1674 else
1675 data = Pico.sv.data;
1676 break;
1677 case RETRO_MEMORY_SYSTEM_RAM:
1678 if (PicoIn.AHW & PAHW_SMS)
1679 data = PicoMem.zram;
1680 else
1681 data = PicoMem.ram;
1682 break;
1683 case RETRO_MEMORY_VIDEO_RAM:
1684 data = PicoMem.vram;
1685 break;
1686 case 4:
1687 data = PicoMem.cram;
1688 break;
1689 default:
1690 data = NULL;
1691 break;
1692 }
1693
1694 return data;
1695}
1696
1697size_t retro_get_memory_size(unsigned type)
1698{
1699 unsigned int i;
1700 int sum;
1701
1702 switch(type)
1703 {
1704 case RETRO_MEMORY_SAVE_RAM:
1705 if (PicoIn.AHW & PAHW_MCD)
1706 {
1707 if (PicoIn.opt & POPT_EN_MCD_RAMCART)
1708 return 0x12000;
1709 else /* bram */
1710 return 0x2000;
1711 }
1712
1713 if (Pico.m.frame_count == 0)
1714 return Pico.sv.size;
1715
1716 // if game doesn't write to sram, don't report it to
1717 // libretro so that RA doesn't write out zeroed .srm
1718 for (i = 0, sum = 0; i < Pico.sv.size; i++)
1719 sum |= Pico.sv.data[i];
1720
1721 return (sum != 0) ? Pico.sv.size : 0;
1722
1723 case RETRO_MEMORY_SYSTEM_RAM:
1724 if (PicoIn.AHW & PAHW_SMS)
1725 return 0x2000;
1726 else
1727 return sizeof(PicoMem.ram);
1728
1729 default:
1730 return 0;
1731 }
1732
1733}
1734
1735void retro_reset(void)
1736{
1737 PicoReset();
1738}
1739
1740static const unsigned short retro_pico_map[] = {
1741 [RETRO_DEVICE_ID_JOYPAD_B] = 1 << GBTN_B,
1742 [RETRO_DEVICE_ID_JOYPAD_Y] = 1 << GBTN_A,
1743 [RETRO_DEVICE_ID_JOYPAD_SELECT] = 1 << GBTN_MODE,
1744 [RETRO_DEVICE_ID_JOYPAD_START] = 1 << GBTN_START,
1745 [RETRO_DEVICE_ID_JOYPAD_UP] = 1 << GBTN_UP,
1746 [RETRO_DEVICE_ID_JOYPAD_DOWN] = 1 << GBTN_DOWN,
1747 [RETRO_DEVICE_ID_JOYPAD_LEFT] = 1 << GBTN_LEFT,
1748 [RETRO_DEVICE_ID_JOYPAD_RIGHT] = 1 << GBTN_RIGHT,
1749 [RETRO_DEVICE_ID_JOYPAD_A] = 1 << GBTN_C,
1750 [RETRO_DEVICE_ID_JOYPAD_X] = 1 << GBTN_Y,
1751 [RETRO_DEVICE_ID_JOYPAD_L] = 1 << GBTN_X,
1752 [RETRO_DEVICE_ID_JOYPAD_R] = 1 << GBTN_Z,
1753};
1754#define RETRO_PICO_MAP_LEN (sizeof(retro_pico_map) / sizeof(retro_pico_map[0]))
1755
1756static int has_4_pads;
1757
1758static void snd_write(int len)
1759{
1760 audio_batch_cb(PicoIn.sndOut, len / 4);
1761}
1762
1763static enum input_device input_name_to_val(const char *name)
1764{
1765 if (strcmp(name, "3 button pad") == 0)
1766 return PICO_INPUT_PAD_3BTN;
1767 if (strcmp(name, "6 button pad") == 0)
1768 return PICO_INPUT_PAD_6BTN;
1769 if (strcmp(name, "team player") == 0)
1770 return PICO_INPUT_PAD_TEAM;
1771 if (strcmp(name, "4way play") == 0)
1772 return PICO_INPUT_PAD_4WAY;
1773 if (strcmp(name, "None") == 0)
1774 return PICO_INPUT_NOTHING;
1775
1776 if (log_cb)
1777 log_cb(RETRO_LOG_WARN, "invalid picodrive_input: '%s'\n", name);
1778 return PICO_INPUT_PAD_3BTN;
1779}
1780
1781static void update_variables(bool first_run)
1782{
1783 struct retro_variable var;
1784 int OldPicoRegionOverride;
1785 float old_vout_aspect;
1786 unsigned old_frameskip_type;
1787 int old_vout_format;
1788 double new_sound_rate;
1789 unsigned short old_snd_filter;
1790 int32_t old_snd_filter_range;
1791
1792 var.value = NULL;
1793 var.key = "picodrive_input1";
1794 if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value) {
1795 int input = input_name_to_val(var.value);
1796 PicoSetInputDevice(0, input);
1797 has_4_pads = input == PICO_INPUT_PAD_TEAM || input == PICO_INPUT_PAD_4WAY;
1798 }
1799
1800 var.value = NULL;
1801 var.key = "picodrive_input2";
1802 if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value)
1803 PicoSetInputDevice(1, input_name_to_val(var.value));
1804
1805 var.value = NULL;
1806 var.key = "picodrive_ramcart";
1807 if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value) {
1808 if (strcmp(var.value, "enabled") == 0)
1809 PicoIn.opt |= POPT_EN_MCD_RAMCART;
1810 else
1811 PicoIn.opt &= ~POPT_EN_MCD_RAMCART;
1812 }
1813
1814 var.value = NULL;
1815 var.key = "picodrive_smstype";
1816 if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value) {
1817 if (strcmp(var.value, "Auto") == 0)
1818 PicoIn.hwSelect = PHWS_AUTO;
1819 else if (strcmp(var.value, "Game Gear") == 0)
1820 PicoIn.hwSelect = PHWS_GG;
1821 else if (strcmp(var.value, "SG-1000") == 0)
1822 PicoIn.hwSelect = PHWS_SG;
1823 else if (strcmp(var.value, "SC-3000") == 0)
1824 PicoIn.hwSelect = PHWS_SC;
1825 else
1826 PicoIn.hwSelect = PHWS_SMS;
1827 }
1828
1829 var.value = NULL;
1830 var.key = "picodrive_smsfm";
1831 if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value) {
1832 if (strcmp(var.value, "on") == 0)
1833 PicoIn.opt |= POPT_EN_YM2413;
1834 else
1835 PicoIn.opt &= ~POPT_EN_YM2413;
1836 }
1837
1838 var.value = NULL;
1839 var.key = "picodrive_smstms";
1840 if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value) {
1841 if (strcmp(var.value, "SG-1000") == 0)
1842 PicoIn.tmsPalette = 1;
1843 else
1844 PicoIn.tmsPalette = 0;
1845 }
1846
1847 var.value = NULL;
1848 var.key = "picodrive_smsmapper";
1849 if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value) {
1850 if (strcmp(var.value, "Auto") == 0)
1851 PicoIn.mapper = PMS_MAP_AUTO;
1852 else if (strcmp(var.value, "Codemasters") == 0)
1853 PicoIn.mapper = PMS_MAP_CODEM;
1854 else if (strcmp(var.value, "Korea") == 0)
1855 PicoIn.mapper = PMS_MAP_KOREA;
1856 else if (strcmp(var.value, "Korea MSX") == 0)
1857 PicoIn.mapper = PMS_MAP_MSX;
1858 else if (strcmp(var.value, "Korea X-in-1") == 0)
1859 PicoIn.mapper = PMS_MAP_N32K;
1860 else if (strcmp(var.value, "Korea 4-Pak") == 0)
1861 PicoIn.mapper = PMS_MAP_N16K;
1862 else if (strcmp(var.value, "Korea Janggun") == 0)
1863 PicoIn.mapper = PMS_MAP_JANGGUN;
1864 else if (strcmp(var.value, "Korea Nemesis") == 0)
1865 PicoIn.mapper = PMS_MAP_NEMESIS;
1866 else if (strcmp(var.value, "Taiwan 8K RAM") == 0)
1867 PicoIn.mapper = PMS_MAP_8KBRAM;
1868 else
1869 PicoIn.mapper = PMS_MAP_SEGA;
1870 }
1871
1872 var.value = NULL;
1873 var.key = "picodrive_ggghost";
1874 if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value) {
1875 if (strcmp(var.value, "normal") == 0)
1876 vout_ghosting = 2;
1877 else if (strcmp(var.value, "weak") == 0)
1878 vout_ghosting = 1;
1879 else
1880 vout_ghosting = 0;
1881 }
1882
1883 OldPicoRegionOverride = PicoIn.regionOverride;
1884 var.value = NULL;
1885 var.key = "picodrive_region";
1886 if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value) {
1887 if (strcmp(var.value, "Auto") == 0)
1888 PicoIn.regionOverride = 0;
1889 else if (strcmp(var.value, "Japan NTSC") == 0)
1890 PicoIn.regionOverride = 1;
1891 else if (strcmp(var.value, "Japan PAL") == 0)
1892 PicoIn.regionOverride = 2;
1893 else if (strcmp(var.value, "US") == 0)
1894 PicoIn.regionOverride = 4;
1895 else if (strcmp(var.value, "Europe") == 0)
1896 PicoIn.regionOverride = 8;
1897 }
1898
1899 // Update region, fps and sound flags if needed
1900 if (Pico.rom && PicoIn.regionOverride != OldPicoRegionOverride)
1901 {
1902 PicoDetectRegion();
1903 PicoLoopPrepare();
1904 if (PicoIn.sndRate > 52000 && PicoIn.sndRate < 54000)
1905 PicoIn.sndRate = YM2612_NATIVE_RATE();
1906 PsndRerate(!first_run);
1907 }
1908
1909 old_vout_aspect = vout_aspect;
1910 var.value = NULL;
1911 var.key = "picodrive_aspect";
1912 if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value) {
1913 if (strcmp(var.value, "4/3") == 0)
1914 vout_aspect = VOUT_4_3;
1915 else if (strcmp(var.value, "CRT") == 0)
1916 vout_aspect = VOUT_CRT;
1917 else
1918 vout_aspect = VOUT_PAR;
1919 }
1920
1921 /* Notify frontend of geometry update */
1922 if (vout_aspect != old_vout_aspect)
1923 libretro_update_geometry = true;
1924
1925 var.value = NULL;
1926 var.key = "picodrive_sprlim";
1927 if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value) {
1928 if (strcmp(var.value, "enabled") == 0)
1929 PicoIn.opt |= POPT_DIS_SPRITE_LIM;
1930 else
1931 PicoIn.opt &= ~POPT_DIS_SPRITE_LIM;
1932 }
1933
1934 var.value = NULL;
1935 var.key = "picodrive_overclk68k";
1936 if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value) {
1937 PicoIn.overclockM68k = 0;
1938 if (var.value[0] == '+')
1939 PicoIn.overclockM68k = atoi(var.value + 1);
1940 }
1941
1942#ifdef DRC_SH2
1943 var.value = NULL;
1944 var.key = "picodrive_drc";
1945 if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value) {
1946 if (strcmp(var.value, "enabled") == 0)
1947 PicoIn.opt |= POPT_EN_DRC;
1948 else
1949 PicoIn.opt &= ~POPT_EN_DRC;
1950 }
1951#endif
1952#ifdef _3DS
1953 if(!ctr_svchack_successful)
1954 PicoIn.opt &= ~POPT_EN_DRC;
1955#endif
1956
1957 var.value = NULL;
1958 var.key = "picodrive_dacnoise";
1959 if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value) {
1960 if (strcmp(var.value, "enabled") == 0)
1961 PicoIn.opt |= POPT_EN_FM_DAC;
1962 else
1963 PicoIn.opt &= ~POPT_EN_FM_DAC;
1964 }
1965
1966 var.value = NULL;
1967 var.key = "picodrive_fm_filter";
1968 if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value) {
1969 if (strcmp(var.value, "on") == 0)
1970 PicoIn.opt |= POPT_EN_FM_FILTER;
1971 else
1972 PicoIn.opt &= ~POPT_EN_FM_FILTER;
1973 }
1974
1975 old_snd_filter = PicoIn.opt & POPT_EN_SNDFILTER;
1976 var.value = NULL;
1977 var.key = "picodrive_audio_filter";
1978 PicoIn.opt &= ~POPT_EN_SNDFILTER;
1979 if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value) {
1980 if (strcmp(var.value, "low-pass") == 0)
1981 PicoIn.opt |= POPT_EN_SNDFILTER;
1982 }
1983
1984 old_snd_filter_range = PicoIn.sndFilterAlpha;
1985 var.value = NULL;
1986 var.key = "picodrive_lowpass_range";
1987 PicoIn.sndFilterAlpha = (60 * 0x10000 / 100);
1988 if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value) {
1989 PicoIn.sndFilterAlpha = (atoi(var.value) * 0x10000 / 100);
1990 }
1991
1992 if (((old_snd_filter ^ PicoIn.opt) & POPT_EN_SNDFILTER) ||
1993 old_snd_filter_range != PicoIn.sndFilterAlpha) {
1994 mix_reset (PicoIn.opt & POPT_EN_SNDFILTER ? PicoIn.sndFilterAlpha : 0);
1995 }
1996
1997 old_frameskip_type = frameskip_type;
1998 frameskip_type = 0;
1999 var.key = "picodrive_frameskip";
2000 if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value) {
2001 if (strcmp(var.value, "auto") == 0)
2002 frameskip_type = 1;
2003 else if (strcmp(var.value, "manual") == 0)
2004 frameskip_type = 2;
2005 }
2006
2007 frameskip_threshold = 33;
2008 var.key = "picodrive_frameskip_threshold";
2009 var.value = NULL;
2010 if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value)
2011 frameskip_threshold = strtol(var.value, NULL, 10);
2012
2013 old_vout_format = vout_format;
2014 var.value = NULL;
2015 var.key = "picodrive_renderer";
2016 if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value) {
2017 if (strcmp(var.value, "fast") == 0)
2018 vout_format = PDF_NONE;
2019 else if (strcmp(var.value, "good") == 0)
2020 vout_format = PDF_8BIT;
2021 else if (strcmp(var.value, "accurate") == 0)
2022 vout_format = PDF_RGB555;
2023 vout_16bit = vout_format == PDF_RGB555 || (PicoIn.AHW & PAHW_32X);
2024
2025 apply_renderer();
2026 }
2027
2028 var.value = NULL;
2029 var.key = "picodrive_sound_rate";
2030 if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value) {
2031 if (!strcmp(var.value, "native"))
2032 new_sound_rate = YM2612_NATIVE_RATE();
2033 else
2034 new_sound_rate = atoi(var.value);
2035 if (new_sound_rate != PicoIn.sndRate) {
2036 /* Update the sound rate */
2037 PicoIn.sndRate = new_sound_rate;
2038 PsndRerate(!first_run);
2039 libretro_update_av_info = true;
2040 }
2041 }
2042
2043 /* setup video if required */
2044 if (vout_format != old_vout_format)
2045 {
2046 if (vout_buf &&
2047 (vm_current_start_line != -1) && (vm_current_line_count != -1) &&
2048 (vm_current_start_col != -1) && (vm_current_col_count != -1))
2049 emu_video_mode_change(
2050 vm_current_start_line, vm_current_line_count,
2051 vm_current_start_col, vm_current_col_count);
2052 }
2053
2054 /* Reinitialise frameskipping, if required */
2055 if (((frameskip_type != old_frameskip_type) ||
2056 (Pico.rom && PicoIn.regionOverride != OldPicoRegionOverride)) &&
2057 !first_run)
2058 init_frameskip();
2059}
2060
2061void emu_status_msg(const char *format, ...)
2062{
2063 va_list vl;
2064 int ret;
2065 static char msg[512];
2066
2067 memset (msg, 0, sizeof(msg));
2068
2069 va_start(vl, format);
2070 ret = vsnprintf(msg, sizeof(msg), format, vl);
2071 va_end(vl);
2072
2073 static struct retro_message rmsg;
2074 rmsg.msg = msg;
2075 rmsg.frames = 600;
2076 environ_cb(RETRO_ENVIRONMENT_SET_MESSAGE, &rmsg);
2077}
2078
2079static void draw_pico_ptr(void)
2080{
2081 int up = (PicoPicohw.pen_pos[0]|PicoPicohw.pen_pos[1]) & 0x8000;
2082 int x, y, pitch = vout_width;
2083 unsigned short *p = (unsigned short *)((char *)vout_buf + vout_offset);
2084 int o = (up ? 0x0000 : 0xffff), _ = (up ? 0xffff : 0x0000);
2085 // storyware pages are actually squished, 2:1
2086 int h = (pico_inp_mode == 1 ? 160 : vout_height);
2087 if (h < 224) y++;
2088
2089 x = ((pico_pen_x * vout_width * ((1ULL<<32) / 320 + 1)) >> 32);
2090 y = ((pico_pen_y * h * ((1ULL<<32) / 224 + 1)) >> 32);
2091 p += x + y * pitch;
2092
2093 p[-pitch-1] ^= o; p[-pitch] ^= _; p[-pitch+1] ^= _; p[-pitch+2] ^= o;
2094 p[-1] ^= _; p[0] ^= o; p[1] ^= o; p[2] ^= _;
2095 p[pitch-1] ^= _; p[pitch] ^= o; p[pitch+1] ^= o; p[pitch+2] ^= _;
2096 p[2*pitch-1]^= o; p[2*pitch]^= _; p[2*pitch+1]^= _; p[2*pitch+2]^= o;
2097}
2098
2099static int readpng(unsigned short *dest, const char *fname, int req_w, int req_h)
2100{
2101 rpng_t *rpng = rpng_alloc();
2102 FILE *pf = fopen(fname, "rb");
2103 void *png = NULL, *img = NULL;
2104 size_t len;
2105 unsigned int x, y, w = req_w, h = req_h;
2106 int ret = -1;
2107
2108 if (!rpng || !pf) {
2109 lprintf("can't read png file %s", fname);
2110 goto done;
2111 }
2112
2113 // who designed this, reading the whole file for inflating, really?
2114 fseek(pf, 0, SEEK_END);
2115 len = ftell(pf);
2116 fseek(pf, 0, SEEK_SET);
2117 if (!(png = malloc(len))) {
2118 lprintf("oom while reading png file %s", fname);
2119 goto done;
2120 }
2121 fread(png, 1, len, pf);
2122
2123 // again, who designed this? why all this superfluous iterating here?
2124 rpng_set_buf_ptr(rpng, png, len);
2125 rpng_start(rpng);
2126 while (rpng_iterate_image(rpng));
2127 do {
2128 ret = rpng_process_image(rpng, &img, len, &w, &h);
2129 } while (ret == IMAGE_PROCESS_NEXT);
2130
2131 // there's already a scaled pngread in libpicofe, but who cares :-/
2132 if (img && rpng_is_valid(rpng)) {
2133 int x_scale = w*65536 / req_w;
2134 int y_scale = h*65536 / req_h;
2135 int x_ofs, y_ofs, x_pos, y_pos;
2136
2137 if (x_scale < y_scale)
2138 x_scale = y_scale;
2139 else y_scale = x_scale;
2140 x_ofs = req_w - w*65536 / x_scale;
2141 y_ofs = req_h - h*65536 / y_scale;
2142
2143 dest += y_ofs/2*req_w + x_ofs/2;
2144 for (y_pos = 0; y_pos < h*65536; y_pos += y_scale+1)
2145 {
2146 unsigned char *src = (unsigned char *)img + 4*w*(y_pos >> 16);
2147 for (x_pos = 0, len = 0; x_pos < w*65536; x_pos += x_scale+1, len++)
2148 {
2149 // to add insult to injury, rpng writes the image endian dependant!
2150 unsigned int d = *(unsigned int *)&src[4*(x_pos >> 16)];
2151 int r = d >> 16, g = d >> 8, b = d;
2152 *dest++ = PXMAKE(r & 0xff, g & 0xff, b & 0xff);
2153 }
2154 dest += req_w - len;
2155 }
2156 }
2157 ret = 0;
2158
2159done:
2160 if (img) free(img);
2161 if (png) free(png);
2162 if (pf) fclose(pf);
2163 rpng_free(rpng);
2164 return ret;
2165}
2166
2167static unsigned short *load_pico_overlay(int page, int w, int h)
2168{
2169 static const char *pic_exts[] = { "png", "PNG" };
2170 char buffer[PATH_MAX];
2171 char *ext, *fname = NULL;
2172 int extpos, i;
2173
2174 if (pico_page == page && pico_w == w && pico_h == h)
2175 return pico_overlay;
2176 pico_page = page;
2177 pico_w = w, pico_h = h;
2178
2179 ext = strrchr(pico_overlay_path, '.');
2180 extpos = ext ? ext-pico_overlay_path : strlen(pico_overlay_path);
2181 strcpy(buffer, pico_overlay_path);
2182 buffer[extpos++] = '_';
2183 if (page < 0) {
2184 buffer[extpos++] = 'p';
2185 buffer[extpos++] = 'a';
2186 buffer[extpos++] = 'd';
2187 } else
2188 buffer[extpos++] = '0'+PicoPicohw.page;
2189 buffer[extpos++] = '.';
2190
2191 for (i = 0; i < ARRAY_SIZE(pic_exts); i++) {
2192 strcpy(buffer+extpos, pic_exts[i]);
2193 if (path_is_valid(buffer) == RETRO_VFS_STAT_IS_VALID) {
2194 printf("found Pico file: %s\n", buffer);
2195 fname = buffer;
2196 break;
2197 }
2198 }
2199
2200 pico_overlay = realloc(pico_overlay, w*h*2);
2201 memset(pico_overlay, 0, w*h*2);
2202 if (!fname || !pico_overlay || readpng(pico_overlay, fname, w, h)) {
2203 if (pico_overlay)
2204 free(pico_overlay);
2205 pico_overlay = NULL;
2206 }
2207
2208 return pico_overlay;
2209}
2210
2211void emu_pico_overlay(u16 *pd, int w, int h, int pitch)
2212{
2213 u16 *overlay = NULL;
2214 int y, oh = h;
2215
2216 // get overlay
2217 if (pico_inp_mode == 1) {
2218 oh = (w/2 < h ? w/2 : h); // storyware has squished h
2219 overlay = load_pico_overlay(PicoPicohw.page, w, oh);
2220 } else if (pico_inp_mode == 2)
2221 overlay = load_pico_overlay(-1, w, oh);
2222
2223 // copy overlay onto buffer
2224 if (overlay) {
2225 for (y = 0; y < oh; y++)
2226 memcpy(pd + y*pitch, overlay + y*w, w*2);
2227 if (y < h)
2228 memset(pd + y*pitch, 0, w*2);
2229 }
2230}
2231
2232void run_events_pico(unsigned int events)
2233{
2234 int lim_x;
2235
2236 if (events & (1 << RETRO_DEVICE_ID_JOYPAD_L)) {
2237 PicoPicohw.page--;
2238 if (PicoPicohw.page < 0)
2239 PicoPicohw.page = 0;
2240 emu_status_msg("Page %i", PicoPicohw.page);
2241 }
2242 if (events & (1 << RETRO_DEVICE_ID_JOYPAD_R)) {
2243 PicoPicohw.page++;
2244 if (PicoPicohw.page > 6)
2245 PicoPicohw.page = 6;
2246 emu_status_msg("Page %i", PicoPicohw.page);
2247 }
2248 if (events & (1 << RETRO_DEVICE_ID_JOYPAD_X)) {
2249 if (pico_inp_mode == 2) {
2250 pico_inp_mode = 0;
2251 emu_status_msg("Input: D-Pad");
2252 } else {
2253 pico_inp_mode = 2;
2254 emu_status_msg("Input: Pen on Pad");
2255 }
2256 }
2257 if (events & (1 << RETRO_DEVICE_ID_JOYPAD_SELECT)) {
2258 if (pico_inp_mode == 1) {
2259 pico_inp_mode = 0;
2260 emu_status_msg("Input: D-Pad");
2261 } else {
2262 pico_inp_mode = 1;
2263 emu_status_msg("Input: Pen on Storyware");
2264 }
2265 }
2266 if (events & (1 << RETRO_DEVICE_ID_JOYPAD_START)) {
2267 PicoPicohw.pen_pos[0] ^= 0x8000;
2268 PicoPicohw.pen_pos[1] ^= 0x8000;
2269 emu_status_msg("Pen %s", PicoPicohw.pen_pos[0] & 0x8000 ? "Up" : "Down");
2270 }
2271
2272 if ((PicoIn.pad[0] & 0x20) && pico_inp_mode && pico_overlay) {
2273 pico_inp_mode = 0;
2274 emu_status_msg("Input: D-Pad");
2275 }
2276 if (pico_inp_mode == 0)
2277 return;
2278
2279 /* handle other input modes */
2280 if (PicoIn.pad[0] & 1) pico_pen_y--;
2281 if (PicoIn.pad[0] & 2) pico_pen_y++;
2282 if (PicoIn.pad[0] & 4) pico_pen_x--;
2283 if (PicoIn.pad[0] & 8) pico_pen_x++;
2284 PicoIn.pad[0] &= ~0x0f; // release UDLR
2285
2286 if (pico_pen_y < PICO_PEN_ADJUST_Y)
2287 pico_pen_y = PICO_PEN_ADJUST_Y;
2288 if (pico_pen_y > 223-1 - PICO_PEN_ADJUST_Y)
2289 pico_pen_y = 223-1 - PICO_PEN_ADJUST_Y;
2290 if (pico_pen_x < PICO_PEN_ADJUST_X)
2291 pico_pen_x = PICO_PEN_ADJUST_X;
2292 if (pico_pen_x > 319-1 - PICO_PEN_ADJUST_X)
2293 pico_pen_x = 319-1 - PICO_PEN_ADJUST_X;
2294
2295 PicoPicohw.pen_pos[0] &= 0x8000;
2296 PicoPicohw.pen_pos[1] &= 0x8000;
2297 PicoPicohw.pen_pos[0] |= 0x3c + pico_pen_x;
2298 PicoPicohw.pen_pos[1] |= (pico_inp_mode == 1 ? 0x2f8 : 0x1fc) + pico_pen_y;
2299}
2300
2301void retro_run(void)
2302{
2303 bool updated = false;
2304 int pad, i, padcount;
2305 static void *buff;
2306
2307 PicoIn.skipFrame = 0;
2308
2309 if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE_UPDATE, &updated) && updated)
2310 update_variables(false);
2311
2312 input_poll_cb();
2313
2314 PicoIn.pad[0] = PicoIn.pad[1] = PicoIn.pad[2] = PicoIn.pad[3] = 0;
2315 if (PicoIn.AHW & PAHW_PICO)
2316 padcount = 1;
2317 else if (PicoIn.AHW & PAHW_SMS)
2318 padcount = 2;
2319 else
2320 padcount = has_4_pads ? 4 : 2;
2321
2322 int16_t input[4] = {0, 0};
2323
2324 if (libretro_supports_bitmasks)
2325 {
2326 for (pad = 0; pad < padcount; pad++)
2327 {
2328 input[pad] = input_state_cb(
2329 pad, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_MASK);
2330 }
2331 }
2332 else
2333 {
2334 for (pad = 0; pad < padcount; pad++)
2335 {
2336 for (i = 0; i < RETRO_PICO_MAP_LEN; i++)
2337 if (input_state_cb(pad, RETRO_DEVICE_JOYPAD, 0, i))
2338 input[pad] |= 1 << i;
2339 }
2340 }
2341
2342 for (pad = 0; pad < padcount; pad++)
2343 for (i = 0; i < RETRO_PICO_MAP_LEN; i++)
2344 if (input[pad] & (1 << i))
2345 PicoIn.pad[pad] |= retro_pico_map[i];
2346
2347 if (PicoIn.AHW == PAHW_PICO) {
2348 uint16_t ev = input[0] &
2349 ((1 << RETRO_DEVICE_ID_JOYPAD_L) | (1 << RETRO_DEVICE_ID_JOYPAD_R) |
2350 (1 << RETRO_DEVICE_ID_JOYPAD_X) | (1 << RETRO_DEVICE_ID_JOYPAD_SELECT) |
2351 (1 << RETRO_DEVICE_ID_JOYPAD_START));
2352 uint16_t new_ev = ev & ~pico_events;
2353 pico_events = ev;
2354 run_events_pico(new_ev);
2355 }
2356
2357 if (PicoPatches)
2358 PicoPatchApply();
2359
2360 /* Check whether current frame should
2361 * be skipped */
2362 if ((frameskip_type > 0) && retro_audio_buff_active) {
2363 switch (frameskip_type)
2364 {
2365 case 1: /* auto */
2366 PicoIn.skipFrame = retro_audio_buff_underrun ? 1 : 0;
2367 break;
2368 case 2: /* manual */
2369 PicoIn.skipFrame = (retro_audio_buff_occupancy < frameskip_threshold) ? 1 : 0;
2370 break;
2371 default:
2372 PicoIn.skipFrame = 0;
2373 break;
2374 }
2375
2376 if (!PicoIn.skipFrame || (frameskip_counter >= FRAMESKIP_MAX)) {
2377 PicoIn.skipFrame = 0;
2378 frameskip_counter = 0;
2379 } else
2380 frameskip_counter++;
2381 }
2382
2383 /* If frameskip settings have changed, update
2384 * frontend audio latency */
2385 if (update_audio_latency) {
2386 environ_cb(RETRO_ENVIRONMENT_SET_MINIMUM_AUDIO_LATENCY,
2387 &audio_latency);
2388 update_audio_latency = false;
2389 }
2390
2391 PicoFrame();
2392
2393 /* Check whether frontend needs to be notified
2394 * of timing/geometry changes */
2395 if (libretro_update_av_info || libretro_update_geometry) {
2396 struct retro_system_av_info av_info;
2397 retro_get_system_av_info(&av_info);
2398 environ_cb(libretro_update_av_info ?
2399 RETRO_ENVIRONMENT_SET_SYSTEM_AV_INFO :
2400 RETRO_ENVIRONMENT_SET_GEOMETRY,
2401 &av_info);
2402 libretro_update_av_info = false;
2403 libretro_update_geometry = false;
2404 }
2405
2406 /* If frame was skipped, call video_cb() with
2407 * a NULL buffer and return immediately */
2408 if (PicoIn.skipFrame) {
2409 video_cb(NULL, vout_width, vout_height, vout_width * 2);
2410 return;
2411 }
2412
2413#if defined(RENDER_GSKIT_PS2)
2414 buff = (uint32_t *)RETRO_HW_FRAME_BUFFER_VALID;
2415
2416 if (!ps2) {
2417 // get access to the graphics hardware
2418 if (!environ_cb(RETRO_ENVIRONMENT_GET_HW_RENDER_INTERFACE, (void **)&ps2) || !ps2) {
2419 printf("Failed to get HW rendering interface!\n");
2420 return;
2421 }
2422
2423 if (ps2->interface_version != RETRO_HW_RENDER_INTERFACE_GSKIT_PS2_VERSION) {
2424 printf("HW render interface mismatch, expected %u, got %u!\n",
2425 RETRO_HW_RENDER_INTERFACE_GSKIT_PS2_VERSION, ps2->interface_version);
2426 return;
2427 }
2428
2429 ps2->coreTexture->ClutPSM = GS_PSM_CT16;
2430 ps2->coreTexture->Filter = GS_FILTER_LINEAR;
2431 ps2->coreTexture->Clut = retro_palette;
2432
2433 ps2->coreTexture->Mem = vout_buf;
2434 ps2->coreTexture->Width = vout_width;
2435 ps2->coreTexture->Height = vout_height;
2436 ps2->coreTexture->PSM = (vout_16bit ? GS_PSM_CT16 : GS_PSM_T8);
2437 ps2->padding = padding;
2438 }
2439
2440 // CLUT update needed?
2441 if (!vout_16bit && Pico.m.dirtyPal) {
2442 PicoDrawUpdateHighPal();
2443
2444 // Rotate CLUT. PS2 is special since entries in CLUT are not in sequence.
2445 unsigned short int *pal=(void *)retro_palette;
2446 for (i = 0; i < 256; i+=8) {
2447 if ((i&0x18) == 0x08)
2448 memcpy(pal+i,Pico.est.HighPal+i+8,16);
2449 else if ((i&0x18) == 0x10)
2450 memcpy(pal+i,Pico.est.HighPal+i-8,16);
2451 else
2452 memcpy(pal+i,Pico.est.HighPal+i,16);
2453 }
2454 }
2455#else
2456 if (!vout_16bit) {
2457 /* The 8 bit renderers write a CLUT image in Pico.est.Draw2FB, while libretro wants RGB in vout_buf.
2458 * We need to manually copy that to vout_buf, applying the CLUT on the way. Especially
2459 * with the fast renderer this is improving performance, at the expense of accuracy.
2460 */
2461 /* This section is mostly copied from pemu_finalize_frame in platform/linux/emu.c */
2462 unsigned short *pd = (unsigned short *)((char *)vout_buf + vout_offset);
2463 /* Skip the leftmost 8 columns (it is used as an overlap area for rendering) */
2464 unsigned char *ps = Pico.est.Draw2FB + vm_current_start_line * 328 + 8;
2465 unsigned short *pal = Pico.est.HighPal;
2466 int x;
2467 if (Pico.m.dirtyPal)
2468 PicoDrawUpdateHighPal();
2469 /* 8 bit renderers have an extra offset for SMS wíth 1st tile blanked */
2470 if (vout_width == 248)
2471 ps += 8;
2472 /* Copy, and skip the leftmost 8 columns again */
2473 for (i = 0; i < vout_height; i++, ps += 8) {
2474 for (x = 0; x < vout_width; x+=4) {
2475 *pd++ = pal[*ps++];
2476 *pd++ = pal[*ps++];
2477 *pd++ = pal[*ps++];
2478 *pd++ = pal[*ps++];
2479 }
2480 ps += 320-vout_width; /* Advance to next line in case of 32col mode */
2481 }
2482 }
2483
2484 if (vout_ghosting && vout_height == 144) {
2485 unsigned short *pd = (unsigned short *)vout_buf;
2486 unsigned short *ps = (unsigned short *)vout_ghosting_buf;
2487 int y;
2488 for (y = 0; y < vout_height; y++) {
2489 if (vout_ghosting == 1)
2490 v_blend(pd, ps, vout_width, p_075_round);
2491 else
2492 v_blend(pd, ps, vout_width, p_05_round);
2493 pd += vout_width;
2494 ps += vout_width;
2495 }
2496 }
2497
2498 if (PicoIn.AHW & PAHW_PICO) {
2499 int h = vout_height, w = vout_width;
2500 unsigned short *pd = (unsigned short *)((char *)vout_buf + vout_offset);
2501
2502 if (pico_inp_mode)
2503 emu_pico_overlay(pd, w, h, vout_width);
2504 if (pico_inp_mode /*== 2 || overlay*/)
2505 draw_pico_ptr();
2506 }
2507
2508 buff = (char*)vout_buf + vout_offset;
2509#endif
2510
2511 video_cb((short *)buff, vout_width, vout_height, vout_width * 2);
2512}
2513
2514void retro_init(void)
2515{
2516 unsigned dci_version = 0;
2517 struct retro_log_callback log;
2518 int level;
2519
2520 level = 0;
2521 environ_cb(RETRO_ENVIRONMENT_SET_PERFORMANCE_LEVEL, &level);
2522
2523 if (environ_cb(RETRO_ENVIRONMENT_GET_LOG_INTERFACE, &log))
2524 log_cb = log.log;
2525 else
2526 log_cb = NULL;
2527
2528 environ_cb(RETRO_ENVIRONMENT_SET_DISK_CONTROL_INTERFACE, &disk_control);
2529
2530 if (environ_cb(RETRO_ENVIRONMENT_GET_INPUT_BITMASKS, NULL))
2531 libretro_supports_bitmasks = true;
2532
2533 disk_initial_index = 0;
2534 disk_initial_path[0] = '\0';
2535 if (environ_cb(RETRO_ENVIRONMENT_GET_DISK_CONTROL_INTERFACE_VERSION, &dci_version) && (dci_version >= 1))
2536 environ_cb(RETRO_ENVIRONMENT_SET_DISK_CONTROL_EXT_INTERFACE, &disk_control_ext);
2537 else
2538 environ_cb(RETRO_ENVIRONMENT_SET_DISK_CONTROL_INTERFACE, &disk_control);
2539
2540#ifdef _3DS
2541 ctr_svchack_successful = ctr_svchack_init();
2542 check_rosalina();
2543#elif defined(VITA)
2544 sceBlock = getVMBlock();
2545#endif
2546
2547 PicoIn.opt = POPT_EN_STEREO|POPT_EN_FM
2548 | POPT_EN_PSG|POPT_EN_Z80|POPT_EN_GG_LCD
2549 | POPT_EN_MCD_PCM|POPT_EN_MCD_CDDA|POPT_EN_MCD_GFX
2550 | POPT_EN_32X|POPT_EN_PWM
2551 | POPT_ACC_SPRITES|POPT_DIS_32C_BORDER;
2552#ifdef DRC_SH2
2553#ifdef _3DS
2554 if (ctr_svchack_successful)
2555#endif
2556 PicoIn.opt |= POPT_EN_DRC;
2557#endif
2558
2559 struct retro_variable var = { .key = "picodrive_sound_rate" };
2560 if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value)
2561 PicoIn.sndRate = atoi(var.value);
2562 else
2563 PicoIn.sndRate = SND_RATE_DEFAULT;
2564
2565 PicoIn.autoRgnOrder = 0x184; // US, EU, JP
2566
2567 vout_width = VOUT_MAX_WIDTH;
2568 vout_height = VOUT_MAX_HEIGHT;
2569#ifdef _3DS
2570 vout_buf = linearMemAlign(VOUT_MAX_WIDTH * VOUT_MAX_HEIGHT * 2, 0x80);
2571#elif defined(RENDER_GSKIT_PS2)
2572 vout_buf = memalign(4096, VOUT_MAX_WIDTH * VOUT_MAX_HEIGHT * 2);
2573 retro_palette = memalign(128, gsKit_texture_size_ee(16, 16, GS_PSM_CT16));
2574#else
2575 vout_buf = malloc(VOUT_MAX_WIDTH * VOUT_MAX_HEIGHT * 2);
2576#endif
2577
2578 PicoInit();
2579
2580 //PicoIn.osdMessage = plat_status_msg_busy_next;
2581 PicoIn.mcdTrayOpen = disk_tray_open;
2582 PicoIn.mcdTrayClose = disk_tray_close;
2583
2584 frameskip_type = 0;
2585 frameskip_threshold = 0;
2586 frameskip_counter = 0;
2587 retro_audio_buff_active = false;
2588 retro_audio_buff_occupancy = 0;
2589 retro_audio_buff_underrun = false;
2590 audio_latency = 0;
2591 update_audio_latency = false;
2592
2593 update_variables(true);
2594}
2595
2596void retro_deinit(void)
2597{
2598 size_t i;
2599
2600 PicoExit();
2601
2602 disk_init();
2603
2604#ifdef _3DS
2605 linearFree(vout_buf);
2606#elif defined(RENDER_GSKIT_PS2)
2607 free(vout_buf);
2608 free(retro_palette);
2609 ps2 = NULL;
2610#elif defined(__PS3__)
2611 free(vout_buf);
2612 if (page_table[0] > 0 && page_table[1] > 0)
2613 ps3mapi_process_page_free(sysProcessGetPid(), 0x2F, page_table);
2614#else
2615 free(vout_buf);
2616#endif
2617 vout_buf = NULL;
2618
2619 if (vout_ghosting_buf)
2620 free(vout_ghosting_buf);
2621 vout_ghosting_buf = NULL;
2622 if (pico_overlay)
2623 free(pico_overlay);
2624 pico_overlay = NULL;
2625
2626 libretro_supports_bitmasks = false;
2627}