all repos — mgba @ 026f5233db5a96707d2b4a06f0b22747f0b16b71

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 "core/core.h"
  9
 10#ifdef M_CORE_GBA
 11#include "gba/gba.h"
 12#endif
 13#ifdef M_CORE_GB
 14#include "gb/gb.h"
 15#endif
 16
 17#include "feature/gui/gui-runner.h"
 18#include "gba/input.h"
 19
 20#include "util/memory.h"
 21#include "util/circle-buffer.h"
 22#include "util/ring-fifo.h"
 23#include "util/threading.h"
 24#include "util/vfs.h"
 25#include "platform/psp2/sce-vfs.h"
 26#include "third-party/blip_buf/blip_buf.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	struct SceCtrlActuator state = {
138		rumble->current * 31,
139		0
140	};
141	sceCtrlSetActuator(1, &state);
142}
143
144uint16_t mPSP2PollInput(struct mGUIRunner* runner) {
145	SceCtrlData pad;
146	sceCtrlPeekBufferPositive(0, &pad, 1);
147
148	int activeKeys = mInputMapKeyBits(&runner->core->inputMap, PSP2_INPUT, pad.buttons, 0);
149	int angles = mInputMapAxis(&runner->core->inputMap, PSP2_INPUT, 0, pad.ly);
150	if (angles != GBA_KEY_NONE) {
151		activeKeys |= 1 << angles;
152	}
153	angles = mInputMapAxis(&runner->core->inputMap, PSP2_INPUT, 1, pad.lx);
154	if (angles != GBA_KEY_NONE) {
155		activeKeys |= 1 << angles;
156	}
157	angles = mInputMapAxis(&runner->core->inputMap, PSP2_INPUT, 2, pad.ry);
158	if (angles != GBA_KEY_NONE) {
159		activeKeys |= 1 << angles;
160	}
161	angles = mInputMapAxis(&runner->core->inputMap, PSP2_INPUT, 3, pad.rx);
162	if (angles != GBA_KEY_NONE) {
163		activeKeys |= 1 << angles;
164	}
165	return activeKeys;
166}
167
168void mPSP2SetFrameLimiter(struct mGUIRunner* runner, bool limit) {
169	UNUSED(runner);
170	frameLimiter = limit;
171}
172
173void mPSP2Setup(struct mGUIRunner* runner) {
174	mCoreConfigSetDefaultIntValue(&runner->config, "threadedVideo", 1);
175	mCoreLoadForeignConfig(runner->core, &runner->config);
176
177	scePowerSetArmClockFrequency(80);
178	mPSP2MapKey(&runner->core->inputMap, SCE_CTRL_CROSS, GBA_KEY_A);
179	mPSP2MapKey(&runner->core->inputMap, SCE_CTRL_CIRCLE, GBA_KEY_B);
180	mPSP2MapKey(&runner->core->inputMap, SCE_CTRL_START, GBA_KEY_START);
181	mPSP2MapKey(&runner->core->inputMap, SCE_CTRL_SELECT, GBA_KEY_SELECT);
182	mPSP2MapKey(&runner->core->inputMap, SCE_CTRL_UP, GBA_KEY_UP);
183	mPSP2MapKey(&runner->core->inputMap, SCE_CTRL_DOWN, GBA_KEY_DOWN);
184	mPSP2MapKey(&runner->core->inputMap, SCE_CTRL_LEFT, GBA_KEY_LEFT);
185	mPSP2MapKey(&runner->core->inputMap, SCE_CTRL_RIGHT, GBA_KEY_RIGHT);
186	mPSP2MapKey(&runner->core->inputMap, SCE_CTRL_LTRIGGER, GBA_KEY_L);
187	mPSP2MapKey(&runner->core->inputMap, SCE_CTRL_RTRIGGER, GBA_KEY_R);
188
189	struct mInputAxis desc = { GBA_KEY_DOWN, GBA_KEY_UP, 192, 64 };
190	mInputBindAxis(&runner->core->inputMap, PSP2_INPUT, 0, &desc);
191	desc = (struct mInputAxis) { GBA_KEY_RIGHT, GBA_KEY_LEFT, 192, 64 };
192	mInputBindAxis(&runner->core->inputMap, PSP2_INPUT, 1, &desc);
193
194	tex = vita2d_create_empty_texture_format(256, 256, SCE_GXM_TEXTURE_FORMAT_X8U8U8U8_1BGR);
195	screenshot = vita2d_create_empty_texture_format(256, 256, SCE_GXM_TEXTURE_FORMAT_X8U8U8U8_1BGR);
196
197	outputBuffer = vita2d_texture_get_datap(tex);
198	runner->core->setVideoBuffer(runner->core, outputBuffer, 256);
199
200	rotation.d.sample = _sampleRotation;
201	rotation.d.readTiltX = _readTiltX;
202	rotation.d.readTiltY = _readTiltY;
203	rotation.d.readGyroZ = _readGyroZ;
204	runner->core->setRotation(runner->core, &rotation.d);
205
206	rumble.d.setRumble = _setRumble;
207	CircleBufferInit(&rumble.history, RUMBLE_PWM);
208	runner->core->setRumble(runner->core, &rumble.d);
209
210	frameLimiter = true;
211	backdrop = vita2d_load_PNG_buffer(_binary_backdrop_png_start);
212
213	unsigned mode;
214	if (mCoreConfigGetUIntValue(&runner->config, "screenMode", &mode) && mode < SM_MAX) {
215		screenMode = mode;
216	}
217}
218
219void mPSP2LoadROM(struct mGUIRunner* runner) {
220	scePowerSetArmClockFrequency(444);
221	float rate = 60.0f / 1.001f;
222	sceDisplayGetRefreshRate(&rate);
223	double ratio = GBAAudioCalculateRatio(1, rate, 1);
224	blip_set_rates(runner->core->getAudioChannel(runner->core, 0), runner->core->frequency(runner->core), 48000 * ratio);
225	blip_set_rates(runner->core->getAudioChannel(runner->core, 1), runner->core->frequency(runner->core), 48000 * ratio);
226
227	switch (runner->core->platform(runner->core)) {
228#ifdef M_CORE_GBA
229	case PLATFORM_GBA:
230		if (((struct GBA*) runner->core->board)->memory.hw.devices & (HW_TILT | HW_GYRO)) {
231			sceMotionStartSampling();
232		}
233		break;
234#endif
235#ifdef M_CORE_GB
236	case PLATFORM_GB:
237		if (((struct GB*) runner->core->board)->memory.mbcType == GB_MBC7) {
238			sceMotionStartSampling();
239		}
240		break;
241#endif
242	default:
243		break;
244	}
245
246	RingFIFOInit(&audioContext.buffer, PSP2_AUDIO_BUFFER_SIZE * sizeof(struct GBAStereoSample));
247	MutexInit(&audioContext.mutex);
248	ConditionInit(&audioContext.cond);
249	audioContext.running = true;
250	ThreadCreate(&audioThread, _audioThread, &audioContext);
251}
252
253void mPSP2PrepareForFrame(struct mGUIRunner* runner) {
254	int nSamples = 0;
255	while (blip_samples_avail(runner->core->getAudioChannel(runner->core, 0)) >= PSP2_SAMPLES) {
256		struct GBAStereoSample* samples = audioContext.buffer.writePtr;
257		if (nSamples > (PSP2_AUDIO_BUFFER_SIZE >> 2) + (PSP2_AUDIO_BUFFER_SIZE >> 1)) { // * 0.75
258			if (!frameLimiter) {
259				blip_clear(runner->core->getAudioChannel(runner->core, 0));
260				blip_clear(runner->core->getAudioChannel(runner->core, 1));
261				break;
262			}
263			sceKernelDelayThread(400);
264		}
265		blip_read_samples(runner->core->getAudioChannel(runner->core, 0), &samples[0].left, PSP2_SAMPLES, true);
266		blip_read_samples(runner->core->getAudioChannel(runner->core, 1), &samples[0].right, PSP2_SAMPLES, true);
267		while (!RingFIFOWrite(&audioContext.buffer, NULL, PSP2_SAMPLES * 4)) {
268			ConditionWake(&audioContext.cond);
269			// Spinloooooooop!
270		}
271		MutexLock(&audioContext.mutex);
272		audioContext.samples += PSP2_SAMPLES;
273		nSamples = audioContext.samples;
274		ConditionWake(&audioContext.cond);
275		MutexUnlock(&audioContext.mutex);
276	}
277}
278
279void mPSP2UnloadROM(struct mGUIRunner* runner) {
280	switch (runner->core->platform(runner->core)) {
281#ifdef M_CORE_GBA
282	case PLATFORM_GBA:
283		if (((struct GBA*) runner->core->board)->memory.hw.devices & (HW_TILT | HW_GYRO)) {
284			sceMotionStopSampling();
285		}
286		break;
287#endif
288#ifdef M_CORE_GB
289	case PLATFORM_GB:
290		if (((struct GB*) runner->core->board)->memory.mbcType == GB_MBC7) {
291			sceMotionStopSampling();
292		}
293		break;
294#endif
295	default:
296		break;
297	}
298	scePowerSetArmClockFrequency(80);
299}
300
301void mPSP2Paused(struct mGUIRunner* runner) {
302	UNUSED(runner);
303	struct SceCtrlActuator state = {
304		0,
305		0
306	};
307	sceCtrlSetActuator(1, &state);
308}
309
310void mPSP2Unpaused(struct mGUIRunner* runner) {
311	unsigned mode;
312	if (mCoreConfigGetUIntValue(&runner->config, "screenMode", &mode) && mode != screenMode) {
313		screenMode = mode;
314	}
315}
316
317void mPSP2Teardown(struct mGUIRunner* runner) {
318	CircleBufferDeinit(&rumble.history);
319	vita2d_free_texture(tex);
320	vita2d_free_texture(screenshot);
321	frameLimiter = true;
322}
323
324void _drawTex(vita2d_texture* t, unsigned width, unsigned height, bool faded) {
325	unsigned w = width;
326	unsigned h = height;
327	// Get greatest common divisor
328	while (w != 0) {
329		int temp = h % w;
330		h = w;
331		w = temp;
332	}
333	int gcd = h;
334	int aspectw = width / gcd;
335	int aspecth = height / gcd;
336	float scalex;
337	float scaley;
338
339	switch (screenMode) {
340	case SM_BACKDROP:
341	default:
342		vita2d_draw_texture_tint(backdrop, 0, 0, (faded ? 0 : 0xC0000000) | 0x3FFFFFFF);
343		// Fall through
344	case SM_PLAIN:
345		w = 960 / width;
346		h = 544 / height;
347		if (w * height > 544) {
348			scalex = h;
349			w = width * h;
350			h = height * h;
351		} else {
352			scalex = w;
353			w = width * w;
354			h = height * w;
355		}
356		scaley = scalex;
357		break;
358	case SM_ASPECT:
359		w = 960 / aspectw;
360		h = 544 / aspecth;
361		if (w * aspecth > 544) {
362			w = aspectw * h;
363			h = aspecth * h;
364		} else {
365			w = aspectw * w;
366			h = aspecth * w;
367		}
368		scalex = w / (float) width;
369		scaley = scalex;
370		break;
371	case SM_FULL:
372		w = 960;
373		h = 544;
374		scalex = 960.0f / width;
375		scaley = 544.0f / height;
376		break;
377	}
378	vita2d_draw_texture_tint_part_scale(t,
379	                                    (960.0f - w) / 2.0f, (544.0f - h) / 2.0f,
380	                                    0, 0, width, height,
381	                                    scalex, scaley,
382	                                    (faded ? 0 : 0xC0000000) | 0x3FFFFFFF);
383}
384
385void mPSP2Draw(struct mGUIRunner* runner, bool faded) {
386	unsigned width, height;
387	runner->core->desiredVideoDimensions(runner->core, &width, &height);
388	_drawTex(tex, width, height, faded);
389}
390
391void mPSP2DrawScreenshot(struct mGUIRunner* runner, const uint32_t* pixels, unsigned width, unsigned height, bool faded) {
392	UNUSED(runner);
393	uint32_t* texpixels = vita2d_texture_get_datap(screenshot);
394	int y;
395	for (y = 0; y < height; ++y) {
396		memcpy(&texpixels[256 * y], &pixels[width * y], width * 4);
397	}
398	_drawTex(screenshot, width, height, faded);
399}
400
401void mPSP2IncrementScreenMode(struct mGUIRunner* runner) {
402	screenMode = (screenMode + 1) % SM_MAX;
403	mCoreConfigSetUIntValue(&runner->config, "screenMode", screenMode);
404}
405
406__attribute__((noreturn, weak)) void __assert_func(const char* file, int line, const char* func, const char* expr) {
407	printf("ASSERT FAILED: %s in %s at %s:%i\n", expr, func, file, line);
408	exit(1);
409}