Manic EMU is an all-in-one retro game emulator for iOS. It packs powerful features while keeping a clean, sleek UI and delivering buttery-smooth gameplay.
Swift
Optimized fast-forward logic; fixed the WFC DNS configuration issue; resolved the unresponsive keyboard problem in iOS 26
Daiuno6f5882a9b033
diff --git a/Cores/DeltaCore/DeltaCore/Emulator Core/Audio/AudioUtils.swift b/Cores/DeltaCore/DeltaCore/Emulator Core/Audio/AudioUtils.swiftindex 08fae51e..5e89d271 100644--- a/Cores/DeltaCore/DeltaCore/Emulator Core/Audio/AudioUtils.swift+++ b/Cores/DeltaCore/DeltaCore/Emulator Core/Audio/AudioUtils.swift@@ -16,8 +16,9 @@ internal extension AVAudioFormat {private extension AVAudioSession {func setManicEmuCategory() throws {- try AVAudioSession.sharedInstance().setCategory(.playAndRecord,- options: [.mixWithOthers, .allowBluetoothA2DP, .allowAirPlay])+ //Manic修改+// try AVAudioSession.sharedInstance().setCategory(.playAndRecord,+// options: [.mixWithOthers, .allowBluetoothA2DP, .allowAirPlay])}}@@ -149,153 +150,154 @@ public class AudioUtils: NSObject, AudioRenderProtocol {super.init()- self.audioEngine.attach(self.sourceNode)+ //Manic修改+// self.audioEngine.attach(self.sourceNode)- self.updateVolume()+// self.updateVolume()- NotificationCenter.default.addObserver(self, selector: #selector(AudioUtils.resetAudioEngine), name: .AVAudioEngineConfigurationChange, object: nil)- NotificationCenter.default.addObserver(self, selector: #selector(AudioUtils.resetAudioEngine), name: AVAudioSession.routeChangeNotification, object: nil)+// NotificationCenter.default.addObserver(self, selector: #selector(AudioUtils.resetAudioEngine), name: .AVAudioEngineConfigurationChange, object: nil)+// NotificationCenter.default.addObserver(self, selector: #selector(AudioUtils.resetAudioEngine), name: AVAudioSession.routeChangeNotification, object: nil)}func render(_ inputBuffer: AVAudioPCMBuffer, into outputBuffer: AVAudioPCMBuffer) {- guard let buffer = inputBuffer.int16ChannelData, let audioConverter = audioConverter else { return }-- // Ensure any buffers from previous audio route configurations are no longer processed.- guard inputBuffer.format == audioConverter.inputFormat && outputBuffer.format == audioConverter.outputFormat else { return }-- if audioConverterNeedCount == nil {- // Determine the minimum number of input frames needed to perform a conversion.- audioConverter.convert(to: outputBuffer, error: nil) { [weak self] (requiredPacketCount, outStatus) -> AVAudioBuffer? in- guard let self = self else { return nil }- // In Linear PCM, one packet = one frame.- self.audioConverterNeedCount = requiredPacketCount-- // Setting to ".noDataNow" sometimes results in crash, so we set to ".endOfStream" and reset audioConverter afterwards.- outStatus.pointee = .endOfStream- return nil- }-- audioConverter.reset()- }-- guard let audioConverterRequiredFrameCount = audioConverterNeedCount else { return }-- let availableFrameCount = AVAudioFrameCount(audioBuffer.enableBytesForReading / self.audioFormat.frameSize)- if self.audioEngine.isRunning && availableFrameCount >= audioConverterRequiredFrameCount {- var conversionError: NSError?- let status = audioConverter.convert(to: outputBuffer, error: &conversionError) { [weak self] (requiredPacketCount, outStatus) -> AVAudioBuffer? in- guard let self = self else { return nil }-- // Copy requiredPacketCount frames into inputBuffer's first channel (since audio is interleaved, no need to modify other channels).- let preferredSize = min(Int(requiredPacketCount) * self.audioFormat.frameSize, Int(inputBuffer.frameCapacity) * self.audioFormat.frameSize)- buffer[0].withMemoryRebound(to: UInt8.self, capacity: preferredSize) { (uint8Buffer) in- let readBytes = self.audioBuffer.read(into: uint8Buffer, preferredSize: preferredSize)-- let frameLength = AVAudioFrameCount(readBytes / self.audioFormat.frameSize)- inputBuffer.frameLength = frameLength- }-- if inputBuffer.frameLength == 0 {- outStatus.pointee = .noDataNow- return nil- } else {- outStatus.pointee = .haveData- return inputBuffer- }- }-- if status == .error {- if let error = conversionError {- print(error, error.userInfo)- }- }- } else {- // If not running or not enough input frames, set frameLength to 0 to minimize time until we check again.- inputBuffer.frameLength = 0- }-- audioPlayerNode.scheduleBuffer(outputBuffer) { [weak self, weak node = audioPlayerNode] in- guard let self = self else { return }-- self.renderingQueue.async {- if node?.isPlaying == true- {- self.render(inputBuffer, into: outputBuffer)- }- }- }+// guard let buffer = inputBuffer.int16ChannelData, let audioConverter = audioConverter else { return }+//+// // Ensure any buffers from previous audio route configurations are no longer processed.+// guard inputBuffer.format == audioConverter.inputFormat && outputBuffer.format == audioConverter.outputFormat else { return }+//+// if audioConverterNeedCount == nil {+// // Determine the minimum number of input frames needed to perform a conversion.+// audioConverter.convert(to: outputBuffer, error: nil) { [weak self] (requiredPacketCount, outStatus) -> AVAudioBuffer? in+// guard let self = self else { return nil }+// // In Linear PCM, one packet = one frame.+// self.audioConverterNeedCount = requiredPacketCount+//+// // Setting to ".noDataNow" sometimes results in crash, so we set to ".endOfStream" and reset audioConverter afterwards.+// outStatus.pointee = .endOfStream+// return nil+// }+//+// audioConverter.reset()+// }+//+// guard let audioConverterRequiredFrameCount = audioConverterNeedCount else { return }+//+// let availableFrameCount = AVAudioFrameCount(audioBuffer.enableBytesForReading / self.audioFormat.frameSize)+// if self.audioEngine.isRunning && availableFrameCount >= audioConverterRequiredFrameCount {+// var conversionError: NSError?+// let status = audioConverter.convert(to: outputBuffer, error: &conversionError) { [weak self] (requiredPacketCount, outStatus) -> AVAudioBuffer? in+// guard let self = self else { return nil }+//+// // Copy requiredPacketCount frames into inputBuffer's first channel (since audio is interleaved, no need to modify other channels).+// let preferredSize = min(Int(requiredPacketCount) * self.audioFormat.frameSize, Int(inputBuffer.frameCapacity) * self.audioFormat.frameSize)+// buffer[0].withMemoryRebound(to: UInt8.self, capacity: preferredSize) { (uint8Buffer) in+// let readBytes = self.audioBuffer.read(into: uint8Buffer, preferredSize: preferredSize)+//+// let frameLength = AVAudioFrameCount(readBytes / self.audioFormat.frameSize)+// inputBuffer.frameLength = frameLength+// }+//+// if inputBuffer.frameLength == 0 {+// outStatus.pointee = .noDataNow+// return nil+// } else {+// outStatus.pointee = .haveData+// return inputBuffer+// }+// }+//+// if status == .error {+// if let error = conversionError {+// print(error, error.userInfo)+// }+// }+// } else {+// // If not running or not enough input frames, set frameLength to 0 to minimize time until we check again.+// inputBuffer.frameLength = 0+// }+//+// audioPlayerNode.scheduleBuffer(outputBuffer) { [weak self, weak node = audioPlayerNode] in+// guard let self = self else { return }+//+// self.renderingQueue.async {+// if node?.isPlaying == true+// {+// self.render(inputBuffer, into: outputBuffer)+// }+// }+// }}@objc func resetAudioEngine() {- renderingQueue.sync { [weak self] in- guard let self = self else { return }- self.audioPlayerNode.reset()-- guard let outputAudioFormat = AVAudioFormat(standardFormatWithSampleRate: AVAudioSession.sharedInstance().sampleRate, channels: self.audioFormat.channelCount) else { return }-- let inputAudioBufferFrameCount = Int(self.audioFormat.sampleRate * self.frameDuration)- let outputAudioBufferFrameCount = Int(outputAudioFormat.sampleRate * self.frameDuration)-- // Allocate enough space to prevent us from overwriting data before we've used it.- let ringBufferAudioBufferCount = Int((self.audioFormat.sampleRate / outputAudioFormat.sampleRate).rounded(.up) + 10.0)-- let preferredBufferSize = inputAudioBufferFrameCount * self.audioFormat.frameSize * ringBufferAudioBufferCount- guard let ringBuffer = RingingBuffer(preferredBufferSize: preferredBufferSize) else {- fatalError("Cannot initialize RingBuffer with preferredBufferSize of \(preferredBufferSize)")- }- self.audioBuffer = ringBuffer-- let audioConverter = AVAudioConverter(from: self.audioFormat, to: outputAudioFormat)- self.audioConverter = audioConverter-- self.audioConverterNeedCount = nil-- self.audioEngine.disconnectNodeOutput(self.timePitchEffect)- self.audioEngine.connect(self.timePitchEffect, to: self.audioEngine.mainMixerNode, format: outputAudioFormat)-- self.audioEngine.detach(self.sourceNode)-- self.sourceNode = self.makeSourceNode()- self.audioEngine.attach(self.sourceNode)-- self.audioEngine.connect(self.sourceNode, to: self.timePitchEffect, format: outputAudioFormat)-- do {- // Explicitly set output port since .defaultToSpeaker option pauses external audio.- if AVAudioSession.sharedInstance().currentRoute.isOutToReceiver {- try AVAudioSession.sharedInstance().overrideOutputAudioPort(.speaker)- }-- try self.audioEngine.start()-- } catch {- print(error)- }- }+// renderingQueue.sync { [weak self] in+// guard let self = self else { return }+// self.audioPlayerNode.reset()+//+// guard let outputAudioFormat = AVAudioFormat(standardFormatWithSampleRate: AVAudioSession.sharedInstance().sampleRate, channels: self.audioFormat.channelCount) else { return }+//+// let inputAudioBufferFrameCount = Int(self.audioFormat.sampleRate * self.frameDuration)+// let outputAudioBufferFrameCount = Int(outputAudioFormat.sampleRate * self.frameDuration)+//+// // Allocate enough space to prevent us from overwriting data before we've used it.+// let ringBufferAudioBufferCount = Int((self.audioFormat.sampleRate / outputAudioFormat.sampleRate).rounded(.up) + 10.0)+//+// let preferredBufferSize = inputAudioBufferFrameCount * self.audioFormat.frameSize * ringBufferAudioBufferCount+// guard let ringBuffer = RingingBuffer(preferredBufferSize: preferredBufferSize) else {+// fatalError("Cannot initialize RingBuffer with preferredBufferSize of \(preferredBufferSize)")+// }+// self.audioBuffer = ringBuffer+//+// let audioConverter = AVAudioConverter(from: self.audioFormat, to: outputAudioFormat)+// self.audioConverter = audioConverter+//+// self.audioConverterNeedCount = nil+//+// self.audioEngine.disconnectNodeOutput(self.timePitchEffect)+// self.audioEngine.connect(self.timePitchEffect, to: self.audioEngine.mainMixerNode, format: outputAudioFormat)+//+// self.audioEngine.detach(self.sourceNode)+//+// self.sourceNode = self.makeSourceNode()+// self.audioEngine.attach(self.sourceNode)+//+// self.audioEngine.connect(self.sourceNode, to: self.timePitchEffect, format: outputAudioFormat)+//+// do {+// // Explicitly set output port since .defaultToSpeaker option pauses external audio.+// if AVAudioSession.sharedInstance().currentRoute.isOutToReceiver {+// try AVAudioSession.sharedInstance().overrideOutputAudioPort(.speaker)+// }+//+// try self.audioEngine.start()+//+// } catch {+// print(error)+// }+// }}@objc func updateVolume() {- if !isEnabled {- audioEngine.mainMixerNode.outputVolume = 0.0- } else {- let route = AVAudioSession.sharedInstance().currentRoute-- if AVAudioSession.sharedInstance().isOtherAudioPlaying {- // Always mute if another app is playing audio.- audioEngine.mainMixerNode.outputVolume = 0.0- } else if followSilentMode {- if isMuted && (route.isHeadset || !route.isOutToExternalDevice) {- // Respect mute switch IFF playing through speaker or headphones.- audioEngine.mainMixerNode.outputVolume = 0.0- } else {- // Ignore mute switch for other audio routes (e.g. AirPlay).- self.audioEngine.mainMixerNode.outputVolume = 1.0- }- } else {- // Ignore silent mode and always play game audio (unless another app is playing audio).- audioEngine.mainMixerNode.outputVolume = 1.0- }- }+// if !isEnabled {+// audioEngine.mainMixerNode.outputVolume = 0.0+// } else {+// let route = AVAudioSession.sharedInstance().currentRoute+//+// if AVAudioSession.sharedInstance().isOtherAudioPlaying {+// // Always mute if another app is playing audio.+// audioEngine.mainMixerNode.outputVolume = 0.0+// } else if followSilentMode {+// if isMuted && (route.isHeadset || !route.isOutToExternalDevice) {+// // Respect mute switch IFF playing through speaker or headphones.+// audioEngine.mainMixerNode.outputVolume = 0.0+// } else {+// // Ignore mute switch for other audio routes (e.g. AirPlay).+// self.audioEngine.mainMixerNode.outputVolume = 1.0+// }+// } else {+// // Ignore silent mode and always play game audio (unless another app is playing audio).+// audioEngine.mainMixerNode.outputVolume = 1.0+// }+// }}func makeSourceNode() -> AVAudioSourceNode {@@ -343,35 +345,35 @@ public class AudioUtils: NSObject, AudioRenderProtocol {}public func start() {- muteMonitor.startMonitoring { [weak self] (isMuted) in- guard let self = self else { return }- self.isMuted = isMuted- }-- do {- try AVAudioSession.sharedInstance().setManicEmuCategory()- try AVAudioSession.sharedInstance().setPreferredIOBufferDuration(0.005)-- try AVAudioSession.sharedInstance().setAllowHapticsAndSystemSoundsDuringRecording(true)-- try AVAudioSession.sharedInstance().setActive(true)- }- catch {- print(error)- }-- resetAudioEngine()+// muteMonitor.startMonitoring { [weak self] (isMuted) in+// guard let self = self else { return }+// self.isMuted = isMuted+// }+//+// do {+// try AVAudioSession.sharedInstance().setManicEmuCategory()+// try AVAudioSession.sharedInstance().setPreferredIOBufferDuration(0.005)+//+// try AVAudioSession.sharedInstance().setAllowHapticsAndSystemSoundsDuringRecording(true)+//+// try AVAudioSession.sharedInstance().setActive(true)+// }+// catch {+// print(error)+// }+//+// resetAudioEngine()}public func stop() {- muteMonitor.stopMonitoring()-- renderingQueue.sync { [weak self] in- guard let self = self else { return }- self.audioPlayerNode.stop()- self.audioEngine.stop()- }-- audioBuffer.isEnabled = false+// muteMonitor.stopMonitoring()+//+// renderingQueue.sync { [weak self] in+// guard let self = self else { return }+// self.audioPlayerNode.stop()+// self.audioEngine.stop()+// }+//+// audioBuffer.isEnabled = false}}diff --git a/Cores/DeltaCore/DeltaCore/Emulator Core/EmulatorCore.swift b/Cores/DeltaCore/DeltaCore/Emulator Core/EmulatorCore.swiftindex 41378834..d91cc7e4 100644--- a/Cores/DeltaCore/DeltaCore/Emulator Core/EmulatorCore.swift+++ b/Cores/DeltaCore/DeltaCore/Emulator Core/EmulatorCore.swift@@ -113,6 +113,10 @@ public final class EmulatorCore: NSObject {// Since they don't actually need to be lazy, we now explicitly initialize them in the initializer.self.audioManager = AudioUtils(audioFormat: deltaCore.audioFormat)self.videoManager = VideoUtils(videoFormat: videoFormat, options: options)++ //Manic修改+ self.audioManager.isEnabled = false+ self.videoManager.isEnabled = falsesuper.init()diff --git a/Cores/DeltaCore/DeltaCore/Game Controllers/Keyboard/KeyboardResponder.swift b/Cores/DeltaCore/DeltaCore/Game Controllers/Keyboard/KeyboardResponder.swiftindex dbd63cd2..8ef53227 100644--- a/Cores/DeltaCore/DeltaCore/Game Controllers/Keyboard/KeyboardResponder.swift+++ b/Cores/DeltaCore/DeltaCore/Game Controllers/Keyboard/KeyboardResponder.swift@@ -66,8 +66,11 @@ public class KeyboardResponder: UIResponderextension KeyboardResponder{// Implementation based on Steve Troughton-Smith's gist: https://gist.github.com/steventroughtonsmith/7515380- internal override func _keyCommand(for event: UIEvent, target: UnsafeMutablePointer<UIResponder>) -> UIKeyCommand?- {+ internal override func _keyCommand(for event: UIEvent, target: UnsafeMutablePointer<UIResponder>) -> UIKeyCommand? {+ return handleKeyboardKey(for: event)+ }++ internal func handleKeyboardKey(for event: UIEvent) -> UIKeyCommand? {// Retrieve information from event.guardlet key = event.value(forKey: "_unmodifiedInput") as? String,diff --git a/Cores/DeltaCore/DeltaCore/UI/Controller/ControllerView.swift b/Cores/DeltaCore/DeltaCore/UI/Controller/ControllerView.swiftindex e7cf0867..1eee23ad 100644--- a/Cores/DeltaCore/DeltaCore/UI/Controller/ControllerView.swift+++ b/Cores/DeltaCore/DeltaCore/UI/Controller/ControllerView.swift@@ -701,6 +701,12 @@ public class ControllerView: UIView, GameController}}+ public func handleKeyboardKey(for event: UIEvent) {+ if #available(iOS 26.0, *) {+ keyboardResponder.handleKeyboardKey(for: event)+ }+ }+func presentInputView(){guard !isControllerInputView else { return }diff --git a/Cores/Libretro/runloop.c b/Cores/Libretro/runloop.cindex 419c2b61..4a9ffa8f 100644--- a/Cores/Libretro/runloop.c+++ b/Cores/Libretro/runloop.c@@ -344,6 +344,12 @@ void set_melonds_custom_layout(const char *layout) {g_melonds_custom_layout = strdup(layout);}+//定义WFC NDS信息+static const char *g_melonds_wfc_dns = NULL;+void set_melonds_wfc_dns(const char *dns) {+ g_melonds_wfc_dns = strdup(dns);+}+static runloop_state_t runloop_state = {0};/* GLOBAL POINTER GETTERS */@@ -1436,6 +1442,11 @@ bool runloop_environment_cb(unsigned cmd, void *data)var->value = strdup(g_melonds_custom_layout);break;}++ if (g_melonds_wfc_dns && string_is_equal(var->key, "melonds_firmware_wfc_dns")) {+ var->value = strdup(g_melonds_wfc_dns);+ break;+ }if (core_option_manager_get_idx(runloop_st->core_options,var->key, &opt_idx))diff --git a/Cores/Libretro/runloop.h b/Cores/Libretro/runloop.hindex 15a4af63..3e9d270e 100644--- a/Cores/Libretro/runloop.h+++ b/Cores/Libretro/runloop.h@@ -318,6 +318,9 @@ void shutdown_register_callback(ShutdownCallback callback);//定义melonDS的布局信息void set_melonds_custom_layout(const char *layout);+//定义WFC NDS信息+void set_melonds_wfc_dns(const char *dns);+void runloop_path_fill_names(void);/**diff --git a/Cores/Libretro/ui/drivers/LibretroCore.m b/Cores/Libretro/ui/drivers/LibretroCore.mindex 54eaf17a..9490f9e4 100644--- a/Cores/Libretro/ui/drivers/LibretroCore.m+++ b/Cores/Libretro/ui/drivers/LibretroCore.m@@ -515,6 +515,16 @@ static void wfcStatusCallback(bool isConnect) {}}+- (void)setNDSWFCDNS:(NSString *_Nullable)nds {+ if (nds) {+ set_melonds_wfc_dns([nds cStringUsingEncoding:NSUTF8StringEncoding]);+ [self setCoreOptionNeedsUpdate];+ } else {+ set_melonds_wfc_dns(NULL);+ [self setCoreOptionNeedsUpdate];+ }+}+- (void)setCoreOptionNeedsUpdate {// 通知核心配置已更新runloop_state_t *runloop_st = runloop_state_get_ptr();diff --git a/Cores/Libretro/ui/drivers/cocoa/LibretroCore.h b/Cores/Libretro/ui/drivers/cocoa/LibretroCore.hindex 3285719e..e747818b 100644--- a/Cores/Libretro/ui/drivers/cocoa/LibretroCore.h+++ b/Cores/Libretro/ui/drivers/cocoa/LibretroCore.h@@ -82,6 +82,7 @@ extern NSString * const RetroAchievementsNotification;- (BOOL)getSensorEnable:(int)playerIndex;- (void)startWFCStatusMonitor;- (void)setNDSCustomLayout:(NSString *_Nullable)layout;+- (void)setNDSWFCDNS:(NSString *_Nullable)nds;- (void)setCoreOptionNeedsUpdate;- (void)sendTouchEventX:(CGFloat)x y:(CGFloat)y;- (void)releaseTouchEvent;diff --git a/Cores/Libretro/ui/drivers/ui_cocoatouch.m b/Cores/Libretro/ui/drivers/ui_cocoatouch.mindex 6cbc62bc..ca1dbc7d 100644--- a/Cores/Libretro/ui/drivers/ui_cocoatouch.m+++ b/Cores/Libretro/ui/drivers/ui_cocoatouch.m@@ -987,6 +987,10 @@ static BOOL RespectSilentMode = false;if (LibretroInitial) {return;}++ //防止音频驱动加载的时候中断别的应用的音频+ [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryAmbient error:nil];+LibretroInitial = true;set_libretro_is_going_to_stop(false);char arguments[] = "retroarch";@@ -996,7 +1000,7 @@ static BOOL RespectSilentMode = false;[CocoaView get].view.frame = [[UIScreen mainScreen] bounds];-// [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleAudioSessionInterruption:) name:AVAudioSessionInterruptionNotification object:[AVAudioSession sharedInstance]];+ [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleAudioSessionInterruption:) name:AVAudioSessionInterruptionNotification object:[AVAudioSession sharedInstance]];dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{command_event(CMD_EVENT_AUDIO_START, NULL);@@ -1012,35 +1016,7 @@ static BOOL RespectSilentMode = false;}rarch_main(argc, argv, NULL);--// uico_driver_state_t *uico_st = uico_state_get_ptr();-// rarch_setting_t *appicon_setting = menu_setting_find_enum(MENU_ENUM_LABEL_APPICON_SETTINGS);-// struct string_list *icons;-// if ( appicon_setting-// && uico_st->drv-// && uico_st->drv->get_app_icons-// && (icons = uico_st->drv->get_app_icons())-// && icons->size > 1)-// {-// int i;-// size_t _len = 0;-// char *options = NULL;-// const char *icon_name;-//-// appicon_setting->default_value.string = icons->elems[0].data;-// icon_name = [@"appicon" cStringUsingEncoding:kCFStringEncodingUTF8]; /* need to ask uico_st for this */-// for (i = 0; i < (int)icons->size; i++)-// {-// _len += strlen(icons->elems[i].data) + 1;-// if (string_is_equal(icon_name, icons->elems[i].data))-// appicon_setting->value.target.string = icons->elems[i].data;-// }-// options = (char*)calloc(_len, sizeof(char));-// string_list_join_concat(options, _len, icons, "|");-// if (appicon_setting->values)-// free((void*)appicon_setting->values);-// appicon_setting->values = options;-// }+rarch_start_draw_observer();}@@ -1060,17 +1036,13 @@ static BOOL RespectSilentMode = false;main_exit(NULL);self.gamePath = nil;self.corePath = nil;+ [[NSNotificationCenter defaultCenter] removeObserver:self name:AVAudioSessionInterruptionNotification object:[AVAudioSession sharedInstance]];}- (void)resume {if (!LibretroInitial) { return; }rarch_start_draw_observer();- NSError *error;- settings_t *settings = config_get_ptr();- if (settings->bools.audio_respect_silent_mode)- [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryAmbient error:&error];- else- [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:&error];+command_event(CMD_EVENT_RESUME, NULL);if (needToLoadStatePath) {[self loadGame:self.gamePath corePath:self.corePath completion:nil];@@ -1097,6 +1069,16 @@ static BOOL RespectSilentMode = false;content_info.args = NULL;content_info.environ_get = NULL;+ NSError *error;+ AVAudioSessionCategoryOptions options = AVAudioSessionCategoryOptionMixWithOthers |+ AVAudioSessionCategoryOptionAllowBluetoothA2DP |+ AVAudioSessionCategoryOptionAllowAirPlay;+ if (RespectSilentMode) {+ [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryAmbient withOptions:options error:&error];+ } else {+ [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback withOptions:options error:&error];+ }+task_push_load_content_with_new_core_from_menu(corePath.UTF8String,gamePath.UTF8String,&content_info,@@ -1292,43 +1274,55 @@ extern void manic_input_analog_event(unsigned port, unsigned stick_id, float x_v}- (void)fastForward:(float)rate {- settings_t *settings = config_get_ptr();- if (!settings) {- return;- }runloop_state_t *runloop_st = runloop_state_get_ptr();- input_driver_state_t *input_st = input_state_get_ptr();- audio_driver_state_t *audio_st = audio_state_get_ptr();- if (rate <= 1) {- //恢复速度- settings->floats.fastforward_ratio = 1.0f;- // 1. 清除快进标志- runloop_st->flags &= ~RUNLOOP_FLAG_FASTMOTION;- // 2. 清除非阻塞输入- input_st->flags &= ~INP_FLAG_NONBLOCKING;- // 3. 更新帧率限制- command_event(CMD_EVENT_SET_FRAME_LIMIT, NULL);- // 4. 恢复音频缓冲区大小- audio_st->chunk_size = AUDIO_CHUNK_SIZE_BLOCKING;- // 5. 恢复音频阻塞模式- if (audio_st->current_audio && audio_st->context_audio_data)- audio_st->current_audio->set_nonblock_state(audio_st->context_audio_data, false);+ if (!runloop_st) return;+ if (rate <= 1.0f) {+ // 清除快进覆盖+ struct retro_fastforwarding_override override = {0};+ override.ratio = -1.0f;+ override.fastforward = false;+ override.notification = false;+ override.inhibit_toggle = false;++ runloop_st->fastmotion_override.next = override;++ // 标记为待应用,系统会在下一个runloop周期自动应用+ runloop_st->fastmotion_override.pending = true;} else {- //快进- // 1. 设置快进比例- settings->floats.fastforward_ratio = rate;- // 2. 设置快进标志- runloop_st->flags |= RUNLOOP_FLAG_FASTMOTION;- // 3. 设置非阻塞输入- input_st->flags |= INP_FLAG_NONBLOCKING;- // 4. 更新帧率限制- command_event(CMD_EVENT_SET_FRAME_LIMIT, NULL);- // 5. 设置音频缓冲区大小- audio_st->chunk_size = AUDIO_CHUNK_SIZE_NONBLOCKING;- // 6. 设置音频非阻塞模式- if (audio_st->current_audio && audio_st->context_audio_data)- audio_st->current_audio->set_nonblock_state(audio_st->context_audio_data, true);+ // 使用RetroArch的官方快进覆盖API+ struct retro_fastforwarding_override override = {0};+ override.ratio = rate;+ override.fastforward = true;+ override.notification = false;+ override.inhibit_toggle = false;++ // 设置快进覆盖+ runloop_st->fastmotion_override.next = override;++ // 标记为待应用,系统会在下一个runloop周期自动应用+ runloop_st->fastmotion_override.pending = true;+ }+}++// 获取当前快进状态+- (BOOL)isFastForwarding {+ runloop_state_t *runloop_st = runloop_state_get_ptr();+ if (!runloop_st) return NO;+ return runloop_st->fastmotion_override.current.fastforward;+}++// 获取当前快进比例+- (float)getCurrentFastForwardRate {+ runloop_state_t *runloop_st = runloop_state_get_ptr();+ if (!runloop_st) return 1.0f;++ if (runloop_st->fastmotion_override.current.fastforward &&+ runloop_st->fastmotion_override.current.ratio >= 0.0f) {+ return runloop_st->fastmotion_override.current.ratio;}++ settings_t *settings = config_get_ptr();+ return settings ? settings->floats.fastforward_ratio : 1.0f;}- (void)reload {diff --git a/ManicEmu/ManicEmu/Sources/Base/Application.swift b/ManicEmu/ManicEmu/Sources/Base/Application.swiftindex 8d1626e6..7e33a4c1 100644--- a/ManicEmu/ManicEmu/Sources/Base/Application.swift+++ b/ManicEmu/ManicEmu/Sources/Base/Application.swift@@ -8,10 +8,37 @@// SPDX-License-Identifier: AGPL-3.0-or-laterimport UIKit+import ManicEmuCore++private extension UIApplication {+ @objc(handleKeyUIEvent:)+ @NSManaged func handleKeyboardKey(for event: UIEvent)+}class ManicApplication: UIApplication {+ // 上次键盘事件的时间戳,用于避免重复处理+ private static var lastKeyboardEventTimestamp: TimeInterval = 0+override func sendEvent(_ event: UIEvent) {super.sendEvent(event)// LibretroCore.sharedInstance().send(event)}++ // 处理键盘事件 - 对应Objective-C中的handleKeyUIEvent方法+ override func handleKeyboardKey(for event: UIEvent) {+ super.handleKeyboardKey(for: event)+ if #available(iOS 26.0, *) {+ guard let firstResponder = UIResponder.firstResponder as? ControllerView else { return }+ // 检查是否是重复的时间戳,避免重复处理+ if ManicApplication.lastKeyboardEventTimestamp == event.timestamp {+ return+ }++ ManicApplication.lastKeyboardEventTimestamp = event.timestamp++ firstResponder.handleKeyboardKey(for: event)+ }+ }++}diff --git a/ManicEmu/ManicEmu/Sources/Business/Play/VIewControllers/PlayViewController.swift b/ManicEmu/ManicEmu/Sources/Business/Play/VIewControllers/PlayViewController.swiftindex 1310c81d..14db40b3 100644--- a/ManicEmu/ManicEmu/Sources/Business/Play/VIewControllers/PlayViewController.swift+++ b/ManicEmu/ManicEmu/Sources/Business/Play/VIewControllers/PlayViewController.swift@@ -642,20 +642,6 @@ class PlayViewController: GameViewController {}}- override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {- guard context == &kvoContext else { return super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context) }- guard let rawValue = change?[.oldKey] as? Int, let previousState = EmulatorCore.State(rawValue: rawValue) else { return }- if let manicEmuCore {- if previousState != .stopped, manicEmuCore.state == .stopped {- DispatchQueue.main.async {- if self.manicGame.isNDSHomeMenuGame {- self.handleMenuGameSetting(GameSetting(type: .quit), nil)- }- }- }- }- }-@MainActor required init() {fatalError("init() has not been implemented")}@@ -726,12 +712,6 @@ class PlayViewController: GameViewController {super.viewDidDisappear(animated)repeatTimer.suspend()//清理AirPlay画面- if let airPlayViewController = ExternalSceneDelegate.airPlayViewController, let airPlayGameView = airPlayViewController.gameView, manicGame.gameType != ._3ds {- self.manicEmuCore?.remove(airPlayGameView)- airPlayGameView.removeFromSuperview()- airPlayViewController.gameView = nil- }-if let airPlayViewController = ExternalSceneDelegate.airPlayViewController, let airPlayGameView = airPlayViewController.libretroView, manicGame.gameType.isLibretroType {airPlayGameView.parentViewController?.removeFromParent()airPlayGameView.removeFromSuperview()@@ -1478,9 +1458,6 @@ extension PlayViewController {} else if manicGame.gameType.isLibretroType {LibretroCore.sharedInstance().reload()updateFilter()- } else {- manicEmuCore?.stop()- manicEmuCore?.start()}case .quit:if manicGame.gameType == ._3ds {@@ -1494,9 +1471,6 @@ extension PlayViewController {DispatchQueue.main.asyncAfter(delay: 0.5) {self.dismiss(animated: true)}- } else {- manicEmuCore?.stop()- dismiss(animated: true)}case .resolution:guard manicGame.gameType == ._3ds || manicGame.gameType == .psp || manicGame.gameType == .n64 || manicGame.gameType == .ps1 || manicGame.gameType == .dc else { return true }@@ -1751,14 +1725,6 @@ extension PlayViewController {} else {LibretroCore.sharedInstance().mute(manicGame.volume)}- } else {- if let manicEmuCore = manicEmuCore {- if manicGame.volume && !manicEmuCore.audioManager.isEnabled {- manicEmuCore.audioManager.isEnabled = true- } else if manicEmuCore.audioManager.isEnabled && !manicGame.volume {- manicEmuCore.audioManager.isEnabled = false- }- }}}@@ -1816,32 +1782,6 @@ extension PlayViewController {}}- } else {- if let manicEmuCore = manicEmuCore {- let lastState = manicEmuCore.state- pauseEmulation()- var success = [String]()- for cheatCode in manicGame.gameCheats {- if cheatCode.activate {- if manicEmuCore.cheatCodes[cheatCode.code] == nil {- do {- try manicEmuCore.activate(Cheat(code: cheatCode.code, type: CheatType(cheatCode.type)))- success.append(cheatCode.name)- } catch {- UIView.makeToast(message: R.string.localizable.gameCheatActivateFailed(cheatCode.name))- }- }- } else {- manicEmuCore.deactivate(Cheat(code: cheatCode.code, type: CheatType(cheatCode.type)))- }- }- if success.count > 0 {- UIView.makeToast(message: R.string.localizable.gameCheatActivateSuccess(String.successMessage(from: success)))- }- if lastState == .running {- resumeEmulationAndHandleAudio()- }- }}}@@ -1935,17 +1875,15 @@ extension PlayViewController {}//wfc- let dns = WFC.currentDNS()-LibretroCore.sharedInstance().updateConfig(LibretroCore.Cores.melonDSDS.name,configs: ["melonds_firmware_language": dsLanguageOption,"melonds_console_mode": systemType,- "melonds_firmware_wfc_dns": dns,"melonds_mic_input_active": "always","melonds_number_of_screen_layouts": "1","melonds_screen_layout1": "custom","melonds_show_cursor": "disabled"],reload: false)+ LibretroCore.sharedInstance().setNDSWFCDNS( WFC.currentDNS());} else if manicGame.gameType == .gba {if manicGame.defaultCore == 1 {