all repos — mgba @ 22400e336f2fb1b7aa994a8e0e666b8f78fc6fd3

mGBA Game Boy Advance Emulator

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/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
 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 256
 67#define PSP2_AUDIO_BUFFER_SIZE (PSP2_SAMPLES * 20)
 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	mPSP2MapKey(&runner->core->inputMap, SCE_CTRL_CROSS, GBA_KEY_A);
180	mPSP2MapKey(&runner->core->inputMap, SCE_CTRL_CIRCLE, GBA_KEY_B);
181	mPSP2MapKey(&runner->core->inputMap, SCE_CTRL_START, GBA_KEY_START);
182	mPSP2MapKey(&runner->core->inputMap, SCE_CTRL_SELECT, GBA_KEY_SELECT);
183	mPSP2MapKey(&runner->core->inputMap, SCE_CTRL_UP, GBA_KEY_UP);
184	mPSP2MapKey(&runner->core->inputMap, SCE_CTRL_DOWN, GBA_KEY_DOWN);
185	mPSP2MapKey(&runner->core->inputMap, SCE_CTRL_LEFT, GBA_KEY_LEFT);
186	mPSP2MapKey(&runner->core->inputMap, SCE_CTRL_RIGHT, GBA_KEY_RIGHT);
187	mPSP2MapKey(&runner->core->inputMap, SCE_CTRL_LTRIGGER, GBA_KEY_L);
188	mPSP2MapKey(&runner->core->inputMap, SCE_CTRL_RTRIGGER, GBA_KEY_R);
189
190	struct mInputAxis desc = { GBA_KEY_DOWN, GBA_KEY_UP, 192, 64 };
191	mInputBindAxis(&runner->core->inputMap, PSP2_INPUT, 0, &desc);
192	desc = (struct mInputAxis) { GBA_KEY_RIGHT, GBA_KEY_LEFT, 192, 64 };
193	mInputBindAxis(&runner->core->inputMap, PSP2_INPUT, 1, &desc);
194
195	unsigned width, height;
196	runner->core->desiredVideoDimensions(runner->core, &width, &height);
197	tex = vita2d_create_empty_texture_format(256, toPow2(height), SCE_GXM_TEXTURE_FORMAT_X8U8U8U8_1BGR);
198	screenshot = vita2d_create_empty_texture_format(256, toPow2(height), SCE_GXM_TEXTURE_FORMAT_X8U8U8U8_1BGR);
199
200	outputBuffer = vita2d_texture_get_datap(tex);
201	runner->core->setVideoBuffer(runner->core, outputBuffer, 256);
202
203	rotation.d.sample = _sampleRotation;
204	rotation.d.readTiltX = _readTiltX;
205	rotation.d.readTiltY = _readTiltY;
206	rotation.d.readGyroZ = _readGyroZ;
207	runner->core->setPeripheral(runner->core, mPERIPH_ROTATION, &rotation.d);
208
209	rumble.d.setRumble = _setRumble;
210	CircleBufferInit(&rumble.history, RUMBLE_PWM);
211	runner->core->setPeripheral(runner->core, mPERIPH_RUMBLE, &rumble.d);
212
213	frameLimiter = true;
214	backdrop = vita2d_load_PNG_buffer(_binary_backdrop_png_start);
215
216	unsigned mode;
217	if (mCoreConfigGetUIntValue(&runner->config, "screenMode", &mode) && mode < SM_MAX) {
218		screenMode = mode;
219	}
220}
221
222void mPSP2LoadROM(struct mGUIRunner* runner) {
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		}
266		blip_read_samples(runner->core->getAudioChannel(runner->core, 0), &samples[0].left, PSP2_SAMPLES, true);
267		blip_read_samples(runner->core->getAudioChannel(runner->core, 1), &samples[0].right, PSP2_SAMPLES, true);
268		while (!RingFIFOWrite(&audioContext.buffer, NULL, PSP2_SAMPLES * 4)) {
269			ConditionWake(&audioContext.cond);
270			// Spinloooooooop!
271		}
272		MutexLock(&audioContext.mutex);
273		audioContext.samples += PSP2_SAMPLES;
274		nSamples = audioContext.samples;
275		ConditionWake(&audioContext.cond);
276		MutexUnlock(&audioContext.mutex);
277	}
278}
279
280void mPSP2UnloadROM(struct mGUIRunner* runner) {
281	switch (runner->core->platform(runner->core)) {
282#ifdef M_CORE_GBA
283	case PLATFORM_GBA:
284		if (((struct GBA*) runner->core->board)->memory.hw.devices & (HW_TILT | HW_GYRO)) {
285			sceMotionStopSampling();
286		}
287		break;
288#endif
289#ifdef M_CORE_GB
290	case PLATFORM_GB:
291		if (((struct GB*) runner->core->board)->memory.mbcType == GB_MBC7) {
292			sceMotionStopSampling();
293		}
294		break;
295#endif
296	default:
297		break;
298	}
299}
300
301void mPSP2Paused(struct mGUIRunner* runner) {
302	UNUSED(runner);
303	struct SceCtrlActuator state = {
304		0,
305		0
306	};
307	sceCtrlSetActuator(1, &state);
308	frameLimiter = true;
309}
310
311void mPSP2Unpaused(struct mGUIRunner* runner) {
312	unsigned mode;
313	if (mCoreConfigGetUIntValue(&runner->config, "screenMode", &mode) && mode != screenMode) {
314		screenMode = mode;
315	}
316}
317
318void mPSP2Teardown(struct mGUIRunner* runner) {
319	UNUSED(runner);
320	CircleBufferDeinit(&rumble.history);
321	vita2d_free_texture(tex);
322	vita2d_free_texture(screenshot);
323	frameLimiter = true;
324}
325
326void _drawTex(vita2d_texture* t, unsigned width, unsigned height, bool faded) {
327	unsigned w = width;
328	unsigned h = height;
329	// Get greatest common divisor
330	while (w != 0) {
331		int temp = h % w;
332		h = w;
333		w = temp;
334	}
335	int gcd = h;
336	int aspectw = width / gcd;
337	int aspecth = height / gcd;
338	float scalex;
339	float scaley;
340
341	switch (screenMode) {
342	case SM_BACKDROP:
343	default:
344		vita2d_draw_texture_tint(backdrop, 0, 0, (faded ? 0 : 0xC0000000) | 0x3FFFFFFF);
345		// Fall through
346	case SM_PLAIN:
347		w = 960 / width;
348		h = 544 / height;
349		if (w * height > 544) {
350			scalex = h;
351			w = width * h;
352			h = height * h;
353		} else {
354			scalex = w;
355			w = width * w;
356			h = height * w;
357		}
358		scaley = scalex;
359		break;
360	case SM_ASPECT:
361		w = 960 / aspectw;
362		h = 544 / aspecth;
363		if (w * aspecth > 544) {
364			w = aspectw * h;
365			h = aspecth * h;
366		} else {
367			w = aspectw * w;
368			h = aspecth * w;
369		}
370		scalex = w / (float) width;
371		scaley = scalex;
372		break;
373	case SM_FULL:
374		w = 960;
375		h = 544;
376		scalex = 960.0f / width;
377		scaley = 544.0f / height;
378		break;
379	}
380	vita2d_draw_texture_tint_part_scale(t,
381	                                    (960.0f - w) / 2.0f, (544.0f - h) / 2.0f,
382	                                    0, 0, width, height,
383	                                    scalex, scaley,
384	                                    (faded ? 0 : 0xC0000000) | 0x3FFFFFFF);
385}
386
387void mPSP2Draw(struct mGUIRunner* runner, bool faded) {
388	unsigned width, height;
389	runner->core->desiredVideoDimensions(runner->core, &width, &height);
390	_drawTex(tex, width, height, faded);
391}
392
393void mPSP2DrawScreenshot(struct mGUIRunner* runner, const uint32_t* pixels, unsigned width, unsigned height, bool faded) {
394	UNUSED(runner);
395	uint32_t* texpixels = vita2d_texture_get_datap(screenshot);
396	unsigned y;
397	for (y = 0; y < height; ++y) {
398		memcpy(&texpixels[256 * y], &pixels[width * y], width * 4);
399	}
400	_drawTex(screenshot, width, height, faded);
401}
402
403void mPSP2IncrementScreenMode(struct mGUIRunner* runner) {
404	screenMode = (screenMode + 1) % SM_MAX;
405	mCoreConfigSetUIntValue(&runner->config, "screenMode", screenMode);
406}
407
408__attribute__((noreturn, weak)) void __assert_func(const char* file, int line, const char* func, const char* expr) {
409	printf("ASSERT FAILED: %s in %s at %s:%i\n", expr, func, file, line);
410	exit(1);
411}