HeadlessRyujinx.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  1. using CommandLine;
  2. using Gommon;
  3. using Ryujinx.Ava;
  4. using Ryujinx.Ava.Utilities.Configuration;
  5. using Ryujinx.Common;
  6. using Ryujinx.Common.Configuration;
  7. using Ryujinx.Common.Configuration.Hid;
  8. using Ryujinx.Common.GraphicsDriver;
  9. using Ryujinx.Common.Logging;
  10. using Ryujinx.Common.Logging.Targets;
  11. using Ryujinx.Common.SystemInterop;
  12. using Ryujinx.Common.Utilities;
  13. using Ryujinx.Cpu;
  14. using Ryujinx.Graphics.GAL;
  15. using Ryujinx.Graphics.Gpu;
  16. using Ryujinx.Graphics.Gpu.Shader;
  17. using Ryujinx.Graphics.Vulkan.MoltenVK;
  18. using Ryujinx.HLE;
  19. using Ryujinx.HLE.FileSystem;
  20. using Ryujinx.HLE.HOS;
  21. using Ryujinx.HLE.HOS.Services.Account.Acc;
  22. using Ryujinx.Input;
  23. using Ryujinx.Input.HLE;
  24. using Ryujinx.Input.SDL2;
  25. using Ryujinx.SDL2.Common;
  26. using System;
  27. using System.Collections.Generic;
  28. using System.IO;
  29. using System.Threading;
  30. namespace Ryujinx.Headless
  31. {
  32. public partial class HeadlessRyujinx
  33. {
  34. private static VirtualFileSystem _virtualFileSystem;
  35. private static ContentManager _contentManager;
  36. private static AccountManager _accountManager;
  37. private static LibHacHorizonManager _libHacHorizonManager;
  38. private static UserChannelPersistence _userChannelPersistence;
  39. private static InputManager _inputManager;
  40. private static Switch _emulationContext;
  41. private static WindowBase _window;
  42. private static WindowsMultimediaTimerResolution _windowsMultimediaTimerResolution;
  43. private static List<InputConfig> _inputConfiguration = [];
  44. private static bool _enableKeyboard;
  45. private static bool _enableMouse;
  46. private static readonly InputConfigJsonSerializerContext _serializerContext = new(JsonHelper.GetDefaultSerializerOptions());
  47. public static void Entrypoint(string[] args)
  48. {
  49. // Make process DPI aware for proper window sizing on high-res screens.
  50. ForceDpiAware.Windows();
  51. Console.Title = $"Ryujinx Console {Program.Version} (Headless)";
  52. if (OperatingSystem.IsMacOS() || OperatingSystem.IsLinux())
  53. {
  54. AutoResetEvent invoked = new(false);
  55. // MacOS must perform SDL polls from the main thread.
  56. SDL2Driver.MainThreadDispatcher = action =>
  57. {
  58. invoked.Reset();
  59. WindowBase.QueueMainThreadAction(() =>
  60. {
  61. action();
  62. invoked.Set();
  63. });
  64. invoked.WaitOne();
  65. };
  66. }
  67. if (OperatingSystem.IsMacOS())
  68. {
  69. MVKInitialization.InitializeResolver();
  70. }
  71. Parser.Default.ParseArguments<Options>(args)
  72. .WithParsed(options => Load(args, options))
  73. .WithNotParsed(errors =>
  74. {
  75. Logger.Error?.PrintMsg(LogClass.Application, "Error parsing command-line arguments:");
  76. errors.ForEach(err => Logger.Error?.PrintMsg(LogClass.Application, $" - {err.Tag}"));
  77. });
  78. }
  79. public static void ReloadConfig(string customConfigPath = null)
  80. {
  81. string localConfigurationPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, ReleaseInformation.ConfigName);
  82. string appDataConfigurationPath = Path.Combine(AppDataManager.BaseDirPath, ReleaseInformation.ConfigName);
  83. string configurationPath = null;
  84. // Now load the configuration as the other subsystems are now registered
  85. if (customConfigPath != null && File.Exists(customConfigPath))
  86. {
  87. configurationPath = customConfigPath;
  88. }
  89. else if (File.Exists(localConfigurationPath))
  90. {
  91. configurationPath = localConfigurationPath;
  92. }
  93. else if (File.Exists(appDataConfigurationPath))
  94. {
  95. configurationPath = appDataConfigurationPath;
  96. }
  97. if (configurationPath == null)
  98. {
  99. // No configuration, we load the default values and save it to disk
  100. configurationPath = appDataConfigurationPath;
  101. Logger.Notice.Print(LogClass.Application, $"No configuration file found. Saving default configuration to: {configurationPath}");
  102. ConfigurationState.Instance.LoadDefault();
  103. ConfigurationState.Instance.ToFileFormat().SaveConfig(configurationPath);
  104. }
  105. else
  106. {
  107. Logger.Notice.Print(LogClass.Application, $"Loading configuration from: {configurationPath}");
  108. if (ConfigurationFileFormat.TryLoad(configurationPath, out ConfigurationFileFormat configurationFileFormat))
  109. {
  110. ConfigurationState.Instance.Load(configurationFileFormat, configurationPath);
  111. }
  112. else
  113. {
  114. Logger.Warning?.PrintMsg(LogClass.Application, $"Failed to load config! Loading the default config instead.\nFailed config location: {configurationPath}");
  115. ConfigurationState.Instance.LoadDefault();
  116. }
  117. }
  118. }
  119. static void Load(string[] originalArgs, Options option)
  120. {
  121. Initialize();
  122. bool useLastUsedProfile = false;
  123. if (option.InheritConfig)
  124. {
  125. option.InheritMainConfig(originalArgs, ConfigurationState.Instance, out useLastUsedProfile);
  126. }
  127. AppDataManager.Initialize(option.BaseDataDir);
  128. if (useLastUsedProfile && AccountSaveDataManager.GetLastUsedUser().TryGet(out var profile))
  129. option.UserProfile = profile.Name;
  130. // Check if keys exists.
  131. if (!File.Exists(Path.Combine(AppDataManager.KeysDirPath, "prod.keys")))
  132. {
  133. if (!(AppDataManager.Mode == AppDataManager.LaunchMode.UserProfile && File.Exists(Path.Combine(AppDataManager.KeysDirPathUser, "prod.keys"))))
  134. {
  135. Logger.Error?.Print(LogClass.Application, "Keys not found");
  136. }
  137. }
  138. ReloadConfig();
  139. _virtualFileSystem = VirtualFileSystem.CreateInstance();
  140. _libHacHorizonManager = new LibHacHorizonManager();
  141. _libHacHorizonManager.InitializeFsServer(_virtualFileSystem);
  142. _libHacHorizonManager.InitializeArpServer();
  143. _libHacHorizonManager.InitializeBcatServer();
  144. _libHacHorizonManager.InitializeSystemClients();
  145. _contentManager = new ContentManager(_virtualFileSystem);
  146. _accountManager = new AccountManager(_libHacHorizonManager.RyujinxClient, option.UserProfile);
  147. _userChannelPersistence = new UserChannelPersistence();
  148. _inputManager = new InputManager(new SDL2KeyboardDriver(), new SDL2GamepadDriver());
  149. GraphicsConfig.EnableShaderCache = !option.DisableShaderCache;
  150. if (OperatingSystem.IsMacOS())
  151. {
  152. if (option.GraphicsBackend == GraphicsBackend.OpenGl)
  153. {
  154. option.GraphicsBackend = GraphicsBackend.Vulkan;
  155. Logger.Warning?.Print(LogClass.Application, "OpenGL is not supported on macOS, switching to Vulkan!");
  156. }
  157. }
  158. if (option.ListInputIds)
  159. {
  160. Logger.Info?.Print(LogClass.Application, "Input Ids:");
  161. foreach (string id in _inputManager.KeyboardDriver.GamepadsIds)
  162. {
  163. IGamepad gamepad = _inputManager.KeyboardDriver.GetGamepad(id);
  164. Logger.Info?.Print(LogClass.Application, $"- {id} (\"{gamepad.Name}\")");
  165. gamepad.Dispose();
  166. }
  167. foreach (string id in _inputManager.GamepadDriver.GamepadsIds)
  168. {
  169. IGamepad gamepad = _inputManager.GamepadDriver.GetGamepad(id);
  170. Logger.Info?.Print(LogClass.Application, $"- {id} (\"{gamepad.Name}\")");
  171. gamepad.Dispose();
  172. }
  173. return;
  174. }
  175. if (option.InputPath == null)
  176. {
  177. Logger.Error?.Print(LogClass.Application, "Please provide a file to load");
  178. return;
  179. }
  180. _inputConfiguration ??= [];
  181. _enableKeyboard = option.EnableKeyboard;
  182. _enableMouse = option.EnableMouse;
  183. static void LoadPlayerConfiguration(string inputProfileName, string inputId, PlayerIndex index)
  184. {
  185. InputConfig inputConfig = HandlePlayerConfiguration(inputProfileName, inputId, index);
  186. if (inputConfig != null)
  187. {
  188. _inputConfiguration.Add(inputConfig);
  189. }
  190. }
  191. LoadPlayerConfiguration(option.InputProfile1Name, option.InputId1, PlayerIndex.Player1);
  192. LoadPlayerConfiguration(option.InputProfile2Name, option.InputId2, PlayerIndex.Player2);
  193. LoadPlayerConfiguration(option.InputProfile3Name, option.InputId3, PlayerIndex.Player3);
  194. LoadPlayerConfiguration(option.InputProfile4Name, option.InputId4, PlayerIndex.Player4);
  195. LoadPlayerConfiguration(option.InputProfile5Name, option.InputId5, PlayerIndex.Player5);
  196. LoadPlayerConfiguration(option.InputProfile6Name, option.InputId6, PlayerIndex.Player6);
  197. LoadPlayerConfiguration(option.InputProfile7Name, option.InputId7, PlayerIndex.Player7);
  198. LoadPlayerConfiguration(option.InputProfile8Name, option.InputId8, PlayerIndex.Player8);
  199. LoadPlayerConfiguration(option.InputProfileHandheldName, option.InputIdHandheld, PlayerIndex.Handheld);
  200. if (_inputConfiguration.Count == 0)
  201. {
  202. return;
  203. }
  204. // Setup logging level
  205. Logger.SetEnable(LogLevel.Debug, option.LoggingEnableDebug);
  206. Logger.SetEnable(LogLevel.Stub, !option.LoggingDisableStub);
  207. Logger.SetEnable(LogLevel.Info, !option.LoggingDisableInfo);
  208. Logger.SetEnable(LogLevel.Warning, !option.LoggingDisableWarning);
  209. Logger.SetEnable(LogLevel.Error, !option.LoggingDisableError);
  210. Logger.SetEnable(LogLevel.Trace, option.LoggingEnableTrace);
  211. Logger.SetEnable(LogLevel.Guest, !option.LoggingDisableGuest);
  212. Logger.SetEnable(LogLevel.AccessLog, option.LoggingEnableFsAccessLog);
  213. if (!option.DisableFileLog)
  214. {
  215. string logDir = AppDataManager.LogsDirPath;
  216. FileStream logFile = null;
  217. if (!string.IsNullOrEmpty(logDir))
  218. {
  219. logFile = FileLogTarget.PrepareLogFile(logDir);
  220. }
  221. if (logFile != null)
  222. {
  223. Logger.AddTarget(new AsyncLogTargetWrapper(
  224. new FileLogTarget("file", logFile),
  225. 1000
  226. ));
  227. }
  228. else
  229. {
  230. Logger.Error?.Print(LogClass.Application, "No writable log directory available. Make sure either the Logs directory, Application Data, or the Ryujinx directory is writable.");
  231. }
  232. }
  233. // Setup graphics configuration
  234. GraphicsConfig.EnableShaderCache = !option.DisableShaderCache;
  235. GraphicsConfig.EnableTextureRecompression = option.EnableTextureRecompression;
  236. GraphicsConfig.ResScale = option.ResScale;
  237. GraphicsConfig.MaxAnisotropy = option.MaxAnisotropy;
  238. GraphicsConfig.ShadersDumpPath = option.GraphicsShadersDumpPath;
  239. GraphicsConfig.EnableMacroHLE = !option.DisableMacroHLE;
  240. DriverUtilities.InitDriverConfig(option.BackendThreading == BackendThreading.Off);
  241. while (true)
  242. {
  243. LoadApplication(option);
  244. if (_userChannelPersistence.PreviousIndex == -1 || !_userChannelPersistence.ShouldRestart)
  245. {
  246. break;
  247. }
  248. _userChannelPersistence.ShouldRestart = false;
  249. }
  250. _inputManager.Dispose();
  251. }
  252. private static void SetupProgressHandler()
  253. {
  254. if (_emulationContext.Processes.ActiveApplication.DiskCacheLoadState != null)
  255. {
  256. _emulationContext.Processes.ActiveApplication.DiskCacheLoadState.StateChanged -= ProgressHandler;
  257. _emulationContext.Processes.ActiveApplication.DiskCacheLoadState.StateChanged += ProgressHandler;
  258. }
  259. _emulationContext.Gpu.ShaderCacheStateChanged -= ProgressHandler;
  260. _emulationContext.Gpu.ShaderCacheStateChanged += ProgressHandler;
  261. }
  262. private static void ProgressHandler<T>(T state, int current, int total) where T : Enum
  263. {
  264. string label = state switch
  265. {
  266. LoadState => $"PTC : {current}/{total}",
  267. ShaderCacheState => $"Shaders : {current}/{total}",
  268. _ => throw new ArgumentException($"Unknown Progress Handler type {typeof(T)}"),
  269. };
  270. Logger.Info?.Print(LogClass.Application, label);
  271. }
  272. private static WindowBase CreateWindow(Options options)
  273. {
  274. return options.GraphicsBackend switch
  275. {
  276. GraphicsBackend.Vulkan => new VulkanWindow(_inputManager, options.LoggingGraphicsDebugLevel, options.AspectRatio, options.EnableMouse, options.HideCursorMode, options.IgnoreControllerApplet),
  277. GraphicsBackend.Metal => OperatingSystem.IsMacOS() ?
  278. new MetalWindow(_inputManager, options.LoggingGraphicsDebugLevel, options.AspectRatio, options.EnableKeyboard, options.HideCursorMode, options.IgnoreControllerApplet) :
  279. throw new Exception("Attempted to use Metal renderer on non-macOS platform!"),
  280. _ => new OpenGLWindow(_inputManager, options.LoggingGraphicsDebugLevel, options.AspectRatio, options.EnableMouse, options.HideCursorMode, options.IgnoreControllerApplet)
  281. };
  282. }
  283. private static void ExecutionEntrypoint()
  284. {
  285. if (OperatingSystem.IsWindows())
  286. {
  287. _windowsMultimediaTimerResolution = new WindowsMultimediaTimerResolution(1);
  288. }
  289. DisplaySleep.Prevent();
  290. _window.Initialize(_emulationContext, _inputConfiguration, _enableKeyboard, _enableMouse);
  291. _window.Execute();
  292. _emulationContext.Dispose();
  293. _window.Dispose();
  294. if (OperatingSystem.IsWindows())
  295. {
  296. _windowsMultimediaTimerResolution?.Dispose();
  297. _windowsMultimediaTimerResolution = null;
  298. }
  299. }
  300. private static bool LoadApplication(Options options)
  301. {
  302. string path = options.InputPath;
  303. Logger.RestartTime();
  304. WindowBase window = CreateWindow(options);
  305. IRenderer renderer = CreateRenderer(options, window);
  306. _window = window;
  307. _window.IsFullscreen = options.IsFullscreen;
  308. _window.DisplayId = options.DisplayId;
  309. _window.IsExclusiveFullscreen = options.IsExclusiveFullscreen;
  310. _window.ExclusiveFullscreenWidth = options.ExclusiveFullscreenWidth;
  311. _window.ExclusiveFullscreenHeight = options.ExclusiveFullscreenHeight;
  312. _window.AntiAliasing = options.AntiAliasing;
  313. _window.ScalingFilter = options.ScalingFilter;
  314. _window.ScalingFilterLevel = options.ScalingFilterLevel;
  315. _emulationContext = InitializeEmulationContext(window, renderer, options);
  316. SystemVersion firmwareVersion = _contentManager.GetCurrentFirmwareVersion();
  317. Logger.Notice.Print(LogClass.Application, $"Using Firmware Version: {firmwareVersion?.VersionString}");
  318. if (Directory.Exists(path))
  319. {
  320. string[] romFsFiles = Directory.GetFiles(path, "*.istorage");
  321. if (romFsFiles.Length == 0)
  322. {
  323. romFsFiles = Directory.GetFiles(path, "*.romfs");
  324. }
  325. if (romFsFiles.Length > 0)
  326. {
  327. Logger.Info?.Print(LogClass.Application, "Loading as cart with RomFS.");
  328. if (!_emulationContext.LoadCart(path, romFsFiles[0]))
  329. {
  330. _emulationContext.Dispose();
  331. return false;
  332. }
  333. }
  334. else
  335. {
  336. Logger.Info?.Print(LogClass.Application, "Loading as cart WITHOUT RomFS.");
  337. if (!_emulationContext.LoadCart(path))
  338. {
  339. _emulationContext.Dispose();
  340. return false;
  341. }
  342. }
  343. }
  344. else if (File.Exists(path))
  345. {
  346. switch (Path.GetExtension(path).ToLowerInvariant())
  347. {
  348. case ".xci":
  349. Logger.Info?.Print(LogClass.Application, "Loading as XCI.");
  350. if (!_emulationContext.LoadXci(path))
  351. {
  352. _emulationContext.Dispose();
  353. return false;
  354. }
  355. break;
  356. case ".nca":
  357. Logger.Info?.Print(LogClass.Application, "Loading as NCA.");
  358. if (!_emulationContext.LoadNca(path))
  359. {
  360. _emulationContext.Dispose();
  361. return false;
  362. }
  363. break;
  364. case ".nsp":
  365. case ".pfs0":
  366. Logger.Info?.Print(LogClass.Application, "Loading as NSP.");
  367. if (!_emulationContext.LoadNsp(path))
  368. {
  369. _emulationContext.Dispose();
  370. return false;
  371. }
  372. break;
  373. default:
  374. Logger.Info?.Print(LogClass.Application, "Loading as Homebrew.");
  375. try
  376. {
  377. if (!_emulationContext.LoadProgram(path))
  378. {
  379. _emulationContext.Dispose();
  380. return false;
  381. }
  382. }
  383. catch (ArgumentOutOfRangeException)
  384. {
  385. Logger.Error?.Print(LogClass.Application, "The specified file is not supported by Ryujinx.");
  386. _emulationContext.Dispose();
  387. return false;
  388. }
  389. break;
  390. }
  391. }
  392. else
  393. {
  394. Logger.Warning?.Print(LogClass.Application, $"Couldn't load '{options.InputPath}'. Please specify a valid XCI/NCA/NSP/PFS0/NRO file.");
  395. _emulationContext.Dispose();
  396. return false;
  397. }
  398. SetupProgressHandler();
  399. ExecutionEntrypoint();
  400. return true;
  401. }
  402. }
  403. }