src/platform/psp2/psp2-context.c (view raw)
1/* Copyright (c) 2013-2015 Jeffrey Pfau
2 *
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6#include "psp2-context.h"
7
8#include <mgba/core/blip_buf.h>
9#include <mgba/core/core.h>
10
11#ifdef M_CORE_GBA
12#include <mgba/internal/gba/gba.h>
13#endif
14#ifdef M_CORE_GB
15#include <mgba/internal/gb/gb.h>
16#endif
17
18#include "feature/gui/gui-runner.h"
19#include <mgba/internal/gba/input.h>
20
21#include <mgba-util/memory.h>
22#include <mgba-util/circle-buffer.h>
23#include <mgba-util/math.h>
24#include <mgba-util/ring-fifo.h>
25#include <mgba-util/threading.h>
26#include <mgba-util/vfs.h>
27#include <mgba-util/platform/psp2/sce-vfs.h>
28
29#include <psp2/audioout.h>
30#include <psp2/camera.h>
31#include <psp2/ctrl.h>
32#include <psp2/display.h>
33#include <psp2/gxm.h>
34#include <psp2/kernel/sysmem.h>
35#include <psp2/motion.h>
36
37#include <vita2d.h>
38
39#define RUMBLE_PWM 8
40#define CDRAM_ALIGN 0x40000
41
42static enum ScreenMode {
43 SM_BACKDROP,
44 SM_PLAIN,
45 SM_FULL,
46 SM_ASPECT,
47 SM_MAX
48} screenMode;
49
50static void* outputBuffer;
51static vita2d_texture* tex;
52static vita2d_texture* screenshot;
53static Thread audioThread;
54
55static struct mSceRotationSource {
56 struct mRotationSource d;
57 struct SceMotionSensorState state;
58} rotation;
59
60static struct mSceRumble {
61 struct mRumble d;
62 struct CircleBuffer history;
63 int current;
64} rumble;
65
66static struct mSceImageSource {
67 struct mImageSource d;
68 SceUID memblock;
69 void* buffer;
70 unsigned cam;
71 size_t bufferOffset;
72} camera;
73
74bool frameLimiter = true;
75
76extern const uint8_t _binary_backdrop_png_start[];
77static vita2d_texture* backdrop = 0;
78
79#define PSP2_SAMPLES 256
80#define PSP2_AUDIO_BUFFER_SIZE (PSP2_SAMPLES * 20)
81
82static struct mPSP2AudioContext {
83 struct RingFIFO buffer;
84 size_t samples;
85 Mutex mutex;
86 Condition cond;
87 bool running;
88} audioContext;
89
90void mPSP2MapKey(struct mInputMap* map, int pspKey, int key) {
91 mInputBindKey(map, PSP2_INPUT, __builtin_ctz(pspKey), key);
92}
93
94static THREAD_ENTRY _audioThread(void* context) {
95 struct mPSP2AudioContext* audio = (struct mPSP2AudioContext*) context;
96 int audioPort = sceAudioOutOpenPort(SCE_AUDIO_OUT_PORT_TYPE_MAIN, PSP2_SAMPLES, 48000, SCE_AUDIO_OUT_MODE_STEREO);
97 while (audio->running) {
98 MutexLock(&audio->mutex);
99 int len = audio->samples;
100 if (len > PSP2_SAMPLES) {
101 len = PSP2_SAMPLES;
102 }
103 struct GBAStereoSample* buffer = audio->buffer.readPtr;
104 RingFIFORead(&audio->buffer, NULL, len * 4);
105 audio->samples -= len;
106 ConditionWake(&audio->cond);
107
108 MutexUnlock(&audio->mutex);
109 sceAudioOutOutput(audioPort, buffer);
110 MutexLock(&audio->mutex);
111
112 if (audio->samples < PSP2_SAMPLES) {
113 ConditionWait(&audio->cond, &audio->mutex);
114 }
115 MutexUnlock(&audio->mutex);
116 }
117 sceAudioOutReleasePort(audioPort);
118 return 0;
119}
120
121static void _sampleRotation(struct mRotationSource* source) {
122 struct mSceRotationSource* rotation = (struct mSceRotationSource*) source;
123 sceMotionGetSensorState(&rotation->state, 1);
124}
125
126static int32_t _readTiltX(struct mRotationSource* source) {
127 struct mSceRotationSource* rotation = (struct mSceRotationSource*) source;
128 return rotation->state.accelerometer.x * 0x30000000;
129}
130
131static int32_t _readTiltY(struct mRotationSource* source) {
132 struct mSceRotationSource* rotation = (struct mSceRotationSource*) source;
133 return rotation->state.accelerometer.y * -0x30000000;
134}
135
136static int32_t _readGyroZ(struct mRotationSource* source) {
137 struct mSceRotationSource* rotation = (struct mSceRotationSource*) source;
138 return rotation->state.gyro.z * -0x10000000;
139}
140
141static void _setRumble(struct mRumble* source, int enable) {
142 struct mSceRumble* rumble = (struct mSceRumble*) source;
143 rumble->current += enable;
144 if (CircleBufferSize(&rumble->history) == RUMBLE_PWM) {
145 int8_t oldLevel;
146 CircleBufferRead8(&rumble->history, &oldLevel);
147 rumble->current -= oldLevel;
148 }
149 CircleBufferWrite8(&rumble->history, enable);
150 int small = (rumble->current << 21) / 65793;
151 int big = ((rumble->current * rumble->current) << 18) / 65793;
152 struct SceCtrlActuator state = {
153 small,
154 big
155 };
156 sceCtrlSetActuator(1, &state);
157}
158
159static void _resetCamera(struct mSceImageSource* imageSource) {
160 if (!imageSource->cam) {
161 return;
162 }
163
164 sceCameraOpen(imageSource->cam - 1, &(SceCameraInfo) {
165 .size = sizeof(SceCameraInfo),
166 .format = 5, // SCE_CAMERA_FORMAT_ABGR
167 .resolution = SCE_CAMERA_RESOLUTION_176_144,
168 .framerate = SCE_CAMERA_FRAMERATE_30_FPS,
169 .sizeIBase = 176 * 144 * 4,
170 .pitch = 0,
171 .pIBase = imageSource->buffer,
172 });
173 sceCameraStart(imageSource->cam - 1);
174}
175
176static void _startRequestImage(struct mImageSource* source, unsigned w, unsigned h, int colorFormats) {
177 UNUSED(colorFormats);
178 struct mSceImageSource* imageSource = (struct mSceImageSource*) source;
179
180 if (!imageSource->buffer) {
181 imageSource->memblock = sceKernelAllocMemBlock("camera", SCE_KERNEL_MEMBLOCK_TYPE_USER_CDRAM_RW, CDRAM_ALIGN, NULL);
182 sceKernelGetMemBlockBase(imageSource->memblock, &imageSource->buffer);
183 }
184
185 if (!imageSource->cam) {
186 return;
187 }
188
189 _resetCamera(imageSource);
190 imageSource->bufferOffset = (176 - w) / 2 + (144 - h) * 176 / 2;
191
192 SceCameraRead read = {
193 sizeof(SceCameraRead),
194 1
195 };
196 sceCameraRead(imageSource->cam - 1, &read);
197}
198
199static void _stopRequestImage(struct mImageSource* source) {
200 struct mSceImageSource* imageSource = (struct mSceImageSource*) source;
201 if (imageSource->cam) {
202 sceCameraStop(imageSource->cam - 1);
203 sceCameraClose(imageSource->cam - 1);
204 }
205 sceKernelFreeMemBlock(imageSource->memblock);
206 imageSource->buffer = NULL;
207}
208
209
210static void _requestImage(struct mImageSource* source, const void** buffer, size_t* stride, enum mColorFormat* colorFormat) {
211 struct mSceImageSource* imageSource = (struct mSceImageSource*) source;
212
213 if (!imageSource->cam) {
214 memset(imageSource->buffer, 0, 176 * 144 * 4);
215 *buffer = (uint32_t*) imageSource->buffer;
216 *stride = 176;
217 *colorFormat = mCOLOR_XBGR8;
218 return;
219 }
220
221 *buffer = (uint32_t*) imageSource->buffer + imageSource->bufferOffset;
222 *stride = 176;
223 *colorFormat = mCOLOR_XBGR8;
224
225 SceCameraRead read = {
226 sizeof(SceCameraRead),
227 1
228 };
229 sceCameraRead(imageSource->cam - 1, &read);
230}
231
232uint16_t mPSP2PollInput(struct mGUIRunner* runner) {
233 SceCtrlData pad;
234 sceCtrlPeekBufferPositive(0, &pad, 1);
235
236 int activeKeys = mInputMapKeyBits(&runner->core->inputMap, PSP2_INPUT, pad.buttons, 0);
237 int angles = mInputMapAxis(&runner->core->inputMap, PSP2_INPUT, 0, pad.ly);
238 if (angles != GBA_KEY_NONE) {
239 activeKeys |= 1 << angles;
240 }
241 angles = mInputMapAxis(&runner->core->inputMap, PSP2_INPUT, 1, pad.lx);
242 if (angles != GBA_KEY_NONE) {
243 activeKeys |= 1 << angles;
244 }
245 angles = mInputMapAxis(&runner->core->inputMap, PSP2_INPUT, 2, pad.ry);
246 if (angles != GBA_KEY_NONE) {
247 activeKeys |= 1 << angles;
248 }
249 angles = mInputMapAxis(&runner->core->inputMap, PSP2_INPUT, 3, pad.rx);
250 if (angles != GBA_KEY_NONE) {
251 activeKeys |= 1 << angles;
252 }
253 return activeKeys;
254}
255
256void mPSP2SetFrameLimiter(struct mGUIRunner* runner, bool limit) {
257 UNUSED(runner);
258 frameLimiter = limit;
259}
260
261void mPSP2Setup(struct mGUIRunner* runner) {
262 mCoreConfigSetDefaultIntValue(&runner->config, "threadedVideo", 1);
263 mCoreLoadForeignConfig(runner->core, &runner->config);
264
265 mPSP2MapKey(&runner->core->inputMap, SCE_CTRL_CROSS, GBA_KEY_A);
266 mPSP2MapKey(&runner->core->inputMap, SCE_CTRL_CIRCLE, GBA_KEY_B);
267 mPSP2MapKey(&runner->core->inputMap, SCE_CTRL_START, GBA_KEY_START);
268 mPSP2MapKey(&runner->core->inputMap, SCE_CTRL_SELECT, GBA_KEY_SELECT);
269 mPSP2MapKey(&runner->core->inputMap, SCE_CTRL_UP, GBA_KEY_UP);
270 mPSP2MapKey(&runner->core->inputMap, SCE_CTRL_DOWN, GBA_KEY_DOWN);
271 mPSP2MapKey(&runner->core->inputMap, SCE_CTRL_LEFT, GBA_KEY_LEFT);
272 mPSP2MapKey(&runner->core->inputMap, SCE_CTRL_RIGHT, GBA_KEY_RIGHT);
273 mPSP2MapKey(&runner->core->inputMap, SCE_CTRL_LTRIGGER, GBA_KEY_L);
274 mPSP2MapKey(&runner->core->inputMap, SCE_CTRL_RTRIGGER, GBA_KEY_R);
275
276 struct mInputAxis desc = { GBA_KEY_DOWN, GBA_KEY_UP, 192, 64 };
277 mInputBindAxis(&runner->core->inputMap, PSP2_INPUT, 0, &desc);
278 desc = (struct mInputAxis) { GBA_KEY_RIGHT, GBA_KEY_LEFT, 192, 64 };
279 mInputBindAxis(&runner->core->inputMap, PSP2_INPUT, 1, &desc);
280
281 unsigned width, height;
282 runner->core->desiredVideoDimensions(runner->core, &width, &height);
283 tex = vita2d_create_empty_texture_format(256, toPow2(height), SCE_GXM_TEXTURE_FORMAT_X8U8U8U8_1BGR);
284 screenshot = vita2d_create_empty_texture_format(256, toPow2(height), SCE_GXM_TEXTURE_FORMAT_X8U8U8U8_1BGR);
285
286 outputBuffer = vita2d_texture_get_datap(tex);
287 runner->core->setVideoBuffer(runner->core, outputBuffer, 256);
288
289 rotation.d.sample = _sampleRotation;
290 rotation.d.readTiltX = _readTiltX;
291 rotation.d.readTiltY = _readTiltY;
292 rotation.d.readGyroZ = _readGyroZ;
293 runner->core->setPeripheral(runner->core, mPERIPH_ROTATION, &rotation.d);
294
295 rumble.d.setRumble = _setRumble;
296 CircleBufferInit(&rumble.history, RUMBLE_PWM);
297 runner->core->setPeripheral(runner->core, mPERIPH_RUMBLE, &rumble.d);
298
299 camera.d.startRequestImage = _startRequestImage;
300 camera.d.stopRequestImage = _stopRequestImage;
301 camera.d.requestImage = _requestImage;
302 camera.buffer = NULL;
303 camera.cam = 1;
304 runner->core->setPeripheral(runner->core, mPERIPH_IMAGE_SOURCE, &camera.d);
305
306 frameLimiter = true;
307 backdrop = vita2d_load_PNG_buffer(_binary_backdrop_png_start);
308
309 unsigned mode;
310 if (mCoreConfigGetUIntValue(&runner->config, "screenMode", &mode) && mode < SM_MAX) {
311 screenMode = mode;
312 }
313 if (mCoreConfigGetUIntValue(&runner->config, "camera", &mode)) {
314 camera.cam = mode;
315 }
316}
317
318void mPSP2LoadROM(struct mGUIRunner* runner) {
319 float rate = 60.0f / 1.001f;
320 sceDisplayGetRefreshRate(&rate);
321 double ratio = GBAAudioCalculateRatio(1, rate, 1);
322 blip_set_rates(runner->core->getAudioChannel(runner->core, 0), runner->core->frequency(runner->core), 48000 * ratio);
323 blip_set_rates(runner->core->getAudioChannel(runner->core, 1), runner->core->frequency(runner->core), 48000 * ratio);
324
325 switch (runner->core->platform(runner->core)) {
326#ifdef M_CORE_GBA
327 case PLATFORM_GBA:
328 if (((struct GBA*) runner->core->board)->memory.hw.devices & (HW_TILT | HW_GYRO)) {
329 sceMotionStartSampling();
330 }
331 break;
332#endif
333#ifdef M_CORE_GB
334 case PLATFORM_GB:
335 if (((struct GB*) runner->core->board)->memory.mbcType == GB_MBC7) {
336 sceMotionStartSampling();
337 }
338 break;
339#endif
340 default:
341 break;
342 }
343
344 RingFIFOInit(&audioContext.buffer, PSP2_AUDIO_BUFFER_SIZE * sizeof(struct GBAStereoSample));
345 MutexInit(&audioContext.mutex);
346 ConditionInit(&audioContext.cond);
347 audioContext.running = true;
348 ThreadCreate(&audioThread, _audioThread, &audioContext);
349}
350
351void mPSP2PrepareForFrame(struct mGUIRunner* runner) {
352 int nSamples = 0;
353 while (blip_samples_avail(runner->core->getAudioChannel(runner->core, 0)) >= PSP2_SAMPLES) {
354 struct GBAStereoSample* samples = audioContext.buffer.writePtr;
355 if (nSamples > (PSP2_AUDIO_BUFFER_SIZE >> 2) + (PSP2_AUDIO_BUFFER_SIZE >> 1)) { // * 0.75
356 if (!frameLimiter) {
357 blip_clear(runner->core->getAudioChannel(runner->core, 0));
358 blip_clear(runner->core->getAudioChannel(runner->core, 1));
359 break;
360 }
361 }
362 blip_read_samples(runner->core->getAudioChannel(runner->core, 0), &samples[0].left, PSP2_SAMPLES, true);
363 blip_read_samples(runner->core->getAudioChannel(runner->core, 1), &samples[0].right, PSP2_SAMPLES, true);
364 while (!RingFIFOWrite(&audioContext.buffer, NULL, PSP2_SAMPLES * 4)) {
365 ConditionWake(&audioContext.cond);
366 // Spinloooooooop!
367 }
368 MutexLock(&audioContext.mutex);
369 audioContext.samples += PSP2_SAMPLES;
370 nSamples = audioContext.samples;
371 ConditionWake(&audioContext.cond);
372 MutexUnlock(&audioContext.mutex);
373 }
374}
375
376void mPSP2UnloadROM(struct mGUIRunner* runner) {
377 switch (runner->core->platform(runner->core)) {
378#ifdef M_CORE_GBA
379 case PLATFORM_GBA:
380 if (((struct GBA*) runner->core->board)->memory.hw.devices & (HW_TILT | HW_GYRO)) {
381 sceMotionStopSampling();
382 }
383 break;
384#endif
385#ifdef M_CORE_GB
386 case PLATFORM_GB:
387 if (((struct GB*) runner->core->board)->memory.mbcType == GB_MBC7) {
388 sceMotionStopSampling();
389 }
390 break;
391#endif
392 default:
393 break;
394 }
395}
396
397void mPSP2Paused(struct mGUIRunner* runner) {
398 UNUSED(runner);
399 struct SceCtrlActuator state = {
400 0,
401 0
402 };
403 sceCtrlSetActuator(1, &state);
404 frameLimiter = true;
405}
406
407void mPSP2Unpaused(struct mGUIRunner* runner) {
408 unsigned mode;
409 if (mCoreConfigGetUIntValue(&runner->config, "screenMode", &mode) && mode != screenMode) {
410 screenMode = mode;
411 }
412
413 if (mCoreConfigGetUIntValue(&runner->config, "camera", &mode)) {
414 if (mode != camera.cam) {
415 if (camera.buffer) {
416 sceCameraStop(camera.cam - 1);
417 sceCameraClose(camera.cam - 1);
418 }
419 camera.cam = mode;
420 if (camera.buffer) {
421 _resetCamera(&camera);
422 }
423 }
424 }
425}
426
427void mPSP2Teardown(struct mGUIRunner* runner) {
428 UNUSED(runner);
429 CircleBufferDeinit(&rumble.history);
430 vita2d_free_texture(tex);
431 vita2d_free_texture(screenshot);
432 frameLimiter = true;
433}
434
435void _drawTex(vita2d_texture* t, unsigned width, unsigned height, bool faded) {
436 unsigned w = width;
437 unsigned h = height;
438 // Get greatest common divisor
439 while (w != 0) {
440 int temp = h % w;
441 h = w;
442 w = temp;
443 }
444 int gcd = h;
445 int aspectw = width / gcd;
446 int aspecth = height / gcd;
447 float scalex;
448 float scaley;
449
450 switch (screenMode) {
451 case SM_BACKDROP:
452 default:
453 vita2d_draw_texture_tint(backdrop, 0, 0, (faded ? 0 : 0xC0000000) | 0x3FFFFFFF);
454 // Fall through
455 case SM_PLAIN:
456 w = 960 / width;
457 h = 544 / height;
458 if (w * height > 544) {
459 scalex = h;
460 w = width * h;
461 h = height * h;
462 } else {
463 scalex = w;
464 w = width * w;
465 h = height * w;
466 }
467 scaley = scalex;
468 break;
469 case SM_ASPECT:
470 w = 960 / aspectw;
471 h = 544 / aspecth;
472 if (w * aspecth > 544) {
473 w = aspectw * h;
474 h = aspecth * h;
475 } else {
476 w = aspectw * w;
477 h = aspecth * w;
478 }
479 scalex = w / (float) width;
480 scaley = scalex;
481 break;
482 case SM_FULL:
483 w = 960;
484 h = 544;
485 scalex = 960.0f / width;
486 scaley = 544.0f / height;
487 break;
488 }
489 vita2d_draw_texture_tint_part_scale(t,
490 (960.0f - w) / 2.0f, (544.0f - h) / 2.0f,
491 0, 0, width, height,
492 scalex, scaley,
493 (faded ? 0 : 0xC0000000) | 0x3FFFFFFF);
494}
495
496void mPSP2Draw(struct mGUIRunner* runner, bool faded) {
497 unsigned width, height;
498 runner->core->desiredVideoDimensions(runner->core, &width, &height);
499 _drawTex(tex, width, height, faded);
500}
501
502void mPSP2DrawScreenshot(struct mGUIRunner* runner, const uint32_t* pixels, unsigned width, unsigned height, bool faded) {
503 UNUSED(runner);
504 uint32_t* texpixels = vita2d_texture_get_datap(screenshot);
505 unsigned y;
506 for (y = 0; y < height; ++y) {
507 memcpy(&texpixels[256 * y], &pixels[width * y], width * 4);
508 }
509 _drawTex(screenshot, width, height, faded);
510}
511
512void mPSP2IncrementScreenMode(struct mGUIRunner* runner) {
513 screenMode = (screenMode + 1) % SM_MAX;
514 mCoreConfigSetUIntValue(&runner->config, "screenMode", screenMode);
515}
516
517__attribute__((noreturn, weak)) void __assert_func(const char* file, int line, const char* func, const char* expr) {
518 printf("ASSERT FAILED: %s in %s at %s:%i\n", expr, func, file, line);
519 exit(1);
520}