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/threading.h>
25#include <mgba-util/vfs.h>
26#include <mgba-util/platform/psp2/sce-vfs.h>
27
28#include <psp2/appmgr.h>
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
42mLOG_DECLARE_CATEGORY(GUI_PSP2);
43mLOG_DEFINE_CATEGORY(GUI_PSP2, "Vita", "gui.psp2");
44
45static enum ScreenMode {
46 SM_BACKDROP,
47 SM_PLAIN,
48 SM_FULL,
49 SM_ASPECT,
50 SM_MAX
51} screenMode;
52
53static void* outputBuffer;
54static vita2d_texture* tex;
55static vita2d_texture* oldTex;
56static vita2d_texture* screenshot;
57static Thread audioThread;
58static bool interframeBlending = false;
59
60static struct mSceRotationSource {
61 struct mRotationSource d;
62 struct SceMotionSensorState state;
63} rotation;
64
65static struct mSceRumble {
66 struct mRumble d;
67 struct CircleBuffer history;
68 int current;
69} rumble;
70
71static struct mSceImageSource {
72 struct mImageSource d;
73 SceUID memblock;
74 void* buffer;
75 unsigned cam;
76 size_t bufferOffset;
77} camera;
78
79static struct mAVStream stream;
80
81bool frameLimiter = true;
82
83extern const uint8_t _binary_backdrop_png_start[];
84static vita2d_texture* backdrop = 0;
85
86#define PSP2_SAMPLES 512
87#define PSP2_AUDIO_BUFFER_SIZE (PSP2_SAMPLES * 16)
88
89static struct mPSP2AudioContext {
90 struct GBAStereoSample buffer[PSP2_AUDIO_BUFFER_SIZE];
91 size_t writeOffset;
92 size_t readOffset;
93 size_t samples;
94 Mutex mutex;
95 Condition cond;
96 bool running;
97} audioContext;
98
99void mPSP2MapKey(struct mInputMap* map, int pspKey, int key) {
100 mInputBindKey(map, PSP2_INPUT, __builtin_ctz(pspKey), key);
101}
102
103static THREAD_ENTRY _audioThread(void* context) {
104 struct mPSP2AudioContext* audio = (struct mPSP2AudioContext*) context;
105 uint32_t zeroBuffer[PSP2_SAMPLES] = {0};
106 void* buffer = zeroBuffer;
107 int audioPort = sceAudioOutOpenPort(SCE_AUDIO_OUT_PORT_TYPE_MAIN, PSP2_SAMPLES, 48000, SCE_AUDIO_OUT_MODE_STEREO);
108 while (audio->running) {
109 MutexLock(&audio->mutex);
110 if (buffer != zeroBuffer) {
111 // Can only happen in successive iterations
112 audio->samples -= PSP2_SAMPLES;
113 ConditionWake(&audio->cond);
114 }
115 if (audio->samples >= PSP2_SAMPLES) {
116 buffer = &audio->buffer[audio->readOffset];
117 audio->readOffset += PSP2_SAMPLES;
118 if (audio->readOffset >= PSP2_AUDIO_BUFFER_SIZE) {
119 audio->readOffset = 0;
120 }
121 // Don't mark samples as read until the next loop iteration to prevent
122 // writing to the buffer while being read (see above)
123 } else {
124 buffer = zeroBuffer;
125 }
126 MutexUnlock(&audio->mutex);
127
128 sceAudioOutOutput(audioPort, buffer);
129 }
130 sceAudioOutReleasePort(audioPort);
131 return 0;
132}
133
134static void _sampleRotation(struct mRotationSource* source) {
135 struct mSceRotationSource* rotation = (struct mSceRotationSource*) source;
136 sceMotionGetSensorState(&rotation->state, 1);
137}
138
139static int32_t _readTiltX(struct mRotationSource* source) {
140 struct mSceRotationSource* rotation = (struct mSceRotationSource*) source;
141 return rotation->state.accelerometer.x * 0x30000000;
142}
143
144static int32_t _readTiltY(struct mRotationSource* source) {
145 struct mSceRotationSource* rotation = (struct mSceRotationSource*) source;
146 return rotation->state.accelerometer.y * -0x30000000;
147}
148
149static int32_t _readGyroZ(struct mRotationSource* source) {
150 struct mSceRotationSource* rotation = (struct mSceRotationSource*) source;
151 return rotation->state.gyro.z * -0x10000000;
152}
153
154static void _setRumble(struct mRumble* source, int enable) {
155 struct mSceRumble* rumble = (struct mSceRumble*) source;
156 rumble->current += enable;
157 if (CircleBufferSize(&rumble->history) == RUMBLE_PWM) {
158 int8_t oldLevel;
159 CircleBufferRead8(&rumble->history, &oldLevel);
160 rumble->current -= oldLevel;
161 }
162 CircleBufferWrite8(&rumble->history, enable);
163 int small = (rumble->current << 21) / 65793;
164 int big = ((rumble->current * rumble->current) << 18) / 65793;
165 struct SceCtrlActuator state = {
166 small,
167 big
168 };
169 sceCtrlSetActuator(1, &state);
170}
171
172static void _resetCamera(struct mSceImageSource* imageSource) {
173 if (!imageSource->cam) {
174 return;
175 }
176
177 sceCameraOpen(imageSource->cam - 1, &(SceCameraInfo) {
178 .size = sizeof(SceCameraInfo),
179 .format = 5, // SCE_CAMERA_FORMAT_ABGR
180 .resolution = SCE_CAMERA_RESOLUTION_176_144,
181 .framerate = SCE_CAMERA_FRAMERATE_30_FPS,
182 .sizeIBase = 176 * 144 * 4,
183 .pitch = 0,
184 .pIBase = imageSource->buffer,
185 });
186 sceCameraStart(imageSource->cam - 1);
187}
188
189static void _startRequestImage(struct mImageSource* source, unsigned w, unsigned h, int colorFormats) {
190 UNUSED(colorFormats);
191 struct mSceImageSource* imageSource = (struct mSceImageSource*) source;
192
193 if (!imageSource->buffer) {
194 imageSource->memblock = sceKernelAllocMemBlock("camera", SCE_KERNEL_MEMBLOCK_TYPE_USER_CDRAM_RW, CDRAM_ALIGN, NULL);
195 sceKernelGetMemBlockBase(imageSource->memblock, &imageSource->buffer);
196 }
197
198 if (!imageSource->cam) {
199 return;
200 }
201
202 _resetCamera(imageSource);
203 imageSource->bufferOffset = (176 - w) / 2 + (144 - h) * 176 / 2;
204
205 SceCameraRead read = {
206 sizeof(SceCameraRead),
207 1
208 };
209 sceCameraRead(imageSource->cam - 1, &read);
210}
211
212static void _stopRequestImage(struct mImageSource* source) {
213 struct mSceImageSource* imageSource = (struct mSceImageSource*) source;
214 if (imageSource->cam) {
215 sceCameraStop(imageSource->cam - 1);
216 sceCameraClose(imageSource->cam - 1);
217 }
218 sceKernelFreeMemBlock(imageSource->memblock);
219 imageSource->buffer = NULL;
220}
221
222
223static void _requestImage(struct mImageSource* source, const void** buffer, size_t* stride, enum mColorFormat* colorFormat) {
224 struct mSceImageSource* imageSource = (struct mSceImageSource*) source;
225
226 if (!imageSource->cam) {
227 memset(imageSource->buffer, 0, 176 * 144 * 4);
228 *buffer = (uint32_t*) imageSource->buffer;
229 *stride = 176;
230 *colorFormat = mCOLOR_XBGR8;
231 return;
232 }
233
234 *buffer = (uint32_t*) imageSource->buffer + imageSource->bufferOffset;
235 *stride = 176;
236 *colorFormat = mCOLOR_XBGR8;
237
238 SceCameraRead read = {
239 sizeof(SceCameraRead),
240 1
241 };
242 sceCameraRead(imageSource->cam - 1, &read);
243}
244
245static void _postAudioBuffer(struct mAVStream* stream, blip_t* left, blip_t* right) {
246 UNUSED(stream);
247 MutexLock(&audioContext.mutex);
248 while (audioContext.samples + PSP2_SAMPLES >= PSP2_AUDIO_BUFFER_SIZE) {
249 if (!frameLimiter) {
250 blip_clear(left);
251 blip_clear(right);
252 MutexUnlock(&audioContext.mutex);
253 return;
254 }
255 ConditionWait(&audioContext.cond, &audioContext.mutex);
256 }
257 struct GBAStereoSample* samples = &audioContext.buffer[audioContext.writeOffset];
258 blip_read_samples(left, &samples[0].left, PSP2_SAMPLES, true);
259 blip_read_samples(right, &samples[0].right, PSP2_SAMPLES, true);
260 audioContext.samples += PSP2_SAMPLES;
261 audioContext.writeOffset += PSP2_SAMPLES;
262 if (audioContext.writeOffset >= PSP2_AUDIO_BUFFER_SIZE) {
263 audioContext.writeOffset = 0;
264 }
265 MutexUnlock(&audioContext.mutex);
266}
267
268uint16_t mPSP2PollInput(struct mGUIRunner* runner) {
269 SceCtrlData pad;
270 sceCtrlPeekBufferPositiveExt2(0, &pad, 1);
271
272 int activeKeys = mInputMapKeyBits(&runner->core->inputMap, PSP2_INPUT, pad.buttons, 0);
273 int angles = mInputMapAxis(&runner->core->inputMap, PSP2_INPUT, 0, pad.ly);
274 if (angles != GBA_KEY_NONE) {
275 activeKeys |= 1 << angles;
276 }
277 angles = mInputMapAxis(&runner->core->inputMap, PSP2_INPUT, 1, pad.lx);
278 if (angles != GBA_KEY_NONE) {
279 activeKeys |= 1 << angles;
280 }
281 angles = mInputMapAxis(&runner->core->inputMap, PSP2_INPUT, 2, pad.ry);
282 if (angles != GBA_KEY_NONE) {
283 activeKeys |= 1 << angles;
284 }
285 angles = mInputMapAxis(&runner->core->inputMap, PSP2_INPUT, 3, pad.rx);
286 if (angles != GBA_KEY_NONE) {
287 activeKeys |= 1 << angles;
288 }
289 return activeKeys;
290}
291
292void mPSP2SetFrameLimiter(struct mGUIRunner* runner, bool limit) {
293 UNUSED(runner);
294 if (!frameLimiter && limit) {
295 MutexLock(&audioContext.mutex);
296 while (audioContext.samples) {
297 ConditionWait(&audioContext.cond, &audioContext.mutex);
298 }
299 MutexUnlock(&audioContext.mutex);
300 }
301 frameLimiter = limit;
302}
303
304void mPSP2Setup(struct mGUIRunner* runner) {
305 mCoreConfigSetDefaultIntValue(&runner->config, "threadedVideo", 1);
306 mCoreLoadForeignConfig(runner->core, &runner->config);
307
308 mPSP2MapKey(&runner->core->inputMap, SCE_CTRL_CROSS, GBA_KEY_A);
309 mPSP2MapKey(&runner->core->inputMap, SCE_CTRL_CIRCLE, GBA_KEY_B);
310 mPSP2MapKey(&runner->core->inputMap, SCE_CTRL_START, GBA_KEY_START);
311 mPSP2MapKey(&runner->core->inputMap, SCE_CTRL_SELECT, GBA_KEY_SELECT);
312 mPSP2MapKey(&runner->core->inputMap, SCE_CTRL_UP, GBA_KEY_UP);
313 mPSP2MapKey(&runner->core->inputMap, SCE_CTRL_DOWN, GBA_KEY_DOWN);
314 mPSP2MapKey(&runner->core->inputMap, SCE_CTRL_LEFT, GBA_KEY_LEFT);
315 mPSP2MapKey(&runner->core->inputMap, SCE_CTRL_RIGHT, GBA_KEY_RIGHT);
316 mPSP2MapKey(&runner->core->inputMap, SCE_CTRL_L1, GBA_KEY_L);
317 mPSP2MapKey(&runner->core->inputMap, SCE_CTRL_R1, GBA_KEY_R);
318
319 struct mInputAxis desc = { GBA_KEY_DOWN, GBA_KEY_UP, 192, 64 };
320 mInputBindAxis(&runner->core->inputMap, PSP2_INPUT, 0, &desc);
321 desc = (struct mInputAxis) { GBA_KEY_RIGHT, GBA_KEY_LEFT, 192, 64 };
322 mInputBindAxis(&runner->core->inputMap, PSP2_INPUT, 1, &desc);
323
324 unsigned width, height;
325 runner->core->desiredVideoDimensions(runner->core, &width, &height);
326 tex = vita2d_create_empty_texture_format(256, toPow2(height), SCE_GXM_TEXTURE_FORMAT_X8U8U8U8_1BGR);
327 oldTex = vita2d_create_empty_texture_format(256, toPow2(height), SCE_GXM_TEXTURE_FORMAT_X8U8U8U8_1BGR);
328 screenshot = vita2d_create_empty_texture_format(256, toPow2(height), SCE_GXM_TEXTURE_FORMAT_X8U8U8U8_1BGR);
329
330 outputBuffer = anonymousMemoryMap(256 * toPow2(height) * 4);
331 runner->core->setVideoBuffer(runner->core, outputBuffer, 256);
332 runner->core->setAudioBufferSize(runner->core, PSP2_SAMPLES);
333
334 rotation.d.sample = _sampleRotation;
335 rotation.d.readTiltX = _readTiltX;
336 rotation.d.readTiltY = _readTiltY;
337 rotation.d.readGyroZ = _readGyroZ;
338 runner->core->setPeripheral(runner->core, mPERIPH_ROTATION, &rotation.d);
339
340 rumble.d.setRumble = _setRumble;
341 CircleBufferInit(&rumble.history, RUMBLE_PWM);
342 runner->core->setPeripheral(runner->core, mPERIPH_RUMBLE, &rumble.d);
343
344 camera.d.startRequestImage = _startRequestImage;
345 camera.d.stopRequestImage = _stopRequestImage;
346 camera.d.requestImage = _requestImage;
347 camera.buffer = NULL;
348 camera.cam = 1;
349 runner->core->setPeripheral(runner->core, mPERIPH_IMAGE_SOURCE, &camera.d);
350
351
352 stream.videoDimensionsChanged = NULL;
353 stream.postAudioFrame = NULL;
354 stream.postAudioBuffer = _postAudioBuffer;
355 stream.postVideoFrame = NULL;
356 runner->core->setAVStream(runner->core, &stream);
357
358 frameLimiter = true;
359 backdrop = vita2d_load_PNG_buffer(_binary_backdrop_png_start);
360
361 unsigned mode;
362 if (mCoreConfigGetUIntValue(&runner->config, "screenMode", &mode) && mode < SM_MAX) {
363 screenMode = mode;
364 }
365 if (mCoreConfigGetUIntValue(&runner->config, "camera", &mode)) {
366 camera.cam = mode;
367 }
368}
369
370void mPSP2LoadROM(struct mGUIRunner* runner) {
371 float rate = 60.0f / 1.001f;
372 sceDisplayGetRefreshRate(&rate);
373 double ratio = GBAAudioCalculateRatio(1, rate, 1);
374 blip_set_rates(runner->core->getAudioChannel(runner->core, 0), runner->core->frequency(runner->core), 48000 * ratio);
375 blip_set_rates(runner->core->getAudioChannel(runner->core, 1), runner->core->frequency(runner->core), 48000 * ratio);
376
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 sceMotionStartSampling();
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 sceMotionStartSampling();
389 }
390 break;
391#endif
392 default:
393 break;
394 }
395
396 int fakeBool;
397 if (mCoreConfigGetIntValue(&runner->config, "interframeBlending", &fakeBool)) {
398 interframeBlending = fakeBool;
399 }
400
401 // Backcompat: Old versions of mGBA use an older binding system that has different mappings for L/R
402 if (!sceKernelIsPSVitaTV()) {
403 int key = mInputMapKey(&runner->core->inputMap, PSP2_INPUT, __builtin_ctz(SCE_CTRL_L2));
404 if (key >= 0) {
405 mPSP2MapKey(&runner->core->inputMap, SCE_CTRL_L1, key);
406 }
407 key = mInputMapKey(&runner->core->inputMap, PSP2_INPUT, __builtin_ctz(SCE_CTRL_R2));
408 if (key >= 0) {
409 mPSP2MapKey(&runner->core->inputMap, SCE_CTRL_R1, key);
410 }
411 }
412
413 MutexInit(&audioContext.mutex);
414 ConditionInit(&audioContext.cond);
415 memset(audioContext.buffer, 0, sizeof(audioContext.buffer));
416 audioContext.readOffset = 0;
417 audioContext.writeOffset = 0;
418 audioContext.running = true;
419 ThreadCreate(&audioThread, _audioThread, &audioContext);
420}
421
422
423void mPSP2UnloadROM(struct mGUIRunner* runner) {
424 switch (runner->core->platform(runner->core)) {
425#ifdef M_CORE_GBA
426 case PLATFORM_GBA:
427 if (((struct GBA*) runner->core->board)->memory.hw.devices & (HW_TILT | HW_GYRO)) {
428 sceMotionStopSampling();
429 }
430 break;
431#endif
432#ifdef M_CORE_GB
433 case PLATFORM_GB:
434 if (((struct GB*) runner->core->board)->memory.mbcType == GB_MBC7) {
435 sceMotionStopSampling();
436 }
437 break;
438#endif
439 default:
440 break;
441 }
442 audioContext.running = false;
443 ThreadJoin(&audioThread);
444}
445
446void mPSP2Paused(struct mGUIRunner* runner) {
447 UNUSED(runner);
448 struct SceCtrlActuator state = {
449 0,
450 0
451 };
452 sceCtrlSetActuator(1, &state);
453 frameLimiter = true;
454}
455
456void mPSP2Unpaused(struct mGUIRunner* runner) {
457 unsigned mode;
458 if (mCoreConfigGetUIntValue(&runner->config, "screenMode", &mode) && mode != screenMode) {
459 screenMode = mode;
460 }
461
462 if (mCoreConfigGetUIntValue(&runner->config, "camera", &mode)) {
463 if (mode != camera.cam) {
464 if (camera.buffer) {
465 sceCameraStop(camera.cam - 1);
466 sceCameraClose(camera.cam - 1);
467 }
468 camera.cam = mode;
469 if (camera.buffer) {
470 _resetCamera(&camera);
471 }
472 }
473 }
474
475 int fakeBool;
476 mCoreConfigGetIntValue(&runner->config, "interframeBlending", &fakeBool);
477 interframeBlending = fakeBool;
478}
479
480void mPSP2Teardown(struct mGUIRunner* runner) {
481 UNUSED(runner);
482 CircleBufferDeinit(&rumble.history);
483 vita2d_free_texture(tex);
484 vita2d_free_texture(oldTex);
485 vita2d_free_texture(screenshot);
486 mappedMemoryFree(outputBuffer, 256 * 256 * 4);
487 frameLimiter = true;
488}
489
490void _drawTex(vita2d_texture* t, unsigned width, unsigned height, bool faded, bool interframe) {
491 unsigned w = width;
492 unsigned h = height;
493 // Get greatest common divisor
494 while (w != 0) {
495 int temp = h % w;
496 h = w;
497 w = temp;
498 }
499 int gcd = h;
500 int aspectw = width / gcd;
501 int aspecth = height / gcd;
502 float scalex;
503 float scaley;
504
505 unsigned tint = 0x1FFFFFFF;
506 if (!faded) {
507 if (interframe) {
508 tint |= 0x60000000;
509 } else {
510 tint |= 0xE0000000;
511 }
512 } else if (!interframe) {
513 tint |= 0x20000000;
514 }
515
516 switch (screenMode) {
517 case SM_BACKDROP:
518 default:
519 vita2d_draw_texture_tint(backdrop, 0, 0, tint);
520 // Fall through
521 case SM_PLAIN:
522 w = 960 / width;
523 h = 544 / height;
524 if (w * height > 544) {
525 scalex = h;
526 w = width * h;
527 h = height * h;
528 } else {
529 scalex = w;
530 w = width * w;
531 h = height * w;
532 }
533 scaley = scalex;
534 break;
535 case SM_ASPECT:
536 w = 960 / aspectw;
537 h = 544 / aspecth;
538 if (w * aspecth > 544) {
539 w = aspectw * h;
540 h = aspecth * h;
541 } else {
542 w = aspectw * w;
543 h = aspecth * w;
544 }
545 scalex = w / (float) width;
546 scaley = scalex;
547 break;
548 case SM_FULL:
549 w = 960;
550 h = 544;
551 scalex = 960.0f / width;
552 scaley = 544.0f / height;
553 break;
554 }
555 vita2d_draw_texture_tint_part_scale(t,
556 (960.0f - w) / 2.0f, (544.0f - h) / 2.0f,
557 0, 0, width, height,
558 scalex, scaley,
559 tint);
560}
561
562void mPSP2Draw(struct mGUIRunner* runner, bool faded) {
563 unsigned width, height;
564 runner->core->desiredVideoDimensions(runner->core, &width, &height);
565 void* texpixels = vita2d_texture_get_datap(tex);
566 if (interframeBlending) {
567 void* oldTexpixels = vita2d_texture_get_datap(oldTex);
568 memcpy(oldTexpixels, texpixels, 256 * height * 4);
569 _drawTex(oldTex, width, height, faded, false);
570 }
571 memcpy(texpixels, outputBuffer, 256 * height * 4);
572 _drawTex(tex, width, height, faded, interframeBlending);
573}
574
575void mPSP2DrawScreenshot(struct mGUIRunner* runner, const uint32_t* pixels, unsigned width, unsigned height, bool faded) {
576 UNUSED(runner);
577 uint32_t* texpixels = vita2d_texture_get_datap(screenshot);
578 unsigned y;
579 for (y = 0; y < height; ++y) {
580 memcpy(&texpixels[256 * y], &pixels[width * y], width * 4);
581 }
582 _drawTex(screenshot, width, height, faded, false);
583}
584
585void mPSP2IncrementScreenMode(struct mGUIRunner* runner) {
586 screenMode = (screenMode + 1) % SM_MAX;
587 mCoreConfigSetUIntValue(&runner->config, "screenMode", screenMode);
588}
589
590bool mPSP2SystemPoll(struct mGUIRunner* runner) {
591 SceAppMgrSystemEvent event;
592 if (sceAppMgrReceiveSystemEvent(&event) < 0) {
593 return true;
594 }
595 if (event.systemEvent == SCE_APPMGR_SYSTEMEVENT_ON_RESUME) {
596 mLOG(GUI_PSP2, INFO, "Suspend detected, reloading save");
597 mCoreAutoloadSave(runner->core);
598 }
599 return true;
600}
601
602__attribute__((noreturn, weak)) void __assert_func(const char* file, int line, const char* func, const char* expr) {
603 printf("ASSERT FAILED: %s in %s at %s:%i\n", expr, func, file, line);
604 exit(1);
605}