Skip to content

Play your Steam library's Windows games on a jailbroken PS5.

C++

Stage kit H r10 with the static media backend

Leonardo Lobato3b9c5be63367
diff --git a/tests/kit_h_media_registry_test.py b/tests/kit_h_media_registry_test.py
new file mode 100644
index 0000000..5382a77
--- /dev/null
+++ b/tests/kit_h_media_registry_test.py
@@ -0,0 +1,29 @@
+#!/usr/bin/env python3
+import importlib.util,unittest
+from pathlib import Path
+P=Path(__file__).resolve().parents[1]/'tools/kit-h/media_registry.py'
+spec=importlib.util.spec_from_file_location('media_registry',P);m=importlib.util.module_from_spec(spec);spec.loader.exec_module(m)
+GUID='317df618-5e5a-468a-9f15-d827a9a08162'
+class Registry(unittest.TestCase):
+ def fixture(self):
+ idl='uuid('+GUID+')'
+ before='WINE REGISTRY Version 2\n#arch=win64\n\n[Software\\\\Retained]\n"value"="keep"\n\n'
+ after=before
+ for view,folder in [('', 'system32'),('Wow6432Node\\\\','syswow64')]:
+ after+='[Software\\\\Classes\\\\'+view+'CLSID\\\\{'+GUID+'}\\\\InprocServer32] 123\n#time=abcdef\n@="C:\\\\windows\\\\'+folder+'\\\\winegstreamer.dll"\n"ThreadingModel"="Both"\n\n'
+ after+='[System\\\\ControlSet001\\\\Enum\\\\DISPLAY\\\\Host]\n"value"="noise"\n'
+ return before,after,idl
+ def test_both_views_without_host_noise(self):
+ before,after,idl=self.fixture();delta=m.registration_delta(before,after,idl)
+ self.assertEqual(len(delta),2)
+ merged=m.merge_registry(before,delta)
+ self.assertEqual(m.blocks(merged)['Software\\\\Retained'],'"value"="keep"')
+ self.assertNotIn('DISPLAY',merged);self.assertIn('#arch=win64',merged)
+ with self.assertRaisesRegex(ValueError,'already has'):m.merge_registry(merged,delta)
+ def test_missing_architecture_rejected(self):
+ before,after,idl=self.fixture()
+ with self.assertRaisesRegex(ValueError,'missing or invalid'):m.registration_delta(before,after.replace('Wow6432Node','Other'),idl)
+ def test_host_path_rejected(self):
+ before,after,idl=self.fixture()
+ with self.assertRaisesRegex(ValueError,'host path'):m.registration_delta(before,after.replace('C:\\\\windows\\\\system32','Z:\\\\home\\\\builder'),idl)
+if __name__=='__main__':unittest.main()
diff --git a/tests/kit_h_media_staging_test.py b/tests/kit_h_media_staging_test.py
new file mode 100644
index 0000000..17c4e20
--- /dev/null
+++ b/tests/kit_h_media_staging_test.py
@@ -0,0 +1,401 @@
+#!/usr/bin/env python3
+"""Incomplete native audits must fail before staging mutates kit inputs."""
+import importlib.util
+import hashlib
+import json
+from pathlib import Path
+import sys
+import struct
+import tempfile
+import unittest
+
+TOOLS = Path(__file__).resolve().parents[1] / "tools/kit-h"
+sys.path.insert(0, str(TOOLS))
+spec = importlib.util.spec_from_file_location("update_r10", TOOLS / "update_r10.py")
+module = importlib.util.module_from_spec(spec)
+spec.loader.exec_module(module)
+
+
+class MediaStagingTests(unittest.TestCase):
+ def test_corrupt_binary_evidence_is_rejected_before_writes(self):
+ for defect, error in (("prx", "PRX differs"), ("architecture", "wrong PE architecture"),
+ ("registration", "registered DLL/build report mismatch")):
+ with self.subTest(defect=defect), tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ kit, previous, cross, registration = (root / name for name in ("r10", "r9", "cross", "registration"))
+ (kit / "inputs").mkdir(parents=True)
+ previous.mkdir()
+ (cross / "prx/sce_module").mkdir(parents=True)
+ registration.mkdir()
+ original = {kit / "kit-spec.json": "{}\n", kit / "inputs/stage-record.json": "{}\n"}
+ for path, value in original.items():
+ path.write_text(value)
+ prx = cross / "prx/sce_module/winegstreamer.prx"
+ prx.write_bytes(b"native module fixture")
+ entry = {"built": True, "sha256": module.sha(prx), **{name: [] for name in
+ ("unresolved", "errors", "title_unbound", "webkit_unbound", "raw_syscalls")}}
+ if defect == "prx":
+ prx.write_bytes(b"corrupt module")
+ pe_hashes = {}
+ registered = {}
+ for architecture, machine in (("i386-windows", 0x14c), ("x86_64-windows", 0x8664)):
+ data = bytearray(128)
+ data[:2] = b"MZ"
+ struct.pack_into("<I", data, 60, 64)
+ data[64:68] = b"PE\0\0"
+ struct.pack_into("<H", data, 68, 0x8664 if defect == "architecture" else machine)
+ path = cross / "pe" / architecture / "winegstreamer.dll"
+ path.parent.mkdir(parents=True)
+ path.write_bytes(data)
+ digest = hashlib.sha256(data).hexdigest()
+ pe_hashes[architecture + "/winegstreamer.dll"] = digest
+ registered[architecture] = "0" * 64 if defect == "registration" else digest
+ (registration / "dll-sha256.json").write_text(json.dumps(registered))
+ (cross / "report.json").write_text(json.dumps({"prx": {"modules": {"winegstreamer": entry}}, "pe": pe_hashes}))
+ with self.assertRaisesRegex(ValueError, error):
+ module.stage(kit, previous, cross, registration, root / "media", root / "r9-report.json", "a" * 40)
+ self.assertEqual({p: p.read_text() for p in original}, original)
+
+ def test_incomplete_or_malformed_audit_is_rejected_before_writes(self):
+ fields = ("unresolved", "errors", "title_unbound", "webkit_unbound", "raw_syscalls")
+ for field in fields:
+ for invalid in ("missing", None, {}, "", ["failure"]):
+ with self.subTest(field=field, invalid=invalid), tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ kit, previous, cross = (root / name for name in ("r10", "r9", "cross"))
+ (kit / "inputs").mkdir(parents=True)
+ previous.mkdir()
+ cross.mkdir()
+ original = {kit / "kit-spec.json": "{}\n",
+ kit / "inputs/stage-record.json": "{}\n"}
+ for path, value in original.items():
+ path.write_text(value)
+ entry = {"built": True, **{name: [] for name in fields}}
+ if invalid == "missing":
+ del entry[field]
+ else:
+ entry[field] = invalid
+ (cross / "report.json").write_text(json.dumps({"prx": {"modules": {"winegstreamer": entry}}}))
+ with self.assertRaisesRegex(ValueError, "media PRX.*audit"):
+ module.stage(kit, previous, cross, root / "registration", root / "media", root / "r9-report.json", "a" * 40)
+ self.assertEqual({p: p.read_text() for p in original}, original)
+
+# These fixtures contain no proprietary media or executable code.
+class NormalMediaStagingTests(unittest.TestCase):
+ def fixture(self, root):
+ cross, registration, media = (root / name for name in ('cross', 'registration', 'media'))
+ (cross / 'prx/sce_module').mkdir(parents=True)
+ registration.mkdir()
+ prx = cross / 'prx/sce_module/winegstreamer.prx'
+ prx.write_bytes(b'fixture PRX')
+ entry = {'built': True, 'sha256': module.sha(prx), **{k: [] for k in
+ ('unresolved', 'errors', 'title_unbound', 'webkit_unbound', 'raw_syscalls')}}
+ hashes, pe = {}, {}
+ for arch, machine in [('i386-windows', 0x14c), ('x86_64-windows', 0x8664)]:
+ data = bytearray(128)
+ data[:2] = b'MZ'
+ struct.pack_into('<I', data, 60, 64)
+ data[64:68] = b'PE\0\0'
+ struct.pack_into('<H', data, 68, machine)
+ path = cross / 'pe' / arch / 'winegstreamer.dll'
+ path.parent.mkdir(parents=True)
+ path.write_bytes(data)
+ hashes[arch] = module.sha(path)
+ pe[arch + '/winegstreamer.dll'] = module.sha(path)
+ module.write_json(cross / 'report.json', {'prx': {'modules': {'winegstreamer': entry}}, 'pe': pe,
+ 'wine_commit': 'a' * 40, 'patches': []})
+ module.write_json(registration / 'dll-sha256.json', hashes)
+ guid = '317df618-5e5a-468a-9f15-d827a9a08162'
+ idl = cross / 'source/dlls/winegstreamer/winegstreamer_classes.idl'
+ idl.parent.mkdir(parents=True)
+ idl.write_text('uuid(' + guid + ')')
+ base = 'WINE REGISTRY Version 2\n\n[Software\\\\Game]\n"keep"="yes"\n\n'
+ (registration / 'system-before.reg').write_text(base)
+ after = base
+ for view, folder in [('', 'system32'), ('Wow6432Node\\\\', 'syswow64')]:
+ after += ('[Software\\\\Classes\\\\' + view + 'CLSID\\\\{' + guid + '}\\\\InprocServer32]\n'
+ '@="C:\\\\windows\\\\' + folder + '\\\\winegstreamer.dll"\n"ThreadingModel"="Both"\n\n')
+ (registration / 'system-after.reg').write_text(after)
+ components = ['ffmpeg', 'libffi', 'pcre2', 'zlib', 'libiconv', 'glib', 'gstreamer',
+ 'gst-plugins-base', 'gst-plugins-good', 'gst-plugins-bad', 'gst-libav']
+ for component in components:
+ archive = media / 'root/lib' / (component + '.a')
+ archive.parent.mkdir(parents=True, exist_ok=True)
+ archive.write_bytes(b'fixture static archive')
+ license = cross / 'prx/licenses/media' / component / 'COPYING'
+ license.parent.mkdir(parents=True, exist_ok=True)
+ license.write_text('fixture license text')
+ module.write_json(media / (component + '-manifest.json'), {
+ 'component': component, 'source': {'revision': 'pinned', 'sha256': 'b' * 64}, 'configure': [],
+ 'archives': {str(archive.relative_to(media / 'root')): module.sha(archive)},
+ 'licenses': {'licenses/' + component + '/COPYING': module.sha(license)}})
+ module.write_json(cross / 'media-flags.json', {'libs': str(media / 'root/lib/ffmpeg.a')})
+ module.write_json(cross / 'prx/media-adapters.json', {'schema': 'fixture'})
+ template, runtime = root / 'template', root / 'runtime'
+ template.mkdir()
+ (template / 'system.reg').write_text(base)
+ return cross, registration, media, template, runtime
+
+ def test_media_stages_registry_license_sources_and_notice(self):
+ from media_staging import stage_media
+ with tempfile.TemporaryDirectory() as directory:
+ cross, registration, media, template, runtime = self.fixture(Path(directory))
+ files = []
+ result = stage_media(runtime, template, cross, registration, media, files)
+ self.assertFalse(result['playback_verified'])
+ self.assertEqual(len(files), 2)
+ self.assertIn('Wow6432Node', (template / 'system.reg').read_text())
+ self.assertEqual(len(json.loads((runtime / 'share/wine/media-build/media-registry.json').read_text())['values']), 4)
+ source = json.loads((runtime / 'share/wine/licenses/media/source-manifest.json').read_text())
+ self.assertEqual(len(source['components']), 11)
+ self.assertNotIn(directory, json.dumps(source))
+ for component in source['components']:
+ self.assertTrue((runtime / 'share/wine/licenses/media' / component['component'] / 'COPYING').is_file())
+ self.assertIn('FFmpeg', (runtime / 'share/wine/THIRD_PARTY').read_text())
+
+ def test_bad_license_missing_archive_and_gpl_reject_before_writes(self):
+ from media_staging import stage_media
+ for defect in ('license', 'archive', 'gpl', 'nonfree', 'source', 'unlisted'):
+ with self.subTest(defect=defect), tempfile.TemporaryDirectory() as directory:
+ cross, registration, media, template, runtime = self.fixture(Path(directory))
+ manifest = media / 'ffmpeg-manifest.json'
+ value = json.loads(manifest.read_text())
+ if defect == 'license':
+ (cross / 'prx/licenses/media/ffmpeg/COPYING').write_text('changed')
+ elif defect == 'archive':
+ (media / 'root/lib/ffmpeg.a').write_bytes(b'changed')
+ elif defect in ('gpl', 'nonfree'):
+ value['configure'] = ['--enable-' + defect]
+ elif defect == 'source':
+ value.pop('source')
+ else:
+ value['archives'] = {}
+ module.write_json(manifest, value)
+ before = (template / 'system.reg').read_bytes()
+ with self.assertRaises(ValueError):
+ stage_media(runtime, template, cross, registration, media, [])
+ self.assertFalse(runtime.exists())
+ self.assertEqual((template / 'system.reg').read_bytes(), before)
+
+ def test_wrapped_registry_binary_is_normalized_before_staging(self):
+ from media_staging import registry_values
+ self.assertEqual(registry_values({'Software\\\\Classes\\\\media': '"FilterData"=hex:01,02,\\\n 03,04'}),
+ [{'key': 'Software\\Classes\\media', 'name': 'FilterData', 'data': 'hex:01,02,03,04'}])
+ with self.assertRaisesRegex(ValueError, 'unsupported media registry'):
+ registry_values({'Software\\\\Classes\\\\media': 'malformed'})
+
+ def test_tls_licenses_required_and_shipped_with_native_module(self):
+ from media_staging import stage_media
+ with tempfile.TemporaryDirectory() as directory:
+ cross, registration, media, template, runtime = self.fixture(Path(directory))
+ (cross / 'prx/sce_module/libgnutls.prx').write_bytes(b'fixture TLS')
+ with self.assertRaisesRegex(ValueError, 'TLS license inventory missing'):
+ stage_media(runtime, template, cross, registration, media, [])
+ self.assertFalse(runtime.exists())
+ for component, names in [('gnutls', ('COPYING.LESSERv2', 'COPYING', 'AUTHORS', 'lib-inih-LICENSE.txt')),
+ ('nettle', ('COPYING.LESSERv3', 'COPYINGv2', 'COPYINGv3', 'AUTHORS'))]:
+ source = cross / 'prx/licenses' / component
+ source.mkdir()
+ for name in names:
+ (source / name).write_text('fixture license')
+ stage_media(runtime, template, cross, registration, media, [])
+ self.assertTrue((runtime / 'share/wine/licenses/nettle/COPYING.LESSERv3').is_file())
+ self.assertTrue((runtime / 'share/wine/licenses/gnutls/COPYING.LESSERv2').is_file())
+ self.assertIn('GnuTLS and Nettle', (runtime / 'share/wine/THIRD_PARTY').read_text())
+
+ def test_legacy_overlay_cannot_retain_tls_without_notices(self):
+ from media_staging import stage_media
+ with tempfile.TemporaryDirectory() as directory:
+ cross, registration, media, template, runtime = self.fixture(Path(directory))
+ retained = runtime / 'lib/wine/x86_64-unix/libgnutls.prx'
+ retained.parent.mkdir(parents=True)
+ retained.write_bytes(b'old TLS')
+ original = (template / 'system.reg').read_bytes()
+ with self.assertRaisesRegex(ValueError, 'retained runtime'):
+ stage_media(runtime, template, cross, registration, media, [])
+ self.assertEqual((template / 'system.reg').read_bytes(), original)
+ self.assertEqual([p for p in runtime.rglob('*') if p.is_file()], [retained])
+
+ def run_stager(self, root, with_media):
+ import os
+ import subprocess
+ if True:
+ cross, registration, media, template, runtime = self.fixture(root)
+ work = root / 'work'
+ (work / 'kit-h').mkdir(parents=True)
+ (work / 'kit-h/wine-ps5').symlink_to(cross, target_is_directory=True)
+ install = work / 'kit-h/source/.deps/wine-host/install/usr'
+ for folder in ('lib/wine/i386-windows', 'lib/wine/x86_64-windows', 'share/wine/nls'):
+ (install / folder).mkdir(parents=True)
+ build = root / 'build'
+ entries = []
+ for index in range(516):
+ name = 'fixture-' + str(index) + '.dll'
+ rel = 'lib/wine/x86_64-windows/' + name
+ original = build / 'kit-f/inputs/runtime/wine' / rel
+ original.parent.mkdir(parents=True, exist_ok=True)
+ original.write_bytes(b'fixture PE')
+ (install / rel).write_bytes(b'fixture PE')
+ target = 'drive_c/windows/system32/' + name
+ path = build / 'kit-a-6a77259/inputs/template/game' / target
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_bytes(b'fixture PE')
+ entries.append({'template_path': target, 'runtime_source': rel, 'after_sha256': module.sha(path)})
+ a = build / 'kit-a-6a77259/inputs'
+ module.write_json(a / 'template-substitutions.json', {'count': 516, 'files': entries})
+ (a / 'template/game/drive_c/windows/syswow64').mkdir(parents=True)
+ (a / 'template/game/system.reg').write_bytes((template / 'system.reg').read_bytes())
+ for name in ('hidclass.sys', 'hidparse.sys', 'winebus.sys', 'winehid.sys', 'winexinput.sys'):
+ (install / 'lib/wine/i386-windows' / name).write_bytes(b'fixture driver')
+ mesa = root / 'mesa'
+ for arch in ('i386-windows', 'x86_64-windows'):
+ (mesa / arch).mkdir(parents=True)
+ (mesa / arch / 'opengl32.dll').write_bytes(b'fixture Mesa')
+ license_file = mesa / 'LICENSES/llvm/LICENSE.txt'
+ license_file.parent.mkdir(parents=True)
+ license_file.write_text('fixture compiler license')
+ module.write_json(mesa / 'manifest.json', {'mesa_commit': 'fixture',
+ 'license_sha256': {'LICENSES/llvm/LICENSE.txt': module.sha(license_file)}})
+ kit = root / 'kit'
+ (kit / ('inputs/titles/any-' + 'a' * 7)).mkdir(parents=True)
+ env = {**os.environ, 'PLAYDEN_KIT_WORK': str(work), 'PLAYDEN_BUILD': str(build),
+ 'PLAYDEN_KIT_DIR': str(kit), 'PLAYDEN_MESA_ARTIFACTS': str(mesa)}
+ env.pop('PLAYDEN_MEDIA_WORK', None)
+ env.pop('PLAYDEN_MEDIA_REGISTRATION', None)
+ if with_media:
+ env.update(PLAYDEN_MEDIA_REGISTRATION=str(registration), PLAYDEN_MEDIA_WORK=str(media))
+ completed = subprocess.run([sys.executable, str(TOOLS / 'stage_kit_h.py'), 'a' * 40],
+ env=env, capture_output=True, text=True)
+ self.assertEqual(completed.returncode, 0, completed.stderr)
+ return kit, license_file, (template / 'system.reg').read_text()
+
+ def test_normal_stager_includes_media_without_overlay(self):
+ with tempfile.TemporaryDirectory() as directory:
+ kit, license_file, _ = self.run_stager(Path(directory), with_media=True)
+ inventory = json.loads((kit / 'inputs/runtime-inventory.json').read_text())
+ self.assertIn('wine/share/wine/licenses/media/source-manifest.json', inventory)
+ self.assertTrue((kit / 'inputs/template/game/drive_c/windows/syswow64/winegstreamer.dll').is_file())
+ self.assertIn('Wow6432Node', (kit / 'inputs/template/game/system.reg').read_text())
+ self.assertEqual((kit / ('inputs/titles/any-' + 'a' * 7) / 'LICENSES/llvm/LICENSE.txt').read_bytes(),
+ license_file.read_bytes())
+
+ def test_normal_stager_without_media_settings_leaves_media_out(self):
+ with tempfile.TemporaryDirectory() as directory:
+ kit, _, base = self.run_stager(Path(directory), with_media=False)
+ inventory = json.loads((kit / 'inputs/runtime-inventory.json').read_text())
+ self.assertFalse([k for k in inventory if 'winegstreamer' in k or '/licenses/media/' in k])
+ self.assertFalse((kit / 'inputs/template/game/drive_c/windows/syswow64/winegstreamer.dll').exists())
+ self.assertEqual((kit / 'inputs/template/game/system.reg').read_text(), base)
+ self.assertIsNone(json.loads((kit / 'inputs/stage-record.json').read_text())['media'])
+
+ def test_mesa_license_inventory_rejects_missing_changed_and_unsafe(self):
+ from mesa_staging import validate_licenses
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ for licenses in ({}, {'LICENSES/missing': '0' * 64}, {'../outside': '0' * 64}):
+ module.write_json(root / 'manifest.json', {'license_sha256': licenses})
+ with self.assertRaises(ValueError):
+ validate_licenses(root)
+ source = root / 'LICENSES/COPYING'
+ source.parent.mkdir()
+ source.write_text('changed')
+ module.write_json(root / 'manifest.json', {'license_sha256': {'LICENSES/COPYING': '0' * 64}})
+ with self.assertRaisesRegex(ValueError, 'hash mismatch'):
+ validate_licenses(root)
+
+
+class R10UpdateTests(unittest.TestCase):
+ """r9 -> r10: the build is r9's plus the media patches, and every cross module replaces r9's."""
+ BASE_PATCHES = ['0958-ntdll-honor-wine-cpu-topology-s-processor-count.patch', '0963-vkd3d-shader-hlsl.patch']
+
+ def kit(self, root, extra_patch=False, new_module=False, skip_ntdll=False):
+ cross, registration, media, _, _ = NormalMediaStagingTests().fixture(root)
+ previous, here = root / 'r9', root / 'r10'
+ runtime, template = here / 'inputs/runtime/wine', here / 'inputs/template/game'
+ files = []
+ modules = [('x86_64-unix', 'ntdll.prx', None, True), ('x86_64-unix', 'libgnutls.prx', None, False),
+ ('i386-windows', 'rtworkq.dll', 'syswow64', True), ('x86_64-windows', 'rtworkq.dll', 'system32', True),
+ ('x86_64-windows', 'wined3d.dll', 'system32', False)]
+ for arch, name, folder, rebuilt in modules:
+ old = runtime / 'lib/wine' / arch / name
+ old.parent.mkdir(parents=True, exist_ok=True)
+ old.write_bytes(b'r9 ' + name.encode())
+ if folder:
+ target = template / 'drive_c/windows' / folder / name
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.write_bytes(old.read_bytes())
+ files.append({'template_path': str(target.relative_to(template)), 'runtime_source': f'lib/wine/{arch}/{name}',
+ 'before_sha256': module.sha(target), 'after_sha256': module.sha(target)})
+ if name == 'ntdll.prx' and skip_ntdll:
+ continue
+ new = cross / ('prx/sce_module' if arch == 'x86_64-unix' else 'pe/' + arch) / name
+ new.parent.mkdir(parents=True, exist_ok=True)
+ new.write_bytes(b'r10 ' + name.encode() if rebuilt else old.read_bytes())
+ if new_module:
+ (cross / 'pe/x86_64-windows/mfplat.dll').write_bytes(b'r10 mfplat')
+ for component, names in [('gnutls', ('COPYING.LESSERv2', 'COPYING', 'AUTHORS', 'lib-inih-LICENSE.txt')),
+ ('nettle', ('COPYING.LESSERv3', 'COPYINGv2', 'COPYINGv3', 'AUTHORS'))]:
+ for name in names:
+ path = cross / 'prx/licenses' / component / name
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text('fixture license')
+ report = json.loads((cross / 'report.json').read_text())
+ report['patches'] = self.BASE_PATCHES + module.WINE_PATCHES + (['0999-extra.patch'] if extra_patch else [])
+ module.write_json(cross / 'report.json', report)
+ module.write_json(root / 'r9-report.json', {'wine_commit': report['wine_commit'], 'patches': self.BASE_PATCHES})
+ (template / 'system.reg').write_text('WINE REGISTRY Version 2\n\n[Software\\\\Game]\n"keep"="yes"\n\n')
+ previous.mkdir()
+ module.write_json(here / 'kit-spec.json', {'runtime': {'artifact_revision': 'b9b0aa5-kit-h-r9'},
+ 'sources': {'wine': {'revision': 'b' * 40}}})
+ module.write_json(here / 'inputs/template-substitutions.json', {'count': len(files), 'files': files})
+ module.write_json(here / 'inputs/stage-record.json', {'artifact_revision': 'b9b0aa5-kit-h-r9',
+ 'cross_pe_modules': ['x86_64-windows/wined3d.dll']})
+ return here, previous, cross, registration, media, root / 'r9-report.json'
+
+ def test_stages_media_and_the_rebuilt_modules(self):
+ with tempfile.TemporaryDirectory() as directory:
+ here, previous, cross, registration, media, base = self.kit(Path(directory))
+ result = module.stage(here, previous, cross, registration, media, base, 'c' * 40, 'r10-dev-20261015.1')
+ self.assertEqual(sorted(result['changed']), ['lib/wine/i386-windows/rtworkq.dll',
+ 'lib/wine/x86_64-unix/ntdll.prx', 'lib/wine/x86_64-windows/rtworkq.dll'])
+ self.assertEqual(sorted(result['template_changed']), ['drive_c/windows/system32/rtworkq.dll',
+ 'drive_c/windows/syswow64/rtworkq.dll'])
+ self.assertEqual(result['wine_patches'][-1], '0964-ntdll-ps5-retire-thread-alert-kqueues')
+ runtime = here / 'inputs/runtime/wine/lib/wine'
+ self.assertEqual((runtime / 'x86_64-unix/ntdll.prx').read_bytes(), b'r10 ntdll.prx')
+ self.assertEqual((runtime / 'x86_64-windows/wined3d.dll').read_bytes(), b'r9 wined3d.dll')
+ self.assertTrue((runtime / 'x86_64-unix/winegstreamer.prx').is_file())
+ self.assertEqual((here / 'inputs/template/game/drive_c/windows/syswow64/rtworkq.dll').read_bytes(),
+ b'r10 rtworkq.dll')
+ spec = json.loads((here / 'kit-spec.json').read_text())
+ self.assertEqual(spec['runtime']['artifact_revision'], 'ccccccc-kit-h-r10-dev-20261015.1')
+ self.assertFalse(spec['sources']['media']['playback_verified'])
+ record = json.loads((here / 'inputs/stage-record.json').read_text())
+ self.assertEqual(record['r10']['base_runtime'], 'b9b0aa5-kit-h-r9')
+ self.assertIn('i386-windows/winegstreamer.dll', record['cross_pe_modules'])
+ inventory = json.loads((here / 'inputs/runtime-inventory.json').read_text())
+ self.assertEqual(inventory['wine/lib/wine/x86_64-unix/ntdll.prx'], module.sha(runtime / 'x86_64-unix/ntdll.prx'))
+
+ def test_other_patches_new_modules_or_missing_modules_stop_before_writes(self):
+ for case, error in (({'extra_patch': True}, 'patches differ.*0999'),
+ ({'new_module': True}, 'r9 does not have.*mfplat'),
+ ({'skip_ntdll': True}, 'missing from the build.*ntdll')):
+ with self.subTest(case=case), tempfile.TemporaryDirectory() as directory:
+ here, previous, cross, registration, media, base = self.kit(Path(directory), **case)
+ before = {p: p.read_bytes() for p in here.rglob('*') if p.is_file()}
+ with self.assertRaisesRegex(ValueError, error):
+ module.stage(here, previous, cross, registration, media, base, 'c' * 40)
+ self.assertEqual({p: p.read_bytes() for p in here.rglob('*') if p.is_file()}, before)
+
+ def test_rejects_a_base_other_than_r9_and_bad_names(self):
+ with tempfile.TemporaryDirectory() as directory:
+ here, previous, cross, registration, media, base = self.kit(Path(directory))
+ with self.assertRaisesRegex(ValueError, 'name is r10'):
+ module.stage(here, previous, cross, registration, media, base, 'c' * 40, 'r11')
+ module.write_json(here / 'kit-spec.json', {'runtime': {'artifact_revision': 'x-kit-h-r8'}})
+ with self.assertRaisesRegex(ValueError, 'starts from r9'):
+ module.stage(here, previous, cross, registration, media, base, 'c' * 40)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tools/kit-h/README.md b/tools/kit-h/README.md
index 1523048..5bd3a21 100644
--- a/tools/kit-h/README.md
+++ b/tools/kit-h/README.md
@@ -31,6 +31,8 @@ The scripts read these environment variables. The defaults fit a plain checkout.
| `PLAYDEN_BUILD` | `stage_kit_h.py`: the build folder that holds kits A and F | `build/` |
| `PLAYDEN_KIT_F` | `make_spec.py`: kit F's build, whose spec kit H starts from | `build/kit-f` |
| `PLAYDEN_MESA_ARTIFACTS` | `stage_kit_h.py`: the output of `tools/build_mesa_zink.sh` | `~/mesa-zink/work/artifacts` |
+| `PLAYDEN_MEDIA_WORK` | `build_cross.sh`, `stage_kit_h.py`: pinned media manifests and `root/` static archives; unset builds and stages without the media backend | none |
+| `PLAYDEN_MEDIA_REGISTRATION` | `stage_kit_h.py`: matching disposable-prefix registry and DLL hash evidence | none, required with `PLAYDEN_MEDIA_WORK` |
| `PS5_NATIVE_FOUNDATION` | `make_shell.sh`: the prospero-foundation checkout | `third_party/prospero-foundation` |
## What does the work
@@ -84,6 +86,60 @@ Recreate. RADV (`libvulkan.prx`) comes
from [PS5_Vulkan](https://github.com/mpereiraesaa/PS5_Vulkan) 8aee3af / [PS5_Mesa](https://github.com/mpereiraesaa/PS5_Mesa)
01d7057, the same as kit G r2. OpenGL games under Zink need at least PS5_Mesa f2ee389.
+## Media backend
+
+Wine's `winegstreamer` can be built with a static GStreamer/FFmpeg backend. Media Foundation, DirectShow and the WMA
+decoder DMO (`wmadmod`, which XAudio2 uses for xWMA) need it. Build the pinned
+LGPL dependencies with prospero-win's `tools/build_media_ps5.py`, then set
+`PLAYDEN_MEDIA_WORK` to its work directory. `build_cross.sh` passes its `root/` to
+`tools/build_wine_ps5.sh --media-root`. Both PE architectures and all static support
+libraries need the builder's file-prefix mapping; stripping debug sections alone
+leaves `__FILE__` paths in diagnostics.
+
+Register the matching i386 and x86_64 `winegstreamer.dll` in a disposable native x86
+Wine prefix using each architecture's `regsvr32.exe`. Preserve `system-before.reg`,
+`system-after.reg` and `dll-sha256.json` (keys `i386-windows` and `x86_64-windows`),
+and set `PLAYDEN_MEDIA_REGISTRATION` to that directory. With both set, `stage_kit_h.py FULL_COMMIT`
+includes the backend; without them it leaves `winegstreamer` out. Staging validates the PRX's
+native import audit, both DLL architectures and registration hashes, both media
+registry views, dependency/archive hashes and license hashes before copying inputs.
+Host devices and other unrelated registry changes are excluded.
+
+The runtime includes `share/wine/licenses/media/` with each component's license text
+and `source-manifest.json` (pinned source releases, checksums and linked archives),
+plus `share/wine/THIRD_PARTY` and neutral build provenance in `share/wine/media-build/`.
+FFmpeg configurations with `--enable-gpl` or `--enable-nonfree` are rejected. Use only
+LGPL GStreamer plugin sets. Package with the matching runtime revision's
+`tools/package_playden_kit.py` in strict mode: omit `--development-build-paths`.
+A release requires zero build-path exceptions. Decoder probes alone do not qualify
+the kit for playback capability.
+
+Kit H r10 is r9 with the media backend (Wine patches 0480-0482 and 0964). Build `build_wine_ps5.sh` on the
+prospero-win commit with `--media-root` (or `build_cross.sh` with `PLAYDEN_MEDIA_WORK` set). Keep r9's build `report.json`:
+the media build maps build paths out of every module, so every cross PRX and PE module differs from r9's and is replaced.
+Strip the build's PE modules except `winegstreamer.dll` with `*-mingw32-strip -s` (the registration records that DLL's
+hash), register `winegstreamer.dll` as above, then run `update_r10.py --kit NEW_KIT --from-kit R9_KIT --cross WINE_WORK
+--registration REGISTRATION_DIR --media-work MEDIA_WORK --base-report R9_REPORT --revision FULL_COMMIT` on a copy of r9's
+inputs and spec, where the absolute archive paths in `media-flags.json` resolve. Staging stops before it writes when the
+build's Wine commit or patch list is not r9's plus those four patches, or when the build makes a module r9 lacks (besides
+`winegstreamer`; `rtworkq.dll` is now cross-built). `--name r10-dev-YYYYMMDD.N` stages a development kit with the same checks.
+
+Install a matching Playden app with the kit. On the next Play, Playden merges the
+kit's media COM/parser values into the stopped bottle's `system.reg`, in both the
+64-bit and WoW64 registry views. It backs up and atomically replaces the hive,
+preserves unrelated values, and leaves the file untouched when the values already
+match. It also copies the kit's `winegstreamer.dll` into the bottle's `system32` and
+`syswow64` when missing: once a prefix exists, Wine loads a builtin DLL only through its
+file there, and kit bottles never run wineboot. Existing bottles get the backend
+without Recreate bottle (Fallout 4's r9 bottle plays its xWMA sound after one Play).
+Older kits without the media metadata keep working.
+
+For a game that cannot handle the backend, add `PW_MEDIA_DISABLE=1` to Playden's
+Environment variables setting. Playden writes it as a `[debug] env` line, which every
+kit H title shell accepts. The runtime then rejects media creation, so games that
+check errors can skip movies; a game that ignores errors can still fail (Metal Wolf
+Chaos XD crashes with it). Remove the switch when testing actual video and audio.
+
## Not done yet
A build from a clean machine, with every input fetched or built by a script, is not written yet.
diff --git a/tools/kit-h/build_cross.sh b/tools/kit-h/build_cross.sh
index 68f166a..a902bb4 100644
--- a/tools/kit-h/build_cross.sh
+++ b/tools/kit-h/build_cross.sh
@@ -12,6 +12,9 @@ export PATH=$task/wrappers:$PATH LLVM_CONFIG=/usr/bin/llvm-config-18 TZ=UTC
export LC_ALL=en_US.UTF-8
: "${PROSPERO_FREETYPE_TARBALL:?set it to freetype-2.13.3.tar.xz}"
export PROSPERO_FREETYPE_TARBALL
+# PLAYDEN_MEDIA_WORK: tools/build_media_ps5.py's work folder; when set, Wine links the static media backend from its root/.
+media=()
+[ -n "${PLAYDEN_MEDIA_WORK:-}" ] && media=(--media-root "$PLAYDEN_MEDIA_WORK/root")
sdk=$root/.deps/ps5-native-app-boilerplate/.deps/native/ps5-payload-sdk
cd "$root"
# Upstream #388: schannel through a static GnuTLS (libgnutls.prx) and a pinned CA bundle.
@@ -19,7 +22,7 @@ PS5_PAYLOAD_SDK=$sdk PROSPERO_WINE_PS5_WORK=$out/wine-ps5 sh tools/build_tls_ps5
sh tools/build_wine_ps5.sh --source "$root/.deps/wine/source" \
--host-tools "$root/.deps/wine-host/build" --foundation "$root/.deps/ps5-native-app-boilerplate" \
--prx-foundation "$task/prx-foundation" --radv "$task/radv-g" --jobs 14 \
- --work "$out/wine-ps5" > "$logs/cross-build.log" 2>&1
+ --work "$out/wine-ps5" "${media[@]}" > "$logs/cross-build.log" 2>&1
sh tools/build_wowprospero.sh --build "$root/.deps/wine-host/build" --source "$root/.deps/wine-host/source" --jobs 14 \
> "$logs/wowprospero-build.log" 2>&1
stubs=$out/wow64native-stubs
diff --git a/tools/kit-h/media_registry.py b/tools/kit-h/media_registry.py
new file mode 100644
index 0000000..763a502
--- /dev/null
+++ b/tools/kit-h/media_registry.py
@@ -0,0 +1,54 @@
+#!/usr/bin/env python3
+"""Extract Wine's actual media registration without host device changes."""
+import re
+SEPARATOR='\\\\'
+
+def blocks(text):
+ matches=list(re.finditer(r'^\[([^\n]+)\][^\n]*\n',text,re.M))
+ result={}
+ for i,match in enumerate(matches):
+ key=match.group(1)
+ value=text[match.end():matches[i+1].start() if i+1<len(matches) else len(text)]
+ result[key]='\n'.join(line for line in value.splitlines() if line and not line.startswith('#time='))
+ return result
+
+def registration_delta(before,after,idl):
+ classes={g.lower() for g in re.findall(r'uuid\(([0-9a-fA-F-]{36})\)',idl)}
+ if '317df618-5e5a-468a-9f15-d827a9a08162' not in classes:
+ raise ValueError('Wine IDL lacks the expected media handler')
+ old,new=blocks(before),blocks(after)
+ delta={}
+ for key,value in new.items():
+ if old.get(key)==value:continue
+ parts=key.lower().split(SEPARATOR)
+ if parts[:2]!=['software','classes']:continue
+ tail=parts[2:]
+ if tail and tail[0]=='wow6432node':tail=tail[1:]
+ allowed=False
+ if len(tail)>=2 and tail[0]=='clsid':
+ allowed=(tail[1].strip('{}') in classes and tail[2:] in ([],['inprocserver32']))
+ allowed |= tail==['clsid','{083863f1-70de-11d0-bd40-00a0c911ce86}','instance','{f9d8d64e-a144-47dc-8ee0-f53498372c29}']
+ allowed |= tail==['media type','{e436eb83-524f-11ce-9f53-0020af0ba770}','{ffffffff-128f-4dd1-ad22-becfa66ce7aa}']
+ if not allowed:continue
+ if re.search(r'/home/|/users/|\\\\home\\\\|\\\\users\\\\|scratch|z:',value,re.I):
+ raise ValueError('host path in media registration: '+key)
+ if key in old and old[key]!=value:
+ raise ValueError('media registration overwrites an existing key: '+key)
+ delta[key]=value
+ for view,folder in [('', 'system32'),('Wow6432Node'+SEPARATOR,'syswow64')]:
+ for cls in classes:
+ key=('Software'+SEPARATOR+'Classes'+SEPARATOR+view+'CLSID'+SEPARATOR+'{'+cls+'}'+SEPARATOR+'InprocServer32').lower()
+ value=next((v for k,v in delta.items() if k.lower()==key),None)
+ expected='C:'+SEPARATOR+'windows'+SEPARATOR+folder+SEPARATOR+'winegstreamer.dll'
+ if value is None or f'@="{expected}"'.lower() not in value.lower() or '"ThreadingModel"="Both"'.lower() not in value.lower():
+ raise ValueError('missing or invalid media registration: '+key)
+ return delta
+
+def merge_registry(base,delta):
+ original=blocks(base)
+ existing={k.lower():v for k,v in original.items()}
+ for key,value in delta.items():
+ if key.lower() in existing:raise ValueError('template already has media key: '+key)
+ original[key]=value
+ header=base[:base.index('[')]
+ return header+''.join('['+key+']\n'+value+'\n\n' for key,value in sorted(original.items(),key=lambda kv:[p.lower() for p in kv[0].split(SEPARATOR)]))
diff --git a/tools/kit-h/media_staging.py b/tools/kit-h/media_staging.py
new file mode 100644
index 0000000..f889c87
--- /dev/null
+++ b/tools/kit-h/media_staging.py
@@ -0,0 +1,132 @@
+#!/usr/bin/env python3
+"""Validate and stage static media inputs for normal kits and legacy overlays."""
+import hashlib,json,re,shutil,struct,shlex
+from pathlib import Path
+from media_registry import registration_delta,merge_registry
+
+def sha(path):return hashlib.sha256(path.read_bytes()).hexdigest()
+def write_json(path,value):path.write_text(json.dumps(value,indent=1,sort_keys=True)+'\n')
+def copy(source,target,mode=0o644):
+ target.parent.mkdir(parents=True,exist_ok=True)
+ target.unlink(missing_ok=True);shutil.copyfile(source,target);target.chmod(mode)
+def pe_machine(path):
+ data=path.read_bytes()
+ if data[:2]!=b'MZ' or len(data)<64:raise ValueError('not PE: '+str(path))
+ offset=struct.unpack_from('<I',data,60)[0]
+ if data[offset:offset+4]!=b'PE\0\0':raise ValueError('invalid PE header: '+str(path))
+ return struct.unpack_from('<H',data,offset+4)[0]
+
+def registry_values(delta):
+ values=[]
+ for key,body in delta.items():
+ # Wine wraps long REG_BINARY assignments with backslash-newline continuations.
+ body=re.sub(r'\\\n[ \t]*','',body)
+ for line in body.splitlines():
+ match=re.fullmatch(r'(@|"[^"\n]+")=(.+)',line)
+ if not match:raise ValueError('unsupported media registry assignment: '+line)
+ values.append({'key':key.replace('\\\\','\\'), 'name': '' if match[1]=='@' else match[1][1:-1], 'data':match[2]})
+ return values
+
+def validate_media(cross,registration,media_work):
+ cross,registration,media_work=map(lambda p:Path(p).resolve(),(cross,registration,media_work))
+ report=json.loads((cross/'report.json').read_text());entry=report['prx']['modules']['winegstreamer']
+ audits=('unresolved','errors','title_unbound','webkit_unbound','raw_syscalls')
+ if entry.get('built') is not True or any(not isinstance(entry.get(k),list) or entry[k] for k in audits):
+ raise ValueError('media PRX failed the title import audit')
+ prx=cross/'prx/sce_module/winegstreamer.prx'
+ if sha(prx)!=entry['sha256']:raise ValueError('media PRX differs from its audit')
+ dll_hashes=json.loads((registration/'dll-sha256.json').read_text())
+ modules=[]
+ for arch,machine,folder in [('i386-windows',0x14c,'syswow64'),('x86_64-windows',0x8664,'system32')]:
+ p=cross/'pe'/arch/'winegstreamer.dll';h=sha(p)
+ if pe_machine(p)!=machine:raise ValueError('wrong PE architecture: '+arch)
+ if dll_hashes.get(arch)!=h or report['pe'].get(arch+'/winegstreamer.dll')!=h:
+ raise ValueError('registered DLL/build report mismatch: '+arch)
+ modules.append((arch,folder,p,h))
+ idl=cross/'source/dlls/winegstreamer/winegstreamer_classes.idl'
+ delta=registration_delta((registration/'system-before.reg').read_text(),(registration/'system-after.reg').read_text(),idl.read_text())
+ values=registry_values(delta)
+ licenses=cross/'prx/licenses/media'
+ if not licenses.is_dir() or not any(licenses.rglob('*')):raise ValueError('media license inventory missing')
+ manifests={p.name:json.loads(p.read_text()) for p in media_work.glob('*-manifest.json')}
+ required={'ffmpeg','libffi','pcre2','zlib','libiconv','glib','gstreamer','gst-plugins-base','gst-plugins-good','gst-plugins-bad','gst-libav'}
+ if {v['component'] for v in manifests.values()}!=required:raise ValueError('incomplete media build manifests')
+ for name,manifest in manifests.items():
+ for rel,digest in manifest['archives'].items():
+ if sha(media_work/'root'/rel)!=digest:raise ValueError('media archive changed since manifest: '+name+'/'+rel)
+ for rel,digest in manifest['licenses'].items():
+ if sha(licenses/Path(rel).relative_to('licenses'))!=digest:raise ValueError('media license differs from manifest: '+rel)
+ link_flags=json.loads((cross/'media-flags.json').read_text())
+ linked_archives={}
+ for flag in shlex.split(link_flags['libs']):
+ if flag.endswith('.a'):
+ path=Path(flag).resolve()
+ if not path.is_relative_to(media_work/'root'):raise ValueError('non-target media archive')
+ linked_archives[path.relative_to(media_work/'root').as_posix()]=sha(path)
+ if not linked_archives:raise ValueError('empty static media link inventory')
+ adapter_manifest=cross/'prx/media-adapters.json'
+ if not adapter_manifest.is_file():raise ValueError('media adapter provenance missing')
+ declared_archives={rel:digest for manifest in manifests.values() for rel,digest in manifest['archives'].items()}
+ if any(declared_archives.get(rel)!=digest for rel,digest in linked_archives.items()):
+ raise ValueError('linked archive missing from dependency manifests')
+ for manifest in manifests.values():
+ if not manifest.get('archives') or not manifest.get('licenses') or not manifest.get('source'):
+ raise ValueError('media source/archive/license inventory missing')
+ if not re.fullmatch(r'[0-9a-f]{64}',manifest['source'].get('sha256','')):
+ raise ValueError('media source checksum missing')
+ if any(flag.split('=')[0] in ('--enable-gpl','--enable-nonfree') for flag in manifest.get('configure',[])):
+ raise ValueError('non-LGPL media configuration')
+ tls_licenses=[]
+ if (cross/'prx/sce_module/libgnutls.prx').is_file():
+ for component,required in [('gnutls',('COPYING.LESSERv2','COPYING','AUTHORS','lib-inih-LICENSE.txt')),
+ ('nettle',('COPYING.LESSERv3','COPYINGv2','COPYINGv3','AUTHORS'))]:
+ directory=cross/'prx/licenses'/component
+ if any(not (directory/name).is_file() for name in required):
+ raise ValueError('TLS license inventory missing: '+component)
+ tls_licenses.append(directory)
+ return dict(delta=delta,values=values,modules=modules,prx=prx,licenses=licenses,manifests=manifests,tls_licenses=tls_licenses,
+ linked_archives=linked_archives,report=report,entry=entry,idl=idl,dll_hashes=dll_hashes)
+
+def stage_media(runtime,template,cross,registration,media_work,substitutions,evidence=None):
+ runtime,template,cross,registration,media_work=map(Path,(runtime,template,cross,registration,media_work))
+ evidence=evidence or validate_media(cross,registration,media_work)
+ if (runtime/'lib/wine/x86_64-unix/libgnutls.prx').is_file() and not evidence['tls_licenses']:
+ raise ValueError('TLS license inventory missing for retained runtime; use a complete cross build')
+ delta,modules,prx,licenses,manifests,linked_archives,report,entry,idl,dll_hashes=(evidence[k] for k in ("delta","modules","prx","licenses","manifests","linked_archives","report","entry","idl","dll_hashes"))
+ system_reg=template/'system.reg'
+ merged=merge_registry(system_reg.read_text(),delta)
+ # All checks above precede mutations to the copied kit.
+ copy(prx,runtime/'lib/wine/x86_64-unix/winegstreamer.prx',0o755)
+ added=['lib/wine/x86_64-unix/winegstreamer.prx']
+ for arch,folder,source,digest in modules:
+ rel='lib/wine/'+arch+'/winegstreamer.dll';dest='drive_c/windows/'+folder+'/winegstreamer.dll'
+ copy(source,runtime/rel);copy(source,template/dest);added.append(rel)
+ previous=next((v for v in substitutions if v['template_path']==dest),None)
+ if previous:substitutions.remove(previous)
+ substitutions.append({'template_path':dest,'runtime_source':rel,'before_sha256':previous['before_sha256'] if previous else None,'after_sha256':digest})
+ system_reg.unlink();system_reg.write_text(merged);system_reg.chmod(0o644)
+ destination=runtime/'share/wine/licenses/media'
+ shutil.copytree(licenses,destination)
+ for directory in evidence['tls_licenses']:
+ shutil.copytree(directory,destination.parent/directory.name,dirs_exist_ok=True)
+ provenance=runtime/'share/wine/media-build';provenance.mkdir(parents=True)
+ for name,value in manifests.items():
+ # Preserve exact source/archive provenance without installing builder paths.
+ neutral={k:v for k,v in value.items() if k not in ('configure','source_directory')}
+ neutral['full_manifest_sha256']=sha(media_work/name)
+ neutral['configure_options']=[v for v in value['configure'] if v.startswith('-') and not any(x in v for x in ('/home/','/Users/','/tmp/'))]
+ write_json(provenance/name,neutral)
+ copy(cross/'prx/media-adapters.json',provenance/'media-adapters.json')
+ write_json(provenance/'linked-archives.json',linked_archives)
+ write_json(provenance/'wine-build-report.json',{'wine_commit':report['wine_commit'],'patches':report['patches'],'media_prx':entry,'pe':{arch+'/winegstreamer.dll':digest for arch,_,_,digest in modules},'full_report_sha256':sha(cross/'report.json')})
+ values=evidence['values']
+ write_json(provenance/'media-registry.json',{'schema':'playden-media-registry/1','values':values})
+ write_json(destination/'source-manifest.json',{'schema':'playden-media-sources/1',
+ 'components':[{k:v for k,v in manifest.items() if k in ('component','source','archives','licenses')}
+ for manifest in manifests.values()], 'linked_archives':linked_archives})
+ (runtime/'share/wine/THIRD_PARTY').write_text('Static media backend: GLib, GStreamer and FFmpeg (LGPL), plus libffi, PCRE2, zlib and libiconv.\n'
+ 'See licenses/media/ for component license texts and source-manifest.json for pinned sources and archive hashes.\n')
+ if evidence['tls_licenses']:
+ with (runtime/'share/wine/THIRD_PARTY').open('a') as notice:
+ notice.write('Static TLS backend: GnuTLS and Nettle; see licenses/gnutls/ and licenses/nettle/.\n')
+ return {'changed':added,'registry_keys':len(delta),'registered_dll_sha256':dll_hashes,'playback_verified':False}
diff --git a/tools/kit-h/mesa_staging.py b/tools/kit-h/mesa_staging.py
new file mode 100644
index 0000000..ce358bf
--- /dev/null
+++ b/tools/kit-h/mesa_staging.py
@@ -0,0 +1,32 @@
+"""Keep the Mesa artifact's declared licenses with its staged DLLs."""
+import hashlib
+import json
+import shutil
+from pathlib import Path
+
+
+def validate_licenses(directory):
+ manifest = json.loads((directory / 'manifest.json').read_text())
+ licenses = manifest.get('license_sha256')
+ if not isinstance(licenses, dict) or not licenses:
+ raise ValueError('Mesa license inventory missing')
+ for name, expected in licenses.items():
+ parts = Path(name).parts
+ if len(parts) < 2 or parts[0] != 'LICENSES' or '..' in parts:
+ raise ValueError('unsafe Mesa license path: ' + name)
+ source = directory
+ for part in parts:
+ source /= part
+ if source.is_symlink():
+ raise ValueError('symlink Mesa license: ' + name)
+ if not source.is_file() or hashlib.sha256(source.read_bytes()).hexdigest() != expected:
+ raise ValueError('Mesa license hash mismatch: ' + name)
+ return manifest
+
+
+def stage_licenses(directory, shell, manifest):
+ for name in manifest['license_sha256']:
+ target = shell / name
+ target.parent.mkdir(parents=True, exist_ok=True)
+ shutil.copyfile(directory / name, target)
+ target.chmod(0o644)
diff --git a/tools/kit-h/stage_kit_h.py b/tools/kit-h/stage_kit_h.py
index 57638be..b8e5393 100644
--- a/tools/kit-h/stage_kit_h.py
+++ b/tools/kit-h/stage_kit_h.py
@@ -12,8 +12,11 @@
# Usage: stage_kit_h.py REVISION
# PLAYDEN_KIT_WORK: the VM build folder (default ~/playden-kit). PLAYDEN_BUILD: the Playden build folder holding kits A and F
# (default build/ next to this script). PLAYDEN_KIT_DIR: where kit H is staged (default build/kit-h). PLAYDEN_MESA_ARTIFACTS:
-# tools/build_mesa_zink.sh's artifacts (default ~/mesa-zink/work/artifacts).
+# tools/build_mesa_zink.sh's artifacts (default ~/mesa-zink/work/artifacts). PLAYDEN_MEDIA_WORK and PLAYDEN_MEDIA_REGISTRATION:
+# set both to stage the static media backend (README.md, Media backend); unset leaves winegstreamer out, as before.
import hashlib, json, os, shutil, subprocess, sys
+from media_staging import validate_media, stage_media
+from mesa_staging import validate_licenses, stage_licenses
from pathlib import Path
revision = sys.argv[1]
@@ -31,9 +34,15 @@ inputs = here / 'inputs'
out = inputs / 'runtime/wine'
template = inputs / 'template/game'
shell = inputs / 'titles' / f'any-{revision[:7]}'
+media = 'PLAYDEN_MEDIA_WORK' in os.environ
+if media:
+ registration = Path(os.environ['PLAYDEN_MEDIA_REGISTRATION'])
+ media_work = Path(os.environ['PLAYDEN_MEDIA_WORK'])
+ media_evidence = validate_media(cross, registration, media_work)
+mesa_manifest = validate_licenses(mesa)
assert not out.exists() and not template.exists(), 'inputs exist'
assert shell.is_dir(), shell
-PACKAGE_RELEASE_SKIPS = {'winex11.drv', 'winegstreamer.dll', 'wpcap.dll', 'sane.ds', 'gphoto2.ds'}
+PACKAGE_RELEASE_SKIPS = {'winex11.drv', 'wpcap.dll', 'sane.ds', 'gphoto2.ds'} | (set() if media else {'winegstreamer.dll'})
def sha(p): return hashlib.sha256(p.read_bytes()).hexdigest()
# --- runtime
@@ -41,6 +50,7 @@ reference = M / 'kit-f/inputs/runtime/wine'
keys = {str(p.relative_to(reference)): p.stat().st_mode & 0o7777 for p in reference.rglob('*') if p.is_file()}
added = {}
for prx in sorted((cross / 'prx/sce_module').glob('*.prx')):
+ if prx.name == 'winegstreamer.prx' and not media: continue
rel = f'lib/wine/x86_64-unix/{prx.name}'
if rel not in keys: keys[rel] = added[rel] = 0o755
for d in ('lib/wine/i386-windows', 'lib/wine/x86_64-windows', 'share/wine/nls'):
@@ -48,6 +58,9 @@ for d in ('lib/wine/i386-windows', 'lib/wine/x86_64-windows', 'share/wine/nls'):
rel = f'{d}/{p.name}'
if p.is_file() and rel not in keys and not p.name.endswith('.a') and p.name not in PACKAGE_RELEASE_SKIPS:
keys[rel] = added[rel] = 0o644
+for arch in ('i386-windows', 'x86_64-windows') if media else ():
+ rel = f'lib/wine/{arch}/winegstreamer.dll'
+ if rel not in keys: keys[rel] = added[rel] = 0o644
ca = cross / 'prx/ca-certificates.crt'
if ca.is_file():
keys['share/wine/ca-certificates.crt'] = added['share/wine/ca-certificates.crt'] = 0o644
@@ -77,11 +90,9 @@ for rel, mode in sorted(keys.items()):
target.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(source, target); target.chmod(mode)
assert not missing, missing
-cross_pe = sorted(str(p.relative_to(cross / 'pe')) for p in (cross / 'pe').glob('*-windows/*') if p.is_file())
+cross_pe = sorted(str(p.relative_to(cross / 'pe')) for p in (cross / 'pe').glob('*-windows/*')
+ if p.is_file() and p.name not in PACKAGE_RELEASE_SKIPS)
assert all(sources[f'lib/wine/{name}'].startswith(str(cross / 'pe')) for name in cross_pe), cross_pe
-inventory = {f'wine/{p.relative_to(out)}': sha(p) for p in sorted(out.rglob('*')) if p.is_file()}
-(inputs / 'runtime-inventory.json').write_text(json.dumps(inventory, indent=1, sort_keys=True) + '\n')
-
# --- template
kit_a = M / 'kit-a-6a77259/inputs'
subprocess.run(['cp', '-a', str(kit_a / 'template'), str(inputs / 'template')], check=True)
@@ -113,6 +124,9 @@ for name in ('hidclass.sys', 'hidparse.sys', 'winebus.sys', 'winehid.sys', 'wine
shutil.copyfile(out / 'lib/wine/i386-windows' / name, target); target.chmod(0o644)
files.append({'template_path': str(target.relative_to(template)), 'runtime_source': f'lib/wine/i386-windows/{name}',
'before_sha256': None, 'after_sha256': sha(target)})
+media_record = stage_media(out, template, cross, registration, media_work, files, media_evidence) if media else None
+inventory = {f'wine/{p.relative_to(out)}': sha(p) for p in sorted(out.rglob('*')) if p.is_file()}
+(inputs / 'runtime-inventory.json').write_text(json.dumps(inventory, indent=1, sort_keys=True) + '\n')
(inputs / 'template-substitutions.json').write_text(json.dumps(
{'schema': 'playden-template-substitution/1', 'base_preparation': 'hl2-fresh-v16-neutral-6a77259',
'runtime_artifact_revision': f'{revision[:7]}-kit-h-r1', 'added_to_kit_a_set': template_added,
@@ -120,7 +134,7 @@ for name in ('hidclass.sys', 'hidparse.sys', 'winebus.sys', 'winehid.sys', 'wine
indent=1) + '\n')
# --- Mesa WGL/Zink in the title shell
-manifest = json.loads((mesa / 'manifest.json').read_text())
+manifest = mesa_manifest
zink = shell / 'win/mesa-zink'
assert not zink.exists()
for arch in ('i386-windows', 'x86_64-windows'):
@@ -128,12 +142,13 @@ for arch in ('i386-windows', 'x86_64-windows'):
for dll in sorted((mesa / arch).iterdir()):
shutil.copyfile(dll, zink / arch / dll.name); (zink / arch / dll.name).chmod(0o644)
shutil.copyfile(mesa / 'manifest.json', shell / 'win/mesa-zink-manifest.json')
+stage_licenses(mesa, shell, manifest)
(inputs / 'stage-record.json').write_text(json.dumps(
{'base': 'kit F runtime key set; kit A template', 'prospero_win': revision,
'artifact_revision': f'{revision[:7]}-kit-h-r1', 'added_to_key_set': sorted(added), 'cross_pe_modules': cross_pe,
'template_added': template_added, 'mesa_commit': manifest.get('mesa_commit'),
- 'mesa_files': sorted(str(p.relative_to(shell)) for p in zink.rglob('*') if p.is_file())}, indent=1) + '\n')
+ 'media': media_record, 'mesa_files': sorted(str(p.relative_to(shell)) for p in zink.rglob('*') if p.is_file())}, indent=1) + '\n')
print('runtime', len(inventory), 'files; added', sorted(added))
print('template', len(files), 'substitutions; added', template_added)
print('mesa', sorted(str(p.relative_to(shell)) for p in zink.rglob('*') if p.is_file()))
diff --git a/tools/kit-h/update_r10.py b/tools/kit-h/update_r10.py
new file mode 100644
index 0000000..b5b28ff
--- /dev/null
+++ b/tools/kit-h/update_r10.py
@@ -0,0 +1,129 @@
+#!/usr/bin/env python3
+"""Kit H r10: kit H r9 plus the static media backend (winegstreamer with GStreamer and FFmpeg, LGPL).
+
+The prospero-win commit adds Wine patches 0480-0482 and 0964 to r9's: 0480-0481 build winegstreamer with static plugins and
+make it fail cleanly, 0482 adds rtworkq cleanup groups and 0964 retires thread-alert kqueues in ntdll's Unix side. The media
+build also maps build paths out of every module (-ffile-prefix-map), so every cross PRX and PE module comes out different from
+r9's, and all of them are replaced. What is checked instead: the build's Wine commit and patch list are r9's plus exactly those
+four patches, and the build makes no module r9 lacks besides winegstreamer (rtworkq.dll is now cross-built; r9 had the host
+build's). The template's copies follow the runtime, and the template gets the media registry values.
+
+Copy kit H r9's inputs and kit-spec.json to the new kit folder first (cp -c works). Build with build_wine_ps5.sh
+--media-root (build_cross.sh with PLAYDEN_MEDIA_WORK set), strip the cross PE modules except winegstreamer.dll with
+*-mingw32-strip -s (its hash is the registered one), and register both winegstreamer.dll builds in a disposable prefix
+(README.md, Media backend). --base-report is r9's cross build report.json. --name sets the artifact suffix, so the same
+script stages a development kit (r10-dev-YYYYMMDD.N) and the release.
+"""
+import argparse, json, re, shutil
+from pathlib import Path
+from media_staging import validate_media, stage_media, sha, write_json
+
+WINE_PATCHES = ['0480-winegstreamer-ps5-static-plugins.patch', '0481-winegstreamer-media-failure.patch',
+ '0482-rtworkq-cleanup-groups.patch', '0964-ntdll-ps5-retire-thread-alert-kqueues.patch']
+NEW = {'x86_64-unix': {'winegstreamer.prx'}, 'i386-windows': {'winegstreamer.dll'}, 'x86_64-windows': {'winegstreamer.dll'}}
+REQUIRED = ['x86_64-unix/ntdll.prx', 'i386-windows/rtworkq.dll', 'x86_64-windows/rtworkq.dll']
+
+
+def cross_modules(cross):
+ yield 'x86_64-unix', sorted(p for p in (cross / 'prx/sce_module').glob('*.prx') if p.is_file())
+ for arch in ('i386-windows', 'x86_64-windows'):
+ yield arch, sorted(p for p in (cross / 'pe' / arch).glob('*') if p.is_file())
+
+
+def check_build(runtime, cross, base_report):
+ """The cross modules that replace r9's, after checking the build is r9's plus the media patches."""
+ report = json.loads((cross / 'report.json').read_text())
+ if report['wine_commit'] != base_report['wine_commit']:
+ raise ValueError('Wine commit differs from r9')
+ added, removed = set(report['patches']) - set(base_report['patches']), set(base_report['patches']) - set(report['patches'])
+ if added != set(WINE_PATCHES) or removed:
+ raise ValueError(f'patches differ from r9 plus the media patches: added {sorted(added)}, removed {sorted(removed)}')
+ replace, unexpected = [], []
+ for arch, sources in cross_modules(cross):
+ for source in sources:
+ if source.name in NEW[arch]:
+ continue
+ module = f'{arch}/{source.name}'
+ (replace if (runtime / 'lib/wine' / module).is_file() else unexpected).append(module)
+ if unexpected:
+ raise ValueError(f'cross modules r9 does not have: {unexpected}')
+ missing = [m for m in REQUIRED if m not in replace]
+ if missing:
+ raise ValueError(f'cross modules missing from the build: {missing}')
+ return replace
+
+
+def stage(here, previous, cross, registration, media_work, base_report, revision, name='r10'):
+ here, previous, cross, registration, media_work = (Path(p).resolve() for p in (here, previous, cross, registration, media_work))
+ if here == previous or previous in here.parents:
+ raise ValueError('r10 must be a separate copy of r9')
+ if not re.fullmatch('[0-9a-f]{40}', revision):
+ raise ValueError('full runtime commit required')
+ if not re.fullmatch(r'r10(-dev-[0-9]{8}\.[0-9]+)?', name):
+ raise ValueError('name is r10 or r10-dev-YYYYMMDD.N')
+ evidence = validate_media(cross, registration, media_work)
+ spec_path = here / 'kit-spec.json'
+ spec = json.loads(spec_path.read_text().replace(str(previous) + '/', str(here) + '/'))
+ if not spec['runtime']['artifact_revision'].endswith('-kit-h-r9'):
+ raise ValueError('r10 starts from r9')
+ record_path = here / 'inputs/stage-record.json'
+ record = json.loads(record_path.read_text())
+ if 'r10' in record:
+ raise ValueError('r10 already staged')
+ runtime, template = here / 'inputs/runtime/wine', here / 'inputs/template/game'
+ replace = check_build(runtime, cross, json.loads(Path(base_report).read_text()))
+ substitutions_path = here / 'inputs/template-substitutions.json'
+ substitutions = json.loads(substitutions_path.read_text())
+
+ # stage_media checks everything else before it writes; the module swaps follow it.
+ media = stage_media(runtime, template, cross, registration, media_work, substitutions['files'], evidence)
+ changed = []
+ for module in replace:
+ arch, file = module.split('/')
+ source = cross / ('prx/sce_module' if arch == 'x86_64-unix' else 'pe/' + arch) / file
+ target = runtime / 'lib/wine' / module
+ if sha(source) == sha(target):
+ continue
+ mode = target.stat().st_mode & 0o7777
+ target.unlink() # the inputs may be a copy-on-write clone of r9's
+ shutil.copyfile(source, target); target.chmod(mode)
+ changed.append(f'lib/wine/{module}')
+ template_changed = []
+ for entry in substitutions['files']:
+ if entry['runtime_source'] in changed:
+ target = template / entry['template_path']
+ if sha(target) != sha(runtime / entry['runtime_source']):
+ target.unlink()
+ shutil.copyfile(runtime / entry['runtime_source'], target); target.chmod(0o644)
+ entry['after_sha256'] = sha(target)
+ template_changed.append(entry['template_path'])
+
+ artifact = f'{revision[:7]}-kit-h-{name}'
+ spec['runtime'].update(wine_revision=revision, artifact_revision=artifact)
+ spec['sources']['wine']['revision'] = revision
+ spec['sources']['media'] = {'wine_commit': evidence['report']['wine_commit'], 'registry_idl_sha256': sha(evidence['idl']),
+ 'playback_verified': False}
+ write_json(spec_path, spec)
+ substitutions['runtime_artifact_revision'] = artifact
+ substitutions['count'] = len(substitutions['files'])
+ substitutions['changed'] = sum(e['before_sha256'] != e['after_sha256'] for e in substitutions['files'])
+ write_json(substitutions_path, substitutions)
+ write_json(here / 'inputs/runtime-inventory.json',
+ {'wine/' + p.relative_to(runtime).as_posix(): sha(p) for p in sorted(runtime.rglob('*')) if p.is_file()})
+ record['r10'] = {'wine_patches': [p.removesuffix('.patch') for p in WINE_PATCHES], 'changed': changed, 'template_changed': template_changed,
+ 'media': media, 'base_runtime': record['artifact_revision']}
+ record['cross_pe_modules'] = sorted(set(record.get('cross_pe_modules', [])) |
+ {c.removeprefix('lib/wine/') for c in changed + media['changed'] if c.endswith('.dll')})
+ record['prospero_win'] = revision
+ record['artifact_revision'] = artifact
+ write_json(record_path, record)
+ return record['r10']
+
+
+if __name__ == '__main__':
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ for option in ('kit', 'from-kit', 'cross', 'registration', 'media-work', 'base-report', 'revision'):
+ parser.add_argument('--' + option, required=True)
+ parser.add_argument('--name', default='r10')
+ a = parser.parse_args()
+ print(json.dumps(stage(a.kit, a.from_kit, a.cross, a.registration, a.media_work, a.base_report, a.revision, a.name), indent=2))