From 57a6a36d9bdee4b19cf34c7a246ebd6fa93c4750 Mon Sep 17 00:00:00 2001 From: Vincent Maas Date: Thu, 19 Jan 2023 19:08:59 +0100 Subject: [PATCH] fix LG connection issues, improve color temperature setting, add rBAR driver settings --- ColorControl/AppContext.cs | 4 +- ColorControl/ColorControl.csproj | 4 +- ColorControl/MainForm.Designer.cs | 4 +- ColorControl/MainForm.cs | 49 ++++--- ColorControl/Program.cs | 32 ++++- ColorControl/Services/AMD/ADL.cs | 7 +- ColorControl/Services/AMD/AmdService.cs | 9 +- .../Services/Common/AppContextProvider.cs | 11 ++ .../Services/Common/GraphicsService.cs | 2 +- ColorControl/Services/Common/ServiceBase.cs | 14 +- .../Services/GameLauncher/GameService.cs | 9 +- ColorControl/Services/LG/LgDevice.cs | 6 +- ColorControl/Services/LG/LgService.cs | 9 +- ColorControl/Services/NVIDIA/NvService.cs | 131 ++++++++++++++++-- .../Svc/ColorControlBackgroundService.cs | 9 ++ ColorControl/Svc/SvcMessage.cs | 14 +- ColorControl/lgtv/LgTvApi.cs | 13 +- ColorControl/lgtv/LgTvConnection.cs | 8 +- Nspector/Common/DrsSettingsMetaService.cs | 2 +- Nspector/Common/DrsSettingsService.cs | 21 +++ Nspector/frmDrvSettings.cs | 2 +- 21 files changed, 296 insertions(+), 64 deletions(-) create mode 100644 ColorControl/Services/Common/AppContextProvider.cs diff --git a/ColorControl/AppContext.cs b/ColorControl/AppContext.cs index ae67d98..719c3b8 100644 --- a/ColorControl/AppContext.cs +++ b/ColorControl/AppContext.cs @@ -7,11 +7,13 @@ public Config Config { get; private set; } public StartUpParams StartUpParams { get; private set; } + public string DataPath { get; private set; } - public AppContext(Config config, StartUpParams startUpParams) + public AppContext(Config config, StartUpParams startUpParams, string dataPath) { Config = config; StartUpParams = startUpParams; + DataPath = dataPath; CurrentContext = this; } diff --git a/ColorControl/ColorControl.csproj b/ColorControl/ColorControl.csproj index 725c61c..72868a4 100644 --- a/ColorControl/ColorControl.csproj +++ b/ColorControl/ColorControl.csproj @@ -19,8 +19,8 @@ Maassoft Maassoft 0 - 8.3.0.0 - 8.3.0.0 + 8.4.0.0 + 8.4.0.0 false true false diff --git a/ColorControl/MainForm.Designer.cs b/ColorControl/MainForm.Designer.cs index 40856c4..eb4b332 100644 --- a/ColorControl/MainForm.Designer.cs +++ b/ColorControl/MainForm.Designer.cs @@ -773,7 +773,6 @@ this.lvNvPresets.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); this.lvNvPresets.MultiSelect = false; this.lvNvPresets.Name = "lvNvPresets"; - this.lvNvPresets.ShowItemToolTips = true; this.lvNvPresets.Size = new System.Drawing.Size(1098, 415); this.lvNvPresets.TabIndex = 0; this.lvNvPresets.UseCompatibleStateImageBehavior = false; @@ -1836,7 +1835,8 @@ "Power on even after manual power off", "Allow triggers to be fired for this device", "Use Windows power settings to power on", - "Use Windows power settings to power off"}); + "Use Windows power settings to power off", + "Use secure connection"}); this.clbLgPower.Location = new System.Drawing.Point(6, 70); this.clbLgPower.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); this.clbLgPower.MultiColumn = true; diff --git a/ColorControl/MainForm.cs b/ColorControl/MainForm.cs index a2ed760..92476bc 100644 --- a/ColorControl/MainForm.cs +++ b/ColorControl/MainForm.cs @@ -9,6 +9,7 @@ using ColorControl.Services.LG; using ColorControl.Services.NVIDIA; using ColorControl.Svc; using LgTv; +using Microsoft.Extensions.DependencyInjection; using NLog; using nspector; using nspector.Common; @@ -193,7 +194,8 @@ namespace ColorControl { //throw new Exception("bla"); Logger.Debug("Initializing NVIDIA..."); - _nvService = new NvService(_dataDir); + var appContextProvider = Program.ServiceProvider.GetRequiredService(); + _nvService = new NvService(appContextProvider); FillNvPresets(); Logger.Debug("Initializing NVIDIA...Done."); @@ -220,7 +222,8 @@ namespace ColorControl { try { - _amdService = new AmdService(_dataDir); + var appContextProvider = Program.ServiceProvider.GetRequiredService(); + _amdService = new AmdService(appContextProvider); FillAmdPresets(); InitSortState(lvAmdPresets, _config.AmdPresetsSortState); @@ -241,7 +244,8 @@ namespace ColorControl { try { - _gameService = new GameService(_dataDir, HandleExternalServiceForLgDevice); + var appContextProvider = Program.ServiceProvider.GetRequiredService(); + _gameService = new GameService(appContextProvider, HandleExternalServiceForLgDevice); FillGamePresets(); InitSortState(lvGamePresets, _config.GamePresetsSortState); @@ -274,7 +278,9 @@ namespace ColorControl { try { - _lgService = new LgService(_dataDir, StartUpParams.RunningFromScheduledTask); + var appContextProvider = Program.ServiceProvider.GetRequiredService(); + + _lgService = new LgService(appContextProvider, StartUpParams.RunningFromScheduledTask); _lgService.RefreshDevices(afterStartUp: true).ContinueWith((_) => BeginInvoke(() => AfterLgServiceRefreshDevices())); _lgService.SelectedDeviceChangedEvent += _lgService_SelectedDeviceChangedEvent; @@ -1933,7 +1939,8 @@ NOTE: installing the service may cause a User Account Control popup."); clbLgPower.SetItemChecked(6, device?.PowerOnAfterManualPowerOff ?? false); clbLgPower.SetItemChecked(7, device?.TriggersEnabled ?? true); clbLgPower.SetItemChecked(8, device?.PowerOffByWindows ?? false); - clbLgPower.SetItemChecked(8, device?.PowerOnByWindows ?? false); + clbLgPower.SetItemChecked(9, device?.PowerOnByWindows ?? false); + clbLgPower.SetItemChecked(10, device?.UseSecureConnection ?? false); } finally { @@ -2123,7 +2130,7 @@ NOTE: installing the service may cause a User Account Control popup."); } try { - var result = _nvService.ApplyPreset(preset, Program.AppContext); + var result = _nvService.ApplyPreset(preset); if (!result) { throw new Exception("Error while applying NVIDIA preset. At least one setting could not be applied. Check the log for details."); @@ -2476,8 +2483,14 @@ You can also activate this option by using the Expert-button and selecting Wake- device.TriggersEnabled = clbLgPower.GetItemChecked(7); device.PowerOffByWindows = clbLgPower.GetItemChecked(8); device.PowerOnByWindows = clbLgPower.GetItemChecked(9); + device.UseSecureConnection = clbLgPower.GetItemChecked(10); _lgService.InstallEventHandlers(); + + if (e.Index == 10) + { + _lgService.RefreshDevices().ContinueWith((_) => BeginInvoke(() => FillLgDevices())); + } }); } @@ -2550,10 +2563,15 @@ Do you want to continue?"; private void MainForm_Activated(object sender, EventArgs e) { - UpdateDisplayInfoItems(); - UpdateDisplayInfoItemsAmd(); - - if (tcMain.SelectedTab == tabLog) + if (tcMain.SelectedTab == tabNVIDIA) + { + UpdateDisplayInfoItems(); + } + else if (tcMain.SelectedTab == tabAMD) + { + UpdateDisplayInfoItemsAmd(); + } + else if (tcMain.SelectedTab == tabLog) { LoadLog(); } @@ -4592,26 +4610,17 @@ Currently ColorControl is {(Utils.IsAdministrator() ? "" : "not ")}running as ad point.X += 10; point.Y += 0; + lvNvPresetsToolTip.Active = false; if (index >= 0) { - if (lvNvPresetsToolTip.Active) - { - lvNvPresetsToolTip.Active = false; - } - lvNvPresetsToolTip.Active = true; lvNvPresetsToolTip.Show("", lvNvPresets, point); lvNvPresetsToolTip.Show(text, lvNvPresets, point); } - else - { - lvNvPresetsToolTip.Active = false; - } } private void lvNvPresets_MouseLeave(object sender, EventArgs e) { - lvNvPresetsToolTip.Active = false; } } } \ No newline at end of file diff --git a/ColorControl/Program.cs b/ColorControl/Program.cs index 6fae815..e74979c 100644 --- a/ColorControl/Program.cs +++ b/ColorControl/Program.cs @@ -1,6 +1,7 @@ using ColorControl.Common; using ColorControl.Forms; using ColorControl.Services.AMD; +using ColorControl.Services.Common; using ColorControl.Services.LG; using ColorControl.Services.NVIDIA; using ColorControl.Svc; @@ -53,8 +54,13 @@ namespace ColorControl Logger.Debug($"Using data path: {DataDir}"); //Logger.Debug("Parent process: " + Process.GetCurrentProcess().Parent()?.ProcessName); + var host = CreateHostBuilder().Build(); + ServiceProvider = host.Services; + if (runAsService) { + AppContext = new AppContext(null, new StartUpParams(), DataDir); + Utils.WaitForTask(RunService(args)); return; } @@ -76,7 +82,7 @@ namespace ColorControl var startUpParams = StartUpParams.Parse(args); - AppContext = new AppContext(Config, startUpParams); + AppContext = new AppContext(Config, startUpParams, DataDir); var existingProcess = Utils.GetProcessByName("ColorControl"); @@ -122,10 +128,10 @@ namespace ColorControl _mainForm = new MainForm(AppContext); Application.Run(_mainForm); - //if (Debugger.IsAttached && !IsRestarting) - //{ - // Utils.StopService(); - //} + if (Debugger.IsAttached && !IsRestarting) + { + Utils.StopService(); + } } catch (Exception ex) { @@ -339,6 +345,16 @@ namespace ColorControl } } + public static IServiceProvider ServiceProvider { get; private set; } + private static IHostBuilder CreateHostBuilder() + { + return Host.CreateDefaultBuilder() + .ConfigureServices((context, services) => + { + //services.AddSingleton(); + services.RegisterSharedServices(); + }); + } private static async Task RunService(string[] args) { Logger.Debug("RUNNING SERVICE"); @@ -350,6 +366,7 @@ namespace ColorControl }) .ConfigureServices(services => { + services.RegisterSharedServices(); services.AddHostedService(); }) .Build(); @@ -357,6 +374,11 @@ namespace ColorControl await host.RunAsync(); } + private static void RegisterSharedServices(this IServiceCollection services) + { + services.AddSingleton(); + } + public static int EnumThreadWindows(IntPtr handle, IntPtr param) { NativeMethods.SendMessageW(handle, Utils.WM_BRINGTOFRONT, UIntPtr.Zero, IntPtr.Zero); diff --git a/ColorControl/Services/AMD/ADL.cs b/ColorControl/Services/AMD/ADL.cs index ce03ee6..757c560 100644 --- a/ColorControl/Services/AMD/ADL.cs +++ b/ColorControl/Services/AMD/ADL.cs @@ -139,6 +139,8 @@ namespace ATI.ADL /// ADL Class internal static class ADL { + private static readonly NLog.Logger Logger = NLog.LogManager.GetCurrentClassLogger(); + #region Internal Constant /// Define the maximum path internal const int ADL_MAX_PATH = 256; @@ -380,7 +382,10 @@ namespace ATI.ADL } } - throw new InvalidProgramException("ADL-function not supported"); + Logger.Error($"ADL-function not supported: {type.Name}"); + + return null; + //throw new InvalidProgramException("ADL-function not supported"); } #endregion Export Functions diff --git a/ColorControl/Services/AMD/AmdService.cs b/ColorControl/Services/AMD/AmdService.cs index e5af97f..cd8221f 100644 --- a/ColorControl/Services/AMD/AmdService.cs +++ b/ColorControl/Services/AMD/AmdService.cs @@ -1,6 +1,7 @@ using ATI.ADL; using ColorControl.Common; using ColorControl.Services.Common; +using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Generic; using System.Linq; @@ -14,9 +15,11 @@ namespace ColorControl.Services.AMD public override string ServiceName => "AMD"; + protected override string PresetsBaseFilename => "AmdPresets.json"; + private ADLDisplayInfo _currentDisplay; - public AmdService(string dataPath) : base(dataPath, "AmdPresets.json") + public AmdService(AppContextProvider appContextProvider) : base(appContextProvider) { LoadPresets(); } @@ -25,7 +28,9 @@ namespace ColorControl.Services.AMD { try { - var service = new AmdService(Program.DataDir); + var appContextProvider = Program.ServiceProvider.GetRequiredService(); + + var service = new AmdService(appContextProvider); var result = service.ApplyPreset(idOrName); diff --git a/ColorControl/Services/Common/AppContextProvider.cs b/ColorControl/Services/Common/AppContextProvider.cs new file mode 100644 index 0000000..43dc84a --- /dev/null +++ b/ColorControl/Services/Common/AppContextProvider.cs @@ -0,0 +1,11 @@ +namespace ColorControl.Services.Common +{ + public class AppContextProvider + { + public AppContext GetAppContext() + { + return Program.AppContext; + } + + } +} diff --git a/ColorControl/Services/Common/GraphicsService.cs b/ColorControl/Services/Common/GraphicsService.cs index 5381efd..bcaab6b 100644 --- a/ColorControl/Services/Common/GraphicsService.cs +++ b/ColorControl/Services/Common/GraphicsService.cs @@ -14,7 +14,7 @@ namespace ColorControl.Services.Common { private static readonly NLog.Logger Logger = NLog.LogManager.GetCurrentClassLogger(); - public GraphicsService(string dataPath, string presetsBaseFilename) : base(dataPath, presetsBaseFilename) + public GraphicsService(AppContextProvider appContextProvider) : base(appContextProvider) { } diff --git a/ColorControl/Services/Common/ServiceBase.cs b/ColorControl/Services/Common/ServiceBase.cs index 208a97c..4073db3 100644 --- a/ColorControl/Services/Common/ServiceBase.cs +++ b/ColorControl/Services/Common/ServiceBase.cs @@ -16,9 +16,9 @@ namespace ColorControl.Services.Common { get; } + protected abstract string PresetsBaseFilename { get; } protected string _dataPath; - protected string _presetsBaseFilename; protected string _presetsFilename; protected string _presetsBackupFilename; protected bool _initialized = false; @@ -26,12 +26,14 @@ namespace ColorControl.Services.Common protected T _lastAppliedPreset; protected string _loadPresetsError; + protected AppContextProvider _appContextProvider; + private List _jsonConverters; - public ServiceBase(string dataPath, string presetsBaseFilename) + public ServiceBase(AppContextProvider appContextProvider) { - _dataPath = dataPath; - _presetsBaseFilename = presetsBaseFilename; + _appContextProvider = appContextProvider; + _dataPath = appContextProvider.GetAppContext().DataPath; _jsonConverters = new List(); Initialize(); @@ -99,8 +101,8 @@ namespace ColorControl.Services.Common protected void LoadPresets() { - _presetsFilename = Path.Combine(_dataPath, _presetsBaseFilename); - _presetsBackupFilename = Path.Combine(_dataPath, $"{_presetsBaseFilename}.backup"); + _presetsFilename = Path.Combine(_dataPath, PresetsBaseFilename); + _presetsBackupFilename = Path.Combine(_dataPath, $"{PresetsBaseFilename}.backup"); try { diff --git a/ColorControl/Services/GameLauncher/GameService.cs b/ColorControl/Services/GameLauncher/GameService.cs index 57ed3e2..85b498d 100644 --- a/ColorControl/Services/GameLauncher/GameService.cs +++ b/ColorControl/Services/GameLauncher/GameService.cs @@ -1,5 +1,6 @@ using ColorControl.Common; using ColorControl.Services.Common; +using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Generic; using System.Diagnostics; @@ -14,9 +15,11 @@ namespace ColorControl.Services.GameLauncher public override string ServiceName => "Game"; + protected override string PresetsBaseFilename => "GamePresets.json"; + private Func _externalServiceHandler; - public GameService(string dataPath, Func externalServiceHandler = null) : base(dataPath, "GamePresets.json") + public GameService(AppContextProvider appContextProvider, Func externalServiceHandler = null) : base(appContextProvider) { LoadPresets(); _externalServiceHandler = externalServiceHandler; @@ -26,7 +29,9 @@ namespace ColorControl.Services.GameLauncher { try { - var service = new GameService(Program.DataDir); + var appContextProvider = Program.ServiceProvider.GetRequiredService(); + + var service = new GameService(appContextProvider); var result = service.ApplyPreset(idOrName); diff --git a/ColorControl/Services/LG/LgDevice.cs b/ColorControl/Services/LG/LgDevice.cs index 9593107..16df178 100644 --- a/ColorControl/Services/LG/LgDevice.cs +++ b/ColorControl/Services/LG/LgDevice.cs @@ -87,6 +87,8 @@ namespace ColorControl.Services.LG public bool TriggersEnabled { get; set; } public int HDMIPortNumber { get; set; } + public bool UseSecureConnection { get; set; } = true; + private List _actionsForGameBar; public List ActionsOnGameBar @@ -165,7 +167,7 @@ namespace ColorControl.Services.LG AddGenericPictureAction("colorGamut", typeof(ColorGamut), title: "Color Gamut"); AddGenericPictureAction("dynamicContrast", typeof(OffToHigh), title: "Dynamic Contrast"); AddGenericPictureAction("gamma", typeof(GammaExp)); - AddGenericPictureAction("colorTemperature", minValue: 0, maxValue: 50, title: "Color Temperature"); + AddGenericPictureAction("colorTemperature", minValue: -50, maxValue: 50, title: "Color Temperature"); AddGenericPictureAction("whiteBalanceColorTemperature", typeof(WhiteBalanceColorTemperature), title: "White Balance Color Temperature"); AddGenericPictureAction("eyeComfortMode", typeof(OffToOn), title: "Eye Comfort Mode"); //AddGenericPictureAction("dynamicColor", typeof(OffToAuto)); @@ -347,7 +349,7 @@ namespace ColorControl.Services.LG try { DisposeConnection(); - _lgTvApi = await LgTvApi.CreateLgTvApi(IpAddress, retries); + _lgTvApi = await LgTvApi.CreateLgTvApi(IpAddress, retries, UseSecureConnection); //Test(); //_lgTvApi.Test3(); diff --git a/ColorControl/Services/LG/LgService.cs b/ColorControl/Services/LG/LgService.cs index 86d0e84..3e08be6 100644 --- a/ColorControl/Services/LG/LgService.cs +++ b/ColorControl/Services/LG/LgService.cs @@ -3,6 +3,7 @@ using ColorControl.Forms; using ColorControl.Services.Common; using ColorControl.Svc; using LgTv; +using Microsoft.Extensions.DependencyInjection; using Microsoft.Win32; using Newtonsoft.Json; using NWin32; @@ -71,6 +72,8 @@ namespace ColorControl.Services.LG public LgServiceConfig Config { get; private set; } public ProcessMonitorContext MonitorContext { get; private set; } + protected override string PresetsBaseFilename => "LgPresets.json"; + private string _configFilename; private bool _allowPowerOn; private LgDevice _selectedDevice; @@ -85,7 +88,7 @@ namespace ColorControl.Services.LG private LgPreset _lastTriggeredPreset; private RestartDetector _restartDetector; - public LgService(string dataPath, bool allowPowerOn) : base(dataPath, "LgPresets.json") + public LgService(AppContextProvider appContextProvider, bool allowPowerOn) : base(appContextProvider) { _allowPowerOn = allowPowerOn; @@ -107,7 +110,9 @@ namespace ColorControl.Services.LG { try { - var lgService = new LgService(Program.DataDir, true); + var appContextProvider = Program.ServiceProvider.GetRequiredService(); + + var lgService = new LgService(appContextProvider, true); await lgService.RefreshDevices(afterStartUp: true); var result = await lgService.ApplyPreset(presetName); diff --git a/ColorControl/Services/NVIDIA/NvService.cs b/ColorControl/Services/NVIDIA/NvService.cs index 23971c1..c840122 100644 --- a/ColorControl/Services/NVIDIA/NvService.cs +++ b/ColorControl/Services/NVIDIA/NvService.cs @@ -1,9 +1,13 @@ using ColorControl.Common; using ColorControl.Forms; using ColorControl.Services.Common; +using ColorControl.Svc; +using Microsoft.Extensions.DependencyInjection; using nspector.Common; using nspector.Common.Meta; using NvAPIWrapper.Display; +using NvAPIWrapper.GPU; +using NvAPIWrapper.Native; using NvAPIWrapper.Native.Display; using NvAPIWrapper.Native.GPU.Structures; using NWin32.NativeTypes; @@ -13,6 +17,8 @@ using System.ComponentModel; using System.Linq; using System.Runtime.InteropServices; using System.Threading; +using static NvAPIWrapper.Native.GPU.Structures.PerformanceStates20ClockEntryV1; +using static NvAPIWrapper.Native.GPU.Structures.PrivateClockBoostLockV2; namespace ColorControl.Services.NVIDIA { @@ -83,6 +89,8 @@ namespace ColorControl.Services.NVIDIA public override string ServiceName => "NVIDIA"; + protected override string PresetsBaseFilename => "NvPresets.json"; + private Display _currentDisplay; private string _baseProfileName = ""; @@ -104,9 +112,29 @@ namespace ColorControl.Services.NVIDIA public const uint DRS_TEXTURE_FILTERING_QUALITY = 0x00CE2691; public const uint DRS_TEXTURE_FILTERING_NEGATIVE_LOD_BIAS = 0x0019BB68; - private static readonly List _driverSettingIds = new() { DRS_GSYNC_APPLICATION_MODE, DRS_VSYNC_CONTROL, DRS_PRERENDERED_FRAMES, DRS_FRAME_RATE_LIMITER_V3, DRS_ANISOTROPIC_FILTERING_SETTING, DRS_ANISOTROPIC_FILTER_OPTIMIZATION, DRS_TEXTURE_FILTERING_QUALITY, DRS_TEXTURE_FILTERING_NEGATIVE_LOD_BIAS, DRS_ANISOTROPIC_FILTER_SAMPLE_OPTIMIZATION }; + public const uint DRS_RBAR_FEATURE = 0X000F00BA; + public const uint DRS_RBAR_OPTIONS = 0X000F00BB; + public const uint DRS_RBAR_SIZE_LIMIT = 0X000F00FF; - public NvService(string dataPath) : base(dataPath, "NvPresets.json") + private static readonly List _driverSettingIds = new() + { + DRS_GSYNC_APPLICATION_MODE, + DRS_VSYNC_CONTROL, + DRS_PRERENDERED_FRAMES, + DRS_FRAME_RATE_LIMITER_V3, + DRS_ANISOTROPIC_FILTERING_SETTING, + DRS_ANISOTROPIC_FILTER_OPTIMIZATION, + DRS_TEXTURE_FILTERING_QUALITY, + DRS_TEXTURE_FILTERING_NEGATIVE_LOD_BIAS, + DRS_ANISOTROPIC_FILTER_SAMPLE_OPTIMIZATION, + DRS_RBAR_FEATURE, + DRS_RBAR_OPTIONS, + DRS_RBAR_SIZE_LIMIT + }; + + private static NvService ServiceInstance; + + public NvService(AppContextProvider appContextProvider) : base(appContextProvider) { NvPreset.NvService = this; @@ -119,7 +147,9 @@ namespace ColorControl.Services.NVIDIA { try { - var nvService = new NvService(Program.DataDir); + var appContextProvider = Program.ServiceProvider.GetRequiredService(); + + var nvService = new NvService(appContextProvider); var result = nvService.ApplyPreset(idOrName); @@ -216,7 +246,7 @@ namespace ColorControl.Services.NVIDIA var preset = GetPresetByIdOrName(idOrName); if (preset != null) { - return ApplyPreset(preset, Program.AppContext); + return ApplyPreset(preset); } else { @@ -225,11 +255,6 @@ namespace ColorControl.Services.NVIDIA } public override bool ApplyPreset(NvPreset preset) - { - return ApplyPreset(preset, Program.AppContext); - } - - public bool ApplyPreset(NvPreset preset, AppContext appContext) { var result = true; @@ -278,6 +303,8 @@ namespace ColorControl.Services.NVIDIA { var colorData = preset.applyColorData ? preset.colorData : display.DisplayDevice.CurrentColorData; + var appContext = _appContextProvider.GetAppContext(); + SetHDRState(display, newHdrEnabled, colorData, appContext.StartUpParams.NoGui); } @@ -309,6 +336,19 @@ namespace ColorControl.Services.NVIDIA return result; } + public static void ApplyDriverSettings(List> settings) + { + var appContextProvider = Program.ServiceProvider.GetRequiredService(); + + if (ServiceInstance == null) + { + ServiceInstance = new NvService(appContextProvider); + ServiceInstance.Initialize(); + } + + ServiceInstance._drs.StoreSettingsToProfile(ServiceInstance._baseProfileName, settings); + } + private void SetDriverSettings(NvPreset preset) { var settings = new List>(); @@ -601,7 +641,7 @@ namespace ColorControl.Services.NVIDIA { var settingMeta = GetSettingMeta(setting.SettingId); - var settingValue = settingMeta.DwordValues.FirstOrDefault(s => s.ValueName == setting.ValueText); + var settingValue = settingMeta.DwordValues?.FirstOrDefault(s => s.ValueName == setting.ValueText); drsValues.Add($"{settingMeta.SettingName}: {settingValue?.ValueName ?? "Unknown"}"); } @@ -676,6 +716,13 @@ namespace ColorControl.Services.NVIDIA _drs.GetProfileNames(ref _baseProfileName, false); + if (!Utils.IsAdministrator()) + { + _drs.ApplySettings += HandleDrsApplySettings; + } + + //SetGpuClocks(); + //Task.Run(() => //{ // RefreshProfileSettings(); @@ -701,6 +748,18 @@ namespace ColorControl.Services.NVIDIA } } + private void HandleDrsApplySettings(object sender, DrsEvent drsEvent) + { + if (Utils.IsAdministrator() || _appContextProvider.GetAppContext()?.Config.ElevationMethod != ElevationMethod.UseService) + { + return; + } + + PipeUtils.SendMessage(new SvcNvDriverSettingsMessage { DriverSettings = drsEvent.Settings }); + + drsEvent.Handled = true; + } + protected override void Uninitialize() { if (_initialized) @@ -708,5 +767,57 @@ namespace ColorControl.Services.NVIDIA NvAPIWrapper.NVIDIA.Unload(); } } + + public void SetGpuClocks() + { + // TEST ONLY + var gpu = PhysicalGPU.GetPhysicalGPUs().FirstOrDefault(); + + if (gpu == null) + { + Logger.Debug("No GPU"); + return; + } + + var handle = gpu.Handle; + + var perf = GPUApi.GetPerformanceStates20(handle); + + var lockv2 = new PrivateClockBoostLockV2(new[] { new ClockBoostLock(NvAPIWrapper.Native.GPU.PublicClockDomain.Graphics, NvAPIWrapper.Native.GPU.ClockLockMode.Manual, 1000000) }); + + var bla = GPUApi.GetClockBoostLock(handle); + + //GPUApi.SetClockBoostLock(handle, lockv2); + + //var curve = GPUApi.GetVFPCurve(handle); + + var currentFreq = perf.Clocks.First().Value.First(v => v.DomainId == NvAPIWrapper.Native.GPU.PublicClockDomain.Graphics).SingleFrequency; + + var delta = new PerformanceStates20ParameterDelta(90000); + //var delta2 = new PerformanceStates20ParameterDelta(0); + //var delta3 = new PerformanceStates20ParameterDelta(0); + //var single1 = new PerformanceStates20ClockDependentSingleFrequency(2670000); + //var single2 = new PerformanceStates20ClockDependentSingleFrequency(2760000); + //var single3 = new PerformanceStates20ClockDependentSingleFrequency(2775000); + + //var clockEntry1 = new PerformanceStates20ClockEntryV1(NvAPIWrapper.Native.GPU.PublicClockDomain.Graphics, delta, single1); + //var clockEntry2 = new PerformanceStates20ClockEntryV1(NvAPIWrapper.Native.GPU.PublicClockDomain.Graphics, delta2, single2); + //var clockEntry3 = new PerformanceStates20ClockEntryV1(NvAPIWrapper.Native.GPU.PublicClockDomain.Graphics, delta3, single3); + + var range = new PerformanceStates20ClockDependentFrequencyRange(2400000, 3000000, NvAPIWrapper.Native.GPU.PerformanceVoltageDomain.Core, 950000, 1050000); + var clockEntry = new PerformanceStates20ClockEntryV1(NvAPIWrapper.Native.GPU.PublicClockDomain.Graphics, delta, range); + + //var range2 = new PerformanceStates20ClockDependentFrequencyRange(2800001, 3000000, NvAPIWrapper.Native.GPU.PerformanceVoltageDomain.Core, 1000000, 1000000); + //var clockEntry2 = new PerformanceStates20ClockEntryV1(NvAPIWrapper.Native.GPU.PublicClockDomain.Graphics, delta2, range2); + + var deltaVoltage = new PerformanceStates20ParameterDelta(0); + var voltage = new PerformanceStates20BaseVoltageEntryV1(NvAPIWrapper.Native.GPU.PerformanceVoltageDomain.Core, deltaVoltage); + + var state = new PerformanceStates20InfoV1.PerformanceState20(NvAPIWrapper.Native.GPU.PerformanceStateId.P0_3DPerformance, new[] { clockEntry }, new[] { voltage }); + + var newPerf = new PerformanceStates20InfoV3(new[] { state }, 1, 1); + + //GPUApi.SetPerformanceStates20(handle, newPerf); + } } } diff --git a/ColorControl/Svc/ColorControlBackgroundService.cs b/ColorControl/Svc/ColorControlBackgroundService.cs index ec90252..0180ee9 100644 --- a/ColorControl/Svc/ColorControlBackgroundService.cs +++ b/ColorControl/Svc/ColorControlBackgroundService.cs @@ -1,5 +1,6 @@ using ColorControl.Common; using ColorControl.Services.LG; +using ColorControl.Services.NVIDIA; using Microsoft.Extensions.Hosting; using Newtonsoft.Json; using NLog; @@ -107,6 +108,7 @@ namespace ColorControl.Svc SvcMessageType.ExecuteRpc => HandleExecuteRpcCommand(message), SvcMessageType.ExecuteUpdate => await HandleExecuteUpdateCommandAsync(JsonConvert.DeserializeObject(json)), SvcMessageType.RestartAfterUpdate => HandleRestartAfterUpdateMessage(), + SvcMessageType.ApplyNvidiaDriverSettings => HandleNvDriverSettingsMessage(JsonConvert.DeserializeObject(json)), _ => SvcResultMessage.FromResult(false, "Unexpected message type") }; @@ -180,6 +182,13 @@ namespace ColorControl.Svc return SvcResultMessage.FromResult(true); } + private SvcResultMessage HandleNvDriverSettingsMessage(SvcNvDriverSettingsMessage message) + { + NvService.ApplyDriverSettings(message.DriverSettings); + + return SvcResultMessage.FromResult(true); + } + private async Task WakeDevicesAsync() { if (!UserSessionInfo.UserLocalSession) diff --git a/ColorControl/Svc/SvcMessage.cs b/ColorControl/Svc/SvcMessage.cs index c28c4e2..9ec5c6e 100644 --- a/ColorControl/Svc/SvcMessage.cs +++ b/ColorControl/Svc/SvcMessage.cs @@ -1,4 +1,6 @@ -namespace ColorControl.Svc +using System.Collections.Generic; + +namespace ColorControl.Svc { public enum SvcMessageType { @@ -8,6 +10,7 @@ ExecuteRpc = 10, ExecuteUpdate = 20, RestartAfterUpdate = 21, + ApplyNvidiaDriverSettings = 101, } public class SvcMessage @@ -28,4 +31,13 @@ public string ClientPath { get; set; } } + public class SvcNvDriverSettingsMessage : SvcMessage + { + public SvcNvDriverSettingsMessage() + { + MessageType = SvcMessageType.ApplyNvidiaDriverSettings; + } + + public List> DriverSettings { get; set; } + } } diff --git a/ColorControl/lgtv/LgTvApi.cs b/ColorControl/lgtv/LgTvApi.cs index 0f44222..cc14e9f 100644 --- a/ColorControl/lgtv/LgTvApi.cs +++ b/ColorControl/lgtv/LgTvApi.cs @@ -282,9 +282,14 @@ namespace LgTv private string _currentPairKey; private string webSocketUri; - public static async Task CreateLgTvApi(string ip, int retries = 1) + protected static readonly NLog.Logger Logger = NLog.LogManager.GetCurrentClassLogger(); + + public static async Task CreateLgTvApi(string ip, int retries = 1, bool useSecureWs = true) { - var instance = new LgTvApi(ip, new LgTvApiCore(), new ClientKeyStore(ip)); + var instance = new LgTvApi(ip, new LgTvApiCore(), new ClientKeyStore(ip), useSecureWs); + + Logger.Debug($"Trying to connect with websocket uri: {instance.webSocketUri}"); + while (retries > 0) { var connected = await instance.Connect(); @@ -300,9 +305,9 @@ namespace LgTv return null; } - private LgTvApi(string ip, LgTvApiCore connection, ClientKeyStore keyStore) + private LgTvApi(string ip, LgTvApiCore connection, ClientKeyStore keyStore, bool useSecureWs) { - webSocketUri = "ws://" + ip + ":3000"; + webSocketUri = useSecureWs ? $"wss://{ip}:3001" : $"ws://{ip}:3000"; _ip = ip; _connection = connection; _keyStore = keyStore; diff --git a/ColorControl/lgtv/LgTvConnection.cs b/ColorControl/lgtv/LgTvConnection.cs index 5c83b19..f433e7d 100644 --- a/ColorControl/lgtv/LgTvConnection.cs +++ b/ColorControl/lgtv/LgTvConnection.cs @@ -7,6 +7,7 @@ using System.Collections.Concurrent; using System.Threading; using System.Threading.Tasks; using Windows.Networking.Sockets; +using Windows.Security.Cryptography.Certificates; using Windows.Storage.Streams; namespace LgTv @@ -40,6 +41,8 @@ namespace LgTv ConnectionClosed = false; _commandCount = 0; _connection = new MessageWebSocket(); + _connection.Control.IgnorableServerCertificateErrors.Add(ChainValidationResult.Untrusted); + _connection.Control.IgnorableServerCertificateErrors.Add(ChainValidationResult.InvalidName); _connection.Control.MessageType = SocketMessageType.Utf8; _connection.MessageReceived += Connection_MessageReceived; _connection.Closed += Connection_Closed; @@ -53,8 +56,9 @@ namespace LgTv IsConnected?.Invoke(true); return true; } - catch (TimeoutException) + catch (TimeoutException te) { + Logger.Error($"Connect to {uri}: {te.Message}"); return false; } } @@ -69,6 +73,8 @@ namespace LgTv // Handle Unknown Error break; } + + Logger.Error($"Connect to {uri}: {e.Message}"); return false; } } diff --git a/Nspector/Common/DrsSettingsMetaService.cs b/Nspector/Common/DrsSettingsMetaService.cs index b7d6c7d..989da44 100644 --- a/Nspector/Common/DrsSettingsMetaService.cs +++ b/Nspector/Common/DrsSettingsMetaService.cs @@ -25,7 +25,7 @@ namespace nspector.Common _customSettings = customSettings; _referenceSettings = referenceSettings; - ResetMetaCache(true); + ResetMetaCache(false); } public void ResetMetaCache(bool initOnly = false) diff --git a/Nspector/Common/DrsSettingsService.cs b/Nspector/Common/DrsSettingsService.cs index cc53151..71bc990 100644 --- a/Nspector/Common/DrsSettingsService.cs +++ b/Nspector/Common/DrsSettingsService.cs @@ -7,8 +7,16 @@ using nvw = nspector.Native.NVAPI2.NvapiDrsWrapper; namespace nspector.Common { + public class DrsEvent : EventArgs + { + public List>? Settings { get; set; } + public bool Handled { get; set; } + } + public class DrsSettingsService : DrsSettingsServiceBase { + public event EventHandler? ApplySettings; + public bool ExternalApplySettings => ApplySettings != null; public DrsSettingsService(DrsSettingsMetaService metaService, DrsDecrypterService decrpterService) : base(metaService, decrpterService) @@ -300,6 +308,19 @@ namespace nspector.Common public int StoreSettingsToProfile(string profileName, List> settings) { + var drsEvent = new DrsEvent + { + Settings = settings, + Handled = false + }; + + ApplySettings?.Invoke(this, drsEvent); + + if (drsEvent.Handled) + { + return 0; + } + DrsSessionScope.DestroyGlobalSession(); DrsSession((hSession) => diff --git a/Nspector/frmDrvSettings.cs b/Nspector/frmDrvSettings.cs index 757813b..5d8a85e 100644 --- a/Nspector/frmDrvSettings.cs +++ b/Nspector/frmDrvSettings.cs @@ -540,7 +540,7 @@ namespace nspector private void frmDrvSettings_Load(object sender, EventArgs e) { - _highlightUnexposedSettings = !IsAdministrator(); + _highlightUnexposedSettings = !IsAdministrator() && !_drs.ExternalApplySettings; SetupLayout(); SetTitleVersion();