forked from xXJSONDeruloXx/Decky-Framegen
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
2198 lines (1975 loc) · 93 KB
/
Copy pathmain.py
File metadata and controls
2198 lines (1975 loc) · 93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import decky
import os
import sys
import subprocess
import json
import shutil
import re
import filecmp
import hashlib
import logging
import time
import ssl
import urllib.request
import urllib.error
from datetime import datetime, timezone
from pathlib import Path
# Decky's sandboxed plugin loader does not put the plugin root directory on
# sys.path (only py_modules), so a bare `from compat_logic import ...` fails at
# load time with ModuleNotFoundError. Add both this file's directory and its
# py_modules subdir to sys.path so the helper module resolves no matter where it
# ends up in the bundle.
_PLUGIN_DIR = os.path.dirname(os.path.abspath(__file__))
for _candidate in (_PLUGIN_DIR, os.path.join(_PLUGIN_DIR, "py_modules")):
if _candidate not in sys.path:
sys.path.insert(0, _candidate)
from compat_logic import (
classify_amd_gpu,
classify_game_compat,
is_curated_match,
normalize_game_name,
parse_curated_markdown,
)
OPTISCALER_ARCHIVE_ASSET = {
"name": "Optiscaler_0.9.3-final.20260618.7z",
"sha256": "e3ac655d60ec11b471ac8cc5f4d3758e4bce9151c86caa339d8f0700c00282e3",
"version": "0.9.3-final.20260618",
}
FSR4_INT8_ASSET = {
"name": "amd_fidelityfx_upscaler_dx12.dll",
"sha256": "c7720bc16bede334f59a1a32cd22edbcbbb159685ed5240e61350a5fb0bc8a94",
"version": "4.0.2c",
}
FSR4_OFFICIAL_411_ASSET = {
"name": "amdxcffx64.dll",
"sha256": "a2b136b6affd35a49b141a936be935f7d5ddc8d8f9b8c9afbe62ff9ddb2538a0",
"version": "4.1.1-official",
}
OPTIPATCHER_ASSET = {
"name": "OptiPatcher_rolling.asi",
"sha256": "88b9e1be3559737cd205fdf5f2c8550cf1923fb1def4c603e5bf03c3e84131b1",
"version": "rolling",
}
FSR4_UPSCALER_FILENAME = "amd_fidelityfx_upscaler_dx12.dll"
FSR4_DRIVER_OVERRIDE_FILENAME = "amdxcffx64.dll"
INSTALL_MANIFEST_FILENAME = "install-manifest.json"
VERSION_FILENAME = "version.txt"
DEFAULT_FSR4_VARIANT = "rdna23-int8"
FSR4_VARIANTS = {
"rdna23-int8": {
"label": "Steam Deck / RDNA2-3 optimized",
"dir_name": "fsr4-rdna2-3",
"sha256": "c7720bc16bede334f59a1a32cd22edbcbbb159685ed5240e61350a5fb0bc8a94",
"source_asset_name": FSR4_INT8_ASSET["name"],
"source_version": FSR4_INT8_ASSET["version"],
"uses_archive_native": False,
"extra_files": [],
},
"rdna4-native": {
"label": "Native bundle / RDNA4",
"dir_name": "fsr4-rdna4",
"sha256": "ec7ed3ca674e288240e6f04b986342aece47454c41d9b0959449e82e22bd7f6d",
"source_asset_name": OPTISCALER_ARCHIVE_ASSET["name"],
"source_version": OPTISCALER_ARCHIVE_ASSET["version"],
"uses_archive_native": True,
"extra_files": [],
},
"rdna34-official-411": {
"label": "4.1.1 official for RDNA 3/4",
"dir_name": "fsr4-rdna3-4-official-411",
"sha256": "ec7ed3ca674e288240e6f04b986342aece47454c41d9b0959449e82e22bd7f6d",
"source_asset_name": OPTISCALER_ARCHIVE_ASSET["name"],
"source_version": OPTISCALER_ARCHIVE_ASSET["version"],
"uses_archive_native": True,
"extra_files": [
{
"name": FSR4_DRIVER_OVERRIDE_FILENAME,
"sha256": FSR4_OFFICIAL_411_ASSET["sha256"],
"source_asset_name": FSR4_OFFICIAL_411_ASSET["name"],
"source_version": FSR4_OFFICIAL_411_ASSET["version"],
}
],
},
}
VARIANT_EXTRA_FILENAMES = sorted(
{
extra_file["name"]
for variant in FSR4_VARIANTS.values()
for extra_file in variant.get("extra_files", [])
}
)
PROXY_DLL_BACKUPS = [
"dxgi.dll",
"winmm.dll",
"dbghelp.dll",
"version.dll",
"wininet.dll",
"winhttp.dll",
"OptiScaler.asi",
]
VALID_DLL_NAMES = set(PROXY_DLL_BACKUPS)
INJECTOR_FILENAMES = [
*PROXY_DLL_BACKUPS,
"nvngx.dll",
"_nvngx.dll",
"nvngx-wrapper.dll",
"dlss-enabler.dll",
"OptiScaler.dll",
]
PATCH_CLEANUP_FILES = [
*INJECTOR_FILENAMES,
*VARIANT_EXTRA_FILENAMES,
"nvapi64.dll",
"nvapi64.dll.b",
"nvngx.ini",
"dlss-enabler-upscaler.dll",
"fakenvapi.log",
"OptiScaler.log",
"dlssg_to_fsr3.log",
"dlssg_to_fsr3_amd_is_better-3.0.dll",
]
PATCH_FINGERPRINT_FILES = [
"FRAMEGEN_PATCH",
"OptiScaler.ini",
"fakenvapi.dll",
"fakenvapi.ini",
"dlssg_to_fsr3_amd_is_better.dll",
"D3D12_Optiscaler",
]
ORIGINAL_DLL_BACKUPS = [
"d3dcompiler_47.dll",
"amd_fidelityfx_dx12.dll",
"amd_fidelityfx_framegeneration_dx12.dll",
FSR4_UPSCALER_FILENAME,
FSR4_DRIVER_OVERRIDE_FILENAME,
"amd_fidelityfx_vk.dll",
]
RESTORABLE_BACKUP_FILES = [
*PROXY_DLL_BACKUPS,
*ORIGINAL_DLL_BACKUPS,
]
SUPPORT_FILES = [
"libxess.dll",
"libxess_dx11.dll",
"libxess_fg.dll",
"libxell.dll",
"amd_fidelityfx_dx12.dll",
"amd_fidelityfx_framegeneration_dx12.dll",
"amd_fidelityfx_vk.dll",
"dlssg_to_fsr3_amd_is_better.dll",
"fakenvapi.dll",
"fakenvapi.ini",
]
MARKER_FILENAME = "FRAMEGEN_PATCH"
BAD_EXE_SUBSTRINGS = [
"crashreport",
"crashreportclient",
"eac",
"easyanticheat",
"beclient",
"eosbootstrap",
"benchmark",
"uninstall",
"setup",
"launcher",
"updater",
"bootstrap",
"_redist",
"prereq",
]
LEGACY_FILES = [
"dlssg_to_fsr3.ini",
"dlssg_to_fsr3.log",
"nvapi64.dll",
"nvapi64.dll.b",
"fakenvapi.log",
"dlss-enabler.dll",
"dlss-enabler-upscaler.dll",
"dlss-enabler.log",
"nvngx.ini",
"nvngx-wrapper.dll",
"_nvngx.dll",
"dlssg_to_fsr3_amd_is_better-3.0.dll",
"OptiScaler.asi",
"OptiScaler.ini",
"OptiScaler.log",
]
# ── GPU detection ──────────────────────────────────────────────────────────
AMD_VENDOR_IDS = {"0x1002", "1002"}
# Marketing-name keywords that identify an RDNA4 GPU (native FSR4 path).
RDNA4_NAME_MARKERS = [
"rx 90",
"radeon rx 9",
"9070",
"9060",
"navi 44",
"navi 48",
]
RDNA35_NAME_MARKERS = [
"radeon 890m",
"radeon 880m",
"strix",
"krackan",
"ryzen ai",
]
RDNA3_NAME_MARKERS = [
"radeon 780m",
"radeon 760m",
"radeon 740m",
"rx 7",
"navi 3",
"phoenix",
"hawk",
]
RDNA2_NAME_MARKERS = [
"van gogh",
"steam deck",
"aerith",
"sephiroth",
"rx 6",
"navi 2",
"680m",
"660m",
]
# Best-effort PCI device-id -> (generation, recommended FSR4 variant) map.
# Names from lspci can be generic (e.g. "Device 150e"), so device ids help.
AMD_DEVICE_ID_MAP = {
# RDNA2
"0x163f": ("RDNA2 (Van Gogh / Steam Deck)", "rdna23-int8"),
# RDNA3 APUs (Phoenix / Hawk Point - Z1 / Z1 Extreme)
"0x15bf": ("RDNA3 (Phoenix)", "rdna23-int8"),
"0x15c8": ("RDNA3 (Phoenix2)", "rdna23-int8"),
# RDNA3.5 APUs (Strix Point - Z2 Extreme / Legion Go 2)
"0x150e": ("RDNA3.5 (Strix Point)", "rdna23-int8"),
"0x1586": ("RDNA3.5 (Strix)", "rdna23-int8"),
# RDNA4 discrete
"0x7550": ("RDNA4 (Navi 48)", "rdna4-native"),
"0x7551": ("RDNA4 (Navi 48)", "rdna4-native"),
"0x7590": ("RDNA4 (Navi 44)", "rdna4-native"),
}
# ── Compatibility marking ──────────────────────────────────────────────────
CURATED_COMPAT_URL = (
"https://raw.githubusercontent.com/wiki/optiscaler/OptiScaler/Compatibility-List.md"
)
CURATED_CACHE_FILENAME = "compat-curated-cache.json"
BUNDLED_CURATED_FILENAME = "Compatibility-List.md"
SCAN_CACHE_FILENAME = "compat-scan-cache.json"
OVERRIDES_FILENAME = "compat-overrides.json"
CURATED_CACHE_TTL_SECONDS = 24 * 60 * 60 # refresh at most once a day
COMPAT_SCAN_MAX_DEPTH = 6
# Signature files that indicate a game already exposes an upscaler OptiScaler can hook.
UPSCALER_SIGNATURES = {
"dlss": ["nvngx_dlss.dll"],
"xess": ["libxess.dll"],
"fsr": [
"amd_fidelityfx_dx12.dll",
"amd_fidelityfx_vk.dll",
"ffx_fsr2_api_dx12_x64.dll",
"ffx_fsr2_api_vk_x64.dll",
],
}
VALID_COMPAT_OVERRIDES = {"compatible", "incompatible", "clear"}
DEBUG_SETTINGS_FILENAME = "debug-logging.json"
class Plugin:
async def _main(self):
self._apply_log_level(self._load_debug_logging())
decky.logger.info("Framegen plugin loaded")
async def _unload(self):
decky.logger.info("Framegen plugin unloaded.")
def _debug_settings_path(self) -> Path:
try:
settings_dir = Path(decky.DECKY_PLUGIN_SETTINGS_DIR)
except (TypeError, AttributeError):
settings_dir = Path(decky.HOME) / "homebrew" / "settings" / "Decky-Framegen"
settings_dir.mkdir(parents=True, exist_ok=True)
return settings_dir / DEBUG_SETTINGS_FILENAME
def _load_debug_logging(self) -> bool:
return bool(self._read_json_file(self._debug_settings_path()).get("enabled"))
def _save_debug_logging(self, enabled: bool) -> None:
self._write_json_file(self._debug_settings_path(), {"enabled": bool(enabled)})
def _apply_log_level(self, enabled: bool) -> None:
decky.logger.setLevel(logging.DEBUG if enabled else logging.INFO)
async def get_debug_logging(self) -> dict:
enabled = self._load_debug_logging()
self._apply_log_level(enabled)
try:
log_path = str(getattr(decky, "DECKY_PLUGIN_LOG", ""))
except (TypeError, AttributeError):
log_path = ""
return {"status": "success", "enabled": enabled, "log_path": log_path}
async def set_debug_logging(self, enabled: bool) -> dict:
enabled = bool(enabled)
self._save_debug_logging(enabled)
self._apply_log_level(enabled)
decky.logger.info(
f"[Framegen] verbose debug logging {'enabled' if enabled else 'disabled'}"
)
try:
log_path = str(getattr(decky, "DECKY_PLUGIN_LOG", ""))
except (TypeError, AttributeError):
log_path = ""
return {"status": "success", "enabled": enabled, "log_path": log_path}
def _create_renamed_copies(self, source_file, renames_dir):
"""Create renamed copies of the OptiScaler.dll file"""
try:
renames_dir.mkdir(exist_ok=True)
rename_files = [
"dxgi.dll",
"winmm.dll",
"dbghelp.dll",
"version.dll",
"wininet.dll",
"winhttp.dll",
"OptiScaler.asi"
]
if source_file.exists():
for rename_file in rename_files:
dest_file = renames_dir / rename_file
shutil.copy2(source_file, dest_file)
decky.logger.debug(f"Created renamed copy: {dest_file}")
return True
else:
decky.logger.error(f"Source file {source_file} does not exist")
return False
except Exception as e:
decky.logger.error(f"Failed to create renamed copies: {e}")
return False
def _copy_launcher_scripts(self, assets_dir, extract_path):
"""Copy launcher scripts from assets directory"""
try:
# Copy fgmod script
fgmod_script_src = assets_dir / "fgmod.sh"
fgmod_script_dest = extract_path / "fgmod"
if fgmod_script_src.exists():
shutil.copy2(fgmod_script_src, fgmod_script_dest)
fgmod_script_dest.chmod(0o755)
decky.logger.debug(f"Copied fgmod script to {fgmod_script_dest}")
# Copy uninstaller script
uninstaller_src = assets_dir / "fgmod-uninstaller.sh"
uninstaller_dest = extract_path / "fgmod-uninstaller.sh"
if uninstaller_src.exists():
shutil.copy2(uninstaller_src, uninstaller_dest)
uninstaller_dest.chmod(0o755)
decky.logger.debug(f"Copied uninstaller script to {uninstaller_dest}")
# Copy optiscaler config updater script
optiscaler_config_updater_src = assets_dir / "update-optiscaler-config.py"
optiscaler_config_updater_dest = extract_path / "update-optiscaler-config.py"
if optiscaler_config_updater_src.exists():
shutil.copy2(optiscaler_config_updater_src, optiscaler_config_updater_dest)
optiscaler_config_updater_dest.chmod(0o755)
decky.logger.debug(f"Copied update-optiscaler-config.py script to {optiscaler_config_updater_dest}")
return True
except Exception as e:
decky.logger.error(f"Failed to copy launcher scripts: {e}")
return False
def _files_match(self, file_a: Path, file_b: Path) -> bool:
try:
return file_a.exists() and file_b.exists() and filecmp.cmp(file_a, file_b, shallow=False)
except Exception:
return False
def _is_bundled_proxy_copy(self, file_path: Path, fgmod_path: Path) -> bool:
bundled_copy = fgmod_path / "renames" / file_path.name
return self._files_match(file_path, bundled_copy)
def _has_patch_fingerprint(self, directory: Path) -> bool:
return any((directory / filename).exists() for filename in PATCH_FINGERPRINT_FILES)
def _backup_preexisting_proxy_files(self, directory: Path, fgmod_path: Path) -> list[str]:
backed_up: list[str] = []
already_patched = self._has_patch_fingerprint(directory)
for filename in PROXY_DLL_BACKUPS:
source = directory / filename
backup = directory / f"{filename}.b"
if not source.exists() or backup.exists():
continue
if already_patched or self._is_bundled_proxy_copy(source, fgmod_path):
continue
shutil.move(source, backup)
backed_up.append(filename)
return backed_up
def _file_sha256(self, path: Path) -> str:
digest = hashlib.sha256()
with open(path, "rb") as f:
for chunk in iter(lambda: f.read(1024 * 1024), b""):
digest.update(chunk)
return digest.hexdigest()
def _read_json_file(self, path: Path) -> dict:
try:
with open(path, "r", encoding="utf-8") as f:
data = json.load(f)
return data if isinstance(data, dict) else {}
except Exception:
return {}
def _write_json_file(self, path: Path, payload: dict) -> None:
with open(path, "w", encoding="utf-8") as f:
json.dump(payload, f, indent=2)
def _extract_archive(self, archive_path: Path, output_dir: Path, members: list[str] | None = None) -> None:
output_dir.mkdir(parents=True, exist_ok=True)
extract_cmd = [
"7z",
"x",
"-y",
"-o" + str(output_dir),
str(archive_path),
]
if members:
extract_cmd.extend(members)
clean_env = os.environ.copy()
clean_env["LD_LIBRARY_PATH"] = ""
result = subprocess.run(
extract_cmd,
capture_output=True,
text=True,
check=False,
env=clean_env,
)
if result.returncode != 0:
raise RuntimeError(result.stderr or result.stdout or f"Failed to extract {archive_path.name}")
def _verify_bundled_asset(self, path: Path, expected_sha256: str, description: str) -> str:
actual_sha256 = self._file_sha256(path)
if actual_sha256.lower() != expected_sha256.lower():
raise RuntimeError(
f"{description} hash mismatch: expected {expected_sha256}, got {actual_sha256}"
)
return actual_sha256
def _install_manifest_path(self, fgmod_path: Path) -> Path:
return fgmod_path / INSTALL_MANIFEST_FILENAME
def _load_install_manifest(self, fgmod_path: Path) -> dict:
return self._read_json_file(self._install_manifest_path(fgmod_path))
def _normalize_fsr4_variant(self, fsr4_variant: str | None) -> str:
variant = str(fsr4_variant or "").strip()
if variant in FSR4_VARIANTS:
return variant
return DEFAULT_FSR4_VARIANT
def _selected_fsr4_variant(self, fgmod_path: Path, requested_variant: str | None = None) -> str:
normalized_requested = str(requested_variant or "").strip()
if normalized_requested in FSR4_VARIANTS:
return normalized_requested
manifest = self._load_install_manifest(fgmod_path)
manifest_variant = str(manifest.get("selected_default_variant") or "").strip()
if manifest_variant in FSR4_VARIANTS:
return manifest_variant
return DEFAULT_FSR4_VARIANT
def _fsr4_variant_info(self, fsr4_variant: str | None) -> dict:
return FSR4_VARIANTS[self._normalize_fsr4_variant(fsr4_variant)]
def _fsr4_variant_dir(self, fgmod_path: Path, fsr4_variant: str | None) -> Path:
variant_id = self._normalize_fsr4_variant(fsr4_variant)
return fgmod_path / FSR4_VARIANTS[variant_id]["dir_name"]
def _fsr4_variant_path(self, fgmod_path: Path, fsr4_variant: str | None) -> Path:
return self._fsr4_variant_dir(fgmod_path, fsr4_variant) / FSR4_UPSCALER_FILENAME
def _fsr4_variant_extra_files(self, fsr4_variant: str | None) -> list[dict]:
variant = self._fsr4_variant_info(fsr4_variant)
return list(variant.get("extra_files") or [])
def _fsr4_variant_extra_file_path(self, fgmod_path: Path, fsr4_variant: str | None, filename: str) -> Path:
return self._fsr4_variant_dir(fgmod_path, fsr4_variant) / filename
def _sync_variant_root_extra_files(self, fgmod_path: Path, fsr4_variant: str | None) -> None:
selected_extra_files = {extra_file["name"]: extra_file for extra_file in self._fsr4_variant_extra_files(fsr4_variant)}
for filename in VARIANT_EXTRA_FILENAMES:
root_path = fgmod_path / filename
if filename not in selected_extra_files:
if root_path.exists():
root_path.unlink()
continue
source_path = self._fsr4_variant_extra_file_path(fgmod_path, fsr4_variant, filename)
if not source_path.exists():
raise FileNotFoundError(f"Prepared FSR4 variant extra file missing: {source_path}")
shutil.copy2(source_path, root_path)
def _activate_default_fsr4_variant(self, fgmod_path: Path, fsr4_variant: str | None) -> str:
variant_id = self._normalize_fsr4_variant(fsr4_variant)
variant_path = self._fsr4_variant_path(fgmod_path, variant_id)
if not variant_path.exists():
raise FileNotFoundError(f"Prepared FSR4 variant missing: {variant_path}")
shutil.copy2(variant_path, fgmod_path / FSR4_UPSCALER_FILENAME)
self._sync_variant_root_extra_files(fgmod_path, variant_id)
return variant_id
def _detect_fsr4_variant(self, directory: Path, upscaler_sha256: str | None) -> str | None:
for variant_id, variant in FSR4_VARIANTS.items():
extra_files = list(variant.get("extra_files") or [])
if not extra_files:
continue
if not upscaler_sha256 or str(variant.get("sha256") or "").lower() != str(upscaler_sha256).lower():
continue
all_match = True
for extra_file in extra_files:
file_path = directory / extra_file["name"]
if not file_path.exists() or self._file_sha256(file_path).lower() != extra_file["sha256"].lower():
all_match = False
break
if all_match:
return variant_id
if not upscaler_sha256:
return None
normalized_sha = str(upscaler_sha256).lower()
for variant_id, variant in FSR4_VARIANTS.items():
if variant.get("extra_files"):
continue
if str(variant.get("sha256") or "").lower() == normalized_sha:
return variant_id
return None
def _fgmod_version(self, fgmod_path: Path) -> str | None:
manifest = self._load_install_manifest(fgmod_path)
optiscaler = manifest.get("optiscaler") if isinstance(manifest, dict) else None
if isinstance(optiscaler, dict) and optiscaler.get("version"):
return str(optiscaler.get("version"))
version_file = fgmod_path / VERSION_FILENAME
try:
if version_file.exists():
return version_file.read_text(encoding="utf-8").strip() or None
except Exception:
return None
return None
def _managed_support_candidate_paths(self, fgmod_path: Path, filename: str) -> list[Path]:
candidates: list[Path] = []
if filename == FSR4_UPSCALER_FILENAME:
candidates.append(fgmod_path / FSR4_UPSCALER_FILENAME)
for variant_id in FSR4_VARIANTS:
candidates.append(self._fsr4_variant_path(fgmod_path, variant_id))
else:
candidates.append(fgmod_path / filename)
for variant_id in FSR4_VARIANTS:
for extra_file in self._fsr4_variant_extra_files(variant_id):
if extra_file["name"] == filename:
candidates.append(self._fsr4_variant_extra_file_path(fgmod_path, variant_id, filename))
unique: list[Path] = []
seen: set[str] = set()
for candidate in candidates:
key = str(candidate)
if key not in seen:
unique.append(candidate)
seen.add(key)
return unique
def _is_managed_support_file(self, path: Path, fgmod_path: Path) -> bool:
if not path.exists():
return False
for candidate in self._managed_support_candidate_paths(fgmod_path, path.name):
if self._files_match(path, candidate):
return True
return False
def _migrate_optiscaler_ini(self, ini_file):
"""Migrate pre-v0.9-final OptiScaler.ini: replace FGType with FGInput + FGOutput.
v0.9-final split the single FGType key into separate FGInput and FGOutput keys.
Games already patched with an older build will have FGType=<value> in their
per-game INI but no FGInput/FGOutput entries, causing the new DLL to silently
fall back to nofg. This migration runs at patch-time and at every fgmod.sh
launch so users never have to manually touch their INI.
"""
try:
if not ini_file.exists():
return False
with open(ini_file, 'r') as f:
content = f.read()
fg_type_match = re.search(r'^FGType\s*=\s*(\S+)', content, re.MULTILINE)
if not fg_type_match:
return True # Nothing to migrate
fg_value = fg_type_match.group(1)
if re.search(r'^FGInput\s*=', content, re.MULTILINE):
# FGInput already present (INI already in v0.9-final format);
# just remove the now-unknown FGType line.
content = re.sub(r'^FGType\s*=\s*\S+\n?', '', content, flags=re.MULTILINE)
decky.logger.debug(f"Removed stale FGType from {ini_file} (FGInput already present)")
else:
# Replace the single FGType=X line with FGInput=X then FGOutput=X
content = re.sub(
r'^FGType\s*=\s*\S+',
f'FGInput={fg_value}\nFGOutput={fg_value}',
content,
flags=re.MULTILINE
)
decky.logger.debug(f"Migrated FGType={fg_value} → FGInput={fg_value}, FGOutput={fg_value} in {ini_file}")
with open(ini_file, 'w') as f:
f.write(content)
return True
except Exception as e:
decky.logger.error(f"Failed to migrate OptiScaler.ini: {e}")
return False
def _disable_hq_font_auto(self, ini_file):
"""Disable the new HQ font auto mode to avoid missing font assertions on Wine/Proton."""
try:
if not ini_file.exists():
decky.logger.warning(f"OptiScaler.ini not found at {ini_file}")
return False
with open(ini_file, 'r') as f:
content = f.read()
updated_content = re.sub(r'UseHQFont\s*=\s*auto', 'UseHQFont=false', content)
if updated_content != content:
with open(ini_file, 'w') as f:
f.write(updated_content)
decky.logger.debug("Set UseHQFont=false to avoid missing font assertions")
return True
except Exception as e:
decky.logger.error(f"Failed to update HQ font setting in OptiScaler.ini: {e}")
return False
def _modify_optiscaler_ini(self, ini_file):
"""Modify OptiScaler.ini to set FG defaults, ASI plugin settings, and safe font defaults."""
try:
if ini_file.exists():
with open(ini_file, 'r') as f:
content = f.read()
# Replace FGInput=auto with FGInput=nukems (final v0.9+ split FGType into FGInput/FGOutput)
updated_content = re.sub(r'FGInput\s*=\s*auto', 'FGInput=nukems', content)
# Replace FGOutput=auto with FGOutput=nukems
updated_content = re.sub(r'FGOutput\s*=\s*auto', 'FGOutput=nukems', updated_content)
# Replace Fsr4Update=auto with Fsr4Update=true
updated_content = re.sub(r'Fsr4Update\s*=\s*auto', 'Fsr4Update=true', updated_content)
# Replace LoadAsiPlugins=auto with LoadAsiPlugins=true
updated_content = re.sub(r'LoadAsiPlugins\s*=\s*auto', 'LoadAsiPlugins=true', updated_content)
# Disable new HQ font auto mode to avoid missing font assertions on Proton
updated_content = re.sub(r'UseHQFont\s*=\s*auto', 'UseHQFont=false', updated_content)
with open(ini_file, 'w') as f:
f.write(updated_content)
decky.logger.debug("Modified OptiScaler.ini to set FGInput=nukems, FGOutput=nukems, Fsr4Update=true, LoadAsiPlugins=true, UseHQFont=false")
return True
else:
decky.logger.warning(f"OptiScaler.ini not found at {ini_file}")
return False
except Exception as e:
decky.logger.error(f"Failed to modify OptiScaler.ini: {e}")
return False
async def extract_static_optiscaler(self, selected_default_variant: str = DEFAULT_FSR4_VARIANT) -> dict:
"""Prepare the shared ~/fgmod bundle with all bundled FSR4 runtime variants."""
try:
decky.logger.debug("Starting extract_static_optiscaler method")
bin_path = Path(decky.DECKY_PLUGIN_DIR) / "bin"
extract_path = Path(decky.HOME) / "fgmod"
assets_dir = Path(decky.DECKY_PLUGIN_DIR) / "assets"
selected_default_variant = self._normalize_fsr4_variant(selected_default_variant)
if not bin_path.exists():
return {"status": "error", "message": f"Bin directory not found: {bin_path}"}
optiscaler_archive = bin_path / OPTISCALER_ARCHIVE_ASSET["name"]
fsr4_int8_src = bin_path / FSR4_INT8_ASSET["name"]
fsr4_official_411_src = bin_path / FSR4_OFFICIAL_411_ASSET["name"]
optipatcher_src = bin_path / OPTIPATCHER_ASSET["name"]
for required_path, asset in [
(optiscaler_archive, OPTISCALER_ARCHIVE_ASSET),
(fsr4_int8_src, FSR4_INT8_ASSET),
(fsr4_official_411_src, FSR4_OFFICIAL_411_ASSET),
(optipatcher_src, OPTIPATCHER_ASSET),
]:
if not required_path.exists():
return {
"status": "error",
"message": f"Required bundled asset missing: {asset['name']}",
}
self._verify_bundled_asset(required_path, asset["sha256"], asset["name"])
if extract_path.exists():
shutil.rmtree(extract_path)
extract_path.mkdir(parents=True, exist_ok=True)
self._extract_archive(optiscaler_archive, extract_path)
source_file = extract_path / "OptiScaler.dll"
renames_dir = extract_path / "renames"
if not self._create_renamed_copies(source_file, renames_dir):
return {"status": "error", "message": "Failed to prepare renamed OptiScaler proxies."}
if not self._copy_launcher_scripts(assets_dir, extract_path):
return {"status": "error", "message": "Failed to copy launcher scripts."}
plugins_dir = extract_path / "plugins"
plugins_dir.mkdir(parents=True, exist_ok=True)
optipatcher_dst = plugins_dir / "OptiPatcher.asi"
shutil.copy2(optipatcher_src, optipatcher_dst)
optipatcher_sha256 = self._verify_bundled_asset(
optipatcher_dst,
OPTIPATCHER_ASSET["sha256"],
"Prepared OptiPatcher plugin",
)
ini_file = extract_path / "OptiScaler.ini"
self._modify_optiscaler_ini(ini_file)
native_upscaler_root = extract_path / FSR4_UPSCALER_FILENAME
native_upscaler_sha256 = self._verify_bundled_asset(
native_upscaler_root,
FSR4_VARIANTS["rdna4-native"]["sha256"],
"Archive-native FSR4 upscaler",
)
rdna4_dir = extract_path / FSR4_VARIANTS["rdna4-native"]["dir_name"]
rdna4_dir.mkdir(parents=True, exist_ok=True)
rdna4_upscaler = rdna4_dir / FSR4_UPSCALER_FILENAME
shutil.copy2(native_upscaler_root, rdna4_upscaler)
self._verify_bundled_asset(
rdna4_upscaler,
FSR4_VARIANTS["rdna4-native"]["sha256"],
"Prepared rdna4-native FSR4 upscaler",
)
official_411_dir = extract_path / FSR4_VARIANTS["rdna34-official-411"]["dir_name"]
official_411_dir.mkdir(parents=True, exist_ok=True)
official_411_upscaler = official_411_dir / FSR4_UPSCALER_FILENAME
shutil.copy2(native_upscaler_root, official_411_upscaler)
self._verify_bundled_asset(
official_411_upscaler,
FSR4_VARIANTS["rdna34-official-411"]["sha256"],
"Prepared rdna34-official-411 FSR4 upscaler",
)
self._verify_bundled_asset(
fsr4_official_411_src,
FSR4_OFFICIAL_411_ASSET["sha256"],
"Bundled rdna34-official-411 driver override",
)
official_411_driver = official_411_dir / FSR4_DRIVER_OVERRIDE_FILENAME
shutil.copy2(fsr4_official_411_src, official_411_driver)
self._verify_bundled_asset(
official_411_driver,
FSR4_OFFICIAL_411_ASSET["sha256"],
"Prepared rdna34-official-411 driver override",
)
rdna23_dir = extract_path / FSR4_VARIANTS["rdna23-int8"]["dir_name"]
rdna23_dir.mkdir(parents=True, exist_ok=True)
self._verify_bundled_asset(
fsr4_int8_src,
FSR4_VARIANTS["rdna23-int8"]["sha256"],
"Bundled rdna23-int8 FSR4 upscaler",
)
shutil.copy2(fsr4_int8_src, rdna23_dir / FSR4_UPSCALER_FILENAME)
self._verify_bundled_asset(
rdna23_dir / FSR4_UPSCALER_FILENAME,
FSR4_VARIANTS["rdna23-int8"]["sha256"],
"Prepared rdna23-int8 FSR4 upscaler",
)
selected_default_variant = self._activate_default_fsr4_variant(extract_path, selected_default_variant)
active_upscaler_sha256 = self._file_sha256(extract_path / FSR4_UPSCALER_FILENAME)
version_file = extract_path / VERSION_FILENAME
version_file.write_text(OPTISCALER_ARCHIVE_ASSET["version"], encoding="utf-8")
install_manifest = {
"schema_version": 1,
"installed_at": datetime.now(timezone.utc).isoformat(),
"optiscaler": {
"asset_name": OPTISCALER_ARCHIVE_ASSET["name"],
"version": OPTISCALER_ARCHIVE_ASSET["version"],
"sha256": OPTISCALER_ARCHIVE_ASSET["sha256"],
"native_upscaler_sha256": native_upscaler_sha256,
},
"optipatcher": {
"asset_name": OPTIPATCHER_ASSET["name"],
"version": OPTIPATCHER_ASSET["version"],
"sha256": optipatcher_sha256,
"target_path": str(optipatcher_dst.relative_to(extract_path)),
},
"fsr4_variants": {
variant_id: {
"label": variant["label"],
"dir_name": variant["dir_name"],
"path": str((Path(variant["dir_name"]) / FSR4_UPSCALER_FILENAME).as_posix()),
"sha256": variant["sha256"],
"source_asset_name": variant["source_asset_name"],
"source_version": variant["source_version"],
"uses_archive_native": bool(variant["uses_archive_native"]),
"extra_files": [
{
"name": extra_file["name"],
"sha256": extra_file["sha256"],
"source_asset_name": extra_file["source_asset_name"],
"source_version": extra_file["source_version"],
"path": str((Path(variant["dir_name"]) / extra_file["name"]).as_posix()),
}
for extra_file in variant.get("extra_files", [])
],
}
for variant_id, variant in FSR4_VARIANTS.items()
},
"selected_default_variant": selected_default_variant,
"active_root_upscaler": {
"path": FSR4_UPSCALER_FILENAME,
"sha256": active_upscaler_sha256,
"variant": selected_default_variant,
},
}
self._write_json_file(self._install_manifest_path(extract_path), install_manifest)
return {
"status": "success",
"message": f"Successfully extracted OptiScaler {OPTISCALER_ARCHIVE_ASSET['version']} to ~/fgmod",
"version": OPTISCALER_ARCHIVE_ASSET["version"],
"selected_default_variant": selected_default_variant,
"selected_default_variant_label": FSR4_VARIANTS[selected_default_variant]["label"],
}
except Exception as e:
decky.logger.error(f"Extract failed with exception: {str(e)}")
import traceback
decky.logger.error(f"Traceback: {traceback.format_exc()}")
return {"status": "error", "message": f"Extract failed: {str(e)}"}
async def run_uninstall_fgmod(self) -> dict:
try:
# Remove fgmod directory
fgmod_path = Path(decky.HOME) / "fgmod"
if fgmod_path.exists():
shutil.rmtree(fgmod_path)
decky.logger.debug(f"Removed directory: {fgmod_path}")
return {
"status": "success",
"output": "Successfully removed fgmod directory"
}
else:
return {
"status": "success",
"output": "No fgmod directory found to remove"
}
except Exception as e:
decky.logger.error(f"Uninstall error: {str(e)}")
return {
"status": "error",
"message": f"Uninstall failed: {str(e)}",
"output": str(e)
}
async def set_default_fsr4_variant(self, selected_default_variant: str = DEFAULT_FSR4_VARIANT) -> dict:
try:
fgmod_path = Path(decky.HOME) / "fgmod"
if not fgmod_path.exists():
return {"status": "error", "message": "OptiScaler bundle not installed. Run Install first."}
selected_default_variant = self._normalize_fsr4_variant(selected_default_variant)
manifest = self._load_install_manifest(fgmod_path)
if not manifest:
return {"status": "error", "message": "Install manifest missing. Reinstall OptiScaler."}
selected_default_variant = self._activate_default_fsr4_variant(fgmod_path, selected_default_variant)
active_upscaler_sha256 = self._file_sha256(fgmod_path / FSR4_UPSCALER_FILENAME)
manifest["selected_default_variant"] = selected_default_variant
manifest["active_root_upscaler"] = {
"path": FSR4_UPSCALER_FILENAME,
"sha256": active_upscaler_sha256,
"variant": selected_default_variant,
}
manifest["updated_at"] = datetime.now(timezone.utc).isoformat()
self._write_json_file(self._install_manifest_path(fgmod_path), manifest)
return {
"status": "success",
"output": f"Default FSR4 runtime switched to {FSR4_VARIANTS[selected_default_variant]['label']}.",
"version": self._fgmod_version(fgmod_path),
"selected_default_variant": selected_default_variant,
"selected_default_variant_label": FSR4_VARIANTS[selected_default_variant]["label"],
}
except Exception as e:
decky.logger.error(f"Failed to switch default FSR4 runtime: {e}")
return {"status": "error", "message": f"Failed to switch default FSR4 runtime: {e}"}
async def run_install_fgmod(self, selected_default_variant: str = DEFAULT_FSR4_VARIANT) -> dict:
try:
decky.logger.debug("Starting OptiScaler installation from static bundle")
selected_default_variant = self._normalize_fsr4_variant(selected_default_variant)
extract_result = await self.extract_static_optiscaler(selected_default_variant)
if extract_result["status"] != "success":
return {
"status": "error",
"message": f"OptiScaler extraction failed: {extract_result.get('message', 'Unknown error')}"
}
return {
"status": "success",
"output": (
"Successfully installed OptiScaler "
f"{extract_result.get('version', OPTISCALER_ARCHIVE_ASSET['version'])} "
f"with {extract_result.get('selected_default_variant_label', FSR4_VARIANTS[selected_default_variant]['label'])}."
),
"version": extract_result.get("version", OPTISCALER_ARCHIVE_ASSET["version"]),
"selected_default_variant": extract_result.get("selected_default_variant", selected_default_variant),
"selected_default_variant_label": extract_result.get(
"selected_default_variant_label",
FSR4_VARIANTS[selected_default_variant]["label"],
),
}
except Exception as e:
decky.logger.error(f"Unexpected error during installation: {str(e)}")
return {
"status": "error",
"message": f"Installation failed: {str(e)}"
}
async def check_fgmod_path(self) -> dict:
path = Path(decky.HOME) / "fgmod"
required_files = [
"OptiScaler.dll",
"OptiScaler.ini",
"dlssg_to_fsr3_amd_is_better.dll",
"fakenvapi.dll",
"fakenvapi.ini",
"amd_fidelityfx_dx12.dll",
"amd_fidelityfx_framegeneration_dx12.dll",
FSR4_UPSCALER_FILENAME,
"amd_fidelityfx_vk.dll",
"libxess.dll",
"libxess_dx11.dll",
"libxess_fg.dll",
"libxell.dll",
"fgmod",
"fgmod-uninstaller.sh",
"update-optiscaler-config.py",
INSTALL_MANIFEST_FILENAME,
]