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