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/ring-fifo.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/ctrl.h>
30#include <psp2/display.h>
31#include <psp2/gxm.h>
32#include <psp2/kernel/sysmem.h>
33#include <psp2/motion.h>
34#include <psp2/power.h>
35
36#include <vita2d.h>
37
38#define RUMBLE_PWM 8
39
40static enum ScreenMode {
41 SM_BACKDROP,
42 SM_PLAIN,
43 SM_FULL,
44 SM_ASPECT,
45 SM_MAX
46} screenMode;
47
48static void* outputBuffer;
49static vita2d_texture* tex;
50static vita2d_texture* screenshot;
51static Thread audioThread;
52static struct mSceRotationSource {
53 struct mRotationSource d;
54 struct SceMotionSensorState state;
55} rotation;
56static struct mSceRumble {
57 struct mRumble d;
58 struct CircleBuffer history;
59 int current;
60} rumble;
61bool frameLimiter = true;
62
63extern const uint8_t _binary_backdrop_png_start[];
64static vita2d_texture* backdrop = 0;
65
66#define PSP2_SAMPLES 128
67#define PSP2_AUDIO_BUFFER_SIZE (PSP2_SAMPLES * 40)
68
69static struct mPSP2AudioContext {
70 struct RingFIFO buffer;
71 size_t samples;
72 Mutex mutex;
73 Condition cond;
74 bool running;
75} audioContext;
76
77void mPSP2MapKey(struct mInputMap* map, int pspKey, int key) {
78 mInputBindKey(map, PSP2_INPUT, __builtin_ctz(pspKey), key);
79}
80
81static THREAD_ENTRY _audioThread(void* context) {
82 struct mPSP2AudioContext* audio = (struct mPSP2AudioContext*) context;
83 int audioPort = sceAudioOutOpenPort(SCE_AUDIO_OUT_PORT_TYPE_MAIN, PSP2_SAMPLES, 48000, SCE_AUDIO_OUT_MODE_STEREO);
84 while (audio->running) {
85 MutexLock(&audio->mutex);
86 int len = audio->samples;
87 if (len > PSP2_SAMPLES) {
88 len = PSP2_SAMPLES;
89 }
90 struct GBAStereoSample* buffer = audio->buffer.readPtr;
91 RingFIFORead(&audio->buffer, NULL, len * 4);
92 audio->samples -= len;
93 ConditionWake(&audio->cond);
94
95 MutexUnlock(&audio->mutex);
96 sceAudioOutOutput(audioPort, buffer);
97 MutexLock(&audio->mutex);
98
99 if (audio->samples < PSP2_SAMPLES) {
100 ConditionWait(&audio->cond, &audio->mutex);
101 }
102 MutexUnlock(&audio->mutex);
103 }
104 sceAudioOutReleasePort(audioPort);
105 return 0;
106}
107
108static void _sampleRotation(struct mRotationSource* source) {
109 struct mSceRotationSource* rotation = (struct mSceRotationSource*) source;
110 sceMotionGetSensorState(&rotation->state, 1);
111}
112
113static int32_t _readTiltX(struct mRotationSource* source) {
114 struct mSceRotationSource* rotation = (struct mSceRotationSource*) source;
115 return rotation->state.accelerometer.x * 0x30000000;
116}
117
118static int32_t _readTiltY(struct mRotationSource* source) {
119 struct mSceRotationSource* rotation = (struct mSceRotationSource*) source;
120 return rotation->state.accelerometer.y * -0x30000000;
121}
122
123static int32_t _readGyroZ(struct mRotationSource* source) {
124 struct mSceRotationSource* rotation = (struct mSceRotationSource*) source;
125 return rotation->state.gyro.z * -0x10000000;
126}
127
128static void _setRumble(struct mRumble* source, int enable) {
129 struct mSceRumble* rumble = (struct mSceRumble*) source;
130 rumble->current += enable;
131 if (CircleBufferSize(&rumble->history) == RUMBLE_PWM) {
132 int8_t oldLevel;
133 CircleBufferRead8(&rumble->history, &oldLevel);
134 rumble->current -= oldLevel;
135 }
136 CircleBufferWrite8(&rumble->history, enable);
137 int small = (rumble->current << 21) / 65793;
138 int big = ((rumble->current * rumble->current) << 18) / 65793;
139 struct SceCtrlActuator state = {
140 small,
141 big
142 };
143 sceCtrlSetActuator(1, &state);
144}
145
146uint16_t mPSP2PollInput(struct mGUIRunner* runner) {
147 SceCtrlData pad;
148 sceCtrlPeekBufferPositive(0, &pad, 1);
149
150 int activeKeys = mInputMapKeyBits(&runner->core->inputMap, PSP2_INPUT, pad.buttons, 0);
151 int angles = mInputMapAxis(&runner->core->inputMap, PSP2_INPUT, 0, pad.ly);
152 if (angles != GBA_KEY_NONE) {
153 activeKeys |= 1 << angles;
154 }
155 angles = mInputMapAxis(&runner->core->inputMap, PSP2_INPUT, 1, pad.lx);
156 if (angles != GBA_KEY_NONE) {
157 activeKeys |= 1 << angles;
158 }
159 angles = mInputMapAxis(&runner->core->inputMap, PSP2_INPUT, 2, pad.ry);
160 if (angles != GBA_KEY_NONE) {
161 activeKeys |= 1 << angles;
162 }
163 angles = mInputMapAxis(&runner->core->inputMap, PSP2_INPUT, 3, pad.rx);
164 if (angles != GBA_KEY_NONE) {
165 activeKeys |= 1 << angles;
166 }
167 return activeKeys;
168}
169
170void mPSP2SetFrameLimiter(struct mGUIRunner* runner, bool limit) {
171 UNUSED(runner);
172 frameLimiter = limit;
173}
174
175void mPSP2Setup(struct mGUIRunner* runner) {
176 mCoreConfigSetDefaultIntValue(&runner->config, "threadedVideo", 1);
177 mCoreLoadForeignConfig(runner->core, &runner->config);
178
179 scePowerSetArmClockFrequency(333);
180 mPSP2MapKey(&runner->core->inputMap, SCE_CTRL_CROSS, GBA_KEY_A);
181 mPSP2MapKey(&runner->core->inputMap, SCE_CTRL_CIRCLE, GBA_KEY_B);
182 mPSP2MapKey(&runner->core->inputMap, SCE_CTRL_START, GBA_KEY_START);
183 mPSP2MapKey(&runner->core->inputMap, SCE_CTRL_SELECT, GBA_KEY_SELECT);
184 mPSP2MapKey(&runner->core->inputMap, SCE_CTRL_UP, GBA_KEY_UP);
185 mPSP2MapKey(&runner->core->inputMap, SCE_CTRL_DOWN, GBA_KEY_DOWN);
186 mPSP2MapKey(&runner->core->inputMap, SCE_CTRL_LEFT, GBA_KEY_LEFT);
187 mPSP2MapKey(&runner->core->inputMap, SCE_CTRL_RIGHT, GBA_KEY_RIGHT);
188 mPSP2MapKey(&runner->core->inputMap, SCE_CTRL_LTRIGGER, GBA_KEY_L);
189 mPSP2MapKey(&runner->core->inputMap, SCE_CTRL_RTRIGGER, GBA_KEY_R);
190
191 struct mInputAxis desc = { GBA_KEY_DOWN, GBA_KEY_UP, 192, 64 };
192 mInputBindAxis(&runner->core->inputMap, PSP2_INPUT, 0, &desc);
193 desc = (struct mInputAxis) { GBA_KEY_RIGHT, GBA_KEY_LEFT, 192, 64 };
194 mInputBindAxis(&runner->core->inputMap, PSP2_INPUT, 1, &desc);
195
196 tex = vita2d_create_empty_texture_format(256, 256, SCE_GXM_TEXTURE_FORMAT_X8U8U8U8_1BGR);
197 screenshot = vita2d_create_empty_texture_format(256, 256, SCE_GXM_TEXTURE_FORMAT_X8U8U8U8_1BGR);
198
199 outputBuffer = vita2d_texture_get_datap(tex);
200 runner->core->setVideoBuffer(runner->core, outputBuffer, 256);
201
202 rotation.d.sample = _sampleRotation;
203 rotation.d.readTiltX = _readTiltX;
204 rotation.d.readTiltY = _readTiltY;
205 rotation.d.readGyroZ = _readGyroZ;
206 runner->core->setRotation(runner->core, &rotation.d);
207
208 rumble.d.setRumble = _setRumble;
209 CircleBufferInit(&rumble.history, RUMBLE_PWM);
210 runner->core->setRumble(runner->core, &rumble.d);
211
212 frameLimiter = true;
213 backdrop = vita2d_load_PNG_buffer(_binary_backdrop_png_start);
214
215 unsigned mode;
216 if (mCoreConfigGetUIntValue(&runner->config, "screenMode", &mode) && mode < SM_MAX) {
217 screenMode = mode;
218 }
219}
220
221void mPSP2LoadROM(struct mGUIRunner* runner) {
222 scePowerSetArmClockFrequency(444);
223 float rate = 60.0f / 1.001f;
224 sceDisplayGetRefreshRate(&rate);
225 double ratio = GBAAudioCalculateRatio(1, rate, 1);
226 blip_set_rates(runner->core->getAudioChannel(runner->core, 0), runner->core->frequency(runner->core), 48000 * ratio);
227 blip_set_rates(runner->core->getAudioChannel(runner->core, 1), runner->core->frequency(runner->core), 48000 * ratio);
228
229 switch (runner->core->platform(runner->core)) {
230#ifdef M_CORE_GBA
231 case PLATFORM_GBA:
232 if (((struct GBA*) runner->core->board)->memory.hw.devices & (HW_TILT | HW_GYRO)) {
233 sceMotionStartSampling();
234 }
235 break;
236#endif
237#ifdef M_CORE_GB
238 case PLATFORM_GB:
239 if (((struct GB*) runner->core->board)->memory.mbcType == GB_MBC7) {
240 sceMotionStartSampling();
241 }
242 break;
243#endif
244 default:
245 break;
246 }
247
248 RingFIFOInit(&audioContext.buffer, PSP2_AUDIO_BUFFER_SIZE * sizeof(struct GBAStereoSample));
249 MutexInit(&audioContext.mutex);
250 ConditionInit(&audioContext.cond);
251 audioContext.running = true;
252 ThreadCreate(&audioThread, _audioThread, &audioContext);
253}
254
255void mPSP2PrepareForFrame(struct mGUIRunner* runner) {
256 int nSamples = 0;
257 while (blip_samples_avail(runner->core->getAudioChannel(runner->core, 0)) >= PSP2_SAMPLES) {
258 struct GBAStereoSample* samples = audioContext.buffer.writePtr;
259 if (nSamples > (PSP2_AUDIO_BUFFER_SIZE >> 2) + (PSP2_AUDIO_BUFFER_SIZE >> 1)) { // * 0.75
260 if (!frameLimiter) {
261 blip_clear(runner->core->getAudioChannel(runner->core, 0));
262 blip_clear(runner->core->getAudioChannel(runner->core, 1));
263 break;
264 }
265 sceKernelDelayThread(400);
266 }
267 blip_read_samples(runner->core->getAudioChannel(runner->core, 0), &samples[0].left, PSP2_SAMPLES, true);
268 blip_read_samples(runner->core->getAudioChannel(runner->core, 1), &samples[0].right, PSP2_SAMPLES, true);
269 while (!RingFIFOWrite(&audioContext.buffer, NULL, PSP2_SAMPLES * 4)) {
270 ConditionWake(&audioContext.cond);
271 // Spinloooooooop!
272 }
273 MutexLock(&audioContext.mutex);
274 audioContext.samples += PSP2_SAMPLES;
275 nSamples = audioContext.samples;
276 ConditionWake(&audioContext.cond);
277 MutexUnlock(&audioContext.mutex);
278 }
279}
280
281void mPSP2UnloadROM(struct mGUIRunner* runner) {
282 switch (runner->core->platform(runner->core)) {
283#ifdef M_CORE_GBA
284 case PLATFORM_GBA:
285 if (((struct GBA*) runner->core->board)->memory.hw.devices & (HW_TILT | HW_GYRO)) {
286 sceMotionStopSampling();
287 }
288 break;
289#endif
290#ifdef M_CORE_GB
291 case PLATFORM_GB:
292 if (((struct GB*) runner->core->board)->memory.mbcType == GB_MBC7) {
293 sceMotionStopSampling();
294 }
295 break;
296#endif
297 default:
298 break;
299 }
300 scePowerSetArmClockFrequency(333);
301}
302
303void mPSP2Paused(struct mGUIRunner* runner) {
304 UNUSED(runner);
305 struct SceCtrlActuator state = {
306 0,
307 0
308 };
309 sceCtrlSetActuator(1, &state);
310 frameLimiter = true;
311}
312
313void mPSP2Unpaused(struct mGUIRunner* runner) {
314 unsigned mode;
315 if (mCoreConfigGetUIntValue(&runner->config, "screenMode", &mode) && mode != screenMode) {
316 screenMode = mode;
317 }
318}
319
320void mPSP2Teardown(struct mGUIRunner* runner) {
321 UNUSED(runner);
322 CircleBufferDeinit(&rumble.history);
323 vita2d_free_texture(tex);
324 vita2d_free_texture(screenshot);
325 frameLimiter = true;
326}
327
328void _drawTex(vita2d_texture* t, unsigned width, unsigned height, bool faded) {
329 unsigned w = width;
330 unsigned h = height;
331 // Get greatest common divisor
332 while (w != 0) {
333 int temp = h % w;
334 h = w;
335 w = temp;
336 }
337 int gcd = h;
338 int aspectw = width / gcd;
339 int aspecth = height / gcd;
340 float scalex;
341 float scaley;
342
343 switch (screenMode) {
344 case SM_BACKDROP:
345 default:
346 vita2d_draw_texture_tint(backdrop, 0, 0, (faded ? 0 : 0xC0000000) | 0x3FFFFFFF);
347 // Fall through
348 case SM_PLAIN:
349 w = 960 / width;
350 h = 544 / height;
351 if (w * height > 544) {
352 scalex = h;
353 w = width * h;
354 h = height * h;
355 } else {
356 scalex = w;
357 w = width * w;
358 h = height * w;
359 }
360 scaley = scalex;
361 break;
362 case SM_ASPECT:
363 w = 960 / aspectw;
364 h = 544 / aspecth;
365 if (w * aspecth > 544) {
366 w = aspectw * h;
367 h = aspecth * h;
368 } else {
369 w = aspectw * w;
370 h = aspecth * w;
371 }
372 scalex = w / (float) width;
373 scaley = scalex;
374 break;
375 case SM_FULL:
376 w = 960;
377 h = 544;
378 scalex = 960.0f / width;
379 scaley = 544.0f / height;
380 break;
381 }
382 vita2d_draw_texture_tint_part_scale(t,
383 (960.0f - w) / 2.0f, (544.0f - h) / 2.0f,
384 0, 0, width, height,
385 scalex, scaley,
386 (faded ? 0 : 0xC0000000) | 0x3FFFFFFF);
387}
388
389void mPSP2Draw(struct mGUIRunner* runner, bool faded) {
390 unsigned width, height;
391 runner->core->desiredVideoDimensions(runner->core, &width, &height);
392 _drawTex(tex, width, height, faded);
393}
394
395void mPSP2DrawScreenshot(struct mGUIRunner* runner, const uint32_t* pixels, unsigned width, unsigned height, bool faded) {
396 UNUSED(runner);
397 uint32_t* texpixels = vita2d_texture_get_datap(screenshot);
398 unsigned y;
399 for (y = 0; y < height; ++y) {
400 memcpy(&texpixels[256 * y], &pixels[width * y], width * 4);
401 }
402 _drawTex(screenshot, width, height, faded);
403}
404
405void mPSP2IncrementScreenMode(struct mGUIRunner* runner) {
406 screenMode = (screenMode + 1) % SM_MAX;
407 mCoreConfigSetUIntValue(&runner->config, "screenMode", screenMode);
408}
409
410__attribute__((noreturn, weak)) void __assert_func(const char* file, int line, const char* func, const char* expr) {
411 printf("ASSERT FAILED: %s in %s at %s:%i\n", expr, func, file, line);
412 exit(1);
413}