SmoovPlay 0.1.0

This commit is contained in:
SmoovPlay committed 2026-11-15 07:34:33 +00:00
commit 7624bed6f0
158 files changed
+34456

No files matched your search

+6
View File
@@ -0,0 +1,6 @@
* text=auto
*.sh text eol=lf
*.bat text eol=crlf
*.png binary
*.jpg binary
*.ico binary
@@ -0,0 +1,46 @@
name: Feedback on an Experimental feature
description: How an Experimental feature worked for you (Low delay window presentation now; capture cards, AMD Radeon and Intel Arc cards, and window capture as they arrive)
title: "[Experimental] "
labels: ["experimental", "feedback"]
body:
- type: markdown
attributes:
value: |
Thanks for trying it. Experimental features are built from the best information we have, without the
hardware to test every setup, so reports like yours are how they get better. Whether it worked or not, it
helps. SmoovPlay's **Send feedback** button has already copied your diagnostics: paste them at the end.
- type: input
id: feature
attributes:
label: Feature
description: Which Experimental feature you tried.
placeholder: Capture card
validations:
required: true
- type: dropdown
id: result
attributes:
label: How did it go?
options:
- It worked well
- It worked, with problems (below)
- It didn't work
validations:
required: true
- type: input
id: hardware
attributes:
label: Your hardware
description: Model names of what you used (capture card, graphics card, console), and the console's video output if you know it.
placeholder: "Capture card model, console at 1080p 60 Hz, HDR off"
- type: textarea
id: details
attributes:
label: What happened
description: What you saw, what you expected, and anything you tried. A screenshot or a short clip helps.
- type: textarea
id: diagnostics
attributes:
label: Diagnostics
description: Paste what Send feedback (or Copy diagnostics, on SmoovPlay's Help page) put on your clipboard. It leaves out your Windows user name, but have a look before posting.
render: text
+18
View File
@@ -0,0 +1,18 @@
.venv/
.venv-tts/
__pycache__/
.pytest_cache/
models/
testdata/
out/
installer/build/
installer/dist/
installer/.cache/
native/*/build/
*.log
# Kept local, not published: marketing and demo-clip tooling, and working notes
promo/
notes/
scripts/make_clips.py
scripts/render_demo.py
+61
View File
@@ -0,0 +1,61 @@
# Changelog
## 0.1.0 (early release)
The first public version. Windows 10 or 11, with an NVIDIA RTX graphics card recommended.
**Play**
- Plays your PS5 on the PC over Remote Play, through chiaki-ng (the open-source Remote Play app, with SmoovPlay's
frame tap built in). Nothing is installed on the console.
- A 30 fps game becomes 60, 90 or 120 fps: RIFE 4.22 lite draws the in-between frames (TensorRT or PyTorch on the
graphics card), and repeats and scene cuts are found so they aren't blended.
- AMD FSR 1 scales the 1080p stream to your monitor (RTX VSR too, when running from source).
- **Sound in sync:** chiaki-ng holds the game's sound back to meet the picture.
- **Delay test:** press L while playing; SmoovPlay presses a button through chiaki-ng and times how long the PS5
takes to show it.
- **Test mode:** try it with a 60 fps game, played as a 30 fps one, with every AI frame scored against the real one.
- When no picture arrives, the video window says why, for example that chiaki-ng isn't streaming yet.
- **Instant replay:** keep the last 30 seconds to 5 minutes and press R (or Ctrl+Alt+R anywhere) to save it as an
MP4 at the frame rate you see, with the game's own sound from PS5 Remote Play or a capture card. B saves a before
& after video: the game's own frames next to SmoovPlay's, split screen or side by side. Recorded on the graphics
card's video encoder; off until you pick a length.
- **Looks:** stack effects like the nodes of a color grading app (color, color wheels, split tone, LUTs, bloom,
halation, blur, clarity, chromatic aberration, sharpening, film grain, vignette, scanlines, letterbox, color-blind
assist) and see the result live on the game while you edit. 14 looks to start from. K turns the look on and off
and J goes to the next one. Share a look as a short code that anyone can paste. Clips stay clean unless you turn
on Looks in clips.
- Optional NVIDIA Video Frame Generation (VFG) as the interpolation model on RTX 40 and 50 series cards: set up from
the launcher, downloaded from NVIDIA under its licence, not part of SmoovPlay.
**Launcher**
- One installer: checks the PC, downloads the AI runtime from official sources, and walks you through pairing the
PS5. Installs for your Windows user only, without admin rights.
- Settings with quick picks, and the rough picture and speed impact of each choice.
- **Updates itself:** when a new version is out, one click downloads it, checks its signature and installs it,
keeping your settings, looks and clips.
- A Looks page to make, change and share looks, drawn as you edit on sample screenshots from GTA VI and five other
games, and shown live on the video while you play.
- Opens where it was last left.
**Experimental** (built and tested with stand-ins, not yet on real hardware: please send feedback)
- **AMD Radeon and Intel Arc cards:** RIFE through DirectML. The same frames as the NVIDIA engine; on the
development PC's NVIDIA card it took about 1.7 times as long as TensorRT. Not yet tried on an AMD or Intel card.
- **Even out 40-60 fps:** games whose frame rate wanders between 40 and 60 have each frame timed and evenly spaced
frames drawn from them, instead of some staying on screen twice as long. Tried with real footage played as 43
and 47 fps games, not yet with a real one.
- **Capture cards:** any console with HDMI, through a capture card, with its sound held back to meet the picture.
MJPEG cards are decoded on the graphics card. On a PS5, turn off HDCP while you use one.
- **App window:** the window of the app you stream with (the Xbox app, Sony's PS Remote Play app, Moonlight, a
browser playing a cloud game), captured on the graphics card and shown smoothly over it. The repeat check learns
the stream's look and keeps to a 30 fps game's rhythm.
- **Low delay** window presentation (a DXGI flip-model swap chain).
**Known limits**
- The installer isn't code-signed yet: Windows shows "Windows protected your PC" (More info, then Run anyway). The
README explains why, and how to check the file is the real one.
- Tested on one PC so far, with an RTX 4070 Ti SUPER. Other RTX 30, 40 and 50 series cards should work; RTX 20
cards and laptops aren't tested yet.
- If the picture stays black, or the PS5 says the content can't be shown, turn off HDCP on the PS5 (Settings →
System → HDMI) and turn it back on when you're done.
- With an app window, the app's sound comes a little ahead of the smooth picture.
- See the README's Known limits for the rest.
+26
View File
@@ -0,0 +1,26 @@
MIT License
Copyright (c) 2026 the SmoovPlay authors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
The chiaki_tap/ folder holds a patch for chiaki-ng, which is licensed under the
GNU AGPL 3.0; the patched chiaki-ng is a separate program under that licence.
Vendored code keeps its own licence: framegen/rife (MIT, HolyWu) and
framegen/shaders/fsr1 (MIT, Advanced Micro Devices).
+309
View File
@@ -0,0 +1,309 @@
<h1 align="center">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="docs/brand/smoovplay-lockup-dark.svg">
<img src="docs/brand/smoovplay-lockup.svg" width="440" alt="SmoovPlay">
</picture>
</h1>
<p align="center">
<b>Your console. Your GPU. Smoother gameplay.</b><br>
Play 30 fps console games at 60, 90 or up to 120 fps on your PC, with real-time AI frame generation and upscaling.
</p>
<p align="center">
<a href="https://github.com/smoovplay/smoovplay/releases/latest"><b>⬇ Download for Windows</b></a>
&nbsp;·&nbsp; <a href="#what-it-does">What it does</a>
&nbsp;·&nbsp; <a href="#get-it">Install</a>
&nbsp;·&nbsp; <a href="#how-it-works">How it works</a>
&nbsp;·&nbsp; <a href="#faq">FAQ</a>
</p>
<p align="center">
<a href="https://github.com/smoovplay/smoovplay/releases"><img alt="Status: early release" src="https://img.shields.io/badge/status-early%20release-FFB02E?style=flat-square"></a>
<img alt="Windows 10 and 11" src="https://img.shields.io/badge/Windows-10%20%7C%2011-3A4250?style=flat-square">
<img alt="Graphics: NVIDIA RTX 30, 40 or 50 series; AMD and Intel as an Experimental option" src="https://img.shields.io/badge/GPU-NVIDIA%20RTX%2030%20%7C%2040%20%7C%2050%2C%20AMD%20%26%20Intel%20experimental-3A4250?style=flat-square">
<a href="LICENSE"><img alt="MIT licence" src="https://img.shields.io/badge/licence-MIT-3A4250?style=flat-square"></a>
</p>
<!-- HERO CLIP: 30 fps as sent | SmoovPlay at 90 fps, side by side -->
<p align="center">
<img src="docs/media/smoothness.svg" width="880" alt="Two dots cross the same track. The top one, labelled Your console, moves 30 times a second, like a 30 fps game; the bottom one moves 60, 90 or 120 times a second, as fast as your screen shows SmoovPlay.">
</p>
SmoovPlay streams your console to your PC, where your graphics card draws new frames between the ones the game
sends, live. A 30 fps game plays at **60, 90 or up to 120 fps** to match your screen, sharpened to fit it.
There's nothing to install on the console, and it's free and open source.
## What it does
<p align="center">
<img src="docs/media/strip-overview.png" width="100%" alt="What it does, in three pictures: a diagram of your console sending 30 frames a second to your PC, where SmoovPlay runs, and your screen getting 60, 90 or 120; a stack of four frames, real, AI, AI, real; and the same picture small at 1080p, then sharpened and scaled up to your screen’s resolution.">
</p>
- **Up to four times the frames.** RIFE, an open-source AI model, draws 1, 2 or 3 new frames between each pair the
game sends, in about 9 ms each on an RTX 4070 Ti SUPER.
- **Sharper on big screens.** The 1080p stream is sharpened and scaled to your monitor by AMD FSR 1 (in 0.1 ms)
or NVIDIA RTX Video Super Resolution.
- **Works with what you have.** A PS5 streams over Remote Play on your home network, through the open-source chiaki-ng,
and your controller connects to the PC. An Xbox through its app, or any console through a capture card, are
Experimental options.
- **Instant replay.** Press **R** to save the last 30 seconds to 5 minutes as an MP4, at the frame rate you see and
with the game's sound. **B** saves a before & after video.
- **Looks.** Restyle the picture live: start from 14 looks, like Golden hour or Noir, or build your own.
- **One installer.** It checks your PC, helps fix anything that's off, downloads the AI runtime from official
sources and walks you through connecting your console. 10 to 20 minutes, once.
- **Free and open.** MIT licensed. No account, ads or tracking: it only talks to GitHub, for updates.
### Works with
| | Status |
|---|---|
| **PS5**, over Remote Play | **Tested.** The recommended way. |
| **NVIDIA GeForce RTX 30, 40 and 50 series** | **Tested** on an RTX 4070 Ti SUPER. RTX 20 cards and laptops aren't tested yet. |
| **Xbox and other streaming apps**, by capturing the app's window | *Experimental.* Tested with a stand-in window, not the Xbox app yet. |
| **Any console over HDMI**, through a capture card | *Experimental.* Tested with recordings standing in for a card. |
| **AMD Radeon and Intel Arc**, through DirectML | *Experimental.* The same frames, about 1.7× more slowly. Not on a real card yet. |
## Get it
> [!NOTE]
> **Early release.** 0.1.0 is the first version: expect rough edges, and please [report them](#help-test-it).
> SmoovPlay offers new versions itself, and updates in one click.
| You need | |
|---|---|
| **PC** | Windows 10 or 11 (64-bit), 8 GB of memory, 12 GB free during setup |
| **Graphics card** | NVIDIA GeForce RTX 30, 40 or 50 series. AMD Radeon and Intel Arc as an Experimental option. |
| **Console** | A PS5 with Remote Play turned on. Or, Experimental: a console through a capture card, or a game streamed to an app on this PC. |
| **Network** | Ethernet for the console and the PC, or 5 GHz Wi-Fi (not needed with a capture card) |
| **Screen** | Any: 60 Hz gets 60 fps, 90 Hz gets 90, 120 Hz or faster gets up to 120. G-Sync or FreeSync helps. |
**1. Install.** Download `SmoovPlay-Setup.exe` from [Releases](https://github.com/smoovplay/smoovplay/releases/latest)
and run it. It isn't code-signed yet, so your browser and Windows warn you first:
[here's how to get past it](#smartscreen). Setup takes 10 to 20 minutes and never asks for admin rights.
<p align="center">
<img src="docs/media/strip-setup.png" width="100%" alt="Setup in three steps: SmoovPlay checks your graphics card, display and network and helps fix anything that's off; downloads about 5 GB and tunes itself to your graphics card; and is ready to play from the Start menu.">
</p>
Setup ends by picking settings for your PC, from a short test of your graphics card and display. To check again,
say after changing the display, press **Auto-detect** on the Settings page.
**2. Connect your console, then play.** For a PS5, follow **Connect your PS5** in the app: turn on Remote Play, sign
in to PSN in chiaki-ng and register the console. About five minutes, once. For an Xbox or a capture card
(Experimental), pick **App window** or **Capture card** on the Play page. Then press **Play**.
<p align="center">
<img src="docs/media/strip-play.png" width="100%" alt="Playing in three steps: a short guide connects your console to your PC once, you press Play, and the same game runs at 60, 90 or up to 120 fps.">
</p>
<a id="smartscreen"></a>
<details>
<summary><b>Windows says "Windows protected your PC"</b></summary>
SmoovPlay isn't code-signed yet, and Windows' SmartScreen warns about new programs that have no download history.
So the first time, you get past two warnings:
1. **Your browser** may say the file isn't commonly downloaded. Choose to keep it. In Edge: **⋯** → **Keep** →
**Show more** → **Keep anyway**.
2. **Windows** says "Windows protected your PC" when you run it. Click **More info**, then **Run anyway**.
Setup installs for your Windows user only, so it never asks for admin rights. To be sure you have the real file,
download it only from this repo's [Releases](https://github.com/smoovplay/smoovplay/releases) page and compare its
SHA-256 with the one listed there (`Get-FileHash .\SmoovPlay-Setup.exe` in PowerShell). Updates from inside the app
must carry SmoovPlay's signature before they run.
</details>
## Make it yours
<p align="center">
<img src="docs/media/strip-custom.png" width="100%" alt="Make it yours: the frame rate and upscaler settings with Auto-detect; one beach picture in Original, Golden hour and Noir; and the in-game menu, open on Which look, set to Neon night.">
</p>
- **Settings apply as you play.** Change the frame rate, upscaler or AI model on the Settings page, or press **M**
in the video window. **Auto-detect** suggests the best for your PC, with the reason for each.
- **Looks** put a grade on the picture: a stack of effects applied top to bottom, like a color grading app's nodes.
Start from one of 14 (Cinematic, Film, Noir, Retro VHS...), save your own, and share it as a short code.
- **Instant replay** keeps the last 30 seconds to 5 minutes of what you played (off until you pick a length). Your
graphics card's video encoder records it, and saving takes a second or two.
| In the video window | |
|---|---|
| **M** | Menu: every setting, live |
| **F** | Fullscreen, for the lowest delay |
| **I** | Frame generation off and on, to compare |
| **R** · **B** | Save the instant replay · a before & after video (**Ctrl+Alt+R** · **Ctrl+Alt+B** from any window) |
| **K** · **J** | Look off and on · next look (**Shift+J** goes back) |
| **S** · **U** | Stats overlay · next upscaler |
| **L** | Delay test (PS5 Remote Play) |
| **Q** | Stop |
## How it works
With a PS5, the tested setup, the console and the PC talk over your home network, the way Sony's Remote Play app
does. chiaki-ng receives the stream, plays the sound and sends your buttons back. A small patch to it, the frame tap
in [`chiaki_tap/`](chiaki_tap/), also hands every video frame to SmoovPlay. SmoovPlay decodes it on the graphics card,
skips repeated frames, draws the in-between ones with RIFE through TensorRT, scales the result with FSR 1 and shows
it at your screen's refresh rate. With an Xbox app window or a capture card (Experimental), the frames come from the
captured window or the card instead, and the rest is the same.
<p align="center">
<img src="docs/media/setup.svg" width="100%" alt="Desk setup. The PS5 connects by Ethernet to the router, which connects to the PC: the Remote Play stream comes in that way and button presses go back. The controller connects to the PC. The PC's DisplayPort output sends 90 or 120 frames a second to the screen. Inside the PC: the network port receives 30 new frames a second; chiaki-ng on the processor unpacks the stream, plays the sound and sends your buttons; on the graphics card (here an NVIDIA RTX card) the video decoder unpacks each frame and skips repeats, the AI cores draw two in-between frames, about 9 ms each, the shader cores scale the picture with AMD FSR 1 in 0.1 ms, and the display output sends a frame every 11.1 ms at 90 fps.">
</p>
<p align="center">
<img src="docs/media/frames.svg" width="100%" alt="Timeline over 133 ms. From your console: four real frames, A to D, each lasting 33 ms. On your screen: twelve frames, each 11 ms. Every third one is real (A, B, C, D) and the two between are AI frames drawn from the real frames on both sides.">
</p>
The timeline shows 90 fps. At 60 fps there's one AI frame between each pair of real ones, and at 120 fps three.
## Good to know
- **Smoother, not faster.** The extra frames are generated: motion gets smoother, but the game still responds like
30 fps, and a little later than without SmoovPlay. Great for driving, exploring and story missions; not for
competitive online play.
- **About 36 ms of delay at 90 fps** (about 20 ms at 60 fps), on top of Remote Play's own. About 22 ms of it is the
wait every frame generator has: each real frame is held back while the in-between frames before it are shown.
Press **L** in the video window to measure your setup.
- **1080p and SDR.** Remote Play arrives at 1080p, so the picture is a little softer than HDMI straight from the
console. Turn HDR off in chiaki-ng's stream settings.
- **Some wobble.** HUD text over fast motion, very fast camera turns and thin objects crossing each other can wobble
a little. Press **I** to compare with frame generation off.
- **Sound stays in step.** chiaki-ng holds the sound back by as long as the picture spends in SmoovPlay.
- **60 fps games pass through unchanged:** there are no gaps to fill. Try one anyway with
[test mode](#only-have-60-fps-games-use-test-mode).
- **Games between 40 and 60 fps** stutter over a 60 Hz stream. **Even out 40-60 fps** (on by default, Experimental)
spaces their frames evenly, for about one frame (17 ms) more delay.
- **One frame generator at a time.** Leave NVIDIA Smooth Motion, AMD Fluid Motion Frames and Lossless Scaling off
for SmoovPlay and chiaki-ng. Your other games aren't affected.
## Help test it
SmoovPlay is new, so finding what breaks is the most useful help right now:
- **Your graphics card:** which does it hold, 60, 90 or 120 fps?
- **Other games:** anything with a 30 fps Quality or Fidelity mode, or one that runs between 40 and 60 fps.
- **Your setup:** Wi-Fi or wired, and your monitor's refresh rate.
- **The Experimental options:** an Xbox through the Xbox app, a capture card, another app's window, or an AMD or
Intel card. None has met the real hardware yet, so any report helps, even "it didn't start".
Report bugs and feedback in [Issues](https://github.com/smoovplay/smoovplay/issues). In the app, **Help → Copy
diagnostics** copies your PC and settings details: paste them in with the game and what happened.
### Only have 60 fps games? Use test mode
Press **Test with a 60 fps game** on the Play page. SmoovPlay leaves out every other frame, so the game arrives like
a 30 fps game, fills the gaps as usual, and scores each AI frame against the real frame it replaced. Play a few
minutes with some fast motion, then press **Q**: a results card says whether your PC keeps up and how close the AI
frames came to the real ones. **Copy results** puts the full report on the clipboard for your issue.
## FAQ
<details>
<summary><b>Does it change anything on my PS5?</b></summary>
No. Nothing is installed on the console. Your PC receives the Remote Play stream the way Sony's own Remote Play app
does, through chiaki-ng, a free, unofficial Remote Play app. You sign in to PSN once in chiaki-ng to register the
console, as you would in Sony's app.
</details>
<details>
<summary><b>The picture stays black, or the PS5 says the content can't be shown</b></summary>
Turn off HDCP on the PS5: **Settings → System → HDMI**, turn off **Enable HDCP**, then connect again. Turn it back
on for video apps like Netflix when you're done. Still black? Press **Q**, then **Help → Copy diagnostics**, and
paste it into an [issue](https://github.com/smoovplay/smoovplay/issues).
</details>
<details>
<summary><b>Does it work with AMD or Intel graphics cards?</b></summary>
Yes, as an Experimental option, through DirectML on any DirectX 12 card; Radeon RX 6000, 7000 and 9000 and Intel Arc
are the ones to try. It draws the same frames as the NVIDIA engine, about 1.7 times more slowly, so expect 60 fps,
and 90 on a fast card. It hasn't met a game on a real AMD or Intel card yet: press **Send feedback** on the Help
page after playing.
</details>
<details>
<summary><b>Does it work with Xbox, Switch or a capture card?</b></summary>
As Experimental options. For any console with HDMI, pick **Capture card** on the Play page. For Xbox, pick **App
window**: SmoovPlay captures the window of the app you stream with (the Xbox app, Sony's PS Remote Play app,
Moonlight or a cloud game in a browser) and shows the smooth picture over it. Neither has been tried with the real
thing yet, so please [send feedback](#help-test-it).
</details>
<details>
<summary><b>How is this different from DLSS Frame Generation or Lossless Scaling?</b></summary>
DLSS Frame Generation runs inside a PC game and uses its motion data; a video stream has none, so SmoovPlay uses
RIFE, which works out the motion from the frames themselves. Lossless Scaling is great and works on any window.
SmoovPlay is free and open source, takes frames straight from chiaki-ng's decoder instead of capturing the screen,
and walks you through connecting your console.
</details>
<details>
<summary><b>What is NVIDIA VFG?</b></summary>
An optional second AI model for RTX 40 and 50 series cards: NVIDIA's own Video Frame Generation. It isn't part of
SmoovPlay. **Set up NVIDIA VFG** on the Settings page downloads it from NVIDIA, only once you accept NVIDIA's
licence. [More in the developer docs](docs/DEVELOPING.md#nvidia-vfg).
</details>
<details>
<summary><b>What does setup download, and what does it cost?</b></summary>
About 5 GB: Python, PyTorch and NVIDIA TensorRT, each from its official source. It costs nothing: SmoovPlay is free
and open source under the MIT licence, and sends nothing about you.
</details>
<details>
<summary><b>Was AI used to build it?</b></summary>
Yes. It was written with a lot of help from AI coding tools, which is part of why all of it is here to read. The
heavy lifting is done by established open-source projects: chiaki-ng for Remote Play, RIFE for the in-between
frames and AMD FSR 1 for scaling.
</details>
## For developers
| Path | What's in it |
|---|---|
| [`framegen/`](framegen/) | The pipeline: video sources, repeat and cut detection, RIFE (PyTorch and TensorRT), FSR 1 and RTX VSR, the OpenGL window and the settings menu |
| [`run.py`](run.py) | Command-line entry point |
| [`chiaki_tap/`](chiaki_tap/) | The patch that adds a frame tap to chiaki-ng |
| [`installer/`](installer/) | `SmoovPlay-Setup.exe` and the launcher, in C# and WPF |
| [`native/rtxvsr/`](native/rtxvsr/) | Optional wrapper around NVIDIA's RTX Video SDK |
| [`scripts/`](scripts/), [`tests/`](tests/) | Benchmarks, a fake chiaki-ng stream for testing without a PS5, and `pytest` tests |
```powershell
py -3.12 -m venv .venv
.venv\Scripts\python -m pip install torch --index-url https://download.pytorch.org/whl/cu128
.venv\Scripts\python -m pip install -r requirements.txt
# A 60 fps recording played as a 30 fps game, live:
.venv\Scripts\python run.py testdata\clip_1080p60.mp4 --realtime --display
```
**[docs/DEVELOPING.md](docs/DEVELOPING.md)** has the rest: every command and tool, settings and hotkeys, how Instant
replay and Looks work inside, the scheduler, upscaling, NVIDIA VFG, measured results and known limits.
## Credits and licences
RIFE by hzwer ([Practical-RIFE](https://github.com/hzwer/Practical-RIFE), MIT). Model definitions and weights
from [vs-rife](https://github.com/HolyWu/vs-rife) by HolyWu (MIT). FSR 1 shaders by AMD
([FidelityFX-FSR](https://github.com/GPUOpen-Effects/FidelityFX-FSR), MIT). PS5 Remote Play through
[chiaki-ng](https://github.com/streetpea/chiaki-ng) (AGPL-3.0). Optional RTX Video Super Resolution and NVIDIA VFG
come from NVIDIA under NVIDIA's licences and aren't included here.
The Looks page's sample pictures are screenshots from Grand Theft Auto VI and Grand Theft Auto V (© Rockstar Games),
Cyberpunk 2077 (© CD PROJEKT RED), Forza Horizon 5 (© Microsoft), Gran Turismo 7 (© Sony Interactive Entertainment)
and skate. (© Electronic Arts), included only to show what a look does. The README's gameplay stills are from
Rockstar Games' published Grand Theft Auto VI footage. They belong to their publishers and aren't covered by
SmoovPlay's MIT licence.
SmoovPlay's own code is MIT licensed ([LICENSE](LICENSE)); [installer/THIRD_PARTY_NOTICES.txt](installer/THIRD_PARTY_NOTICES.txt)
lists everything it bundles or downloads. SmoovPlay is an independent project, not made, supported or endorsed by
Sony Interactive Entertainment, NVIDIA or AMD. PlayStation and PS5 are trademarks of Sony Interactive Entertainment;
NVIDIA and RTX are trademarks of NVIDIA Corporation; AMD and FidelityFX are trademarks of Advanced Micro Devices, Inc.
+135
View File
@@ -0,0 +1,135 @@
# chiaki-ng frame tap: PS5 Remote Play into the pipeline
[chiaki-ng](https://github.com/streetpea/chiaki-ng) is an open-source PS5 Remote Play client. This folder adds a
small "frame tap" to it: every compressed video frame the PS5 sends is also copied into shared memory, where
`run.py --chiaki` decodes it, interpolates it and shows it. chiaki-ng keeps doing everything else: pairing, the
controller (it reads it even when its window is in the background), audio, and asking the PS5 to resend after a
network loss.
```
PS5 ─HEVC/H.264 over LAN─▶ chiaki-ng ─▶ its own decoder + window (stays behind ours)
│
└─ frame tap: each frame + size + loss flags ─▶ shared memory "Local\chiaki-frametap"
│
run.py --chiaki: decode ─▶ repeat check by size ─▶ scheduler ─▶ RIFE ─▶ window
▲
└── "send a keyframe" flag, when it joins mid-stream or falls behind
```
What the stream gives that a capture card can't:
- **Repeats from frame size.** After compression a repeated frame isn't an exact copy, so the image-based
repeat check calls most of them new (tested: 464 of 470 ticks went wrong). But a repeat costs the encoder
almost nothing, ~3 KB against ~55 KB for a new H.264 frame, ~12 KB against ~47 KB for HEVC. The pipeline uses
the size.
- **Loss flags.** Frames that follow a network loss are held instead of interpolated, so corruption isn't
smeared into the generated frame.
## Files
| | |
|---|---|
| `frametap.c`, `frametap.h` | the tap, compiled into chiaki-ng (Windows; a no-op elsewhere). Does nothing unless `CHIAKI_FRAMETAP=1` |
| `apply_patch.py` | adds the tap to a chiaki-ng checkout: 9 exact-text edits to streamsession.cpp and 1 to CMakeLists.txt, and fails loudly if chiaki-ng moved the code. It refuses a checkout with an older tap patch: `git checkout -- gui/src/streamsession.cpp` first |
| `selftest.py`, `selftest.c` | builds a small writer with MSYS2's gcc and checks it against the Python reader byte for byte, including the press, the sound delay and the sound ring. Uses its own tap name, so it runs while chiaki-ng streams |
| `build_windows.sh` | full Windows build in MSYS2, mirroring chiaki-ng's own CI, plus the patch |
| `run_chiaki_frametap.bat` | starts the built chiaki-ng with the tap on |
| `../framegen/chiaki_tap.py` | the reader: `FrameTap` (shared memory), `AudioTap` (the sound ring), `ChiakiSource` (decode, size-based repeats) |
| `../scripts/frametap_fake.py` | a fake PS5 for testing without a console: streams a video file through the tap |
## Build (done once)
You need [MSYS2](https://www.msys2.org/) and a chiaki-ng v1.10.1 source checkout. From PowerShell, in the repo
root (`CHERE_INVOKING` keeps MSYS2's login shell in the current folder). The example assumes MSYS2 in its default
folder, `C:\msys64`, the source in `C:\src\chiaki-ng` and the build going to `C:\src\chiaki-ng-frametap`; use
your own folders, written as MSYS2 paths:
```powershell
$env:MSYSTEM = 'MINGW64'; $env:CHERE_INVOKING = '1'
C:\msys64\usr\bin\bash.exe -lc "bash chiaki_tap/build_windows.sh /c/src/chiaki-ng /c/src/chiaki-ng-frametap"
```
Re-running only rebuilds chiaki-ng. For a newer chiaki-ng, check out its tag in the source folder first; if
`apply_patch.py` stops with "expected the anchor exactly once", the code it hooks into moved.
## Testing with a PS5
1. **PS5:** Settings → System → Remote Play → turn on Enable Remote Play. Wire the PS5 and the PC to the router
with Ethernet if you can. Pick a game that runs at 30 fps (or its 30 fps quality/fidelity mode).
2. **Start chiaki-ng:** run `run_chiaki_frametap.bat` in the build folder. The first time, register the
PS5: sign in to PSN in chiaki-ng (or paste your account ID), then enter the 8-digit code from
PS5 Settings → System → Remote Play → Link Device.
3. **chiaki-ng settings:** resolution 1080p, FPS **60** (the pipeline expects the PS5's 60 Hz output with
repeats), codec H.265, **HDR off** (the pipeline is 8-bit SDR), bitrate as high as your network allows.
4. **Start the pipeline**, ideally before connecting in chiaki-ng:
```powershell
.venv\Scripts\python run.py --chiaki --display --chiaki-log out\session_GAME.csv
```
It waits for the stream, then opens its window and minimises chiaki-ng's (which keeps streaming and reading
the controller; restored on exit). Press **M** for the settings menu: frame rate (60/90/120), upscaler,
AI engine and so on, saved for next time (see the main README). Hotkeys: `f` fullscreen, `i` interpolation
on/off (instant A/B), `u` next upscaler (matters in fullscreen), `s` stats overlay, `l` delay test, `q` quit.
chiaki-ng passes on the stream's codec header only once, as the stream's first packet. If no run.py has
seen this stream start, the pipeline can't decode it and says so: end the stream in chiaki-ng (Ctrl+O, the
x) and connect again. Once one run has seen it, later runs reuse the saved header and join without that.
**No 30 fps game to hand?** Play any 60 fps game as if it were 30 fps, and score every generated frame
against the real frame that was left out:
```powershell
.venv\Scripts\python run.py --chiaki --test-mode --score --display --chiaki-log out\session_GAME_as30.csv
```
Tested with the fake PS5 streaming a 60 fps recording: RIFE 35.5 dB against the real frames, where showing
the repeat (what a 30 fps game does) scores 26.5 dB.
5. **Afterwards**, attach the console summary and the CSV to a GitHub issue. The CSV has one row per tick: frame size, loss flags,
decode time, what the size check and the image check each said, and what the pipeline did. That's what
tunes the size threshold on real PS5 streams.
Decoding runs on the GPU by default (`--chiaki-decoder cuda`, NVDEC); `--chiaki-decoder sw` is the fallback.
## Back the other way: button presses and the sound delay
The tap's header also carries two requests from the pipeline to chiaki-ng (the header's `features` field says
which ones this chiaki-ng understands):
- **Press a button** (the delay test, **L**): the pipeline asks for a button and how long to hold it. chiaki-ng
adds it to the controller state it sends the PS5, notes the time it went out (the clock both sides share), and
lets go after the hold. The pipeline then times the first frame that shows the answer.
- **Hold the sound back** (Sound in sync): chiaki-ng plays the sound as it arrives, while the picture spends a while
in SmoovPlay. The pipeline writes that while (the median of the last ~2 s of frames, every 2 s) and chiaki-ng
delays its sound by as much, 0–500 ms. If the pipeline stops (its heartbeat is over 2 s old), the delay drops
to 0 by itself, so chiaki-ng on its own never plays late sound.
## The game's sound, for instant replay
chiaki-ng also copies the game's sound, as it arrives and before its own volume, into a second shared-memory ring
(`<tap name>-audio`: 512 slots of up to 8 KB of 16-bit PCM, each with its arrival time; layout in `frametap.h`).
A chunk too big for one slot is split by whole samples, each part timed by the samples before it. The header's
`features` gains a bit for it, so SmoovPlay knows a chiaki-ng from before this ring (whose instant replays are
silent). Instant replay (`framegen/replay.py`) reads it every 20 ms and times the sound by SmoovPlay's delay, so
it meets the picture.
`CHIAKI_FRAMETAP_NAME` gives the tap another shared-memory name (the self-test uses it).
## Testing without a PS5
```powershell
.venv\Scripts\python scripts\frametap_fake.py testdata\clip_1080p60.mp4 --seconds 20 --codec hevc --loss 0.01 --jitter 2 --chiaki-like
.venv\Scripts\python run.py --chiaki --display # in another terminal
```
`--chiaki-like` sends the codec header once, as its own packet, the way chiaki-ng does. The clip's sound (or a
tone with a click each second) goes into the sound ring as it's due; `--no-sound` leaves it out. `--native` streams a
60 fps file as a 60 fps game (for test mode, `--test-mode`). While chiaki-ng is streaming, give the fake and run.py
another tap name (`--tap NAME` and `--chiaki-tap NAME`) so they don't collide with it.
## First PS5 session (10 Nov 2026)
- The stream is H.265 1920×1080 at 60 fps. chiaki-ng delivers it as expected: about 57 frames a second, no
losses over Ethernet, about 2 ms to decode a frame.
- The PS5 sends the codec header out of band, once per stream, and answers a keyframe request with an intra
frame that isn't marked as a keyframe in its NAL type. The reader now keeps the header (and saves it for later
runs) and no longer waits for a keyframe after a gap.
- Only menus and near-still screens were played (true 60 fps, passed through), so the 30 fps cadence over
Remote Play is still untested. On near-still screens every frame is about 500 bytes and the size check calls
them all new; harmless there, since nothing moves.
+176
View File
@@ -0,0 +1,176 @@
"""Add the frame tap to a chiaki-ng source checkout (tested against v1.10.1).
python chiaki_tap/apply_patch.py <chiaki-ng source folder>
Copies frametap.c/.h into gui/ and makes nine small edits to gui/src/streamsession.cpp and one to
gui/CMakeLists.txt. Each edit is an exact-text replacement that must match once, so a chiaki-ng change that moves
the code fails loudly here instead of building something subtly wrong. Running it twice is a no-op. A source
patched by an older version (without the game's sound for instant replay) has to be restored first:
git checkout -- gui/src/streamsession.cpp
With the tap built in, chiaki-ng behaves exactly as before unless CHIAKI_FRAMETAP=1 is set. With it set, besides
copying frames out, it presses buttons when SmoovPlay's delay test asks, holds the sound back by SmoovPlay's
picture delay when SmoovPlay asks (both through the shared memory; see frametap.h), and copies the game's sound as
it arrives into a second ring, for SmoovPlay's instant replay.
"""
import shutil
import sys
from pathlib import Path
HERE = Path(__file__).resolve().parent
MARK = "frametap_push_audio" # this version's edits are in
OLD_MARK = "frametap" # an older version's are
EDITS = [
("#include <streamsession.h>\n",
"#include <streamsession.h>\n#include <frametap.h>\n"),
("static void FfmpegFrameCb(ChiakiFfmpegDecoder *decoder, void *user);\n",
"static void FfmpegFrameCb(ChiakiFfmpegDecoder *decoder, void *user);\n"
"static bool FrameTapVideoSampleCb(uint8_t *buf, size_t buf_size, int32_t frames_lost, bool frame_recovered, void *user);\n"
"static void FrameTapQueueAudioCb(StreamSession *session, const QByteArray &buf);\n"
"static void FrameTapAudioFormatCb(unsigned int rate, unsigned int sample_size);\n"),
("\t\tchiaki_session_set_video_sample_cb(&session, chiaki_ffmpeg_decoder_video_sample_cb, ffmpeg_decoder);\n",
"\t\tif(frametap_begin(chiaki_connect_info.video_profile.codec, chiaki_connect_info.video_profile.width,\n"
"\t\t\t\tchiaki_connect_info.video_profile.height, chiaki_connect_info.video_profile.max_fps))\n"
"\t\t{\n"
"\t\t\tCHIAKI_LOGI(GetChiakiLog(), \"Frame tap on: copying every video frame to shared memory \" FRAMETAP_NAME);\n"
"\t\t\tchiaki_session_set_video_sample_cb(&session, FrameTapVideoSampleCb, this);\n"
"\t\t}\n"
"\t\telse\n"
"\t\t\tchiaki_session_set_video_sample_cb(&session, chiaki_ffmpeg_decoder_video_sample_cb, ffmpeg_decoder);\n"),
("\t\tstatic void TriggerFfmpegFrameAvailable(StreamSession *session)",
"\t\tstatic bool FrameTapVideoSample(StreamSession *session, uint8_t *buf, size_t buf_size, int32_t frames_lost, bool frame_recovered)\n"
"\t\t{\n"
"\t\t\t// Copy first (never blocks), then decode as usual. A reader that joined mid-stream or fell behind\n"
"\t\t\t// asks for a keyframe; RequestIDR runs on the GUI thread, like chiaki-ng's own calls to it.\n"
"\t\t\tframetap_push(buf, buf_size, frames_lost, frame_recovered);\n"
"\t\t\tif(frametap_take_idr_request())\n"
"\t\t\t\tQMetaObject::invokeMethod(session, [session]() { session->RequestIDR(); }, Qt::QueuedConnection);\n"
"\t\t\tuint32_t hold_ms = 0;\n"
"\t\t\tif(uint32_t buttons = frametap_take_press_request(&hold_ms))\n"
"\t\t\t\tQMetaObject::invokeMethod(session, [session, buttons, hold_ms]() { FrameTapPress(session, buttons, hold_ms); }, Qt::QueuedConnection);\n"
"\t\t\treturn chiaki_ffmpeg_decoder_video_sample_cb(buf, buf_size, frames_lost, frame_recovered, session->ffmpeg_decoder);\n"
"\t\t}\n"
"\t\t// SmoovPlay's delay test: press the buttons, send the state at once, note the time, let go after hold_ms.\n"
"\t\tstatic void FrameTapPress(StreamSession *session, uint32_t buttons, uint32_t hold_ms)\n"
"\t\t{\n"
"\t\t\tsession->keyboard_state.buttons |= buttons;\n"
"\t\t\tsession->SendFeedbackState();\n"
"\t\t\tframetap_press_sent();\n"
"\t\t\tQTimer::singleShot((int)hold_ms, session, [session, buttons]() {\n"
"\t\t\t\tsession->keyboard_state.buttons &= ~buttons;\n"
"\t\t\t\tsession->SendFeedbackState();\n"
"\t\t\t});\n"
"\t\t}\n"
"\t\t// Sound held back by SmoovPlay's picture delay (frametap_audio_delay_ms): a first-in first-out buffer of\n"
"\t\t// exactly that much sound. Each frame in sends one frame's worth out, so the device is fed as steadily as\n"
"\t\t// before; while the delay grows that's silence, and when it shrinks the oldest sound is skipped.\n"
"\t\tstatic QByteArray &TapAudioFifo() { static QByteArray fifo; return fifo; }\n"
"\t\tstatic size_t &TapAudioBytesPerMs() { static size_t n = 192; return n; } // 48 kHz stereo 16-bit\n"
"\t\tstatic size_t &TapAudioSampleSize() { static size_t n = 4; return n; }\n"
"\t\tstatic void FrameTapAudioFormat(unsigned int rate, unsigned int sample_size)\n"
"\t\t{\n"
"\t\t\tTapAudioFifo().clear();\n"
"\t\t\tTapAudioSampleSize() = sample_size ? sample_size : 4;\n"
"\t\t\tTapAudioBytesPerMs() = (size_t)rate * TapAudioSampleSize() / 1000;\n"
"\t\t\tframetap_audio_format(rate, (uint32_t)(TapAudioSampleSize() / sizeof(int16_t)));\n"
"\t\t}\n"
"\t\tstatic void FrameTapQueueAudio(StreamSession *session, const QByteArray &buf)\n"
"\t\t{\n"
"\t\t\tQByteArray &fifo = TapAudioFifo();\n"
"\t\t\tsize_t ss = TapAudioSampleSize();\n"
"\t\t\tsize_t want = (size_t)frametap_audio_delay_ms() * TapAudioBytesPerMs() / ss * ss;\n"
"\t\t\tif(!want && fifo.isEmpty())\n"
"\t\t\t{\n"
"\t\t\t\tsession->QueueAudioOutData(buf);\n"
"\t\t\t\treturn;\n"
"\t\t\t}\n"
"\t\t\tfifo.append(buf);\n"
"\t\t\tsize_t n = (size_t)buf.size();\n"
"\t\t\tif((size_t)fifo.size() > want + 2 * n) // the delay shrank: skip the oldest sound\n"
"\t\t\t\tfifo.remove(0, (int)((size_t)fifo.size() - want - n));\n"
"\t\t\tif((size_t)fifo.size() >= want + n)\n"
"\t\t\t{\n"
"\t\t\t\tsession->QueueAudioOutData(fifo.left((int)n));\n"
"\t\t\t\tfifo.remove(0, (int)n);\n"
"\t\t\t}\n"
"\t\t\telse // the delay is growing: silence while the buffer fills\n"
"\t\t\t\tsession->QueueAudioOutData(QByteArray((int)n, 0));\n"
"\t\t}\n"
"\t\tstatic void TriggerFfmpegFrameAvailable(StreamSession *session)"),
("\tStreamSessionPrivate::TriggerFfmpegFrameAvailable(session);\n}\n",
"\tStreamSessionPrivate::TriggerFfmpegFrameAvailable(session);\n}\n\n"
"static bool FrameTapVideoSampleCb(uint8_t *buf, size_t buf_size, int32_t frames_lost, bool frame_recovered, void *user)\n"
"{\n"
"\tauto session = reinterpret_cast<StreamSession *>(user);\n"
"\treturn StreamSessionPrivate::FrameTapVideoSample(session, buf, buf_size, frames_lost, frame_recovered);\n"
"}\n\n"
"static void FrameTapQueueAudioCb(StreamSession *session, const QByteArray &buf)\n"
"{\n"
"\tStreamSessionPrivate::FrameTapQueueAudio(session, buf);\n"
"}\n\n"
"static void FrameTapAudioFormatCb(unsigned int rate, unsigned int sample_size)\n"
"{\n"
"\tStreamSessionPrivate::FrameTapAudioFormat(rate, sample_size);\n"
"}\n"),
("\tchiaki_session_fini(&session);\n\tchiaki_opus_decoder_fini(&opus_decoder);\n",
"\tchiaki_session_fini(&session);\n\tframetap_end();\n\tchiaki_opus_decoder_fini(&opus_decoder);\n"),
# Sound: SmoovPlay can ask for it to be held back to meet its picture (FrameTapQueueAudio).
("\taudio_out_sample_size = sizeof(int16_t) * channels;\n",
"\taudio_out_sample_size = sizeof(int16_t) * channels;\n\tFrameTapAudioFormatCb(rate, audio_out_sample_size);\n"),
("queue_audio:\n\tQueueAudioOutData(buf);\n",
"queue_audio:\n\tFrameTapQueueAudioCb(this, buf);\n"),
# Instant replay: the game's sound as it arrives, before chiaki-ng's volume (so a quiet chiaki-ng still records).
("void StreamSession::PushAudioFrame(int16_t *og_buf, size_t samples_count)\n{\n",
"void StreamSession::PushAudioFrame(int16_t *og_buf, size_t samples_count)\n{\n"
"\tif(audio_out_sample_size)\n"
"\t\tframetap_push_audio((const uint8_t *)og_buf, samples_count * audio_out_sample_size);\n"),
]
CMAKE_EDIT = ("\tsrc/streamsession.cpp\n", "\tsrc/streamsession.cpp\n\tinclude/frametap.h\n\tsrc/frametap.c\n")
def replace_once(text: str, old: str, new: str, where: str) -> str:
n = text.count(old)
if n != 1:
sys.exit(f"{where}: expected the anchor exactly once, found {n}:\n{old}")
return text.replace(old, new)
def patch_file(path: Path, edits: list[tuple[str, str]], done_marker: str) -> None:
with open(path, encoding="utf-8", newline="") as f:
text = f.read()
if done_marker in text:
print(f"{path.name}: already patched")
return
if path.suffix == ".cpp" and OLD_MARK in text:
sys.exit(f"{path.name} has an older frame tap: restore it first (git checkout -- gui/src/{path.name})")
crlf = "\r\n" in text
text = text.replace("\r\n", "\n")
for old, new in edits:
text = replace_once(text, old, new, path.name)
with open(path, "w", encoding="utf-8", newline="") as f:
f.write(text.replace("\n", "\r\n") if crlf else text)
print(f"{path.name}: patched")
def main() -> int:
root = Path(sys.argv[1])
gui = root / "gui"
shutil.copy(HERE / "frametap.h", gui / "include" / "frametap.h")
shutil.copy(HERE / "frametap.c", gui / "src" / "frametap.c")
patch_file(gui / "src" / "streamsession.cpp", EDITS, MARK)
patch_file(gui / "CMakeLists.txt", [CMAKE_EDIT], "src/frametap.c")
return 0
if __name__ == "__main__":
sys.exit(main())
+72
View File
@@ -0,0 +1,72 @@
#!/bin/bash
# Build chiaki-ng with the frame tap on Windows. Run in an MSYS2 MINGW64 shell:
#
# bash chiaki_tap/build_windows.sh <chiaki-ng source> <output folder>
#
# Both as MSYS2 paths: C:\src\chiaki-ng is /c/src/chiaki-ng.
#
# Mirrors chiaki-ng's own Windows CI (.github/workflows/build-msys2.yml): same packages, libplacebo commit,
# FFmpeg build, SDL3 + sdl2-compat and deploy script, plus one step: apply_patch.py before compiling.
# Each dependency step is skipped if already done, so re-running only rebuilds chiaki-ng.
# The result is a portable folder; start it with run_chiaki_frametap.bat (copied into it).
set -euo pipefail
SRC="${1:?usage: build_windows.sh <chiaki-ng source> <output folder>}"
OUT="${2:?usage: build_windows.sh <chiaki-ng source> <output folder>}"
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
export LIBPLACEBO_VERSION="${LIBPLACEBO_VERSION:-3be579e6c7f6b421d9ac3ab4860edc437c50b3eb}"
FFMPEG_ZIP=ffmpeg-n9.0-latest-win64-gpl-shared-9.0
if [[ "${MSYSTEM:-}" != "MINGW64" ]]; then
echo "run this from an MSYS2 MINGW64 shell" >&2
exit 1
fi
step() { echo; echo "=== $*"; }
step "packages"
pacman -S --needed --noconfirm git make unzip zip diffutils \
mingw-w64-x86_64-{ca-certificates,cc,cmake,curl,fast_float,fftw,json-c,libevent,lcms2,libdovi,meson,miniupnpc,gcc,nasm,ninja,openssl,opus,pkgconf,protobuf,python,python-protobuf,python-psutil,python-glad,python-jinja,python-pip,qt6-base,qt6-declarative,qt6-svg,shaderc,speexdsp,spirv-cross,vulkan,vulkan-headers}
cd "$SRC"
step "libplacebo $LIBPLACEBO_VERSION"
if [[ -f /mingw64/lib/pkgconfig/libplacebo.pc ]]; then
echo "already installed"
else
scripts/build-libplacebo-windows.sh
fi
step "FFmpeg ($FFMPEG_ZIP)"
if [[ -f /mingw64/include/libavcodec/avcodec.h ]]; then
echo "already installed"
else
[[ -f "$FFMPEG_ZIP.zip" ]] || curl -fLO "https://github.com/streetpea/FFmpeg-Builds/releases/download/latest/$FFMPEG_ZIP.zip"
rm -rf "$FFMPEG_ZIP" && unzip -q "$FFMPEG_ZIP.zip"
cp -a "$FFMPEG_ZIP/bin/." /mingw64/bin
cp -a "$FFMPEG_ZIP/include/." /mingw64/include
cp -a "$FFMPEG_ZIP/lib/." /mingw64/lib
fi
step "SDL3 + sdl2-compat, hidapi"
if [[ -f /mingw64/lib/pkgconfig/sdl2.pc ]]; then
echo "already installed"
else
INSTALL_PREFIX=/mingw64 scripts/build-sdl2-compat.sh .
INSTALL_PREFIX=/mingw64 scripts/build-hidapi.sh .
cp /mingw64/lib/pkgconfig/sdl2-compat.pc /mingw64/lib/pkgconfig/sdl2.pc
fi
step "frame tap patch"
python "$HERE/apply_patch.py" "$SRC"
step "configure + build chiaki-ng"
cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Release -DCHIAKI_ENABLE_CLI=OFF
cmake --build build --config Release --target chiaki
step "deploy to $OUT"
rm -rf "$OUT"
./scripts/deploy-windows-msys2.sh "$OUT" build/gui/chiaki.exe "$SRC/build/third-party/cpp-steam-tools" /mingw64 gui/src/qml
cp "$HERE/run_chiaki_frametap.bat" "$OUT/"
echo
echo "done: $OUT/run_chiaki_frametap.bat"
+273
View File
@@ -0,0 +1,273 @@
// See frametap.h.
#include "frametap.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef _WIN32
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <windows.h>
#define TOTAL_SIZE ((size_t)FRAMETAP_HEADER_SIZE + (size_t)FRAMETAP_SLOT_COUNT * FRAMETAP_SLOT_SIZE)
#define AUDIO_TOTAL_SIZE ((size_t)FRAMETAP_AUDIO_HEADER + (size_t)FRAMETAP_AUDIO_SLOT_COUNT * FRAMETAP_AUDIO_SLOT_SIZE)
static HANDLE g_map = NULL;
static HANDLE g_event = NULL;
static uint8_t *g_base = NULL;
static HANDLE g_amap = NULL;
static uint8_t *g_abase = NULL; // the sound ring; NULL if it couldn't be made (the frames still flow)
static uint32_t g_arate = 48000, g_achannels = 2;
static int g_enabled = -1;
#define H32(off) ((volatile uint32_t *)(g_base + (off)))
#define H64(off) ((volatile uint64_t *)(g_base + (off)))
#define A32(off) ((volatile uint32_t *)(g_abase + (off)))
#define A64(off) ((volatile uint64_t *)(g_abase + (off)))
bool frametap_enabled(void)
{
if(g_enabled < 0)
{
const char *v = getenv("CHIAKI_FRAMETAP");
g_enabled = (v && v[0] == '1') ? 1 : 0;
}
return g_enabled == 1;
}
static bool open_shared(void)
{
if(g_base)
return true;
const char *name = getenv("CHIAKI_FRAMETAP_NAME");
if(!name || !name[0] || strlen(name) > 200)
name = FRAMETAP_NAME;
char event_name[256];
snprintf(event_name, sizeof(event_name), "%s-frame", name);
// Either side may create the mapping first; CreateFileMapping opens the existing one if it's there.
g_map = CreateFileMappingA(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE,
(DWORD)((uint64_t)TOTAL_SIZE >> 32), (DWORD)(TOTAL_SIZE & 0xffffffffu), name);
if(!g_map)
return false;
g_base = (uint8_t *)MapViewOfFile(g_map, FILE_MAP_ALL_ACCESS, 0, 0, TOTAL_SIZE);
if(!g_base)
{
CloseHandle(g_map);
g_map = NULL;
return false;
}
g_event = CreateEventA(NULL, FALSE, FALSE, event_name); // auto-reset, one reader
char audio_name[256];
snprintf(audio_name, sizeof(audio_name), "%s" FRAMETAP_AUDIO_SUFFIX, name);
g_amap = CreateFileMappingA(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, (DWORD)AUDIO_TOTAL_SIZE, audio_name);
if(g_amap)
{
g_abase = (uint8_t *)MapViewOfFile(g_amap, FILE_MAP_ALL_ACCESS, 0, 0, AUDIO_TOTAL_SIZE);
if(!g_abase)
{
CloseHandle(g_amap);
g_amap = NULL;
}
}
return true;
}
static void audio_header(uint64_t qpc_freq)
{
if(!g_abase)
return;
InterlockedExchange((volatile LONG *)A32(0), 0);
*A32(4) = 1;
*A32(8) = FRAMETAP_AUDIO_SLOT_COUNT;
*A32(12) = FRAMETAP_AUDIO_SLOT_SIZE;
*A32(16) = g_arate;
*A32(20) = g_achannels;
*A64(32) = qpc_freq;
InterlockedExchange64((volatile LONG64 *)A64(24), 0);
InterlockedExchange((volatile LONG *)A32(0), (LONG)FRAMETAP_AUDIO_MAGIC);
}
bool frametap_begin(uint32_t codec, uint32_t width, uint32_t height, uint32_t max_fps)
{
if(!frametap_enabled() || !open_shared())
return false;
InterlockedExchange((volatile LONG *)H32(0), 0); // header is being rewritten
LARGE_INTEGER f;
QueryPerformanceFrequency(&f);
*H32(4) = FRAMETAP_VERSION;
*H32(8) = FRAMETAP_SLOT_COUNT;
*H32(12) = FRAMETAP_SLOT_SIZE;
*H32(16) = codec;
*H32(20) = width;
*H32(24) = height;
*H32(28) = max_fps;
*H64(48) = (uint64_t)f.QuadPart;
*H32(40) = 0;
*H32(64) = FRAMETAP_FEATURE_PRESS | FRAMETAP_FEATURE_AUDIO_DELAY | (g_abase ? FRAMETAP_FEATURE_AUDIO_TAP : 0u);
*H32(68) = 0;
audio_header((uint64_t)f.QuadPart);
// The reader treats a new session as a new stream: it resets its decoder and waits for a keyframe.
InterlockedExchange64((volatile LONG64 *)H64(32), 0);
InterlockedIncrement((volatile LONG *)H32(44));
InterlockedExchange((volatile LONG *)H32(0), (LONG)FRAMETAP_MAGIC); // last: header is complete
return true;
}
void frametap_push(const uint8_t *buf, size_t size, int32_t frames_lost, bool recovered)
{
if(!g_base || *H32(0) != FRAMETAP_MAGIC)
return;
LARGE_INTEGER now;
QueryPerformanceCounter(&now);
uint64_t seq = *H64(32);
uint8_t *slot = g_base + FRAMETAP_HEADER_SIZE + (size_t)(seq % FRAMETAP_SLOT_COUNT) * FRAMETAP_SLOT_SIZE;
size_t cap = FRAMETAP_SLOT_SIZE - FRAMETAP_SLOT_HEADER;
uint32_t flags = 0;
if(size > cap)
{
size = cap;
flags |= 1;
}
// Mark the slot as being rewritten first, so a reader copying it sees the sequence change and retries.
*(volatile uint64_t *)(slot + 0) = UINT64_MAX;
MemoryBarrier();
*(volatile uint64_t *)(slot + 8) = (uint64_t)now.QuadPart;
*(volatile uint32_t *)(slot + 16) = (uint32_t)size;
*(volatile int32_t *)(slot + 20) = frames_lost;
*(volatile uint32_t *)(slot + 24) = recovered ? 1u : 0u;
*(volatile uint32_t *)(slot + 28) = flags;
memcpy(slot + FRAMETAP_SLOT_HEADER, buf, size);
MemoryBarrier();
*(volatile uint64_t *)(slot + 0) = seq;
InterlockedExchange64((volatile LONG64 *)H64(32), (LONG64)(seq + 1));
if(g_event)
SetEvent(g_event);
}
bool frametap_take_idr_request(void)
{
if(!g_base)
return false;
return InterlockedCompareExchange((volatile LONG *)H32(40), 0, 1) == 1;
}
uint32_t frametap_take_press_request(uint32_t *hold_ms)
{
if(!g_base)
return 0;
uint32_t buttons = (uint32_t)InterlockedExchange((volatile LONG *)H32(68), 0);
if(buttons && hold_ms)
{
uint32_t h = *H32(72);
*hold_ms = h < 20 ? 20 : h > 2000 ? 2000 : h;
}
return buttons;
}
void frametap_press_sent(void)
{
if(!g_base)
return;
LARGE_INTEGER now;
QueryPerformanceCounter(&now);
InterlockedExchange64((volatile LONG64 *)H64(80), (LONG64)now.QuadPart);
InterlockedIncrement((volatile LONG *)H32(76));
}
uint32_t frametap_audio_delay_ms(void)
{
if(!g_base || *H32(0) != FRAMETAP_MAGIC)
return 0;
uint32_t ms = *H32(88);
uint64_t freq = *H64(48);
if(!ms || !freq)
return 0;
LARGE_INTEGER now;
QueryPerformanceCounter(&now);
if((int64_t)((uint64_t)now.QuadPart - *H64(56)) > (int64_t)(2 * freq)) // SmoovPlay stopped
return 0;
return ms > 500 ? 500 : ms;
}
void frametap_audio_format(uint32_t rate, uint32_t channels)
{
if(!rate || !channels || channels > 8)
return;
g_arate = rate;
g_achannels = channels;
if(g_abase && *A32(0) == FRAMETAP_AUDIO_MAGIC)
{
*A32(16) = rate;
*A32(20) = channels;
}
}
void frametap_push_audio(const uint8_t *buf, size_t size)
{
if(!g_abase || *A32(0) != FRAMETAP_AUDIO_MAGIC || !buf || !size)
return;
LARGE_INTEGER now;
QueryPerformanceCounter(&now);
uint64_t freq = *A64(32);
size_t frame_bytes = 2u * g_achannels;
size_t cap = (FRAMETAP_AUDIO_SLOT_SIZE - FRAMETAP_AUDIO_SLOT_HEADER) / frame_bytes * frame_bytes;
size_t done = 0;
while(done < size)
{
size_t n = size - done < cap ? size - done : cap;
// A chunk too big for one slot goes in several; each slot's time is when its first sample arrived.
uint64_t q = (uint64_t)now.QuadPart;
if(done && freq)
q += (uint64_t)((double)(done / frame_bytes) * (double)freq / (double)g_arate);
uint64_t seq = *A64(24);
uint8_t *slot = g_abase + FRAMETAP_AUDIO_HEADER + (size_t)(seq % FRAMETAP_AUDIO_SLOT_COUNT) * FRAMETAP_AUDIO_SLOT_SIZE;
*(volatile uint64_t *)(slot + 0) = UINT64_MAX;
MemoryBarrier();
*(volatile uint64_t *)(slot + 8) = q;
*(volatile uint32_t *)(slot + 16) = (uint32_t)n;
*(volatile uint32_t *)(slot + 20) = g_arate;
*(volatile uint32_t *)(slot + 24) = g_achannels;
memcpy(slot + FRAMETAP_AUDIO_SLOT_HEADER, buf + done, n);
MemoryBarrier();
*(volatile uint64_t *)(slot + 0) = seq;
InterlockedExchange64((volatile LONG64 *)A64(24), (LONG64)(seq + 1));
done += n;
}
}
void frametap_end(void)
{
if(!g_base)
return;
// Keep the mapping open (the reader may still hold it); just mark the stream as stopped.
InterlockedExchange((volatile LONG *)H32(0), 0);
if(g_abase)
InterlockedExchange((volatile LONG *)A32(0), 0);
if(g_event)
SetEvent(g_event);
}
#else // not Windows: compiled in, does nothing
bool frametap_enabled(void) { return false; }
bool frametap_begin(uint32_t codec, uint32_t width, uint32_t height, uint32_t max_fps)
{
(void)codec; (void)width; (void)height; (void)max_fps;
return false;
}
void frametap_push(const uint8_t *buf, size_t size, int32_t frames_lost, bool recovered)
{
(void)buf; (void)size; (void)frames_lost; (void)recovered;
}
bool frametap_take_idr_request(void) { return false; }
uint32_t frametap_take_press_request(uint32_t *hold_ms) { (void)hold_ms; return 0; }
uint32_t frametap_audio_delay_ms(void) { return 0; }
void frametap_audio_format(uint32_t rate, uint32_t channels) { (void)rate; (void)channels; }
void frametap_push_audio(const uint8_t *buf, size_t size) { (void)buf; (void)size; }
void frametap_press_sent(void) {}
void frametap_end(void) {}
#endif
+97
View File
@@ -0,0 +1,97 @@
// Frame tap for chiaki-ng: copies every compressed video frame the PS5 sends into a shared-memory
// ring, so another process (SmoovPlay's ChiakiSource) can decode and interpolate it. A second, smaller ring
// carries the game's sound as it arrives (16-bit PCM, before chiaki-ng's own volume), for SmoovPlay's instant replay.
//
// Enabled only when the environment variable CHIAKI_FRAMETAP=1 is set; otherwise every call is a no-op.
// CHIAKI_FRAMETAP_NAME, if set, replaces the shared memory's name (tests run beside a real stream that way).
// Windows only (named file mapping + named event); a no-op elsewhere.
//
// Layout (all little-endian, must match framegen/chiaki_tap.py):
// header, 4096 bytes:
// 0 u32 magic 'CFTP' 4 u32 version 8 u32 slot_count 12 u32 slot_size
// 16 u32 codec (0 H.264, 1 H.265, 2 H.265 HDR) 20 u32 width 24 u32 height
// 28 u32 max_fps 32 u64 write_seq (frames written so far; bumped after the slot is complete)
// 40 u32 idr_request (reader sets 1, writer clears it and asks the PS5 for a keyframe)
// 44 u32 session (bumped at every stream start) 48 u64 qpc_freq
// 56 u64 reader_heartbeat_qpc (reader writes it; informational)
// 64 u32 features (writer; bit 0: it presses buttons when asked, for SmoovPlay's delay test)
// 68 u32 press_buttons (reader sets a ChiakiControllerButton mask; writer clears it and presses them)
// 72 u32 press_hold_ms (reader, before press_buttons) 76 u32 press_count (writer: presses sent so far)
// 80 u64 press_qpc (writer: when the latest press went to the PS5; written before press_count goes up)
// 88 u32 audio_delay_ms (reader: hold chiaki-ng's sound back this long, to meet SmoovPlay's picture; ignored
// once the reader's heartbeat is over 2 s old, so sound comes back on time if SmoovPlay stops)
// features bit 1: it honours audio_delay_ms; bit 2: it writes the sound ring below.
// slot i at 4096 + i * slot_size:
// 0 u64 seq 8 u64 qpc_arrival 16 u32 size 20 i32 frames_lost 24 u32 recovered
// 28 u32 flags (bit 0: frame was larger than the slot and got truncated) 64 data[size]
//
// Sound ring: its own mapping, named like the frames' with "-audio" added, so a reader or writer that predates it
// is unaffected. Same scheme as the frames: a slot's seq is set to all ones while it's rewritten.
// header, 64 bytes:
// 0 u32 magic 'CFTA' (0 while no stream) 4 u32 version 8 u32 slot_count 12 u32 slot_size
// 16 u32 rate (Hz) 20 u32 channels 24 u64 write_seq (chunks written so far) 32 u64 qpc_freq
// slot i at 64 + i * slot_size:
// 0 u64 seq 8 u64 qpc_arrival (of the chunk's first sample) 16 u32 size (bytes) 20 u32 rate
// 24 u32 channels 32 data[size]: interleaved signed 16-bit samples
#pragma once
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
#define FRAMETAP_NAME "Local\\chiaki-frametap"
#define FRAMETAP_EVENT_NAME "Local\\chiaki-frametap-frame"
#define FRAMETAP_MAGIC 0x50544643u /* 'CFTP' */
#define FRAMETAP_VERSION 1u
#define FRAMETAP_HEADER_SIZE 4096u
#define FRAMETAP_SLOT_HEADER 64u
#define FRAMETAP_SLOT_COUNT 32u
#define FRAMETAP_SLOT_SIZE (2u * 1024u * 1024u)
#define FRAMETAP_FEATURE_PRESS 1u
#define FRAMETAP_FEATURE_AUDIO_DELAY 2u
#define FRAMETAP_FEATURE_AUDIO_TAP 4u
#define FRAMETAP_AUDIO_SUFFIX "-audio"
#define FRAMETAP_AUDIO_MAGIC 0x41544643u /* 'CFTA' */
#define FRAMETAP_AUDIO_HEADER 64u
#define FRAMETAP_AUDIO_SLOT_HEADER 32u
#define FRAMETAP_AUDIO_SLOT_COUNT 512u
#define FRAMETAP_AUDIO_SLOT_SIZE 8192u
// True if CHIAKI_FRAMETAP=1 is set in the environment.
bool frametap_enabled(void);
// Call when a stream session starts. Creates the shared memory on first use. Returns false if disabled or on error.
bool frametap_begin(uint32_t codec, uint32_t width, uint32_t height, uint32_t max_fps);
// Call for every compressed video frame, before handing it to the decoder. Never blocks.
void frametap_push(const uint8_t *buf, size_t size, int32_t frames_lost, bool recovered);
// Returns true once per reader request for a keyframe (the caller then asks the PS5 for one).
bool frametap_take_idr_request(void);
// The buttons the reader asked to press (a ChiakiControllerButton mask), once per request, or 0; *hold_ms says how
// long to hold them. The caller presses them, sends the controller state, then calls frametap_press_sent().
uint32_t frametap_take_press_request(uint32_t *hold_ms);
// Call right after a press went to the PS5: the reader times the PS5's response from here.
void frametap_press_sent(void);
// How long to hold the sound back (0-500 ms), as the reader asked; 0 if it hasn't, or has stopped.
uint32_t frametap_audio_delay_ms(void);
// The sound's format, when chiaki-ng sets up its sound output (sample rate, channels of 16-bit samples).
void frametap_audio_format(uint32_t rate, uint32_t channels);
// Call for every chunk of decoded sound as it arrives (interleaved signed 16-bit). Never blocks.
void frametap_push_audio(const uint8_t *buf, size_t size);
// Call when the stream session ends.
void frametap_end(void);
#ifdef __cplusplus
}
#endif
+5
View File
@@ -0,0 +1,5 @@
@echo off
rem Start chiaki-ng with the frame tap on, so SmoovPlay's "run.py --chiaki" receives every video frame.
rem Without CHIAKI_FRAMETAP=1 this build behaves exactly like stock chiaki-ng.
set CHIAKI_FRAMETAP=1
start "" "%~dp0chiaki.exe" %*
+72
View File
@@ -0,0 +1,72 @@
// Checks that frametap.c (the C writer inside chiaki-ng) and framegen/chiaki_tap.py (the Python reader) agree
// on the shared-memory layout. Run through chiaki_tap/selftest.py, which builds this with MSYS2's gcc: it writes
// 40 frames with known contents and flags and 21 chunks of sound (the last too big for one slot, so it's split), waits
// for the reader to ask for a keyframe, then answers a button press (as chiaki-ng does for the delay test) and reports
// the sound delay the reader set.
#include "frametap.h"
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
int main(void)
{
_putenv("CHIAKI_FRAMETAP=1");
if(!frametap_enabled() || !frametap_begin(1, 1920, 1080, 60))
{
fprintf(stderr, "frametap_begin failed\n");
return 2;
}
static uint8_t buf[300000];
// Sound first: 20 chunks of 10 ms (480 stereo samples), then one of 5000 samples (20000 bytes, three slots).
frametap_audio_format(48000, 2);
for(int k = 0; k < 21; k++)
{
size_t size = k < 20 ? 1920 : 20000;
for(size_t j = 0; j < size; j++)
buf[j] = (uint8_t)((k * 7 + j) & 0xff);
frametap_push_audio(buf, size);
Sleep(2);
}
for(int i = 0; i < 40; i++)
{
size_t size = (i % 2) ? 1000 + (size_t)i : 50000 + (size_t)i * 1000; // new/repeat-like sizes
for(size_t j = 0; j < size; j++)
buf[j] = (uint8_t)((i * 31 + j) & 0xff);
frametap_push(buf, size, (i == 17) ? 2 : 0, i == 18);
Sleep(16);
}
// The reader asks for a keyframe; chiaki-ng would then call RequestIDR().
int t = 0;
for(; t < 500 && !frametap_take_idr_request(); t++)
Sleep(20);
if(t == 500)
{
fprintf(stderr, "no idr request within 10 s\n");
frametap_end();
return 3;
}
// Then a button press (chiaki-ng presses, sends the state, and notes the time), and the sound delay.
uint32_t buttons = 0, hold_ms = 0;
for(t = 0; t < 500 && !(buttons = frametap_take_press_request(&hold_ms)); t++)
Sleep(10);
if(!buttons)
{
fprintf(stderr, "no press request within 5 s\n");
frametap_end();
return 4;
}
Sleep(30); // "sending"
frametap_press_sent();
uint32_t delay = 0;
for(t = 0; t < 500 && !(delay = frametap_audio_delay_ms()); t++)
Sleep(10);
printf("idr request seen; press %u for %u ms sent; audio delay %u ms\n", buttons, hold_ms, delay);
fflush(stdout);
// Once the reader stops its heartbeat, the delay lapses on its own.
for(t = 0; t < 400 && frametap_audio_delay_ms(); t++)
Sleep(10);
printf("audio delay lapsed: %s\n", frametap_audio_delay_ms() ? "no" : "yes");
frametap_end();
return 0;
}
+87
View File
@@ -0,0 +1,87 @@
"""Build selftest.c against frametap.c with MSYS2's gcc and check its frames with the Python reader.
.venv\\Scripts\\python chiaki_tap\\selftest.py [MSYS2 folder, default C:\\msys64]
Verifies the C writer (what runs inside chiaki-ng) and framegen/chiaki_tap.py agree on every byte: header
fields, frame data, sizes, loss/recovered flags, the keyframe-request flag, the delay test's button press, the
sound delay (and that it lapses without SmoovPlay's heartbeat), the game's sound for instant replay (data, format
and times, including a chunk split over several slots) and the end-of-stream marker. Uses a tap name of
its own (CHIAKI_FRAMETAP_NAME), so it can run while chiaki-ng is streaming.
"""
import os
import subprocess
import sys
import tempfile
import time
from pathlib import Path
HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE.parent))
from framegen.chiaki_tap import (AUDIO_SUFFIX, BUTTON_OPTIONS, FEATURE_AUDIO_DELAY, FEATURE_AUDIO_TAP, # noqa: E402
FEATURE_PRESS, AudioTap, FrameTap)
NAME = r"Local\chiaki-frametap-selftest"
def main() -> int:
msys = Path(sys.argv[1] if len(sys.argv) > 1 else r"C:\msys64") # MSYS2's default install folder
gcc = msys / "mingw64" / "bin" / "gcc.exe"
exe = Path(tempfile.gettempdir()) / "frametap_selftest.exe"
env = dict(os.environ, PATH=str(gcc.parent) + os.pathsep + os.environ["PATH"], CHIAKI_FRAMETAP_NAME=NAME)
subprocess.run([str(gcc), "-O2", "-Wall", "-o", str(exe), str(HERE / "selftest.c"), str(HERE / "frametap.c")],
check=True, env=env)
tap = FrameTap(NAME, NAME + "-frame")
tap.end() # clear any old state
sound = AudioTap(NAME + AUDIO_SUFFIX)
sound.end()
proc = subprocess.Popen([str(exe)], env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
t_end = time.perf_counter() + 10
for i in range(40): # read each frame as it arrives, like ChiakiSource (the ring holds only 32)
while time.perf_counter() < t_end and (not tap.header().live or tap.header().write_seq <= i):
tap.wait(0.1)
h = tap.header()
assert h.live and (h.version, h.codec, h.width, h.height, h.max_fps) == (1, 1, 1920, 1080, 60), h
p = tap.read(i, h.qpc_freq)
size = 1000 + i if i % 2 else 50000 + i * 1000
want = bytes((i * 31 + j) & 0xFF for j in range(size))
assert p is not None and p.data == want, f"frame {i}: data mismatch"
assert p.frames_lost == (2 if i == 17 else 0) and p.recovered == (i == 18) and not p.truncated, i
assert 0 < time.perf_counter() - p.t_arrival < 5, f"frame {i}: arrival time off"
tap.request_idr()
# The game's sound: every byte, in order, with its format, and times that move on with it
assert sound.live(), "sound ring not started"
sound.reset(from_start=True)
chunks = sound.read_new()
want = b"".join(bytes((k * 7 + j) & 0xFF for j in range(1920 if k < 20 else 20000)) for k in range(21))
assert b"".join(c.pcm for c in chunks) == want, f"sound data mismatch ({len(chunks)} chunks)"
assert len(chunks) == 23 and all((c.rate, c.channels) == (48000, 2) for c in chunks), [len(c.pcm) for c in chunks]
assert all(b.t >= a.t for a, b in zip(chunks, chunks[1:])), "sound times go backwards"
assert abs((chunks[-1].t - chunks[-2].t) - 2040 / 48000) < 1e-3, "a split chunk's slots aren't timed by their samples"
assert 0 < time.perf_counter() - chunks[0].t < 10, "sound arrival time off"
# The delay test's press: asked for, sent by the writer, timed in our clock
assert tap.features() == FEATURE_PRESS | FEATURE_AUDIO_DELAY | FEATURE_AUDIO_TAP, tap.features()
t_ask = time.perf_counter()
token = tap.press(BUTTON_OPTIONS, 120)
while (sent := tap.press_sent(token, h.qpc_freq)) is None and time.perf_counter() - t_ask < 5:
time.sleep(0.005)
assert sent is not None and t_ask < sent < time.perf_counter(), "press not sent, or its time is off"
# The sound delay holds while our heartbeat is fresh, then lapses
tap.set_audio_delay(42)
for _ in range(20):
tap.heartbeat()
time.sleep(0.05)
out, err = proc.communicate(timeout=15)
assert proc.returncode == 0, (proc.returncode, out, err)
assert f"press {BUTTON_OPTIONS} for 120 ms sent; audio delay 42 ms" in out, out
assert "audio delay lapsed: yes" in out, out
assert not tap.header().live, "end-of-stream not marked"
assert not sound.live(), "sound ring's end not marked"
print(f"OK: 40 frames and 21 chunks of sound byte-identical, flags and timestamps right, keyframe request, "
f"press and sound delay "
f"({out.strip()})")
return 0
if __name__ == "__main__":
sys.exit(main())
+342
View File
@@ -0,0 +1,342 @@
# Developing SmoovPlay
Everything for working on SmoovPlay itself: every command and tool, settings and hotkeys, how Instant replay and
Looks work inside, the scheduler, upscaling, NVIDIA VFG, measured results and known limits. For what SmoovPlay is
and how to get it, see the [README](../../README.md).
## What's where
| Path | What's in it |
|---|---|
| [`framegen/`](../framegen/) | The pipeline: video sources (file, capture card, app window, chiaki-ng frame tap), repeat and cut detection, RIFE interpolation (PyTorch and TensorRT), FSR 1 and RTX VSR upscaling, the OpenGL window and the settings menu. |
| [`run.py`](../run.py) | Command-line entry point. |
| [`chiaki_tap/`](../chiaki_tap/) | The patch that adds a frame tap to chiaki-ng, and how to build it. |
| [`installer/`](../installer/) | `SmoovPlay-Setup.exe` and the SmoovPlay launcher, in C# and WPF. |
| [`native/rtxvsr/`](../native/rtxvsr/) | Optional wrapper around NVIDIA's RTX Video SDK. |
| [`scripts/`](../scripts/) | Benchmarks, a model check and a fake chiaki-ng stream for testing without a PS5. |
| [`tests/`](../tests/) | `pytest` tests. |
### Setup
Needs 64-bit Windows 10 or 11, an NVIDIA RTX card with a recent driver (or an AMD or Intel card through DirectML,
Experimental), and Python 3.12.
```powershell
py -3.12 -m venv .venv
.venv\Scripts\python -m pip install torch --index-url https://download.pytorch.org/whl/cu128
.venv\Scripts\python -m pip install -r requirements.txt
```
RIFE weights download automatically into `models/` on first run. To build the installer and launcher, see
[installer/README.md](../installer/README.md); to build the patched chiaki-ng, see [chiaki_tap/README.md](../chiaki_tap/README.md).
### Usage
Any 60 fps gameplay recording works for testing; the examples use `testdata\clip_1080p60.mp4`.
```powershell
# Simulate PS5 30 fps output from a native 60 fps recording and watch it live:
.venv\Scripts\python run.py testdata\clip_1080p60.mp4 --realtime --display
# Score interpolated frames against the real frames that were dropped:
.venv\Scripts\python run.py testdata\clip_1080p60.mp4 --score --hitch 0.03 --save-worst out\worst.jpg
# Write the result to a file (NVENC):
.venv\Scripts\python run.py testdata\clip_1080p60.mp4 --out out\clip_interp_60fps.mp4
# Capture card (Experimental, not tested with a real card):
.venv\Scripts\python run.py --list-devices
.venv\Scripts\python run.py --capture 0 --display
# Another app's window (Experimental, not tested with a real app): a preset, exe:NAME, hwnd:N or part of its title
.venv\Scripts\python -m framegen.window --list
.venv\Scripts\python run.py --source window --window ps-remote-play --display
# PS5 Remote Play through the patched chiaki-ng (the CSV: one row per frame, stream facts and decisions):
.venv\Scripts\python run.py --chiaki --display --chiaki-log out\session.csv
# Every Remote Play session ends with a stream check: how well the size-based repeat check read the game (frame
# rate, the 30 fps new/repeat rhythm, likely misreads by the picture, sizes, arrival times, a verdict). It goes in
# the log and, with --results, in stream-check-<stamp>.txt beside the results. The same report from a saved CSV:
.venv\Scripts\python scripts\stream_check_replay.py out\session.csv
# Test mode: a 60 fps game played as if it were 30 fps, each AI frame scored against the frame left out, with a
# plain-language report rewritten every 10 s and at the end (the launcher's results card reads it):
.venv\Scripts\python run.py --chiaki --test-mode --display --results out\results.txt --chiaki-log out\session_as30.csv
# The same report for a file (always played as a 30 fps game, see the scheduler notes below):
.venv\Scripts\python run.py testdata\clip_1080p60.mp4 --score --results out\results.txt
```
`scripts/frametap_fake.py testdata\clip_1080p60.mp4 --native` stands in for a PS5 running a 60 fps game, so test
mode can be tried without a console.
Other tools: `scripts/benchmark.py` (GPU timing per model and resolution), `scripts/bench_120.py` (30 → 120 speed
and quality), `scripts/check_fast.py` (checks the optimised forward pass against the reference), `scripts/latency_video.py`
(delay from a slow-motion phone video) and `pytest tests`.
<details>
<summary><b>Settings, the in-video menu and hotkeys</b></summary>
The settings are in two places, which stay in step:
- **The launcher's Settings page.** With nothing playing, changes are saved for the next session. While a stream
plays, the page shows **LIVE** and changes reach the video straight away, as if made in the video window's menu.
- **The video window's menu.** Press **M** (or Tab): ↑/↓ pick a setting, ←/→ change it, M or Esc closes it. The
video keeps playing behind it, so changes can be judged as they're made.
Both save to `%APPDATA%\framegen\settings.json`. Each setting explains itself on the page, and each choice in a
dropdown has a line on when to pick it.
**Auto-detect**, at the top of the Settings page, suggests the frame rate, interpolation model, motion detail, engine
and upscaler for this PC, with the reason for each; **Apply** sets them. It takes about 10 seconds:
- It times RIFE on a 1080p frame, at full and half motion detail, with the engine Auto would use.
- It reads the main display's refresh rate and resolution, and checks for TensorRT and RTX VSR.
- It picks the fastest frame rate the display can show where an in-between frame fits in 90% of a display tick.
That margin is calibrated from live tests on an RTX 4070 Ti SUPER. 90 fps at full detail is preferred over 120 at
half, as in testing.
- It notes anything worth fixing: a display Windows runs below its top rate, a graphics card busy with something
else, or a frame rate that needs G-Sync or FreeSync for even motion.
Setup runs it on a new install (`python -m framegen.prepare` → `python -m framegen.autodetect --apply --if-new`),
and doesn't save if the card is busy. The logic is `recommend()` in `framegen/autodetect.py`; the tests try it on
made-up PCs.
| Setting | Choices | Applies |
|---|---|---|
| Frame generation | On / Off | live |
| Output frame rate | 60 / 90 / 120 fps | live (falls back to 60 when the GPU can't keep up) |
| Even out 40-60 fps | On / Off (Experimental: even motion for games between 30 and 60 fps) | live |
| Upscaler | AMD FSR 1 / NVIDIA RTX VSR / Bilinear (others may come later) | live |
| FSR sharpening | Max … Minimal | live |
| RTX VSR quality | Low / Medium / High / Ultra | live |
| Stats overlay, Fullscreen, VSync | On / Off | live |
| Window presentation | Standard / Low delay (Experimental: DXGI flip model, so a window skips the compositor's copy and G-Sync works in a window; fullscreen always uses Standard; `--present gl\|dxgi`) | next Play |
| Minimise chiaki-ng | On / Off | live (PS5 Remote Play only) |
| Sound in sync | On / Off (chiaki-ng holds its sound back to meet the picture) | live (PS5 Remote Play only) |
| Simulate a 30 fps game | Off / On | live, this session only, never saved (any 60 Hz source: Remote Play, a capture card, or a file with `--raw`; `--test-mode`) |
| Steady HUD | Off / On (off by default; results vary by game; RIFE only) | live |
| Look, Which look | Off / On, and SmoovPlay's looks and yours (made on the launcher's Looks page) | live |
| Looks in clips | Off / On (the look in saved instant replays too; only SmoovPlay's half of a before & after video) | live |
| Interpolation model | RIFE 4.22 lite / NVIDIA VFG (RTX 40 and 50 series, optional download, see below) | **restart** |
| VFG quality | Low / Medium / High (NVIDIA VFG only) | **restart** |
| AI engine | Auto (TensorRT at full motion detail, PyTorch at half: the faster for each) / TensorRT / PyTorch (RIFE only) | **restart** |
| Motion detail | Auto / Full / Half (RIFE only) | **restart** |
Settings marked *restart* are saved at once. The menu and the Settings page then show **Restart now**, which
rebuilds the AI engine in a few seconds without dropping the stream or closing the window; the first TensorRT
build for a new resolution takes about 2 minutes. Adding a setting means adding one `Spec` to
`framegen/settings.py`: the menu, the launcher's Settings page, the saved file and the command line all read from
that list. The launcher talks to a running session through its stdin and stdout (`run.py --control`; see
`framegen/remote.py`).
Hotkeys: `i` interpolation on/off for this session (instant A/B, not saved), `s` stats overlay, `f`
fullscreen, `u` next upscaler, `l` delay test (PS5 Remote Play), `r` save the instant replay, `b` save a before &
after video of it, `k` look on/off, `j` next look (`Shift+J` back), `q` quit. A short note in the corner confirms each one. While instant replay is on,
`Ctrl+Alt+R` and `Ctrl+Alt+B` work from any window.
Instant replay (`framegen/replay.py`) keeps three tracks in memory as MPEG-TS pieces, one per encoded packet: every
frame shown (timed when it was shown, so 90 fps is 90), each new game frame (timed when it arrived plus SmoovPlay's
delay, so it lines up), and the game's sound, which chiaki-ng copies into a second shared-memory ring (see
[`chiaki_tap/`](../chiaki_tap/)) or a capture card's player hands over. Frames go to YUV on the graphics card (0.3 ms
at 1080p), to memory on a side stream, and to NVENC (else AMF, QSV or x264) on a thread of their own. Saving cuts
from the keyframe before the start (one a second) and remuxes to MP4 without re-encoding; a before & after video is
composed and encoded by `python -m framegen.replay compose` in a low-priority process of its own.
Looks (`framegen/looks.py`, `framegen/looks_gl.py`): a look is JSON, `{"name", "nodes": [{"type", "on", "mix",
...}]}`, cleaned by `normalize()`. Yours are files in `%APPDATA%\framegen\looks`, with LUTs in its `luts` folder. The
video window draws a look in passes: the per-pixel effects share one shader, and each effect that reads neighbouring
pixels (bloom, halation, blur, clarity, aberration, sharpening) starts a new pass on a half-float image; bloom,
halation, blur and clarity use a pyramid of up to 6 halvings. `looks.render()` does the same maths in NumPy, and the tests compare the
shaders with it. With **Looks in clips** on, the look is drawn again at the stream's size into a texture that CUDA
reads, for the SmoovPlay track only. A share code is `SPL1-` and base64url of a compact binary: each value as its
difference from the default, deflated when that's shorter, with a 16-bit checksum; a newer version's extra
settings are skipped by older ones. The launcher's Looks page uses `python -m framegen.looks` (`schema`, `encode`,
`decode`, `import`, `save`, `delete`, `add-lut`) and shows edits live with the `look-show`, `look-hide` and
`looks-reload` commands (`framegen/remote.py`). Its preview is `python -m framegen.looks_preview`, a process that
draws looks on the sample pictures (`framegen/samples`) with the video window's own shaders in a hidden OpenGL context
(about a millisecond a picture; NumPy without OpenGL), one JSON request per line on stdin.
`python -m framegen.looks preview LOOK IN.png OUT.png` puts a look (an id or a code) on a picture.
Command-line flags (`--hz`, `--scaler`, `--fsr-sharpness`, `--vsr-quality`, `--engine`/`--trt`, `--off`,
`--vsync`, `--fullscreen`, `--minimize-chiaki`, `--steady-hud`, `--present gl|dxgi`, `--test-mode`, `--model vfg`
with `--vfg-quality`) override the saved settings for one run without saving them;
`--settings none` starts from defaults and saves nothing. `--model 4.25.lite|4.25|4.26` tries another RIFE
version for testing; those aren't offered in the menus until they're tested for real-time play and setup prepares
them.
</details>
<details>
<summary><b>NVIDIA VFG (optional, RTX 40 and 50 series)</b></summary>
SmoovPlay can draw the in-between frames with NVIDIA's own Video Frame Generation (VFG, part of NVIDIA's Video
Effects SDK) instead of RIFE. It isn't part of SmoovPlay or its downloads. **Set up NVIDIA VFG**, under
Interpolation model on the Settings page, downloads NVIDIA's `nvidia-vfx` package from NVIDIA's own package index
into `runtime\vfx` (about 540 MB, pinned by version and file hash), and only once you accept NVIDIA's licence:
the NVIDIA Software License Agreement, the Product-Specific Terms for NVIDIA AI Products and the NVIDIA Open Model
License. **Remove** deletes it again. NVIDIA supports it on RTX 40 and 50 series cards only; RIFE works on every RTX
card. If VFG can't start, SmoovPlay plays with RIFE instead and says why.
NVIDIA's licence doesn't allow publishing VFG benchmark results, so this page has none, and SmoovPlay keeps VFG's
timings and quality scores out of its logs and out of Copy diagnostics. They're shown on your own PC only: in the
stats overlay, in Auto-detect (which times VFG too once it's set up, and suggests it when it keeps up at least as
well as RIFE) and in test mode's report.
From the command line: `python -m framegen.vfg_setup --install --accept-nvidia-licence --target <folder>` (or
`--status`, `--remove`), then set `FRAMEGEN_VFX_PATH=<folder>` and run `run.py --model vfg --vfg-quality medium`.
</details>
<details>
<summary><b>Upscaling</b></summary>
When the window is bigger than the frame (fullscreen on a 1440p monitor, say), it upscales:
- **AMD FSR 1** (default): edge-adaptive upscaling plus mild sharpening, run as two shader passes while the
frame is drawn, so real and generated frames get the same treatment. It costs about 0.1 ms of GPU time per
frame at 2560×1440 (bilinear: about 0.04 ms).
- **NVIDIA RTX Video Super Resolution**: also cleans up compression artefacts, but costs 1.3–4.9 ms per frame
at 1440p (quality Low…Ultra, RTX 4070 Ti SUPER). At 90 Hz that's three passes per real frame, which costs
some of the extra in-between frames. In side-by-side use it looked about the same as FSR 1. It needs the
[RTX Video SDK](https://developer.nvidia.com/rtx-video-sdk) (free, NVIDIA developer login), unpacked wherever
`NV_RTX_VIDEO_SDK` points. Build `native\rtxvsr\build.bat` once. It only works when frames are decoded on the
GPU (the default for Remote Play).
The overlay names the scaler in use, and the GPU time per frame is printed on exit.
</details>
<details>
<summary><b>The scheduler: repeats, hitches and scene cuts</b></summary>
A 30 fps game in a 60 Hz stream arrives as `A A B B C C`. On the tick a new frame arrives we show
`mid(prev, new)`; on its repeat tick we show the real frame:
```
input : A A B B C C
output: A A mid(A,B) B mid(B,C) C
```
At 60 Hz the added delay is one tick (about 16.7 ms) plus processing, not a full 30 fps frame. At 90 and 120 Hz
two or three frames are drawn between each pair. The scheduler also handles hitches (`A A A B`), stretches of
real 60 fps content (passed through one tick late) and scene cuts (held instead of ghosting two shots together;
a cut must be a sudden jump in frame difference, not just a large one, so fast camera motion isn't mistaken for a
cut). See `framegen/cadence.py`.
A file of about 30 fps is fed frame for frame as a 60 Hz stream with repeats; a file of about 60 fps has its odd
frames dropped and kept as ground truth for `--score`. Test mode does the same to a live 60 fps Remote Play stream
(`ChiakiSource(test=TestMode(True))`, switchable mid-stream from the menu's Simulate a 30 fps game), and scoring turns on with it.
Duplicate detection compares 16×16 block means: noise averages out, but a small moving object still trips the
maximum. Over the Remote Play stream, repeats are recognised by their size before decoding.
`framegen/fastrife.py` is a restructured RIFE forward pass (same maths, verified to about 60 dB against the
reference) that cut 1080p interpolation from about 16 ms to about 9 ms: one warp per direction instead of two,
inputs downsampled before concatenation, fp32 copies made once per frame, NHWC convolutions. All per-frame GPU
work is captured as CUDA graphs, and TensorRT engines are built once per resolution.
</details>
<details>
<summary><b>Results (RTX 4070 Ti SUPER, 1080p, RIFE 4.22.lite)</b></summary>
Live over Remote Play at 90 fps, in test mode (a 60 fps game played as 30): 35.6 ms (p50) from a compressed frame
reaching the frame tap to the buffer swap that puts it on screen, and 99% of in-between frames on time. 22.2 ms of
that is the hold any 3× interpolator needs. Not included: the PS5's encoding, the network, chiaki-ng's own receiving
and the display. A native 30 fps game over Remote Play hasn't been measured yet.
Quality: native 60 fps game recordings → keep the even frames (the "30 fps game") → interpolate → compare
with the real odd frames. 3% random hitches injected. PyTorch fp16.
| Clip | RIFE | 50/50 blend | repeat (what the PS5 shows) |
|---|---|---|---|
| Skate (third person, city) | **36.2 dB** | 31.0 dB | 28.9 dB |
| Deadlock (fast combat, effects) | **25.8 dB** | 23.2 dB | 21.1 dB |
Duplicate detection: 100% correct on both clips (2,444 ticks, with hitches). The worst frames are moments when
the camera passes through geometry and the in-between frame shows content in neither neighbour. The 4.25 and
4.26 models score within ±0.2 dB but cost about 0.8 ms more; half-resolution flow (`--scale 0.5`) saves about
3 ms but costs 1.5–2 dB.
Timing from a recorded clip, not a live stream, paced at 60 Hz with the OpenGL window (20 s, 1,202 ticks). At
60 Hz a real frame is held for one tick (16.7 ms) rather than two, so this is lower than the live 90 fps figure:
| | p50 | p99 | max |
|---|---|---|---|
| interpolation tick (upload → RIFE → download) | 12.2 ms | 12.7 ms | 12.8 ms |
| repeat tick | 1.2 ms | 1.6 ms | 9.7 ms |
| present (texture upload + blit) | 2.6 ms | 3.1 ms | 18.5 ms |
| **real frame arrival → presented** | **20.8 ms** | 21.8 ms | 22.8 ms |
| same, interpolation off (passthrough) | about 7 ms | | |
2 of 1,202 ticks exceeded the 16.7 ms budget; no backlog built up.
</details>
<details>
<summary><b>Known limits</b></summary>
- **Capture cards are Experimental.** The code is there (`--capture`), but it hasn't been tested with a real
card. On a PS5, turn off HDCP while you use the card (Settings → System → HDMI) and keep it at 60 Hz, not 120 Hz.
- **Window capture is Experimental.** Not tested with a real app. The app's sound comes ahead of the smooth
picture and its window has to stay visible. In Windows HDR mode, on a rotated monitor or without an NVIDIA card,
frames go through the CPU instead (a few ms more).
- **4K** input doesn't fit in real time, even with TensorRT.
- **90/120 Hz to a file** (`--out`) isn't supported; those rates are window-only.
- **Soft scene cuts** between two dark shots can occasionally slip past the cut detector and show one blended frame.
- **Packaging**: the installer is unsigned ([SmartScreen warns](../README.md#smartscreen)) and
about 140 MB, because chiaki-ng is embedded. The launcher updates itself from GitHub releases.
- In a window, Standard presentation goes through the Windows compositor, which adds about 12 ms. Fullscreen (`f`)
avoids it, and so does Window presentation: Low delay (Experimental), in a window too.
</details>
## Features in detail
- **Smoother, not faster.** The extra frames are generated: motion gets smoother, but the game still responds like
30 fps, and a little later than without SmoovPlay. Great for driving, exploring and story missions; not for
competitive online play.
- **About 36 ms at 90 fps** (about 20 ms at 60 fps). That's how long a frame spends in SmoovPlay, from arriving to
being on screen, on top of Remote Play's own delay.
About 22 ms of it is a wait every frame generator has: each real frame is held back while the two in-between
frames before it are shown. When the graphics card falls behind for a moment, SmoovPlay drops to 60 fps rather
than add delay.
- **1080p and SDR.** Remote Play arrives at 1080p, so the picture is a little softer than HDMI straight from the
console. Turn HDR off in chiaki-ng's stream settings.
- **Some wobble.** HUD text over fast motion, very fast camera turns and thin objects crossing each other can wobble
a little. Press **I** in the video window to compare with frame generation off.
- **Sound and picture stay in step.** chiaki-ng plays the sound, and SmoovPlay tells it to hold the sound back
by as long as the picture spends in SmoovPlay, measured as you play (**Sound in sync**, on by default).
- **Delay test:** press **L** in the video window, standing still where Options opens a menu. chiaki-ng presses
Options six times and SmoovPlay times each answer, then shows the PS5 and Remote Play's part, its own part and
the two together.
- **Instant replay** (Settings, **Instant replay**: off until you pick a length, 30 seconds to 5 minutes) keeps
the last stretch of what you played. Press **R** in the video window (or **Ctrl+Alt+R** from anywhere) to save
it to your Videos folder, in SmoovPlay, as an MP4 at the frame rate you see, with the game's own sound (PS5
Remote Play and capture cards; window capture has none). Saving takes a second or two. **B** (**Ctrl+Alt+B**)
saves a **before & after** video instead: the game's own frames next to SmoovPlay's, split down the middle or
side by side, made in the background in about as long as the clip. The video encoder on your graphics card does
the recording, apart from the AI; a 1-minute replay at 1080p and 90 fps keeps about 310 MB in memory. Turning it
on during play pauses the picture for about 0.2 s once, while the encoders start.
- **Looks** (the launcher's **Looks** page; off until you use one) put a grade on the picture. A look is a stack of
effects applied top to bottom, like the nodes of a color grading app, each with its own amount: color, color
wheels, split tone, black & white, LUTs (`.cube` files), bloom, halation, blur, clarity, chromatic aberration,
sharpening, film grain, vignette, scanlines, letterbox and color-blind assist. SmoovPlay comes with 14 (Cinematic,
Film, Vivid, Noir, Golden hour, Neon night, Retro VHS, Bleach bypass, Dreamy, Arctic, Sepia and three for color
blindness). Try any change on one of them, and **Save as mine** keeps it as a look of your own (**Reset** puts
SmoovPlay's back). The page draws the look on sample screenshots from Grand Theft
Auto VI and five other games as you change it (hold the picture to see it without the look, and the arrows go to
the next game). While you play, it shows your changes on the video as you make them, and in the video window **K** turns the look on and off and **J** goes to the next one (**Shift+J**
back). **Copy code** gives a short code (`SPL1-`, about 35 to 60 characters) that rebuilds the look on
anyone's SmoovPlay, through **Paste a code**. A look takes about 0.02 to 0.35 ms of graphics card time a frame at
1440p. Saved clips stay clean unless **Looks in clips** is on (Settings, Instant replay); then only SmoovPlay's
half of a before & after video gets the look.
- **Measure the whole delay yourself** with a phone's 240 fps slow motion and `scripts/latency_video.py`: film
the controller and screen (`press`: button to screen), or the PS5's own HDMI picture beside SmoovPlay's
(`side`: what Remote Play and SmoovPlay add). The script's help says how to film it.
- **60 fps games pass through unchanged.** There are no gaps to fill. To see what SmoovPlay would do with one
anyway, use [test mode](../README.md#only-have-60-fps-games-use-test-mode).
- **Games between 40 and 60 fps** (unlocked performance modes) send their frames unevenly over a 60 Hz stream, so
they stutter. **Even out 40-60 fps** (on by default, Experimental) times each frame and draws evenly spaced ones
from them, for about one frame (17 ms) more delay. Tested with real footage played as 43 and 47 fps games, not yet
with a real one.
- **One frame generator at a time.** Leave NVIDIA Smooth Motion, AMD Fluid Motion Frames and Lossless Scaling off
for SmoovPlay and chiaki-ng: on top of SmoovPlay they'd make frames out of its generated ones (more wobble) and
add delay. Your other games aren't affected.
+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1024 1024"><title>SmoovPlay</title><defs><linearGradient id="g" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#FFBD24"/><stop offset="0.5" stop-color="#FC930B"/><stop offset="1" stop-color="#FC5F03"/></linearGradient></defs><rect width="1024" height="1024" rx="228" fill="url(#g)"/><g transform="translate(92.0 229.5) scale(0.8400)"><path fill="#FFB02E" d="M490.7 672.1C487.8 671.6 483.5 669.6 480.4 667.2C474.1 662.4 470.4 654.8 470.4 646.6C470.4 643.3 471.0 640.1 473.2 630.9C476.8 615.4 477.4 612.8 481.2 595.6C482.3 590.7 484.2 582.2 485.5 576.6C486.7 571.1 488.1 564.8 488.5 562.8C488.9 560.8 489.7 557.2 490.2 554.9C490.8 552.6 491.4 549.8 491.6 548.7C491.9 547.6 492.3 545.6 492.7 544.3C494.0 538.4 494.9 534.0 495.9 529.2C496.2 527.2 497.0 523.4 497.6 520.8C498.5 516.5 499.1 513.5 500.6 506.0C500.9 504.5 501.3 502.4 501.6 501.3C502.1 499.0 508.4 467.9 509.1 464.3C509.3 462.9 509.7 460.9 509.9 459.8C510.1 458.7 510.8 455.2 511.4 451.9C512.0 448.7 512.7 445.1 512.9 444.0C513.1 442.9 513.7 439.8 514.1 437.1C514.5 434.4 515.1 430.9 515.4 429.4C516.1 426.1 516.6 423.2 517.3 419.1C517.7 417.3 518.1 414.9 518.4 413.6C518.6 412.4 519.1 409.2 519.6 406.5C520.0 403.8 520.7 400.0 521.0 398.1C521.4 396.2 522.0 393.2 522.3 391.4C522.6 389.6 523.4 385.0 524.1 381.0C524.7 377.1 525.5 372.7 525.8 371.3C526.7 366.4 527.2 363.5 528.4 356.1C529.8 347.9 531.4 339.0 532.1 335.6C532.4 334.4 533.0 331.3 533.4 328.7C534.3 323.6 536.3 313.1 537.1 309.2C537.4 307.8 538.0 304.9 538.4 302.8C538.8 300.6 539.4 297.8 539.6 296.5C540.7 290.5 541.0 289.0 542.3 282.8C545.6 266.0 548.7 251.0 551.0 240.0C551.6 237.3 552.2 234.2 552.4 233.1C552.7 232.0 553.8 227.0 554.9 222.0C557.2 211.8 557.5 210.6 558.3 206.7C559.1 203.2 559.3 202.2 561.8 191.4C563.0 186.4 564.1 181.5 564.3 180.5C564.5 179.6 565.2 176.2 565.9 173.1C566.7 170.0 567.7 165.4 568.3 163.0C571.3 149.6 575.5 139.5 582.0 129.8C593.2 113.1 614.5 98.9 635.4 94.2C646.0 91.8 641.6 91.9 740.3 91.9C839.7 91.9 836.3 91.8 851.9 94.4C861.3 95.9 864.7 96.7 872.9 99.1C886.8 103.0 893.2 105.5 906.4 112.0C946.6 131.8 976.8 167.0 990.4 210.4C995.3 225.8 997.2 236.0 998.6 253.4C1000.0 270.2 999.5 289.6 997.4 307.4C996.5 314.5 992.9 334.0 991.5 339.1C991.2 340.0 990.3 343.6 989.3 347.0C986.9 355.8 984.0 364.2 979.8 374.1C962.3 415.3 934.9 446.4 896.2 468.9C872.6 482.6 846.9 491.9 820.6 496.1C803.2 498.8 797.5 499.0 722.1 499.1C685.9 499.1 656.2 499.3 656.0 499.5C655.7 499.8 654.8 503.4 653.2 511.4C652.9 512.7 652.3 515.8 651.7 518.3C651.1 520.9 650.5 524.0 650.2 525.3C650.0 526.5 649.3 529.6 648.7 532.2C648.2 534.8 647.5 537.9 647.3 539.1C647.0 540.3 646.1 544.5 645.3 548.5C644.4 552.4 643.5 556.5 643.3 557.6C643.1 558.7 642.0 563.9 640.9 569.2C638.0 582.6 638.0 582.9 637.1 586.7C636.7 588.6 635.8 592.8 635.1 595.9C627.3 633.4 627.0 634.3 623.7 641.1C618.2 651.9 608.7 661.9 599.2 666.4C594.0 668.9 585.9 671.4 581.4 672.0C577.5 672.4 493.3 672.5 490.7 672.1Z"/><path fill="#1A1206" fill-rule="evenodd" d="M490.7 672.1C487.8 671.6 483.5 669.6 480.4 667.2C474.1 662.4 470.4 654.8 470.4 646.6C470.4 643.3 471.0 640.1 473.2 630.9C476.8 615.4 477.4 612.8 481.2 595.6C482.3 590.7 484.2 582.2 485.5 576.6C486.7 571.1 488.1 564.8 488.5 562.8C488.9 560.8 489.7 557.2 490.2 554.9C490.8 552.6 491.4 549.8 491.6 548.7C491.9 547.6 492.3 545.6 492.7 544.3C494.0 538.4 494.9 534.0 495.9 529.2C496.2 527.2 497.0 523.4 497.6 520.8C498.5 516.5 499.1 513.5 500.6 506.0C500.9 504.5 501.3 502.4 501.6 501.3C502.1 499.0 508.4 467.9 509.1 464.3C509.3 462.9 509.7 460.9 509.9 459.8C510.1 458.7 510.8 455.2 511.4 451.9C512.0 448.7 512.7 445.1 512.9 444.0C513.1 442.9 513.7 439.8 514.1 437.1C514.5 434.4 515.1 430.9 515.4 429.4C516.1 426.1 516.6 423.2 517.3 419.1C517.7 417.3 518.1 414.9 518.4 413.6C518.6 412.4 519.1 409.2 519.6 406.5C520.0 403.8 520.7 400.0 521.0 398.1C521.4 396.2 522.0 393.2 522.3 391.4C522.6 389.6 523.4 385.0 524.1 381.0C524.7 377.1 525.5 372.7 525.8 371.3C526.7 366.4 527.2 363.5 528.4 356.1C529.8 347.9 531.4 339.0 532.1 335.6C532.4 334.4 533.0 331.3 533.4 328.7C534.3 323.6 536.3 313.1 537.1 309.2C537.4 307.8 538.0 304.9 538.4 302.8C538.8 300.6 539.4 297.8 539.6 296.5C540.7 290.5 541.0 289.0 542.3 282.8C545.6 266.0 548.7 251.0 551.0 240.0C551.6 237.3 552.2 234.2 552.4 233.1C552.7 232.0 553.8 227.0 554.9 222.0C557.2 211.8 557.5 210.6 558.3 206.7C559.1 203.2 559.3 202.2 561.8 191.4C563.0 186.4 564.1 181.5 564.3 180.5C564.5 179.6 565.2 176.2 565.9 173.1C566.7 170.0 567.7 165.4 568.3 163.0C571.3 149.6 575.5 139.5 582.0 129.8C593.2 113.1 614.5 98.9 635.4 94.2C646.0 91.8 641.6 91.9 740.3 91.9C839.7 91.9 836.3 91.8 851.9 94.4C861.3 95.9 864.7 96.7 872.9 99.1C886.8 103.0 893.2 105.5 906.4 112.0C946.6 131.8 976.8 167.0 990.4 210.4C995.3 225.8 997.2 236.0 998.6 253.4C1000.0 270.2 999.5 289.6 997.4 307.4C996.5 314.5 992.9 334.0 991.5 339.1C991.2 340.0 990.3 343.6 989.3 347.0C986.9 355.8 984.0 364.2 979.8 374.1C962.3 415.3 934.9 446.4 896.2 468.9C872.6 482.6 846.9 491.9 8Line truncated

After

Width:  |  Height:  |  Size: 8.4 KiB

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1024 1024"><title>SmoovPlay</title><defs><linearGradient id="g" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#FFBD24"/><stop offset="0.5" stop-color="#FC930B"/><stop offset="1" stop-color="#FC5F03"/></linearGradient></defs><rect width="1024" height="1024" rx="228" fill="url(#g)"/><g transform="translate(72.0 243.4) scale(0.8800)"><path fill="#FFB02E" d="M532.3 610.2C527.0 609.9 525.2 609.2 522.2 606.5C520.1 604.5 518.3 600.8 518.3 598.3C518.3 597.1 519.1 593.2 521.5 582.6C522.1 579.6 524.6 567.7 525.4 563.5C525.8 561.4 527.1 554.7 528.4 548.5C531.8 532.0 532.5 528.5 533.5 523.4C533.9 520.8 536.4 508.5 539.0 496.0C541.5 483.4 544.5 468.9 545.5 463.7C547.6 452.9 551.3 434.8 554.9 417.2C558.8 397.9 560.0 391.8 561.8 382.4C562.7 377.6 564.3 369.8 565.3 365.1C567.4 355.3 572.3 330.9 575.2 315.9C577.2 305.3 578.1 301.4 581.3 285.7C582.3 280.9 584.0 272.7 585.1 267.5C586.1 262.3 587.7 254.8 588.5 250.9C589.4 247.0 590.8 240.1 591.7 235.7C594.5 221.6 597.5 207.5 598.4 203.5C598.9 201.3 600.4 194.5 601.7 188.3C606.5 164.9 608.6 156.6 611.4 149.3C616.7 135.6 625.7 123.6 637.1 114.7C646.4 107.6 658.4 102.6 671.2 100.5C677.4 99.5 842.6 99.5 851.4 100.5C865.9 102.2 878.7 104.8 886.8 107.7C888.2 108.2 890.5 109.0 891.9 109.5C902.4 113.0 920.4 121.6 928.0 126.7C940.2 135.1 943.8 137.9 951.1 145.1C972.4 166.2 986.8 192.2 993.9 222.3C998.4 241.6 1000.0 256.7 999.5 275.1C998.8 302.1 993.7 325.3 982.8 351.7C979.1 360.9 971.1 375.1 963.8 385.4C951.6 402.8 940.4 414.8 923.5 428.5C913.8 436.3 895.7 447.2 882.7 453.0C874.5 456.7 860.9 461.6 854.8 463.0C842.3 466.0 841.0 466.2 835.9 466.9C833.9 467.2 830.6 467.7 828.5 468.0C825.9 468.3 805.2 468.5 756.9 468.6C719.5 468.7 688.5 468.9 688.0 469.0C687.2 469.2 686.9 470.0 686.0 473.5C685.5 475.9 684.1 481.6 683.0 486.3C681.8 491.0 680.5 496.8 680.0 499.2C679.0 503.5 677.1 511.8 676.3 514.9C676.1 515.7 675.7 517.4 675.4 518.5C675.1 519.7 673.3 527.4 671.3 535.6C665.6 558.8 664.3 564.5 663.3 568.9C662.4 573.5 660.0 579.5 657.4 583.7C655.3 587.2 649.4 594.6 646.7 597.1C640.7 602.8 631.0 607.8 622.4 609.6C618.8 610.3 615.0 610.4 577.7 610.5C555.3 610.5 534.9 610.4 532.3 610.2Z"/><path fill="#1A1206" fill-rule="evenodd" d="M532.3 610.2C527.0 609.9 525.2 609.2 522.2 606.5C520.1 604.5 518.3 600.8 518.3 598.3C518.3 597.1 519.1 593.2 521.5 582.6C522.1 579.6 524.6 567.7 525.4 563.5C525.8 561.4 527.1 554.7 528.4 548.5C531.8 532.0 532.5 528.5 533.5 523.4C533.9 520.8 536.4 508.5 539.0 496.0C541.5 483.4 544.5 468.9 545.5 463.7C547.6 452.9 551.3 434.8 554.9 417.2C558.8 397.9 560.0 391.8 561.8 382.4C562.7 377.6 564.3 369.8 565.3 365.1C567.4 355.3 572.3 330.9 575.2 315.9C577.2 305.3 578.1 301.4 581.3 285.7C582.3 280.9 584.0 272.7 585.1 267.5C586.1 262.3 587.7 254.8 588.5 250.9C589.4 247.0 590.8 240.1 591.7 235.7C594.5 221.6 597.5 207.5 598.4 203.5C598.9 201.3 600.4 194.5 601.7 188.3C606.5 164.9 608.6 156.6 611.4 149.3C616.7 135.6 625.7 123.6 637.1 114.7C646.4 107.6 658.4 102.6 671.2 100.5C677.4 99.5 842.6 99.5 851.4 100.5C865.9 102.2 878.7 104.8 886.8 107.7C888.2 108.2 890.5 109.0 891.9 109.5C902.4 113.0 920.4 121.6 928.0 126.7C940.2 135.1 943.8 137.9 951.1 145.1C972.4 166.2 986.8 192.2 993.9 222.3C998.4 241.6 1000.0 256.7 999.5 275.1C998.8 302.1 993.7 325.3 982.8 351.7C979.1 360.9 971.1 375.1 963.8 385.4C951.6 402.8 940.4 414.8 923.5 428.5C913.8 436.3 895.7 447.2 882.7 453.0C874.5 456.7 860.9 461.6 854.8 463.0C842.3 466.0 841.0 466.2 835.9 466.9C833.9 467.2 830.6 467.7 828.5 468.0C825.9 468.3 805.2 468.5 756.9 468.6C719.5 468.7 688.5 468.9 688.0 469.0C687.2 469.2 686.9 470.0 686.0 473.5C685.5 475.9 684.1 481.6 683.0 486.3C681.8 491.0 680.5 496.8 680.0 499.2C679.0 503.5 677.1 511.8 676.3 514.9C676.1 515.7 675.7 517.4 675.4 518.5C675.1 519.7 673.3 527.4 671.3 535.6C665.6 558.8 664.3 564.5 663.3 568.9C662.4 573.5 660.0 579.5 657.4 583.7C655.3 587.2 649.4 594.6 646.7 597.1C640.7 602.8 631.0 607.8 622.4 609.6C618.8 610.3 615.0 610.4 577.7 610.5C555.3 610.5 534.9 610.4 532.3 610.2ZM68.0 527.0C61.5 524.7 58.7 517.5 61.5 510.1C65.2 500.3 74.2 481.3 78.3 474.5C79.5 472.5 81.5 469.2 82.8 467.2C87.0 460.3 98.3 445.7 104.4 439.4C116.1 427.3 127.4 419.0 142.6 411.3C153.1 406.1 162.9 402.9 177.2 400.3L184.1 399.0L289.8 398.9C408.7 398.8 398.7 399.1 406.5 395.2C414.1 391.4 420.4 383.8 422.0 376.4C422.3 375.2 422.5 372.5 422.5 370.4C422.6 358.3 415.2 348.8 402.4 344.4L397.8 342.8L339.6 342.7C307.5 342.7 279.2 342.5 276.7 342.4C265.7 341.8 248.4 337.4 237.3 332.3C228.1 328.2 216.6 321.5 208.7 315.7C202.3 311.1 192.8 303.1 189.8 299.9C175.5 284.6 168.3 274.6 161.2 260.4C155.6 249.2 152.7 241.8 149.5 230.4C148.4 226.6 146.6 217.4 145.8 211.3C144.7 203.2 144.7 183.9 145.8 175.6C147.8 161.1 149.0 156.1 154.2 141.3C157.4 132.1 163.3 119.3 169.0 109.3C177.0 95.3 190.7 77.8 204.2 64.5C218.5 50.4 231.2 40.6 249.5 29.4C258.1 24.2 274.4 16.5 285.3 12.4C300.7 6.6 322.0 1.8 337.0 0.8C342.0 0.5 387.2 0.3 478.2 0.3C628.3 0.3 615.2 0.0 618.9 3.7C621.4 6.2 622.6 9.5 6Line truncated

After

Width:  |  Height:  |  Size: 11 KiB

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="-60 -60 4494 1120"><title>SmoovPlay</title><defs><linearGradient id="g" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#FFBD24"/><stop offset="0.5" stop-color="#FC930B"/><stop offset="1" stop-color="#FC5F03"/></linearGradient></defs><g transform="scale(0.97656)"><rect width="1024" height="1024" rx="228" fill="url(#g)"/><g transform="translate(72.0 243.4) scale(0.8800)"><path fill="#FFB02E" d="M532.3 610.2C527.0 609.9 525.2 609.2 522.2 606.5C520.1 604.5 518.3 600.8 518.3 598.3C518.3 597.1 519.1 593.2 521.5 582.6C522.1 579.6 524.6 567.7 525.4 563.5C525.8 561.4 527.1 554.7 528.4 548.5C531.8 532.0 532.5 528.5 533.5 523.4C533.9 520.8 536.4 508.5 539.0 496.0C541.5 483.4 544.5 468.9 545.5 463.7C547.6 452.9 551.3 434.8 554.9 417.2C558.8 397.9 560.0 391.8 561.8 382.4C562.7 377.6 564.3 369.8 565.3 365.1C567.4 355.3 572.3 330.9 575.2 315.9C577.2 305.3 578.1 301.4 581.3 285.7C582.3 280.9 584.0 272.7 585.1 267.5C586.1 262.3 587.7 254.8 588.5 250.9C589.4 247.0 590.8 240.1 591.7 235.7C594.5 221.6 597.5 207.5 598.4 203.5C598.9 201.3 600.4 194.5 601.7 188.3C606.5 164.9 608.6 156.6 611.4 149.3C616.7 135.6 625.7 123.6 637.1 114.7C646.4 107.6 658.4 102.6 671.2 100.5C677.4 99.5 842.6 99.5 851.4 100.5C865.9 102.2 878.7 104.8 886.8 107.7C888.2 108.2 890.5 109.0 891.9 109.5C902.4 113.0 920.4 121.6 928.0 126.7C940.2 135.1 943.8 137.9 951.1 145.1C972.4 166.2 986.8 192.2 993.9 222.3C998.4 241.6 1000.0 256.7 999.5 275.1C998.8 302.1 993.7 325.3 982.8 351.7C979.1 360.9 971.1 375.1 963.8 385.4C951.6 402.8 940.4 414.8 923.5 428.5C913.8 436.3 895.7 447.2 882.7 453.0C874.5 456.7 860.9 461.6 854.8 463.0C842.3 466.0 841.0 466.2 835.9 466.9C833.9 467.2 830.6 467.7 828.5 468.0C825.9 468.3 805.2 468.5 756.9 468.6C719.5 468.7 688.5 468.9 688.0 469.0C687.2 469.2 686.9 470.0 686.0 473.5C685.5 475.9 684.1 481.6 683.0 486.3C681.8 491.0 680.5 496.8 680.0 499.2C679.0 503.5 677.1 511.8 676.3 514.9C676.1 515.7 675.7 517.4 675.4 518.5C675.1 519.7 673.3 527.4 671.3 535.6C665.6 558.8 664.3 564.5 663.3 568.9C662.4 573.5 660.0 579.5 657.4 583.7C655.3 587.2 649.4 594.6 646.7 597.1C640.7 602.8 631.0 607.8 622.4 609.6C618.8 610.3 615.0 610.4 577.7 610.5C555.3 610.5 534.9 610.4 532.3 610.2Z"/><path fill="#1A1206" fill-rule="evenodd" d="M532.3 610.2C527.0 609.9 525.2 609.2 522.2 606.5C520.1 604.5 518.3 600.8 518.3 598.3C518.3 597.1 519.1 593.2 521.5 582.6C522.1 579.6 524.6 567.7 525.4 563.5C525.8 561.4 527.1 554.7 528.4 548.5C531.8 532.0 532.5 528.5 533.5 523.4C533.9 520.8 536.4 508.5 539.0 496.0C541.5 483.4 544.5 468.9 545.5 463.7C547.6 452.9 551.3 434.8 554.9 417.2C558.8 397.9 560.0 391.8 561.8 382.4C562.7 377.6 564.3 369.8 565.3 365.1C567.4 355.3 572.3 330.9 575.2 315.9C577.2 305.3 578.1 301.4 581.3 285.7C582.3 280.9 584.0 272.7 585.1 267.5C586.1 262.3 587.7 254.8 588.5 250.9C589.4 247.0 590.8 240.1 591.7 235.7C594.5 221.6 597.5 207.5 598.4 203.5C598.9 201.3 600.4 194.5 601.7 188.3C606.5 164.9 608.6 156.6 611.4 149.3C616.7 135.6 625.7 123.6 637.1 114.7C646.4 107.6 658.4 102.6 671.2 100.5C677.4 99.5 842.6 99.5 851.4 100.5C865.9 102.2 878.7 104.8 886.8 107.7C888.2 108.2 890.5 109.0 891.9 109.5C902.4 113.0 920.4 121.6 928.0 126.7C940.2 135.1 943.8 137.9 951.1 145.1C972.4 166.2 986.8 192.2 993.9 222.3C998.4 241.6 1000.0 256.7 999.5 275.1C998.8 302.1 993.7 325.3 982.8 351.7C979.1 360.9 971.1 375.1 963.8 385.4C951.6 402.8 940.4 414.8 923.5 428.5C913.8 436.3 895.7 447.2 882.7 453.0C874.5 456.7 860.9 461.6 854.8 463.0C842.3 466.0 841.0 466.2 835.9 466.9C833.9 467.2 830.6 467.7 828.5 468.0C825.9 468.3 805.2 468.5 756.9 468.6C719.5 468.7 688.5 468.9 688.0 469.0C687.2 469.2 686.9 470.0 686.0 473.5C685.5 475.9 684.1 481.6 683.0 486.3C681.8 491.0 680.5 496.8 680.0 499.2C679.0 503.5 677.1 511.8 676.3 514.9C676.1 515.7 675.7 517.4 675.4 518.5C675.1 519.7 673.3 527.4 671.3 535.6C665.6 558.8 664.3 564.5 663.3 568.9C662.4 573.5 660.0 579.5 657.4 583.7C655.3 587.2 649.4 594.6 646.7 597.1C640.7 602.8 631.0 607.8 622.4 609.6C618.8 610.3 615.0 610.4 577.7 610.5C555.3 610.5 534.9 610.4 532.3 610.2ZM68.0 527.0C61.5 524.7 58.7 517.5 61.5 510.1C65.2 500.3 74.2 481.3 78.3 474.5C79.5 472.5 81.5 469.2 82.8 467.2C87.0 460.3 98.3 445.7 104.4 439.4C116.1 427.3 127.4 419.0 142.6 411.3C153.1 406.1 162.9 402.9 177.2 400.3L184.1 399.0L289.8 398.9C408.7 398.8 398.7 399.1 406.5 395.2C414.1 391.4 420.4 383.8 422.0 376.4C422.3 375.2 422.5 372.5 422.5 370.4C422.6 358.3 415.2 348.8 402.4 344.4L397.8 342.8L339.6 342.7C307.5 342.7 279.2 342.5 276.7 342.4C265.7 341.8 248.4 337.4 237.3 332.3C228.1 328.2 216.6 321.5 208.7 315.7C202.3 311.1 192.8 303.1 189.8 299.9C175.5 284.6 168.3 274.6 161.2 260.4C155.6 249.2 152.7 241.8 149.5 230.4C148.4 226.6 146.6 217.4 145.8 211.3C144.7 203.2 144.7 183.9 145.8 175.6C147.8 161.1 149.0 156.1 154.2 141.3C157.4 132.1 163.3 119.3 169.0 109.3C177.0 95.3 190.7 77.8 204.2 64.5C218.5 50.4 231.2 40.6 249.5 29.4C258.1 24.2 274.4 16.5 285.3 12.4C300.7 6.6 322.0 1.8 337.0 0.8C342.0 0.5 387.2 0.3 478.2 0.3C628.3 0.3 615.2 0Line truncated

After

Width:  |  Height:  |  Size: 23 KiB

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="-60 -60 4494 1120"><title>SmoovPlay</title><defs><linearGradient id="g" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#FFBD24"/><stop offset="0.5" stop-color="#FC930B"/><stop offset="1" stop-color="#FC5F03"/></linearGradient></defs><g transform="scale(0.97656)"><rect width="1024" height="1024" rx="228" fill="url(#g)"/><g transform="translate(72.0 243.4) scale(0.8800)"><path fill="#FFB02E" d="M532.3 610.2C527.0 609.9 525.2 609.2 522.2 606.5C520.1 604.5 518.3 600.8 518.3 598.3C518.3 597.1 519.1 593.2 521.5 582.6C522.1 579.6 524.6 567.7 525.4 563.5C525.8 561.4 527.1 554.7 528.4 548.5C531.8 532.0 532.5 528.5 533.5 523.4C533.9 520.8 536.4 508.5 539.0 496.0C541.5 483.4 544.5 468.9 545.5 463.7C547.6 452.9 551.3 434.8 554.9 417.2C558.8 397.9 560.0 391.8 561.8 382.4C562.7 377.6 564.3 369.8 565.3 365.1C567.4 355.3 572.3 330.9 575.2 315.9C577.2 305.3 578.1 301.4 581.3 285.7C582.3 280.9 584.0 272.7 585.1 267.5C586.1 262.3 587.7 254.8 588.5 250.9C589.4 247.0 590.8 240.1 591.7 235.7C594.5 221.6 597.5 207.5 598.4 203.5C598.9 201.3 600.4 194.5 601.7 188.3C606.5 164.9 608.6 156.6 611.4 149.3C616.7 135.6 625.7 123.6 637.1 114.7C646.4 107.6 658.4 102.6 671.2 100.5C677.4 99.5 842.6 99.5 851.4 100.5C865.9 102.2 878.7 104.8 886.8 107.7C888.2 108.2 890.5 109.0 891.9 109.5C902.4 113.0 920.4 121.6 928.0 126.7C940.2 135.1 943.8 137.9 951.1 145.1C972.4 166.2 986.8 192.2 993.9 222.3C998.4 241.6 1000.0 256.7 999.5 275.1C998.8 302.1 993.7 325.3 982.8 351.7C979.1 360.9 971.1 375.1 963.8 385.4C951.6 402.8 940.4 414.8 923.5 428.5C913.8 436.3 895.7 447.2 882.7 453.0C874.5 456.7 860.9 461.6 854.8 463.0C842.3 466.0 841.0 466.2 835.9 466.9C833.9 467.2 830.6 467.7 828.5 468.0C825.9 468.3 805.2 468.5 756.9 468.6C719.5 468.7 688.5 468.9 688.0 469.0C687.2 469.2 686.9 470.0 686.0 473.5C685.5 475.9 684.1 481.6 683.0 486.3C681.8 491.0 680.5 496.8 680.0 499.2C679.0 503.5 677.1 511.8 676.3 514.9C676.1 515.7 675.7 517.4 675.4 518.5C675.1 519.7 673.3 527.4 671.3 535.6C665.6 558.8 664.3 564.5 663.3 568.9C662.4 573.5 660.0 579.5 657.4 583.7C655.3 587.2 649.4 594.6 646.7 597.1C640.7 602.8 631.0 607.8 622.4 609.6C618.8 610.3 615.0 610.4 577.7 610.5C555.3 610.5 534.9 610.4 532.3 610.2Z"/><path fill="#1A1206" fill-rule="evenodd" d="M532.3 610.2C527.0 609.9 525.2 609.2 522.2 606.5C520.1 604.5 518.3 600.8 518.3 598.3C518.3 597.1 519.1 593.2 521.5 582.6C522.1 579.6 524.6 567.7 525.4 563.5C525.8 561.4 527.1 554.7 528.4 548.5C531.8 532.0 532.5 528.5 533.5 523.4C533.9 520.8 536.4 508.5 539.0 496.0C541.5 483.4 544.5 468.9 545.5 463.7C547.6 452.9 551.3 434.8 554.9 417.2C558.8 397.9 560.0 391.8 561.8 382.4C562.7 377.6 564.3 369.8 565.3 365.1C567.4 355.3 572.3 330.9 575.2 315.9C577.2 305.3 578.1 301.4 581.3 285.7C582.3 280.9 584.0 272.7 585.1 267.5C586.1 262.3 587.7 254.8 588.5 250.9C589.4 247.0 590.8 240.1 591.7 235.7C594.5 221.6 597.5 207.5 598.4 203.5C598.9 201.3 600.4 194.5 601.7 188.3C606.5 164.9 608.6 156.6 611.4 149.3C616.7 135.6 625.7 123.6 637.1 114.7C646.4 107.6 658.4 102.6 671.2 100.5C677.4 99.5 842.6 99.5 851.4 100.5C865.9 102.2 878.7 104.8 886.8 107.7C888.2 108.2 890.5 109.0 891.9 109.5C902.4 113.0 920.4 121.6 928.0 126.7C940.2 135.1 943.8 137.9 951.1 145.1C972.4 166.2 986.8 192.2 993.9 222.3C998.4 241.6 1000.0 256.7 999.5 275.1C998.8 302.1 993.7 325.3 982.8 351.7C979.1 360.9 971.1 375.1 963.8 385.4C951.6 402.8 940.4 414.8 923.5 428.5C913.8 436.3 895.7 447.2 882.7 453.0C874.5 456.7 860.9 461.6 854.8 463.0C842.3 466.0 841.0 466.2 835.9 466.9C833.9 467.2 830.6 467.7 828.5 468.0C825.9 468.3 805.2 468.5 756.9 468.6C719.5 468.7 688.5 468.9 688.0 469.0C687.2 469.2 686.9 470.0 686.0 473.5C685.5 475.9 684.1 481.6 683.0 486.3C681.8 491.0 680.5 496.8 680.0 499.2C679.0 503.5 677.1 511.8 676.3 514.9C676.1 515.7 675.7 517.4 675.4 518.5C675.1 519.7 673.3 527.4 671.3 535.6C665.6 558.8 664.3 564.5 663.3 568.9C662.4 573.5 660.0 579.5 657.4 583.7C655.3 587.2 649.4 594.6 646.7 597.1C640.7 602.8 631.0 607.8 622.4 609.6C618.8 610.3 615.0 610.4 577.7 610.5C555.3 610.5 534.9 610.4 532.3 610.2ZM68.0 527.0C61.5 524.7 58.7 517.5 61.5 510.1C65.2 500.3 74.2 481.3 78.3 474.5C79.5 472.5 81.5 469.2 82.8 467.2C87.0 460.3 98.3 445.7 104.4 439.4C116.1 427.3 127.4 419.0 142.6 411.3C153.1 406.1 162.9 402.9 177.2 400.3L184.1 399.0L289.8 398.9C408.7 398.8 398.7 399.1 406.5 395.2C414.1 391.4 420.4 383.8 422.0 376.4C422.3 375.2 422.5 372.5 422.5 370.4C422.6 358.3 415.2 348.8 402.4 344.4L397.8 342.8L339.6 342.7C307.5 342.7 279.2 342.5 276.7 342.4C265.7 341.8 248.4 337.4 237.3 332.3C228.1 328.2 216.6 321.5 208.7 315.7C202.3 311.1 192.8 303.1 189.8 299.9C175.5 284.6 168.3 274.6 161.2 260.4C155.6 249.2 152.7 241.8 149.5 230.4C148.4 226.6 146.6 217.4 145.8 211.3C144.7 203.2 144.7 183.9 145.8 175.6C147.8 161.1 149.0 156.1 154.2 141.3C157.4 132.1 163.3 119.3 169.0 109.3C177.0 95.3 190.7 77.8 204.2 64.5C218.5 50.4 231.2 40.6 249.5 29.4C258.1 24.2 274.4 16.5 285.3 12.4C300.7 6.6 322.0 1.8 337.0 0.8C342.0 0.5 387.2 0.3 478.2 0.3C628.3 0.3 615.2 0Line truncated

After

Width:  |  Height:  |  Size: 23 KiB

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="-24 -24 1048 658"><title>SmoovPlay</title><path fill="#FFFFFF" fill-rule="evenodd" d="M532.3 610.2C527.0 609.9 525.2 609.2 522.2 606.5C520.1 604.5 518.3 600.8 518.3 598.3C518.3 597.1 519.1 593.2 521.5 582.6C522.1 579.6 524.6 567.7 525.4 563.5C525.8 561.4 527.1 554.7 528.4 548.5C531.8 532.0 532.5 528.5 533.5 523.4C533.9 520.8 536.4 508.5 539.0 496.0C541.5 483.4 544.5 468.9 545.5 463.7C547.6 452.9 551.3 434.8 554.9 417.2C558.8 397.9 560.0 391.8 561.8 382.4C562.7 377.6 564.3 369.8 565.3 365.1C567.4 355.3 572.3 330.9 575.2 315.9C577.2 305.3 578.1 301.4 581.3 285.7C582.3 280.9 584.0 272.7 585.1 267.5C586.1 262.3 587.7 254.8 588.5 250.9C589.4 247.0 590.8 240.1 591.7 235.7C594.5 221.6 597.5 207.5 598.4 203.5C598.9 201.3 600.4 194.5 601.7 188.3C606.5 164.9 608.6 156.6 611.4 149.3C616.7 135.6 625.7 123.6 637.1 114.7C646.4 107.6 658.4 102.6 671.2 100.5C677.4 99.5 842.6 99.5 851.4 100.5C865.9 102.2 878.7 104.8 886.8 107.7C888.2 108.2 890.5 109.0 891.9 109.5C902.4 113.0 920.4 121.6 928.0 126.7C940.2 135.1 943.8 137.9 951.1 145.1C972.4 166.2 986.8 192.2 993.9 222.3C998.4 241.6 1000.0 256.7 999.5 275.1C998.8 302.1 993.7 325.3 982.8 351.7C979.1 360.9 971.1 375.1 963.8 385.4C951.6 402.8 940.4 414.8 923.5 428.5C913.8 436.3 895.7 447.2 882.7 453.0C874.5 456.7 860.9 461.6 854.8 463.0C842.3 466.0 841.0 466.2 835.9 466.9C833.9 467.2 830.6 467.7 828.5 468.0C825.9 468.3 805.2 468.5 756.9 468.6C719.5 468.7 688.5 468.9 688.0 469.0C687.2 469.2 686.9 470.0 686.0 473.5C685.5 475.9 684.1 481.6 683.0 486.3C681.8 491.0 680.5 496.8 680.0 499.2C679.0 503.5 677.1 511.8 676.3 514.9C676.1 515.7 675.7 517.4 675.4 518.5C675.1 519.7 673.3 527.4 671.3 535.6C665.6 558.8 664.3 564.5 663.3 568.9C662.4 573.5 660.0 579.5 657.4 583.7C655.3 587.2 649.4 594.6 646.7 597.1C640.7 602.8 631.0 607.8 622.4 609.6C618.8 610.3 615.0 610.4 577.7 610.5C555.3 610.5 534.9 610.4 532.3 610.2ZM68.0 527.0C61.5 524.7 58.7 517.5 61.5 510.1C65.2 500.3 74.2 481.3 78.3 474.5C79.5 472.5 81.5 469.2 82.8 467.2C87.0 460.3 98.3 445.7 104.4 439.4C116.1 427.3 127.4 419.0 142.6 411.3C153.1 406.1 162.9 402.9 177.2 400.3L184.1 399.0L289.8 398.9C408.7 398.8 398.7 399.1 406.5 395.2C414.1 391.4 420.4 383.8 422.0 376.4C422.3 375.2 422.5 372.5 422.5 370.4C422.6 358.3 415.2 348.8 402.4 344.4L397.8 342.8L339.6 342.7C307.5 342.7 279.2 342.5 276.7 342.4C265.7 341.8 248.4 337.4 237.3 332.3C228.1 328.2 216.6 321.5 208.7 315.7C202.3 311.1 192.8 303.1 189.8 299.9C175.5 284.6 168.3 274.6 161.2 260.4C155.6 249.2 152.7 241.8 149.5 230.4C148.4 226.6 146.6 217.4 145.8 211.3C144.7 203.2 144.7 183.9 145.8 175.6C147.8 161.1 149.0 156.1 154.2 141.3C157.4 132.1 163.3 119.3 169.0 109.3C177.0 95.3 190.7 77.8 204.2 64.5C218.5 50.4 231.2 40.6 249.5 29.4C258.1 24.2 274.4 16.5 285.3 12.4C300.7 6.6 322.0 1.8 337.0 0.8C342.0 0.5 387.2 0.3 478.2 0.3C628.3 0.3 615.2 0.0 618.9 3.7C621.4 6.2 622.6 9.5 622.3 13.1C622.1 15.2 620.9 18.4 616.2 28.9C612.9 36.1 609.6 43.6 608.8 45.5C608.0 47.4 605.0 54.0 602.1 60.2C599.3 66.4 595.8 73.9 594.5 76.9C591.7 83.0 587.4 90.8 584.4 95.0C581.1 99.6 574.3 106.9 570.2 110.2C568.1 111.8 564.5 114.2 562.0 115.4C557.9 117.4 557.5 117.5 554.0 117.5C548.6 117.5 545.7 116.0 539.5 109.8C526.1 96.7 511.7 89.6 494.6 87.6C491.0 87.2 320.6 87.2 316.3 87.6C301.1 89.1 283.8 95.4 270.3 104.5C265.0 108.1 254.0 117.2 251.3 120.3C249.8 122.1 247.5 124.8 246.1 126.3C242.7 130.1 237.0 138.8 233.8 145.0C230.8 151.0 227.6 160.2 226.2 167.6C224.0 178.1 225.0 192.6 228.6 203.2C230.4 208.6 234.5 216.8 237.7 221.7C246.9 235.5 261.2 246.1 278.3 251.7C289.6 255.5 282.4 255.2 371.6 255.5C427.7 255.7 452.1 256.0 454.1 256.4C460.3 257.5 466.6 258.9 469.0 259.7C478.6 262.8 482.7 264.5 492.3 269.8C507.4 278.1 521.9 293.1 530.7 309.4C534.4 316.3 539.2 328.2 541.1 335.4C543.8 345.5 545.9 361.1 545.9 371.6C545.9 375.1 544.9 386.7 544.3 390.9C542.5 402.9 541.5 407.3 538.5 417.4C537.4 421.2 535.1 427.7 533.9 430.3C533.5 431.3 532.6 433.6 531.9 435.4C530.4 439.2 524.7 450.0 521.3 455.2C509.5 473.8 495.2 488.6 477.1 501.1C468.2 507.1 455.9 513.7 446.0 517.6C437.3 521.0 423.7 524.7 415.3 525.9C413.3 526.2 410.8 526.7 409.8 527.0C408.5 527.4 362.5 527.5 238.9 527.6C92.6 527.7 69.6 527.6 68.0 527.0ZM713.5 397.0C716.3 396.1 726.7 390.5 739.2 383.1C742.5 381.2 747.1 378.5 749.5 377.1C751.9 375.8 756.6 373.1 759.9 371.1C763.2 369.2 769.6 365.5 774.2 362.8C778.7 360.2 786.4 355.8 791.2 352.9C796.0 350.1 801.4 346.9 803.2 345.9C805.0 344.9 809.0 342.6 812.1 340.8C815.2 339.0 817.9 337.5 818.0 337.5C818.1 337.5 819.7 336.6 821.5 335.5C823.3 334.4 827.5 331.9 830.8 330.0C834.1 328.1 840.1 324.7 844.2 322.3C848.2 320.0 852.5 317.5 853.6 316.9C854.8 316.3 858.1 314.3 861.0 312.6C863.9 310.9 867.8 308.7 869.6 307.7C878.7 302.4 884.0 296.1 885.5 288.6C886.1 285.1 885.8 278.0 884.7 275.1C883.9 272.7 881.1 268.2 879.0 265.9C877.9 264.7 871.3 260.2 855.7 250.2C846.3 244.0 819.0 226.1 794.7 210.1C743.4 176.1 747.4 178.6 741.9 177.4C734.1 175.8 726.6 177.6 720.3 182.6C717.6 184.7 713.2 190.0 7Line truncated

After

Width:  |  Height:  |  Size: 8.8 KiB

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="-24 -24 1048 658"><title>SmoovPlay</title><path fill="#1A1206" fill-rule="evenodd" d="M532.3 610.2C527.0 609.9 525.2 609.2 522.2 606.5C520.1 604.5 518.3 600.8 518.3 598.3C518.3 597.1 519.1 593.2 521.5 582.6C522.1 579.6 524.6 567.7 525.4 563.5C525.8 561.4 527.1 554.7 528.4 548.5C531.8 532.0 532.5 528.5 533.5 523.4C533.9 520.8 536.4 508.5 539.0 496.0C541.5 483.4 544.5 468.9 545.5 463.7C547.6 452.9 551.3 434.8 554.9 417.2C558.8 397.9 560.0 391.8 561.8 382.4C562.7 377.6 564.3 369.8 565.3 365.1C567.4 355.3 572.3 330.9 575.2 315.9C577.2 305.3 578.1 301.4 581.3 285.7C582.3 280.9 584.0 272.7 585.1 267.5C586.1 262.3 587.7 254.8 588.5 250.9C589.4 247.0 590.8 240.1 591.7 235.7C594.5 221.6 597.5 207.5 598.4 203.5C598.9 201.3 600.4 194.5 601.7 188.3C606.5 164.9 608.6 156.6 611.4 149.3C616.7 135.6 625.7 123.6 637.1 114.7C646.4 107.6 658.4 102.6 671.2 100.5C677.4 99.5 842.6 99.5 851.4 100.5C865.9 102.2 878.7 104.8 886.8 107.7C888.2 108.2 890.5 109.0 891.9 109.5C902.4 113.0 920.4 121.6 928.0 126.7C940.2 135.1 943.8 137.9 951.1 145.1C972.4 166.2 986.8 192.2 993.9 222.3C998.4 241.6 1000.0 256.7 999.5 275.1C998.8 302.1 993.7 325.3 982.8 351.7C979.1 360.9 971.1 375.1 963.8 385.4C951.6 402.8 940.4 414.8 923.5 428.5C913.8 436.3 895.7 447.2 882.7 453.0C874.5 456.7 860.9 461.6 854.8 463.0C842.3 466.0 841.0 466.2 835.9 466.9C833.9 467.2 830.6 467.7 828.5 468.0C825.9 468.3 805.2 468.5 756.9 468.6C719.5 468.7 688.5 468.9 688.0 469.0C687.2 469.2 686.9 470.0 686.0 473.5C685.5 475.9 684.1 481.6 683.0 486.3C681.8 491.0 680.5 496.8 680.0 499.2C679.0 503.5 677.1 511.8 676.3 514.9C676.1 515.7 675.7 517.4 675.4 518.5C675.1 519.7 673.3 527.4 671.3 535.6C665.6 558.8 664.3 564.5 663.3 568.9C662.4 573.5 660.0 579.5 657.4 583.7C655.3 587.2 649.4 594.6 646.7 597.1C640.7 602.8 631.0 607.8 622.4 609.6C618.8 610.3 615.0 610.4 577.7 610.5C555.3 610.5 534.9 610.4 532.3 610.2ZM68.0 527.0C61.5 524.7 58.7 517.5 61.5 510.1C65.2 500.3 74.2 481.3 78.3 474.5C79.5 472.5 81.5 469.2 82.8 467.2C87.0 460.3 98.3 445.7 104.4 439.4C116.1 427.3 127.4 419.0 142.6 411.3C153.1 406.1 162.9 402.9 177.2 400.3L184.1 399.0L289.8 398.9C408.7 398.8 398.7 399.1 406.5 395.2C414.1 391.4 420.4 383.8 422.0 376.4C422.3 375.2 422.5 372.5 422.5 370.4C422.6 358.3 415.2 348.8 402.4 344.4L397.8 342.8L339.6 342.7C307.5 342.7 279.2 342.5 276.7 342.4C265.7 341.8 248.4 337.4 237.3 332.3C228.1 328.2 216.6 321.5 208.7 315.7C202.3 311.1 192.8 303.1 189.8 299.9C175.5 284.6 168.3 274.6 161.2 260.4C155.6 249.2 152.7 241.8 149.5 230.4C148.4 226.6 146.6 217.4 145.8 211.3C144.7 203.2 144.7 183.9 145.8 175.6C147.8 161.1 149.0 156.1 154.2 141.3C157.4 132.1 163.3 119.3 169.0 109.3C177.0 95.3 190.7 77.8 204.2 64.5C218.5 50.4 231.2 40.6 249.5 29.4C258.1 24.2 274.4 16.5 285.3 12.4C300.7 6.6 322.0 1.8 337.0 0.8C342.0 0.5 387.2 0.3 478.2 0.3C628.3 0.3 615.2 0.0 618.9 3.7C621.4 6.2 622.6 9.5 622.3 13.1C622.1 15.2 620.9 18.4 616.2 28.9C612.9 36.1 609.6 43.6 608.8 45.5C608.0 47.4 605.0 54.0 602.1 60.2C599.3 66.4 595.8 73.9 594.5 76.9C591.7 83.0 587.4 90.8 584.4 95.0C581.1 99.6 574.3 106.9 570.2 110.2C568.1 111.8 564.5 114.2 562.0 115.4C557.9 117.4 557.5 117.5 554.0 117.5C548.6 117.5 545.7 116.0 539.5 109.8C526.1 96.7 511.7 89.6 494.6 87.6C491.0 87.2 320.6 87.2 316.3 87.6C301.1 89.1 283.8 95.4 270.3 104.5C265.0 108.1 254.0 117.2 251.3 120.3C249.8 122.1 247.5 124.8 246.1 126.3C242.7 130.1 237.0 138.8 233.8 145.0C230.8 151.0 227.6 160.2 226.2 167.6C224.0 178.1 225.0 192.6 228.6 203.2C230.4 208.6 234.5 216.8 237.7 221.7C246.9 235.5 261.2 246.1 278.3 251.7C289.6 255.5 282.4 255.2 371.6 255.5C427.7 255.7 452.1 256.0 454.1 256.4C460.3 257.5 466.6 258.9 469.0 259.7C478.6 262.8 482.7 264.5 492.3 269.8C507.4 278.1 521.9 293.1 530.7 309.4C534.4 316.3 539.2 328.2 541.1 335.4C543.8 345.5 545.9 361.1 545.9 371.6C545.9 375.1 544.9 386.7 544.3 390.9C542.5 402.9 541.5 407.3 538.5 417.4C537.4 421.2 535.1 427.7 533.9 430.3C533.5 431.3 532.6 433.6 531.9 435.4C530.4 439.2 524.7 450.0 521.3 455.2C509.5 473.8 495.2 488.6 477.1 501.1C468.2 507.1 455.9 513.7 446.0 517.6C437.3 521.0 423.7 524.7 415.3 525.9C413.3 526.2 410.8 526.7 409.8 527.0C408.5 527.4 362.5 527.5 238.9 527.6C92.6 527.7 69.6 527.6 68.0 527.0ZM713.5 397.0C716.3 396.1 726.7 390.5 739.2 383.1C742.5 381.2 747.1 378.5 749.5 377.1C751.9 375.8 756.6 373.1 759.9 371.1C763.2 369.2 769.6 365.5 774.2 362.8C778.7 360.2 786.4 355.8 791.2 352.9C796.0 350.1 801.4 346.9 803.2 345.9C805.0 344.9 809.0 342.6 812.1 340.8C815.2 339.0 817.9 337.5 818.0 337.5C818.1 337.5 819.7 336.6 821.5 335.5C823.3 334.4 827.5 331.9 830.8 330.0C834.1 328.1 840.1 324.7 844.2 322.3C848.2 320.0 852.5 317.5 853.6 316.9C854.8 316.3 858.1 314.3 861.0 312.6C863.9 310.9 867.8 308.7 869.6 307.7C878.7 302.4 884.0 296.1 885.5 288.6C886.1 285.1 885.8 278.0 884.7 275.1C883.9 272.7 881.1 268.2 879.0 265.9C877.9 264.7 871.3 260.2 855.7 250.2C846.3 244.0 819.0 226.1 794.7 210.1C743.4 176.1 747.4 178.6 741.9 177.4C734.1 175.8 726.6 177.6 720.3 182.6C717.6 184.7 713.2 190.0 7Line truncated

After

Width:  |  Height:  |  Size: 8.8 KiB

+65
View File
@@ -0,0 +1,65 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 880 330" width="880" height="330">
<title>Every third frame on screen is real; the two between are drawn by AI</title>
<rect x="0.5" y="0.5" width="879" height="329" rx="18" fill="#0C0E12" stroke="#252B35"/>
<text x="28" y="44" font-family="ui-monospace, 'SF Mono', 'Cascadia Mono', Consolas, Menlo, monospace" font-size="12" letter-spacing="1.5" fill="#8E949F">WHAT REACHES YOUR SCREEN AT 90 FPS</text>
<text x="852" y="44" text-anchor="end" font-family="ui-monospace, 'SF Mono', 'Cascadia Mono', Consolas, Menlo, monospace" font-size="12" letter-spacing="1.5" fill="#8E949F">AT 60 FPS: 1 AI FRAME · AT 120: 3</text>
<text x="28" y="95.0" font-family="'Segoe UI', -apple-system, BlinkMacSystemFont, 'Helvetica Neue', Helvetica, Arial, sans-serif" font-size="16" font-weight="600" fill="#F3EFE8">From your console</text>
<text x="28" y="114.0" font-family="ui-monospace, 'SF Mono', 'Cascadia Mono', Consolas, Menlo, monospace" font-size="12.5" letter-spacing="1" fill="#C3C6CD">30 FPS</text>
<text x="28" y="189.0" font-family="'Segoe UI', -apple-system, BlinkMacSystemFont, 'Helvetica Neue', Helvetica, Arial, sans-serif" font-size="16" font-weight="600" fill="#F3EFE8">On your screen</text>
<text x="28" y="208.0" font-family="ui-monospace, 'SF Mono', 'Cascadia Mono', Consolas, Menlo, monospace" font-size="12.5" letter-spacing="1" fill="#FFB02E">90 FPS</text>
<rect x="225.0" y="76" width="151.5" height="42" rx="9" fill="#DDE3EC"/>
<text x="300.8" y="103" text-anchor="middle" font-family="'Segoe UI', -apple-system, BlinkMacSystemFont, 'Helvetica Neue', Helvetica, Arial, sans-serif" font-size="16" font-weight="700" fill="#1A1206">A</text>
<rect x="382.5" y="76" width="151.5" height="42" rx="9" fill="#DDE3EC"/>
<text x="458.2" y="103" text-anchor="middle" font-family="'Segoe UI', -apple-system, BlinkMacSystemFont, 'Helvetica Neue', Helvetica, Arial, sans-serif" font-size="16" font-weight="700" fill="#1A1206">B</text>
<rect x="540.0" y="76" width="151.5" height="42" rx="9" fill="#DDE3EC"/>
<text x="615.8" y="103" text-anchor="middle" font-family="'Segoe UI', -apple-system, BlinkMacSystemFont, 'Helvetica Neue', Helvetica, Arial, sans-serif" font-size="16" font-weight="700" fill="#1A1206">C</text>
<rect x="697.5" y="76" width="151.5" height="42" rx="9" fill="#DDE3EC"/>
<text x="773.2" y="103" text-anchor="middle" font-family="'Segoe UI', -apple-system, BlinkMacSystemFont, 'Helvetica Neue', Helvetica, Arial, sans-serif" font-size="16" font-weight="700" fill="#1A1206">D</text>
<rect x="225.0" y="170" width="46.5" height="42" rx="9" fill="#DDE3EC"/>
<text x="248.2" y="196" text-anchor="middle" font-family="'Segoe UI', -apple-system, BlinkMacSystemFont, 'Helvetica Neue', Helvetica, Arial, sans-serif" font-size="15" font-weight="700" fill="#1A1206">A</text>
<rect x="277.5" y="170" width="46.5" height="42" rx="9" fill="#FFB02E"/>
<text x="300.8" y="196" text-anchor="middle" font-family="'Segoe UI', -apple-system, BlinkMacSystemFont, 'Helvetica Neue', Helvetica, Arial, sans-serif" font-size="12.5" font-weight="700" fill="#1A1206">AI</text>
<rect x="330.0" y="170" width="46.5" height="42" rx="9" fill="#FFB02E"/>
<text x="353.2" y="196" text-anchor="middle" font-family="'Segoe UI', -apple-system, BlinkMacSystemFont, 'Helvetica Neue', Helvetica, Arial, sans-serif" font-size="12.5" font-weight="700" fill="#1A1206">AI</text>
<rect x="382.5" y="170" width="46.5" height="42" rx="9" fill="#DDE3EC"/>
<text x="405.8" y="196" text-anchor="middle" font-family="'Segoe UI', -apple-system, BlinkMacSystemFont, 'Helvetica Neue', Helvetica, Arial, sans-serif" font-size="15" font-weight="700" fill="#1A1206">B</text>
<rect x="435.0" y="170" width="46.5" height="42" rx="9" fill="#FFB02E"/>
<text x="458.2" y="196" text-anchor="middle" font-family="'Segoe UI', -apple-system, BlinkMacSystemFont, 'Helvetica Neue', Helvetica, Arial, sans-serif" font-size="12.5" font-weight="700" fill="#1A1206">AI</text>
<rect x="487.5" y="170" width="46.5" height="42" rx="9" fill="#FFB02E"/>
<text x="510.8" y="196" text-anchor="middle" font-family="'Segoe UI', -apple-system, BlinkMacSystemFont, 'Helvetica Neue', Helvetica, Arial, sans-serif" font-size="12.5" font-weight="700" fill="#1A1206">AI</text>
<rect x="540.0" y="170" width="46.5" height="42" rx="9" fill="#DDE3EC"/>
<text x="563.2" y="196" text-anchor="middle" font-family="'Segoe UI', -apple-system, BlinkMacSystemFont, 'Helvetica Neue', Helvetica, Arial, sans-serif" font-size="15" font-weight="700" fill="#1A1206">C</text>
<rect x="592.5" y="170" width="46.5" height="42" rx="9" fill="#FFB02E"/>
<text x="615.8" y="196" text-anchor="middle" font-family="'Segoe UI', -apple-system, BlinkMacSystemFont, 'Helvetica Neue', Helvetica, Arial, sans-serif" font-size="12.5" font-weight="700" fill="#1A1206">AI</text>
<rect x="645.0" y="170" width="46.5" height="42" rx="9" fill="#FFB02E"/>
<text x="668.2" y="196" text-anchor="middle" font-family="'Segoe UI', -apple-system, BlinkMacSystemFont, 'Helvetica Neue', Helvetica, Arial, sans-serif" font-size="12.5" font-weight="700" fill="#1A1206">AI</text>
<rect x="697.5" y="170" width="46.5" height="42" rx="9" fill="#DDE3EC"/>
<text x="720.8" y="196" text-anchor="middle" font-family="'Segoe UI', -apple-system, BlinkMacSystemFont, 'Helvetica Neue', Helvetica, Arial, sans-serif" font-size="15" font-weight="700" fill="#1A1206">D</text>
<rect x="750.0" y="170" width="46.5" height="42" rx="9" fill="#FFB02E"/>
<text x="773.2" y="196" text-anchor="middle" font-family="'Segoe UI', -apple-system, BlinkMacSystemFont, 'Helvetica Neue', Helvetica, Arial, sans-serif" font-size="12.5" font-weight="700" fill="#1A1206">AI</text>
<rect x="802.5" y="170" width="46.5" height="42" rx="9" fill="#FFB02E"/>
<text x="825.8" y="196" text-anchor="middle" font-family="'Segoe UI', -apple-system, BlinkMacSystemFont, 'Helvetica Neue', Helvetica, Arial, sans-serif" font-size="12.5" font-weight="700" fill="#1A1206">AI</text>
<g fill="none" stroke="#FFB02E" stroke-width="1.6" stroke-opacity="0.75" stroke-linecap="round"><path d="M300.8,121 C300.8,140 327.0,132 327.0,154"/><path d="M458.2,121 C458.2,140 327.0,132 327.0,154"/><path d="M280.5,164 V154 H373.5 V164"/></g>
<text x="472.2" y="150" font-family="ui-monospace, 'SF Mono', 'Cascadia Mono', Consolas, Menlo, monospace" font-size="12" fill="#FFB02E">drawn from A and B</text>
<line x1="222" y1="238" x2="852" y2="238" stroke="#252B35" stroke-width="1.5"/>
<line x1="222.0" y1="232" x2="222.0" y2="244" stroke="#8E949F" stroke-width="1.5"/>
<text x="222.0" y="260" text-anchor="middle" font-family="ui-monospace, 'SF Mono', 'Cascadia Mono', Consolas, Menlo, monospace" font-size="12" fill="#8E949F">0</text>
<line x1="274.5" y1="235" x2="274.5" y2="241" stroke="#252B35" stroke-width="1.5"/>
<line x1="327.0" y1="235" x2="327.0" y2="241" stroke="#252B35" stroke-width="1.5"/>
<line x1="379.5" y1="232" x2="379.5" y2="244" stroke="#8E949F" stroke-width="1.5"/>
<text x="379.5" y="260" text-anchor="middle" font-family="ui-monospace, 'SF Mono', 'Cascadia Mono', Consolas, Menlo, monospace" font-size="12" fill="#8E949F">33</text>
<line x1="432.0" y1="235" x2="432.0" y2="241" stroke="#252B35" stroke-width="1.5"/>
<line x1="484.5" y1="235" x2="484.5" y2="241" stroke="#252B35" stroke-width="1.5"/>
<line x1="537.0" y1="232" x2="537.0" y2="244" stroke="#8E949F" stroke-width="1.5"/>
<text x="537.0" y="260" text-anchor="middle" font-family="ui-monospace, 'SF Mono', 'Cascadia Mono', Consolas, Menlo, monospace" font-size="12" fill="#8E949F">67</text>
<line x1="589.5" y1="235" x2="589.5" y2="241" stroke="#252B35" stroke-width="1.5"/>
<line x1="642.0" y1="235" x2="642.0" y2="241" stroke="#252B35" stroke-width="1.5"/>
<line x1="694.5" y1="232" x2="694.5" y2="244" stroke="#8E949F" stroke-width="1.5"/>
<text x="694.5" y="260" text-anchor="middle" font-family="ui-monospace, 'SF Mono', 'Cascadia Mono', Consolas, Menlo, monospace" font-size="12" fill="#8E949F">100</text>
<line x1="747.0" y1="235" x2="747.0" y2="241" stroke="#252B35" stroke-width="1.5"/>
<line x1="799.5" y1="235" x2="799.5" y2="241" stroke="#252B35" stroke-width="1.5"/>
<line x1="852.0" y1="232" x2="852.0" y2="244" stroke="#8E949F" stroke-width="1.5"/>
<text x="852.0" y="260" text-anchor="middle" font-family="ui-monospace, 'SF Mono', 'Cascadia Mono', Consolas, Menlo, monospace" font-size="12" fill="#8E949F">133 ms</text>
<text x="28" y="286" font-family="'Segoe UI', -apple-system, BlinkMacSystemFont, 'Helvetica Neue', Helvetica, Arial, sans-serif" font-size="13.5" fill="#C3C6CD">Every third frame you see is a real one from your console. The two in between are drawn by RIFE from the real</text>
<text x="28" y="306" font-family="'Segoe UI', -apple-system, BlinkMacSystemFont, 'Helvetica Neue', Helvetica, Arial, sans-serif" font-size="13.5" fill="#C3C6CD">frames on both sides, so each real frame waits for the next one: about 36 ms from arriving to on screen, at 90 fps.</text>
</svg>

After

Width:  |  Height:  |  Size: 8.8 KiB

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1024 1024" width="1024" height="1024"><title>SmoovPlay</title><defs><linearGradient id="g" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#FFBD24"/><stop offset="0.5" stop-color="#FC930B"/><stop offset="1" stop-color="#FC5F03"/></linearGradient></defs><rect width="1024" height="1024" rx="228" fill="url(#g)"/><g transform="translate(72.0 243.4) scale(0.8800)"><path fill="#FFB02E" d="M532.3 610.2C527.0 609.9 525.2 609.2 522.2 606.5C520.1 604.5 518.3 600.8 518.3 598.3C518.3 597.1 519.1 593.2 521.5 582.6C522.1 579.6 524.6 567.7 525.4 563.5C525.8 561.4 527.1 554.7 528.4 548.5C531.8 532.0 532.5 528.5 533.5 523.4C533.9 520.8 536.4 508.5 539.0 496.0C541.5 483.4 544.5 468.9 545.5 463.7C547.6 452.9 551.3 434.8 554.9 417.2C558.8 397.9 560.0 391.8 561.8 382.4C562.7 377.6 564.3 369.8 565.3 365.1C567.4 355.3 572.3 330.9 575.2 315.9C577.2 305.3 578.1 301.4 581.3 285.7C582.3 280.9 584.0 272.7 585.1 267.5C586.1 262.3 587.7 254.8 588.5 250.9C589.4 247.0 590.8 240.1 591.7 235.7C594.5 221.6 597.5 207.5 598.4 203.5C598.9 201.3 600.4 194.5 601.7 188.3C606.5 164.9 608.6 156.6 611.4 149.3C616.7 135.6 625.7 123.6 637.1 114.7C646.4 107.6 658.4 102.6 671.2 100.5C677.4 99.5 842.6 99.5 851.4 100.5C865.9 102.2 878.7 104.8 886.8 107.7C888.2 108.2 890.5 109.0 891.9 109.5C902.4 113.0 920.4 121.6 928.0 126.7C940.2 135.1 943.8 137.9 951.1 145.1C972.4 166.2 986.8 192.2 993.9 222.3C998.4 241.6 1000.0 256.7 999.5 275.1C998.8 302.1 993.7 325.3 982.8 351.7C979.1 360.9 971.1 375.1 963.8 385.4C951.6 402.8 940.4 414.8 923.5 428.5C913.8 436.3 895.7 447.2 882.7 453.0C874.5 456.7 860.9 461.6 854.8 463.0C842.3 466.0 841.0 466.2 835.9 466.9C833.9 467.2 830.6 467.7 828.5 468.0C825.9 468.3 805.2 468.5 756.9 468.6C719.5 468.7 688.5 468.9 688.0 469.0C687.2 469.2 686.9 470.0 686.0 473.5C685.5 475.9 684.1 481.6 683.0 486.3C681.8 491.0 680.5 496.8 680.0 499.2C679.0 503.5 677.1 511.8 676.3 514.9C676.1 515.7 675.7 517.4 675.4 518.5C675.1 519.7 673.3 527.4 671.3 535.6C665.6 558.8 664.3 564.5 663.3 568.9C662.4 573.5 660.0 579.5 657.4 583.7C655.3 587.2 649.4 594.6 646.7 597.1C640.7 602.8 631.0 607.8 622.4 609.6C618.8 610.3 615.0 610.4 577.7 610.5C555.3 610.5 534.9 610.4 532.3 610.2Z"/><path fill="#1A1206" fill-rule="evenodd" d="M532.3 610.2C527.0 609.9 525.2 609.2 522.2 606.5C520.1 604.5 518.3 600.8 518.3 598.3C518.3 597.1 519.1 593.2 521.5 582.6C522.1 579.6 524.6 567.7 525.4 563.5C525.8 561.4 527.1 554.7 528.4 548.5C531.8 532.0 532.5 528.5 533.5 523.4C533.9 520.8 536.4 508.5 539.0 496.0C541.5 483.4 544.5 468.9 545.5 463.7C547.6 452.9 551.3 434.8 554.9 417.2C558.8 397.9 560.0 391.8 561.8 382.4C562.7 377.6 564.3 369.8 565.3 365.1C567.4 355.3 572.3 330.9 575.2 315.9C577.2 305.3 578.1 301.4 581.3 285.7C582.3 280.9 584.0 272.7 585.1 267.5C586.1 262.3 587.7 254.8 588.5 250.9C589.4 247.0 590.8 240.1 591.7 235.7C594.5 221.6 597.5 207.5 598.4 203.5C598.9 201.3 600.4 194.5 601.7 188.3C606.5 164.9 608.6 156.6 611.4 149.3C616.7 135.6 625.7 123.6 637.1 114.7C646.4 107.6 658.4 102.6 671.2 100.5C677.4 99.5 842.6 99.5 851.4 100.5C865.9 102.2 878.7 104.8 886.8 107.7C888.2 108.2 890.5 109.0 891.9 109.5C902.4 113.0 920.4 121.6 928.0 126.7C940.2 135.1 943.8 137.9 951.1 145.1C972.4 166.2 986.8 192.2 993.9 222.3C998.4 241.6 1000.0 256.7 999.5 275.1C998.8 302.1 993.7 325.3 982.8 351.7C979.1 360.9 971.1 375.1 963.8 385.4C951.6 402.8 940.4 414.8 923.5 428.5C913.8 436.3 895.7 447.2 882.7 453.0C874.5 456.7 860.9 461.6 854.8 463.0C842.3 466.0 841.0 466.2 835.9 466.9C833.9 467.2 830.6 467.7 828.5 468.0C825.9 468.3 805.2 468.5 756.9 468.6C719.5 468.7 688.5 468.9 688.0 469.0C687.2 469.2 686.9 470.0 686.0 473.5C685.5 475.9 684.1 481.6 683.0 486.3C681.8 491.0 680.5 496.8 680.0 499.2C679.0 503.5 677.1 511.8 676.3 514.9C676.1 515.7 675.7 517.4 675.4 518.5C675.1 519.7 673.3 527.4 671.3 535.6C665.6 558.8 664.3 564.5 663.3 568.9C662.4 573.5 660.0 579.5 657.4 583.7C655.3 587.2 649.4 594.6 646.7 597.1C640.7 602.8 631.0 607.8 622.4 609.6C618.8 610.3 615.0 610.4 577.7 610.5C555.3 610.5 534.9 610.4 532.3 610.2ZM68.0 527.0C61.5 524.7 58.7 517.5 61.5 510.1C65.2 500.3 74.2 481.3 78.3 474.5C79.5 472.5 81.5 469.2 82.8 467.2C87.0 460.3 98.3 445.7 104.4 439.4C116.1 427.3 127.4 419.0 142.6 411.3C153.1 406.1 162.9 402.9 177.2 400.3L184.1 399.0L289.8 398.9C408.7 398.8 398.7 399.1 406.5 395.2C414.1 391.4 420.4 383.8 422.0 376.4C422.3 375.2 422.5 372.5 422.5 370.4C422.6 358.3 415.2 348.8 402.4 344.4L397.8 342.8L339.6 342.7C307.5 342.7 279.2 342.5 276.7 342.4C265.7 341.8 248.4 337.4 237.3 332.3C228.1 328.2 216.6 321.5 208.7 315.7C202.3 311.1 192.8 303.1 189.8 299.9C175.5 284.6 168.3 274.6 161.2 260.4C155.6 249.2 152.7 241.8 149.5 230.4C148.4 226.6 146.6 217.4 145.8 211.3C144.7 203.2 144.7 183.9 145.8 175.6C147.8 161.1 149.0 156.1 154.2 141.3C157.4 132.1 163.3 119.3 169.0 109.3C177.0 95.3 190.7 77.8 204.2 64.5C218.5 50.4 231.2 40.6 249.5 29.4C258.1 24.2 274.4 16.5 285.3 12.4C300.7 6.6 322.0 1.8 337.0 0.8C342.0 0.5 387.2 0.3 478.2 0.3C628.3 0.3 615.2 0.0 618.Line truncated

After

Width:  |  Height:  |  Size: 11 KiB

+160
View File
@@ -0,0 +1,160 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="-24 -24 1148 848" width="1148" height="848">
<title>Desk setup: PS5, router, PC and screen, and what happens inside the PC</title>
<style>
.t { font-family: 'Segoe UI', -apple-system, BlinkMacSystemFont, 'Helvetica Neue', Helvetica, Arial, sans-serif; fill: #F3EFE8; }
.s { font-family: 'Segoe UI', -apple-system, BlinkMacSystemFont, 'Helvetica Neue', Helvetica, Arial, sans-serif; fill: #8E949F; }
.m { font-family: ui-monospace, 'SF Mono', 'Cascadia Mono', Consolas, Menlo, monospace; fill: #8E949F; letter-spacing: 0.06em; }
.halo text { paint-order: stroke; stroke: #161A21; stroke-width: 6px; stroke-linejoin: round; }
</style>
<rect x="-23.5" y="-23.5" width="1147" height="847" rx="20" fill="#161A21" stroke="#252B35"/>
<defs>
<linearGradient id="phy-sky" x1="0" y1="0" x2="0" y2="1">
<stop offset="0" stop-color="#2b1d5c"/><stop offset="0.6" stop-color="#c2477a"/><stop offset="1" stop-color="#f39a4c"/>
</linearGradient>
<marker id="pm-n" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="4" markerHeight="4" orient="auto-start-reverse"><path d="M0,0L10,5L0,10z" fill="#AEB4BE"/></marker>
<marker id="pm-a" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="4" markerHeight="4" orient="auto-start-reverse"><path d="M0,0L10,5L0,10z" fill="#FFB02E"/></marker>
<marker id="pm-m" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="4" markerHeight="4" orient="auto"><path d="M0,0L10,5L0,10z" fill="#6E7682"/></marker>
<marker id="pm-s" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto"><path d="M0,0L10,5L0,10z" fill="#AEB4BE"/></marker>
</defs>
<!-- zoom from the PC into the panel below -->
<polygon points="900,540 1010,540 1090,604 10,604" fill="#FFB02E" fill-opacity="0.05"/>
<line x1="900" y1="540" x2="10" y2="604" stroke="#FFB02E" stroke-opacity="0.35" stroke-dasharray="4 5"/>
<line x1="1010" y1="540" x2="1090" y2="604" stroke="#FFB02E" stroke-opacity="0.35" stroke-dasharray="4 5"/>
<text class="m" x="560" y="592" font-size="12" text-anchor="middle">INSIDE THE PC</text>
<!-- desk and floor -->
<line x1="10" y1="540" x2="1090" y2="540" stroke="#3A4250" stroke-width="2"/>
<rect x="20" y="380" width="1060" height="12" rx="2" fill="#2C333E"/>
<rect x="32" y="392" width="12" height="148" fill="#2C333E"/>
<rect x="1056" y="392" width="12" height="148" fill="#2C333E"/>
<!-- screen -->
<text class="t" x="570" y="34" font-size="16" font-weight="700" text-anchor="middle">Your screen</text>
<text class="s" x="570" y="53" font-size="12.5" text-anchor="middle">60, 90 or 120 fps, to match its refresh rate</text>
<rect x="340" y="68" width="460" height="264" rx="10" fill="#1D222B" stroke="#4A5260"/>
<rect x="346" y="74" width="448" height="252" fill="url(#phy-sky)"/>
<circle cx="570" cy="238" r="46" fill="#ffd27a"/>
<g fill="#241640">
<rect x="356" y="224" width="18" height="52"/><rect x="376" y="196" width="14" height="80"/><rect x="392" y="230" width="22" height="46"/>
<rect x="418" y="176" width="16" height="100"/><rect x="436" y="212" width="20" height="64"/><rect x="458" y="238" width="14" height="38"/><rect x="474" y="220" width="18" height="56"/>
<rect x="646" y="232" width="16" height="44"/><rect x="664" y="188" width="24" height="88"/><rect x="690" y="218" width="14" height="58"/>
<rect x="706" y="166" width="18" height="110"/><rect x="726" y="206" width="20" height="70"/><rect x="748" y="228" width="16" height="48"/><rect x="766" y="240" width="18" height="36"/>
</g>
<rect x="346" y="276" width="448" height="50" fill="#1d1236"/>
<g stroke="#ffd27a" stroke-width="2.4" stroke-linecap="round" opacity="0.55">
<line x1="536" y1="288" x2="604" y2="288"/><line x1="546" y1="300" x2="594" y2="300"/><line x1="556" y1="314" x2="584" y2="314"/>
</g>
<g fill="none" stroke="#120b22" stroke-linecap="round">
<path d="M380,326 Q384,290 394,262" stroke-width="4.5"/>
<path d="M394,262 q-18,-6 -32,4 M394,262 q-12,-16 -30,-16 M394,262 q14,-14 32,-9 M394,262 q18,0 27,14" stroke-width="3.2"/>
<path d="M760,326 Q756,290 746,262" stroke-width="4.5"/>
<path d="M746,262 q18,-6 32,4 M746,262 q12,-16 30,-16 M746,262 q-14,-14 -32,-9 M746,262 q-18,0 -27,14" stroke-width="3.2"/>
</g>
<rect x="488" y="86" width="164" height="24" rx="12" fill="#000" fill-opacity="0.55"/>
<text x="570" y="102.5" font-size="12" font-weight="600" text-anchor="middle" fill="#FFCB5C" font-family="'Segoe UI', -apple-system, BlinkMacSystemFont, 'Helvetica Neue', Helvetica, Arial, sans-serif">SmoovPlay · 90 fps</text>
<rect x="556" y="332" width="28" height="34" fill="#2C333E"/>
<rect x="506" y="366" width="128" height="14" rx="3" fill="#2C333E"/>
<rect x="385" y="332" width="14" height="7" rx="1" fill="#6E7682"/>
<rect x="753" y="332" width="14" height="7" rx="1" fill="#FFB02E"/>
<!-- PS5 -->
<text class="t" x="130" y="118" font-size="16" font-weight="700" text-anchor="middle">PS5</text>
<text class="s" x="130" y="136" font-size="12.5" text-anchor="middle">runs the game at 30 fps</text>
<rect x="122" y="150" width="16" height="230" fill="#11141A"/>
<path d="M122,146 C108,150 100,172 100,204 L103,372 Q103,380 111,380 L122,380 Z" fill="#E9ECF1"/>
<path d="M138,146 C152,150 160,172 160,204 L157,372 Q157,380 149,380 L138,380 Z" fill="#E9ECF1"/>
<!-- controller on the desk -->
<text class="t" x="896" y="334" font-size="14" font-weight="600" text-anchor="middle">Controller</text>
<text class="s" x="896" y="350" font-size="12" text-anchor="middle">USB or Bluetooth</text>
<g transform="translate(830,-2)">
<path d="M42,363 H88 Q99,363 100,373 Q101,381 93,380 L84,375 H46 L37,380 Q29,381 30,373 Q31,363 42,363 Z" fill="#E9ECF1"/>
<rect x="55" y="365" width="20" height="6" rx="2" fill="#2C333E"/>
</g>
<path d="M934,368 Q1004,370 1000,404" fill="none" stroke="#AEB4BE" stroke-width="1.6" stroke-dasharray="2 5" stroke-linecap="round"/>
<!-- router on the floor -->
<text class="t" x="265" y="482" font-size="14" font-weight="600" text-anchor="middle">Router</text>
<line x1="234" y1="510" x2="228" y2="492" stroke="#4A5260" stroke-width="3" stroke-linecap="round"/>
<line x1="296" y1="510" x2="302" y2="492" stroke="#4A5260" stroke-width="3" stroke-linecap="round"/>
<rect x="220" y="510" width="90" height="30" rx="4" fill="#232933" stroke="#3A4250"/>
<circle cx="238" cy="525" r="2.5" fill="#7FD49B"/><circle cx="250" cy="525" r="2.5" fill="#7FD49B"/><circle cx="262" cy="525" r="2.5" fill="#7FD49B"/>
<!-- PC under the desk -->
<text class="t" x="884" y="428" font-size="16" font-weight="700" text-anchor="end">Your PC</text>
<text class="s" x="884" y="446" font-size="12.5" text-anchor="end">NVIDIA RTX card</text>
<rect x="900" y="404" width="110" height="136" rx="6" fill="#1D222B" stroke="#4A5260"/>
<circle cx="996" cy="416" r="3.5" fill="#FFB02E"/>
<rect x="908" y="452" width="94" height="34" rx="3" fill="#FFB02E" fill-opacity="0.14" stroke="#FFB02E" stroke-opacity="0.8"/>
<text x="955" y="474" font-size="12" font-weight="700" text-anchor="middle" fill="#FFB02E" font-family="ui-monospace, 'SF Mono', 'Cascadia Mono', Consolas, Menlo, monospace">RTX</text>
<g stroke="#3A4250" stroke-width="2"><line x1="916" y1="504" x2="994" y2="504"/><line x1="916" y1="512" x2="994" y2="512"/><line x1="916" y1="520" x2="994" y2="520"/></g>
<!-- cables -->
<path d="M162,356 H392 V346" fill="none" stroke="#6E7682" stroke-width="2.4" stroke-dasharray="6 6" stroke-linecap="round" marker-end="url(#pm-m)"/>
<path d="M162,370 H184 V525 H212" fill="none" stroke="#AEB4BE" stroke-width="3" stroke-linejoin="round" marker-start="url(#pm-n)" marker-end="url(#pm-n)"/>
<path d="M318,525 H892" fill="none" stroke="#AEB4BE" stroke-width="3" marker-start="url(#pm-n)" marker-end="url(#pm-n)"/>
<path d="M904,469 H760 V346" fill="none" stroke="#FFB02E" stroke-width="3.4" stroke-linejoin="round" marker-end="url(#pm-a)"/>
<g class="halo">
<text class="s" x="277" y="350" font-size="12" text-anchor="middle">HDMI · play direct any time</text>
<text class="s" x="196" y="452" font-size="12">Ethernet</text>
<text class="s" x="600" y="516" font-size="12.5" text-anchor="middle">Ethernet or 5 GHz Wi-Fi · the Remote Play stream in, your button presses out</text>
<text x="750" y="424" font-size="12.5" font-weight="600" text-anchor="end" fill="#FFB02E" font-family="'Segoe UI', -apple-system, BlinkMacSystemFont, 'Helvetica Neue', Helvetica, Arial, sans-serif">DisplayPort · 60, 90 or 120 fps</text>
</g>
<!-- inside the PC -->
<rect x="10" y="604" width="1080" height="188" rx="16" fill="#12151B" stroke="#FFB02E" stroke-opacity="0.35"/>
<rect x="38" y="640" width="140" height="96" rx="10" fill="#1D222B" stroke="#3A4250"/>
<text class="t" x="52" y="666" font-size="14" font-weight="700">Network port</text>
<text class="s" x="52" y="687" font-size="12">the stream arrives,</text>
<text class="s" x="52" y="703" font-size="12">30 new frames</text>
<text class="s" x="52" y="719" font-size="12">a second</text>
<line x1="180" y1="688" x2="202" y2="688" stroke="#AEB4BE" stroke-width="1.6" marker-end="url(#pm-s)"/>
<rect x="206" y="640" width="160" height="96" rx="10" fill="#1D222B" stroke="#3A4250"/>
<text class="t" x="220" y="666" font-size="14" font-weight="700">chiaki-ng</text>
<text class="m" x="352" y="666" font-size="10.5" text-anchor="end">CPU</text>
<text class="s" x="220" y="687" font-size="12">unpacks the stream,</text>
<text class="s" x="220" y="703" font-size="12">plays the sound,</text>
<text class="s" x="220" y="719" font-size="12">sends your buttons</text>
<line x1="368" y1="688" x2="390" y2="688" stroke="#AEB4BE" stroke-width="1.6" marker-end="url(#pm-s)"/>
<rect x="394" y="616" width="498" height="136" rx="12" fill="#FFB02E" fill-opacity="0.06" stroke="#FFB02E" stroke-opacity="0.7"/>
<text x="408" y="633" font-size="11" font-weight="600" fill="#FFB02E" letter-spacing="0.08em" font-family="ui-monospace, 'SF Mono', 'Cascadia Mono', Consolas, Menlo, monospace">GRAPHICS CARD · SMOOVPLAY</text>
<rect x="406" y="642" width="150" height="96" rx="10" fill="#1D222B" stroke="#3A4250"/>
<text class="t" x="420" y="668" font-size="14" font-weight="700">Video decoder</text>
<text class="s" x="420" y="689" font-size="12">unpacks each frame,</text>
<text class="s" x="420" y="705" font-size="12">skips the repeats</text>
<text class="m" x="420" y="726" font-size="10.5">NVDEC</text>
<line x1="557" y1="690" x2="566" y2="690" stroke="#AEB4BE" stroke-width="1.6" marker-end="url(#pm-s)"/>
<rect x="568" y="642" width="150" height="96" rx="10" fill="#2A2216" stroke="#FFB02E"/>
<text x="582" y="668" font-size="14" font-weight="700" fill="#FFB02E" font-family="'Segoe UI', -apple-system, BlinkMacSystemFont, 'Helvetica Neue', Helvetica, Arial, sans-serif">AI cores</text>
<text class="s" x="582" y="689" font-size="12">draw 1 to 3 in-between</text>
<text class="s" x="582" y="705" font-size="12">frames, ~9 ms each</text>
<text class="m" x="582" y="726" font-size="10.5">RIFE · TENSORRT</text>
<line x1="719" y1="690" x2="728" y2="690" stroke="#AEB4BE" stroke-width="1.6" marker-end="url(#pm-s)"/>
<rect x="730" y="642" width="150" height="96" rx="10" fill="#1D222B" stroke="#3A4250"/>
<text class="t" x="744" y="668" font-size="14" font-weight="700">Shader cores</text>
<text class="s" x="744" y="689" font-size="12">fit the picture to</text>
<text class="s" x="744" y="705" font-size="12">your screen, 0.1 ms</text>
<text class="m" x="744" y="726" font-size="10.5">AMD FSR 1</text>
<line x1="894" y1="688" x2="916" y2="688" stroke="#FFB02E" stroke-width="2" marker-end="url(#pm-a)"/>
<rect x="920" y="640" width="140" height="96" rx="10" fill="#1D222B" stroke="#3A4250"/>
<text class="t" x="934" y="666" font-size="14" font-weight="700">Display out</text>
<text class="s" x="934" y="687" font-size="12">a frame every</text>
<text class="s" x="934" y="703" font-size="12">16.7, 11.1 or 8.3 ms</text>
<text class="s" x="934" y="719" font-size="12">at 60, 90 or 120 fps</text>
<text class="m" x="550" y="778" font-size="11.5" text-anchor="middle">ABOUT 36 MS FROM A FRAME ARRIVING TO IT ON SCREEN · MEASURED AT 90 FPS ON AN RTX 4070 TI SUPER</text>
</svg>

After

Width:  |  Height:  |  Size: 13 KiB

+25
View File
@@ -0,0 +1,25 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 880 232" width="880" height="232">
<title>Same motion at 30 frames a second, and at 60, 90 or 120</title>
<style>
.dot { animation: run 1.8s infinite alternate; }
.f30 { animation-timing-function: steps(54, end); }
.f90 { animation-timing-function: steps(216, end); }
@keyframes run { from { transform: translateX(0px); } to { transform: translateX(586px); } }
@media (prefers-reduced-motion: reduce) { .dot { animation: none; } }
</style>
<rect x="0.5" y="0.5" width="879" height="231" rx="18" fill="#0C0E12" stroke="#252B35"/>
<text x="28" y="44" font-family="ui-monospace, 'SF Mono', 'Cascadia Mono', Consolas, Menlo, monospace" font-size="12" letter-spacing="1.5" fill="#8E949F">SAME MOTION, TWO FRAME RATES</text>
<text x="852" y="44" text-anchor="end" font-family="ui-monospace, 'SF Mono', 'Cascadia Mono', Consolas, Menlo, monospace" font-size="12" letter-spacing="1.5" fill="#8E949F">LIVE</text>
<circle cx="808" cy="40" r="4" fill="#FFB02E"/>
<text x="28" y="96" font-family="'Segoe UI', -apple-system, BlinkMacSystemFont, 'Helvetica Neue', Helvetica, Arial, sans-serif" font-size="17" font-weight="600" fill="#F3EFE8">Your console</text>
<text x="28" y="116" font-family="ui-monospace, 'SF Mono', 'Cascadia Mono', Consolas, Menlo, monospace" font-size="12.5" letter-spacing="1" fill="#C3C6CD">30 FPS</text>
<rect x="222" y="75" width="630" height="46" rx="23" fill="#161A21" stroke="#252B35"/>
<g stroke="#252B35" stroke-width="1.5"><line x1="262" y1="92" x2="262" y2="104"/><line x1="302" y1="92" x2="302" y2="104"/><line x1="342" y1="92" x2="342" y2="104"/><line x1="382" y1="92" x2="382" y2="104"/><line x1="422" y1="92" x2="422" y2="104"/><line x1="462" y1="92" x2="462" y2="104"/><line x1="502" y1="92" x2="502" y2="104"/><line x1="542" y1="92" x2="542" y2="104"/><line x1="582" y1="92" x2="582" y2="104"/><line x1="622" y1="92" x2="622" y2="104"/><line x1="662" y1="92" x2="662" y2="104"/><line x1="702" y1="92" x2="702" y2="104"/><line x1="742" y1="92" x2="742" y2="104"/><line x1="782" y1="92" x2="782" y2="104"/><line x1="822" y1="92" x2="822" y2="104"/></g>
<g class="dot f30"><circle cx="244" cy="98" r="12.5" fill="#DDE3EC"/></g>
<text x="28" y="160" font-family="'Segoe UI', -apple-system, BlinkMacSystemFont, 'Helvetica Neue', Helvetica, Arial, sans-serif" font-size="17" font-weight="600" fill="#FFB02E">SmoovPlay</text>
<text x="28" y="180" font-family="ui-monospace, 'SF Mono', 'Cascadia Mono', Consolas, Menlo, monospace" font-size="12.5" letter-spacing="1" fill="#FFB02E">60 · 90 · 120 FPS</text>
<rect x="222" y="139" width="630" height="46" rx="23" fill="#161A21" stroke="#252B35"/>
<g stroke="#252B35" stroke-width="1.5"><line x1="262" y1="156" x2="262" y2="168"/><line x1="302" y1="156" x2="302" y2="168"/><line x1="342" y1="156" x2="342" y2="168"/><line x1="382" y1="156" x2="382" y2="168"/><line x1="422" y1="156" x2="422" y2="168"/><line x1="462" y1="156" x2="462" y2="168"/><line x1="502" y1="156" x2="502" y2="168"/><line x1="542" y1="156" x2="542" y2="168"/><line x1="582" y1="156" x2="582" y2="168"/><line x1="622" y1="156" x2="622" y2="168"/><line x1="662" y1="156" x2="662" y2="168"/><line x1="702" y1="156" x2="702" y2="168"/><line x1="742" y1="156" x2="742" y2="168"/><line x1="782" y1="156" x2="782" y2="168"/><line x1="822" y1="156" x2="822" y2="168"/></g>
<g class="dot f90"><circle cx="244" cy="162" r="21" fill="#FFB02E" opacity="0.18"/><circle cx="244" cy="162" r="12.5" fill="#FFB02E"/></g>
<text x="28" y="210" font-family="'Segoe UI', -apple-system, BlinkMacSystemFont, 'Helvetica Neue', Helvetica, Arial, sans-serif" font-size="13.5" fill="#8E949F">The top dot moves 30 times a second, like a 30 fps game. The bottom one moves 60, 90 or 120 times, as fast as your screen.</text>
</svg>

After

Width:  |  Height:  |  Size: 3.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 764 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 907 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 624 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 358 KiB

+1
View File
@@ -0,0 +1 @@
"""SmoovPlay's pipeline: real-time frame generation and upscaling for 30 fps console games."""
Binary file not shown.

After

Width:  |  Height:  |  Size: 600 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 919 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.7 KiB

+128
View File
@@ -0,0 +1,128 @@
"""Sound from a capture card, played in step with SmoovPlay's picture.
A capture card's sound comes in as its own DirectShow audio device, read with the video (framegen/capture.py). It's
played here on the PC's default output, through WASAPI (sounddevice, which bundles PortAudio), held back by as long
as the picture spends in SmoovPlay, so the two line up: set_delay(), which the pipeline calls every couple of
seconds (Sound in sync), as it does for chiaki-ng's sound.
DelayLine is the part that matters and needs no sound card: PCM goes in as it arrives and comes out at the
output's pace, with the queue kept at the delay. Far off (at the start, or when the delay changes a lot) it jumps:
silence until it has filled, or the oldest sound skipped. Near it, the sound plays half a percent faster or slower
until it's back, which nobody hears, so the card's clock and the output's can drift apart without the delay
creeping.
"""
from __future__ import annotations
import threading
import numpy as np
JUMP_S = 0.040 # further than this from the delay: jump to it
NUDGE_S = 0.004 # further than this: half a percent faster or slower until it's back
NUDGE = 0.005
MAX_S = 1.5 # never queue more than this
class DelayLine:
"""Thread-safe: push() from the reader's thread, pull() from the output's."""
def __init__(self, rate: int, channels: int, sample_bytes: int = 2) -> None:
self.rate, self.channels = rate, channels
self.frame = channels * sample_bytes # bytes per sample frame (all channels)
self._buf = bytearray()
self._lock = threading.Lock()
self.target = 0 # bytes to keep queued
self.underruns = 0 # blocks that came out short (padded with silence) because nothing had arrived
self.jumps = 0
self._filling = True # silent until the queue reaches the delay
def _bytes(self, seconds: float) -> int:
return max(0, int(round(seconds * self.rate))) * self.frame
def set_delay(self, seconds: float) -> None:
with self._lock:
self.target = min(self._bytes(seconds), self._bytes(MAX_S - JUMP_S))
@property
def queued_s(self) -> float:
return len(self._buf) / self.frame / self.rate
def push(self, pcm: bytes) -> None:
with self._lock:
self._buf += pcm
over = len(self._buf) - self._bytes(MAX_S)
if over > 0:
del self._buf[:over + -over % self.frame] # (whole sample frames)
def pull(self, n: int) -> bytes:
"""n bytes (whole sample frames) for the output."""
nf = n // self.frame
with self._lock:
err = len(self._buf) - self.target # how far ahead of the delay the queue is
jump, nudge = self._bytes(JUMP_S), self._bytes(NUDGE_S)
if err < -jump and not self._filling: # too little queued (a stall, or a longer delay): refill
self._filling = True
self.jumps += 1
if self._filling:
if err < 0:
return bytes(n)
self._filling = False
if err > jump: # too much: skip the oldest sound
del self._buf[:err]
self.jumps += 1
err = 0
take = (max(nf + 1, round(nf * (1 + NUDGE))) if err > nudge else
min(nf - 1, round(nf * (1 - NUDGE))) if err < -nudge else nf)
take = max(1, take)
chunk = bytes(self._buf[:take * self.frame])
del self._buf[:take * self.frame]
if len(chunk) < take * self.frame: # (ran dry)
self.underruns += 1
chunk += bytes(take * self.frame - len(chunk))
if take == nf:
return chunk
# Played a little faster (more in than out) or slower: stretched to n bytes, sample by sample.
a = np.frombuffer(chunk, np.int16).reshape(take, self.channels).astype(np.float32)
x = np.linspace(0, take - 1, nf)
out = np.stack([np.interp(x, np.arange(take), a[:, ch]) for ch in range(self.channels)], axis=1)
return np.round(out).astype(np.int16).tobytes()
def wasapi_output() -> int | None:
"""The default output device under WASAPI (lower and steadier delay than MME, PortAudio's default)."""
import sounddevice as sd
for api in sd.query_hostapis():
if "WASAPI" in api["name"] and api["default_output_device"] >= 0:
return api["default_output_device"]
return None
class Player:
"""Plays a DelayLine on the default output (16-bit PCM). latency: the output's own delay, in seconds, which
set_delay() takes off so the total is what was asked for."""
def __init__(self, rate: int, channels: int, device: int | None = None) -> None:
import sounddevice as sd
self.line = DelayLine(rate, channels)
dev = wasapi_output() if device is None else device
extra = sd.WasapiSettings(auto_convert=True) if dev is not None else None # the card's rate, whatever Windows mixes at
self.stream = sd.RawOutputStream(samplerate=rate, channels=channels, dtype="int16", device=dev,
latency="low", extra_settings=extra, callback=self._play)
self.stream.start()
self.latency = float(self.stream.latency)
def _play(self, outdata, frames, time_info, status) -> None: # on PortAudio's thread
outdata[:] = self.line.pull(frames * self.line.frame)
def push(self, pcm: bytes) -> None:
self.line.push(pcm)
def set_delay(self, seconds: float) -> None:
self.line.set_delay(seconds - self.latency)
def close(self) -> None:
try:
self.stream.stop()
self.stream.close()
except Exception: # noqa: BLE001 - closing
pass
+533
View File
@@ -0,0 +1,533 @@
"""Auto-detect: suggests settings for this PC from a short test of the graphics card, the display and what's installed.
The launcher's Settings page runs it ("Auto-detect"), and setup applies it to a new install.
python -m framegen.autodetect # what it found and suggests: "[detect] ..." lines, then one JSON line
python -m framegen.autodetect --apply # also saves the suggestions
python -m framegen.autodetect --apply --if-new # only when there's no settings file yet (what setup runs)
The test times RIFE on a 1080p frame (the Remote Play stream) for a few seconds: one new real frame plus one in-between
frame, at full and at half motion detail, each with the engine "Auto" runs there (DirectML without an NVIDIA card).
If NVIDIA VFG is set up, it times its three quality modes the same way. recommend() turns those times and the display into settings; it's a plain
function, so the tests can try it on any PC.
VFG's times are shown on the launcher's Settings page and written to logs\autodetect.txt only (not the session log
that Copy diagnostics reads): NVIDIA's licence forbids publishing VFG benchmark results.
"""
from __future__ import annotations
import argparse
import json
import subprocess
import sys
import time
from dataclasses import dataclass
from pathlib import Path
from typing import Callable
from .settings import BY_KEY, DEFAULT_PATH, Settings
PREFIX = "[detect-result] "
STREAM = (1920, 1080)
# An in-between frame (a new real frame's preparation, RIFE, the upscaler) has to be ready within one display tick,
# 1000/hz ms. Calibrated on an RTX 4070 Ti SUPER over PS5 Remote Play, where this test measures 9.3 ms at full motion
# detail (TensorRT) and 6.8 at half (PyTorch): 90 fps at full (85% of the tick) showed 99% of the extra frames and
# 120 fps at half (83%) 98%, but 90 fps with RTX VSR on top (98%) only 77%. 90% sits between them.
SHARE = 0.90
LAPTOP_SHARE = 0.80 # laptop graphics slow down as they warm up
# Upscaler times per frame at 1440p on that card (scaled here by the card's speed and the display's size).
FSR_MS = 0.12
VSR_MS = {1: 1.3, 2: 1.6, 3: 3.6, 4: 4.9}
REF_HALF_MS = 6.8 # this test's half-motion time on that card: the yardstick for "the card's speed"
REF_PIXELS = 2560 * 1440
TRT_SPEEDUP = 0.88 # TensorRT's time at full motion detail vs PyTorch's, when its engine isn't built yet to time
# Frame rate and motion detail, best first. 90 fps at full detail beats 120 at half: in testing it looked better.
OPTIONS = ((120, "full"), (90, "full"), (120, "half"), (90, "half"), (60, "full"), (60, "half"))
VFG_QUALITIES = ("high", "medium", "low") # NVIDIA VFG's modes, most careful first
@dataclass(frozen=True)
class Display:
width: int
height: int
hz: int # the refresh rate Windows runs it at
max_hz: int # the fastest it can run at this resolution
def primary_display() -> Display | None:
"""The main display (where the video window opens), or None if it can't be read (not Windows)."""
if sys.platform != "win32":
return None
import ctypes
from ctypes import wintypes as wt
class DisplayDevice(ctypes.Structure):
_fields_ = [("cb", wt.DWORD), ("DeviceName", wt.WCHAR * 32), ("DeviceString", wt.WCHAR * 128),
("StateFlags", wt.DWORD), ("DeviceID", wt.WCHAR * 128), ("DeviceKey", wt.WCHAR * 128)]
class DevMode(ctypes.Structure):
_fields_ = [("dmDeviceName", wt.WCHAR * 32), ("dmSpecVersion", wt.WORD), ("dmDriverVersion", wt.WORD),
("dmSize", wt.WORD), ("dmDriverExtra", wt.WORD), ("dmFields", wt.DWORD),
("dmPositionX", wt.LONG), ("dmPositionY", wt.LONG), ("dmDisplayOrientation", wt.DWORD),
("dmDisplayFixedOutput", wt.DWORD), ("dmColor", ctypes.c_short), ("dmDuplex", ctypes.c_short),
("dmYResolution", ctypes.c_short), ("dmTTOption", ctypes.c_short), ("dmCollate", ctypes.c_short),
("dmFormName", wt.WCHAR * 32), ("dmLogPixels", wt.WORD), ("dmBitsPerPel", wt.DWORD),
("dmPelsWidth", wt.DWORD), ("dmPelsHeight", wt.DWORD), ("dmDisplayFlags", wt.DWORD),
("dmDisplayFrequency", wt.DWORD), ("dmICMMethod", wt.DWORD), ("dmICMIntent", wt.DWORD),
("dmMediaType", wt.DWORD), ("dmDitherType", wt.DWORD), ("dmReserved1", wt.DWORD),
("dmReserved2", wt.DWORD), ("dmPanningWidth", wt.DWORD), ("dmPanningHeight", wt.DWORD)]
u32 = ctypes.windll.user32
dd = DisplayDevice(cb=ctypes.sizeof(DisplayDevice))
i, name = 0, None
while u32.EnumDisplayDevicesW(None, i, ctypes.byref(dd), 0):
if dd.StateFlags & 4: # DISPLAY_DEVICE_PRIMARY_DEVICE
name = dd.DeviceName
break
i += 1
dd = DisplayDevice(cb=ctypes.sizeof(DisplayDevice))
now = DevMode(dmSize=ctypes.sizeof(DevMode))
if not u32.EnumDisplaySettingsW(name, -1, ctypes.byref(now)): # ENUM_CURRENT_SETTINGS
return None
best, m = now.dmDisplayFrequency, 0
while True:
mode = DevMode(dmSize=ctypes.sizeof(DevMode))
if not u32.EnumDisplaySettingsW(name, m, ctypes.byref(mode)):
break
if (mode.dmPelsWidth, mode.dmPelsHeight) == (now.dmPelsWidth, now.dmPelsHeight):
best = max(best, mode.dmDisplayFrequency)
m += 1
return Display(now.dmPelsWidth, now.dmPelsHeight, now.dmDisplayFrequency, best)
def nvidia_smi(samples: int = 3) -> dict:
"""Driver version and how busy the card is (%), from nvidia-smi; {} if it isn't there. Busy is the lowest of a few
readings half a second apart: a game keeps the card busy, a moment's work (like setup's own, just before) doesn't."""
driver, busy = None, []
for i in range(samples):
if i:
time.sleep(0.5)
try:
out = subprocess.run(["nvidia-smi", "--query-gpu=driver_version,utilization.gpu", "--format=csv,noheader,nounits"],
capture_output=True, text=True, timeout=10,
creationflags=0x08000000 if sys.platform == "win32" else 0).stdout # CREATE_NO_WINDOW
d, b = [x.strip() for x in out.splitlines()[0].split(",")[:2]]
driver = d
busy.append(int(b))
except Exception: # noqa: BLE001 - only used for the summary and the "busy" note
break
return {"driver": driver, "busy": min(busy)} if busy else {}
def time_rife(model: str, log: Callable[[str], None] = print) -> dict:
"""ms for one new real frame plus one in-between frame, at 1080p: {"full"/"half": {"ms", "engine", "estimated"}}.
Each motion detail uses the engine Auto runs there (trt.auto_engine). A TensorRT engine that isn't built yet
(setup builds it; otherwise the first start does, in a minute or two) isn't built here: PyTorch is timed instead
and TensorRT's time estimated from it."""
import torch
from .interpolator import RifeInterpolator
from .trt import auto_engine
w, h = STREAM
frame = torch.randint(0, 256, (h, w, 3), dtype=torch.uint8, device="cuda")
out = {}
for motion, scale in (("full", 1.0), ("half", 0.5)):
engine, estimated = auto_engine(scale), False
log(f"timing the AI model at {motion} motion detail ({'TensorRT' if engine == 'trt' else 'PyTorch'})")
try:
it = RifeInterpolator(w, h, model, scale, backend=engine, build_engine=False)
except FileNotFoundError:
it = RifeInterpolator(w, h, model, scale, backend="torch")
estimated = True
it.load(frame)
it.prepare(0)
ms = _time_ticks(it) * (TRT_SPEEDUP if estimated else 1.0)
out[motion] = {"ms": round(ms, 2), "engine": engine, "estimated": estimated}
del it
torch.cuda.empty_cache()
return out
def time_dml(model: str, log: Callable[[str], None] = print) -> dict:
"""time_rife() for the DirectML engine (an AMD or Intel card; framegen/dml.py). Each tick waits for its frame
(it comes back to the CPU), so a plain clock times it, CPU<->GPU copies included, as a session has them."""
import torch
from .dml import DmlInterpolator
w, h = STREAM
frame = torch.randint(0, 256, (h, w, 3), dtype=torch.uint8)
out = {}
for motion, scale in (("full", 1.0), ("half", 0.5)):
log(f"timing the AI model at {motion} motion detail (DirectML)")
it = DmlInterpolator(w, h, model, scale)
it.load(frame)
it.prepare(0)
rounds = []
for r in range(7): # the first two let the card's clocks come up from idle
t0 = time.perf_counter()
for _ in range(12):
it.prepare(1)
it.interpolate(1, 0.5)
if r >= 2:
rounds.append((time.perf_counter() - t0) * 1000 / 12)
out[motion] = {"ms": round(sorted(rounds)[len(rounds) // 2], 2), "engine": "dml", "estimated": False}
del it
return out
def _time_ticks(it) -> float:
"""Median ms of one tick with a new real frame: prepare it (from `in_u8`) and draw the in-between frame."""
import torch
def tick() -> None:
it.prepare(1)
it.interpolate(1, 0.5)
start, end = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)
rounds = []
for r in range(7): # the first two let the card's clocks come up from idle
torch.cuda.synchronize()
start.record()
for _ in range(12):
tick()
end.record()
torch.cuda.synchronize()
if r >= 2:
rounds.append(start.elapsed_time(end) / 12)
return sorted(rounds)[len(rounds) // 2]
def time_vfg(log: Callable[[str], None] = print) -> dict:
"""NVIDIA VFG's time for the same tick at each quality, at 1080p: {"low"/"medium"/"high": {"ms"}}. The two
frames differ (a smooth pattern, moved), so it can't take a shortcut for a still picture. Stays on this PC."""
import torch
import torch.nn.functional as F
from .vfg import VfgInterpolator
w, h = STREAM
g = torch.Generator(device="cuda").manual_seed(1)
small = torch.randint(0, 256, (1, 3, h // 16, w // 16), dtype=torch.uint8, device="cuda", generator=g)
a = F.interpolate(small.float(), size=(h, w), mode="bilinear", align_corners=False).round().to(torch.uint8)
a = a[0].permute(1, 2, 0).contiguous()
b = torch.roll(a, shifts=(6, 14), dims=(0, 1))
out = {}
for q in ("low", "medium", "high"):
log(f"timing NVIDIA VFG at {q} quality")
it = VfgInterpolator(w, h, q)
it.load(a)
it.prepare(0)
it.load(b) # each tick then prepares b into slot 1: a -> b, every time
out[q] = {"ms": round(_time_ticks(it), 2)}
it.close()
del it
torch.cuda.empty_cache()
return out
def _fps(hz: int) -> str:
return BY_KEY["hz"].name(hz)
def recommend(current: dict, timing: dict, display: Display | None, *, gpu: str = "", trt: bool = False,
vsr: str | None = None, busy: int | None = None, vfg: dict | None = None, vfg_why: str = "") -> dict:
"""Settings for this PC. current: the settings now (Settings.values()); timing: time_rife()'s result; vsr: why
RTX VSR can't be used, or None if it can; busy: how busy the card was before the test (%); vfg: time_vfg()'s
result if NVIDIA VFG is set up, else None, with vfg_why saying why.
Returns {"settings": {key: value}, "reasons": {key: text}, "notes": [text]}; only frame generation and picture
settings are suggested, the rest are left as they are. NVIDIA VFG is suggested when it's set up and keeps up at
least as high a frame rate as RIFE: setting it up is the user's choice to use it."""
share = LAPTOP_SHARE if "laptop" in gpu.lower() else SHARE
speed = timing["half"]["ms"] / REF_HALF_MS # above 1 = slower than the card the numbers above come from
pixels = display.width * display.height if display else REF_PIXELS
enlarge = pixels > STREAM[0] * STREAM[1] * 1.05 # a 1080p display shows the stream as it is
fsr_ms = FSR_MS * speed * pixels / REF_PIXELS if enlarge else 0.0
rate = display.hz if display else 60
top = 120 if rate >= 119 else 90 if rate >= 89 else 60 # 119 = 119.88 Hz
def cost(motion: str) -> float:
return timing[motion]["ms"] + fsr_ms
def fits(hz: int, motion: str) -> bool:
return cost(motion) <= share * 1000 / hz
hz, motion = next(((h, m) for h, m in OPTIONS if h <= top and fits(h, m)), (60, "half"))
settings, reasons, notes = {}, {}, []
# ---- model: NVIDIA VFG at the highest frame rate it keeps up with, then its most careful quality that fits
def vfg_fits(h: int, q: str) -> bool:
return vfg[q]["ms"] + fsr_ms <= share * 1000 / h
rife = BY_KEY["model"].default
vfg_pick = next(((h, q) for h in (120, 90, 60) if h <= top for q in VFG_QUALITIES if vfg_fits(h, q)),
None) if vfg else None
if vfg_pick is not None and vfg_pick[0] >= hz:
return _recommend_vfg(vfg_pick, vfg, hz, settings, reasons, notes, current=current, rate=rate, top=top,
share=share, fsr_ms=fsr_ms, speed=speed, pixels=pixels, enlarge=enlarge, vsr=vsr,
display=display, busy=busy)
if vfg:
settings["model"] = rife
reasons["model"] = (f"NVIDIA VFG is set up, but it only keeps up at {_fps(vfg_pick[0])} on this graphics "
f"card, and RIFE at {_fps(hz)}." if vfg_pick else
f"NVIDIA VFG is set up, but it can't keep up at {_fps(60)} on this graphics card.")
elif current.get("model") == "vfg":
settings["model"] = rife
reasons["model"] = vfg_why or "NVIDIA VFG isn't set up on this PC."
tick = 1000 / hz
# ---- frame rate
settings["hz"] = hz
t = cost(motion)
if not fits(hz, motion):
reasons["hz"] = (f"Even 60 fps is tight on this graphics card: an in-between frame takes {t:.1f} ms, and "
f"60 fps leaves {tick:.1f} ms. Expect some frames to be shown twice.")
elif top == 60:
reasons["hz"] = f"Your display runs at {rate} Hz, so 60 fps is the most it can show."
elif hz == top:
reasons["hz"] = (f"Your display runs at {rate} Hz, and your graphics card draws an in-between frame in "
f"{t:.1f} ms, inside the {tick:.1f} ms each frame has at {_fps(hz)}.")
elif hz == 90 and motion == "full" and fits(120, "half"):
reasons["hz"] = ("120 fps would only fit with half motion detail on this graphics card. 90 fps keeps full "
"detail, and looked better in testing.")
else:
need = min(cost(m) for m in ("full", "half"))
reasons["hz"] = (f"At {_fps(top)} each frame has {1000 / top:.1f} ms, but your graphics card needs {need:.1f} "
f"ms for an in-between frame. {_fps(hz)} leaves it enough time.")
# ---- motion detail (run.py: Auto is half at 120 fps for a stream up to 1440p, full otherwise)
auto_motion = "half" if hz == 120 else "full"
settings["motion"] = "auto" if motion == auto_motion else motion
if motion == "half" and hz < 120:
reasons["motion"] = (f"Half detail takes {timing['half']['ms']:.1f} ms instead of {timing['full']['ms']:.1f}, "
f"which is what lets {_fps(hz)} keep up on this graphics card.")
elif motion == "full" and hz == 120:
reasons["motion"] = (f"This graphics card is fast enough for full detail even at 120 fps "
f"({timing['full']['ms']:.1f} ms of {tick:.1f}).")
elif hz == 120:
reasons["motion"] = "Auto uses half detail at 120 fps, which this graphics card needs."
else:
reasons["motion"] = "Auto uses full detail here: the sharpest on fast motion."
# ---- engine
settings["engine"] = "auto"
if timing["full"].get("engine") == "dml":
reasons["engine"] = ("Without an NVIDIA card, RIFE runs through DirectML (Experimental). It's slower than "
"on an NVIDIA card of the same speed, and hasn't been tried with a game on AMD or Intel "
"graphics yet: Send feedback on the Help page says how it went.")
elif trt:
reasons["engine"] = ("TensorRT is installed. Auto uses it at full motion detail and PyTorch at half: the "
"faster of the two for each.")
else:
reasons["engine"] = ("TensorRT isn't installed, so Auto uses PyTorch, about 12% slower at full motion "
"detail. Repair SmoovPlay, on the Help page, puts it back.")
if timing["full"].get("estimated"):
notes.append("TensorRT hasn't been set up for this graphics card yet, so its speed is estimated. It does "
"that the first time you play, in a minute or two.")
_upscaler(settings, reasons, current=current, hz=hz, left=share * tick - timing[motion]["ms"], fsr_ms=fsr_ms,
speed=speed, pixels=pixels, enlarge=enlarge, vsr=vsr, display=display)
_notes(notes, settings, display=display, hz=hz, rate=rate, share=share, busy=busy)
return {"settings": settings, "reasons": reasons, "notes": notes}
def _recommend_vfg(pick: tuple, vfg: dict, rife_hz: int, settings: dict, reasons: dict, notes: list, *, current: dict,
rate: int, top: int, share: float, fsr_ms: float, speed: float, pixels: int, enlarge: bool,
vsr: str | None, display: Display | None, busy: int | None) -> dict:
"""recommend(), when NVIDIA VFG is the pick. RIFE's engine and motion detail aren't used, so not suggested."""
hz, q = pick
tick, name, t = 1000 / hz, BY_KEY["vfg_quality"].name(q), vfg[q]["ms"] + fsr_ms
settings["model"], settings["vfg_quality"], settings["hz"] = "vfg", q, hz
reasons["model"] = ("NVIDIA VFG is set up on this PC and keeps up at " + _fps(hz)
+ (", like RIFE." if rife_hz == hz else f", where RIFE keeps up at {_fps(rife_hz)}."))
if top == 60:
reasons["hz"] = f"Your display runs at {rate} Hz, so 60 fps is the most it can show."
elif hz == top:
reasons["hz"] = (f"Your display runs at {rate} Hz, and NVIDIA VFG draws an in-between frame in {t:.1f} ms at "
f"{name} quality, inside the {tick:.1f} ms each frame has at {_fps(hz)}.")
else:
need = vfg["low"]["ms"] + fsr_ms
reasons["hz"] = (f"At {_fps(top)} each frame has {1000 / top:.1f} ms, but NVIDIA VFG needs {need:.1f} ms for "
f"an in-between frame even at Low quality. {_fps(hz)} leaves it enough time.")
better = [x for x in VFG_QUALITIES[:VFG_QUALITIES.index(q)]]
reasons["vfg_quality"] = (f"{name} is the most careful quality with time to spare at {_fps(hz)}" +
(f": {BY_KEY['vfg_quality'].name(better[-1])} takes {vfg[better[-1]]['ms']:.1f} ms."
if better else "."))
_upscaler(settings, reasons, current=current, hz=hz, left=share * tick - vfg[q]["ms"], fsr_ms=fsr_ms,
speed=speed, pixels=pixels, enlarge=enlarge, vsr=vsr, display=display)
_notes(notes, settings, display=display, hz=hz, rate=rate, share=share, busy=busy)
return {"settings": settings, "reasons": reasons, "notes": notes}
def _upscaler(settings: dict, reasons: dict, *, current: dict, hz: int, left: float, fsr_ms: float, speed: float,
pixels: int, enlarge: bool, vsr: str | None, display: Display | None) -> None:
"""AMD FSR 1, unless RTX VSR is picked and still fits in what frame generation leaves (`left` ms)."""
def vsr_ms(q: int) -> float:
return VSR_MS[q] * speed * pixels / REF_PIXELS
size = f"{display.width}×{display.height}" if display else "your display"
if current.get("scaler") == "vsr" and vsr is None and enlarge:
q = next((q for q in (4, 3, 2, 1) if vsr_ms(q) <= left), None)
if q is not None:
settings["scaler"], settings["vsr_quality"] = "vsr", q
reasons["scaler"] = (f"RTX VSR, as you picked: it fits alongside {_fps(hz)} "
f"(about {vsr_ms(q):.1f} ms a frame at {size}).")
reasons["vsr_quality"] = (f"{BY_KEY['vsr_quality'].name(q)} is the highest quality with time to spare at "
f"{_fps(hz)}.")
else:
settings["scaler"] = "fsr"
room = f"more than {_fps(hz)} leaves ({left:.1f} ms)" if left >= 0.1 else f"and {_fps(hz)} leaves no time for it"
reasons["scaler"] = (f"RTX VSR needs about {vsr_ms(1):.1f} ms a frame at {size}, {room}. AMD FSR 1 looked "
"about the same in testing and takes about 0.1 ms.")
else:
settings["scaler"] = "fsr"
if current.get("scaler") == "vsr":
reasons["scaler"] = (f"RTX VSR isn't set up on this PC ({vsr})." if vsr else
f"Your display is {size}, the stream's own size, so there's nothing for RTX VSR to "
"enlarge. AMD FSR 1 is the lightest.")
elif not enlarge:
reasons["scaler"] = (f"Your display is {size}, the stream's own size, so the picture is hardly "
"enlarged. AMD FSR 1 is the lightest and plenty.")
else:
reasons["scaler"] = (f"Sharp and almost free: about {max(fsr_ms, 0.05):.1f} ms a frame at {size}. RTX VSR "
"looked about the same in testing and takes far longer.")
def _notes(notes: list, settings: dict, *, display: Display | None, hz: int, rate: int, share: float,
busy: int | None) -> None:
if display is None:
notes.append("Couldn't read the display's refresh rate, so this assumes 60 Hz.")
elif display.max_hz > display.hz + 5:
notes.append(f"Your display can run at {display.max_hz} Hz, but Windows has it at {display.hz} Hz. Raise it "
"(Windows Settings > System > Display > Advanced display), then run Auto-detect again for a "
"smoother frame rate.")
if display is not None and hz > 60 and rate % hz > 2 and hz - rate % hz > 2:
notes.append(f"{_fps(hz)} doesn't divide evenly into your display's {rate} Hz, so keep G-Sync or FreeSync "
"on (most fast displays have one) for even motion.")
if share == LAPTOP_SHARE:
notes.append("Laptop graphics slow down as they warm up, so this leaves extra room.")
if busy is not None and busy >= 30:
notes.append(f"Your graphics card was already {busy}% busy, so the test may have run slow. Close games and "
"video apps, then run it again.")
for k, v in settings.items():
assert v in BY_KEY[k].choices, (k, v)
def detect(current: dict, log: Callable[[str], None] = print, timing: dict | None = None,
vfg: dict | None = None) -> dict:
"""The whole test: what was found ("found": label/value/detail rows for the launcher) plus recommend()'s result.
timing, vfg: use these times instead of timing RIFE and NVIDIA VFG (for testing the launcher without loading the
graphics card). With timing but no vfg, VFG isn't timed or suggested."""
log("reading the display")
display = primary_display()
smi = nvidia_smi()
log("starting the graphics card")
import torch
dml_mode = not torch.cuda.is_available()
if dml_mode: # an AMD or Intel card: RIFE through DirectML (framegen/dml.py, Experimental)
from . import dml
why = dml.unavailable_reason()
if why:
raise RuntimeError(f"no NVIDIA card PyTorch can use, and DirectML can't run here either ({why})")
adapter = dml.pick_adapter()
gpu, vram = adapter["name"], adapter["vram_gb"]
else:
gpu = torch.cuda.get_device_name(0)
vram = torch.cuda.get_device_properties(0).total_memory / 2**30
from .rtxvsr import unavailable_reason
from .trt import trt_available
from .vfg import vfg_unavailable
trt, vsr = trt_available(), unavailable_reason()
if dml_mode:
trt, vsr = False, "it needs an NVIDIA RTX card"
vfg_why = "" if vfg is not None else vfg_unavailable()
model = current.get("model", BY_KEY["model"].default)
model = BY_KEY["model"].default if model == "vfg" else model
testing = timing is not None
if timing is None:
timing = time_dml(model, log) if dml_mode else time_rife(model, log)
if vfg is None and not vfg_why and not testing:
try:
vfg = time_vfg(log)
except Exception as e: # noqa: BLE001 - a broken VFG install mustn't stop the rest of the test
vfg_why = f"NVIDIA VFG couldn't start: {str(e)[:160]}"
log(vfg_why)
log("choosing settings")
result = recommend(current, timing, display, gpu=gpu, trt=trt, vsr=vsr, busy=smi.get("busy"), vfg=vfg,
vfg_why=vfg_why)
name = gpu.replace("NVIDIA ", "").replace("GeForce ", "")
engines = {"trt": "TensorRT", "torch": "PyTorch", "dml": "DirectML (Experimental)"}
full, half = timing["full"], timing["half"]
result["found"] = [
{"label": "Graphics card", "value": f"{name}, {vram:.0f} GB",
"detail": f"Driver {smi['driver']}" if smi.get("driver") else ""},
{"label": "AI speed", "value": f"{full['ms']:.1f} ms per in-between frame",
"detail": f"Full motion detail, {engines[full['engine']]}{' (estimated)' if full['estimated'] else ''}. "
f"Half: {half['ms']:.1f} ms, {engines[half['engine']]}."},
{"label": "Display", "value": f"{display.width}×{display.height} at {display.hz} Hz" if display else "Unknown",
"detail": f"Can run at {display.max_hz} Hz" if display and display.max_hz > display.hz + 5 else ""},
{"label": "TensorRT", "value": "NVIDIA cards only" if dml_mode else "Installed" if trt else "Not installed",
"detail": ""},
{"label": "RTX VSR", "value": "NVIDIA cards only" if dml_mode else "Ready" if vsr is None else "Not set up",
"detail": ""},
]
if vfg: # on this PC's Settings page only (NVIDIA's licence: VFG's results aren't for publishing)
result["found"].append({"label": "NVIDIA VFG", "value": f"{vfg['medium']['ms']:.1f} ms per in-between frame",
"detail": f"Medium quality. Low: {vfg['low']['ms']:.1f} ms, "
f"High: {vfg['high']['ms']:.1f} ms."})
else:
from .vfg import NOT_SET_UP
result["found"].append({"label": "NVIDIA VFG",
"value": "Set up" if not vfg_why else "Not set up" if vfg_why == NOT_SET_UP
else "Not available",
"detail": "" if not vfg_why else "Optional: see Interpolation model, below."
if vfg_why == NOT_SET_UP else vfg_why})
result["timing"] = timing
result["vfg_timing"] = vfg
result["busy"] = smi.get("busy")
return result
def main(argv: list[str] | None = None) -> int:
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--apply", action="store_true", help="save the suggested settings")
ap.add_argument("--if-new", action="store_true", help="only if there's no settings file yet")
ap.add_argument("--settings", type=Path, default=DEFAULT_PATH, help=f"settings file (default {DEFAULT_PATH})")
ap.add_argument("--timing", metavar="FULL,HALF", help="for testing: use these ms instead of timing the AI model")
ap.add_argument("--vfg-timing", metavar="LOW,MEDIUM,HIGH",
help="for testing: NVIDIA VFG's ms (as if it's set up) instead of timing it")
a = ap.parse_args(argv)
if a.if_new and a.settings.exists():
print("[detect] settings already saved, so they're left as they are", flush=True)
return 0
settings = Settings.load(a.settings)
try:
timing = None
if a.timing:
from .trt import auto_engine
full, half = (float(x) for x in a.timing.split(","))
timing = {"full": {"ms": full, "engine": auto_engine(1.0), "estimated": False},
"half": {"ms": half, "engine": "torch", "estimated": False}}
vfg = None
if a.vfg_timing:
vfg = {q: {"ms": float(x)} for q, x in zip(("low", "medium", "high"), a.vfg_timing.split(","))}
result = detect(settings.values(), log=lambda m: print(f"[detect] {m}", flush=True), timing=timing, vfg=vfg)
except RuntimeError as e:
print(f"[detect] ERROR: {e}", flush=True)
return 2
print(PREFIX + json.dumps(result), flush=True) # ASCII (\u escapes), whatever the console's code page
if a.apply and a.if_new and (result.get("busy") or 0) >= 30:
# Setup: suggestions from a busy card would be too low, and nobody is looking at them. The defaults stay.
print(f"[detect] the graphics card was {result['busy']}% busy, so nothing was saved", flush=True)
elif a.apply:
for k, v in result["settings"].items():
settings.set(k, v)
print(f"[detect] saved to {a.settings}", flush=True)
return 0
if __name__ == "__main__":
sys.exit(main())
+381
View File
@@ -0,0 +1,381 @@
"""Duplicate-frame detection and output scheduling for a 60 Hz signal carrying 30 fps content.
A console's video (PS5 Remote Play or HDMI) runs at 60 Hz, so a 30 fps game arrives as A A B B C C ...
(each real frame scanned out twice). At 60 Hz output we emit, one tick behind the input:
input : A A B B C C
output: A A mid(A,B) B mid(B,C) C
i.e. on the tick a new frame arrives we show the midpoint between it and the previous
real frame, and on its duplicate tick we show the real frame itself. Net added delay is
one 60 Hz tick (~16.7 ms) plus processing time. At 90 and 120 Hz, two or three frames are drawn between each pair
(see pipeline.py).
The scheduler also has to handle the cadence breaking:
* game hitch (A A A B B): the extra duplicate is just shown again.
* real 60 fps content (menus, some cutscenes: A B C D): two new frames in a row, so
we pass frames through one tick late instead of interpolating.
* scene cut: interpolating across a cut produces a ghosted blend, so hold instead.
"""
from __future__ import annotations
import math
from collections import deque
from dataclasses import dataclass
from enum import Enum
import torch
import torch.nn.functional as F
class Action(Enum):
INTERP = "interp" # show midpoint(prev real, current)
CURRENT = "current" # show the incoming frame as-is
PENDING = "pending" # show the previous new frame (not yet displayed), current becomes pending
HOLD = "hold" # show the previous real frame again (scene cut)
@dataclass
class CutFeatures:
"""How differently two frames are *built*, whatever their brightness: for cuts between dark shots, where the
plain difference stays small."""
corr_dist: float # 1 - correlation of the two frames' block brightness, 0 (same layout) .. 2 (inverted)
hist_dist: float # half the L1 distance between brightness histograms, 0 (same) .. 1 (no overlap)
luma: float # this frame's mean brightness, 0..255
contrast: float # this frame's brightness standard deviation over blocks, 0..255
@dataclass
class FrameDiff:
is_new: bool
max_diff: float # max 16x16 block-mean difference, 0..255
mean_diff: float # mean absolute difference over blocks, 0..255
cut: CutFeatures | None = None # None on the first frame
_LUMA = torch.tensor([0.114, 0.587, 0.299]).view(1, 3, 1, 1) # BGR -> Y (BT.601)
HIST_BINS = 32
def _cut_stats(prev: torch.Tensor, cur: torch.Tensor) -> torch.Tensor:
"""CutFeatures' four numbers as one tensor (no device sync), from two (1, 3, h, w) BGR block-mean images."""
w = _LUMA.to(cur.device)
yp, yc = (prev * w).sum(1).flatten(), (cur * w).sum(1).flatten()
dp, dc = yp - yp.mean(), yc - yc.mean()
sp, sc = dp.square().mean().sqrt(), dc.square().mean().sqrt()
# Correlation is undefined for a flat frame (a black screen); call two flat frames alike, and a flat frame
# next to a detailed one fully different.
denom = (sp * sc).clamp_min(1e-6)
corr = (dp * dc).mean() / denom
flat = (sp < 1.0) | (sc < 1.0)
corr = torch.where(flat, ((sp < 1.0) & (sc < 1.0)).float(), corr)
hp = torch.histc(yp, HIST_BINS, 0, 255) / yp.numel()
hc = torch.histc(yc, HIST_BINS, 0, 255) / yc.numel()
return torch.stack([1 - corr, 0.5 * (hp - hc).abs().sum(), yc.mean(), sc])
def cut_features(prev: torch.Tensor, cur: torch.Tensor) -> CutFeatures:
return CutFeatures(*_cut_stats(prev, cur).tolist())
class DuplicateDetector:
"""Classifies each incoming frame as new content or a repeat of the previous one.
Compares 16x16 block means rather than raw pixels: block averaging suppresses
per-pixel capture noise, while the max over blocks still catches small, local
motion (a character moving on a static background barely moves a global mean).
Over a digital HDMI capture, repeats are normally bit-identical (max_diff == 0).
reference: what each frame is compared with. "previous": the frame before it. "new": the last frame found
to be new content, so a slow change that stays under the threshold from one frame to the next still adds up
and is caught (for capture cards, where a little noise can hide a small real change).
learn: for a window captured from an app that decodes its own stream (window capture), whose repeats are never
quite identical, so a fixed threshold calls most of them new. It watches the last LEARN_N mean differences: when
they fall in two bands (repeats and new frames: the top fifth over LEARN_RATIO times the bottom fifth), the line
between them is their geometric mean; otherwise the fixed rule. On a decoded 30 fps stream it agreed with the
stream's own repeat flags 99% of the time, against 50% for the fixed rule.
With learn, it also keeps to the game's rhythm: once the last RHYTHM_N calls follow one exactly (new every 2nd
frame for a 30 fps game, every 3rd for 20 fps), a frame whose difference is close to the line (less than SURE of
the way, in log terms, from the line to the other band) is called as the rhythm says. A clear exception (a
hitch, a cut to a 60 fps menu) drops the rhythm, as does losing the two bands; it's found again after
RHYTHM_N steady frames. `held` counts the calls the rhythm made.
"""
LEARN_N, LEARN_MIN, LEARN_RATIO = 16, 8, 4.0
RHYTHM_N, RHYTHM_PERIODS, SURE = 24, (2, 3), 0.5
def __init__(self, threshold: float = 2.0, block: int = 16, reference: str = "previous",
learn: bool = False) -> None:
if reference not in ("previous", "new"):
raise ValueError(f"reference: {reference!r}")
self.threshold = threshold
self.block = block
self.reference = reference
self.learn = learn
self._means: deque = deque(maxlen=self.LEARN_N)
self._prev: torch.Tensor | None = None
self._calls: deque = deque(maxlen=self.RHYTHM_N) # the last calls, oldest first
self.rhythm: tuple[int, int] | None = None # (period, where the next new frame falls in it), once steady
self.held = 0
def _learned(self, mean: float) -> tuple[bool, float] | None:
"""The two-band rule's call on a frame's mean difference and how sure it is (0 on the line, 1 at a band's
middle), or None when the recent frames don't show two bands."""
if len(self._means) < self.LEARN_MIN:
return None
xs = sorted(self._means)
lo = max(xs[round(0.2 * (len(xs) - 1))], 1e-3)
hi = xs[round(0.8 * (len(xs) - 1))]
if hi <= self.LEARN_RATIO * lo:
return None
line = math.sqrt(lo * hi)
return mean > line, abs(math.log(max(mean, 1e-6) / line)) / math.log(hi / line)
def _keep_rhythm(self, is_new: bool, sure: float | None) -> bool:
"""The call after the game's rhythm has had its say (learn only), and the rhythm brought up to date."""
if self.rhythm is not None:
period, phase = self.rhythm
expected = phase == 0
if sure is None or (expected != is_new and sure >= self.SURE):
self.rhythm = None # no bands, or a clear exception: listen to the pictures alone for a while
self._calls.clear()
else:
if expected != is_new:
self.held += 1
is_new = expected
self.rhythm = (period, (phase + 1) % period)
self._calls.append(is_new)
if self.rhythm is None and sure is not None and len(self._calls) == self.RHYTHM_N:
calls = list(self._calls)
for period in self.RHYTHM_PERIODS:
first = calls.index(True) if True in calls else -1
if 0 <= first < period and all(c == ((i - first) % period == 0) for i, c in enumerate(calls)):
self.rhythm = (period, (len(calls) - first) % period)
break
return is_new
@torch.no_grad()
def update(self, frame_u8: torch.Tensor) -> FrameDiff:
x = frame_u8.permute(2, 0, 1).unsqueeze(0).float()
small = F.avg_pool2d(x, self.block, ceil_mode=True)
if self._prev is None:
self._prev = small
return FrameDiff(True, float("inf"), float("inf"))
d = (small - self._prev).abs_()
stats = torch.cat([torch.stack([d.amax(), d.mean()]), _cut_stats(self._prev, small)]).tolist() # one sync
is_new = stats[0] > self.threshold
if self.learn:
learned = self._learned(stats[1])
self._means.append(stats[1])
if learned is not None:
is_new = learned[0]
is_new = self._keep_rhythm(is_new, learned[1] if learned is not None else None)
if is_new or self.reference == "previous":
self._prev = small
return FrameDiff(is_new, stats[0], stats[1], CutFeatures(*stats[2:]))
class CutDetector:
"""Flags scene cuts among *new* frames, where interpolating would ghost two shots together.
Like ffmpeg's scdet, a cut must be both large and a sudden jump over the previous new
frame's change: fast-but-continuous motion has consistently large diffs and doesn't
trigger. Tuned on a 30 fps trailer that cuts every ~3 s (catches 53/53 cuts ffmpeg finds) against gameplay
clips (0-3 holds per 600 frames, only on camera-through-geometry moments).
"""
# A second test, on how the picture is built rather than how much it changed, catches cuts between two dark
# shots: their plain difference stays small, but the layout of light and dark changes completely. Like the
# first test it needs a sudden jump, so a fast camera turn (consistently changing layout) isn't a cut.
STRUCTURE = 0.75 # corr_dist jump that marks a cut (tuned with scripts/cut_eval.py)
MIN_DIFF = 6.0 # ...when the frame also changed at least this much (mean_diff), so noise alone never cuts
def __init__(self, threshold: float = 25.0, use_structure: bool = True) -> None:
self.threshold = threshold
self.use_structure = use_structure
self.prev = 0.0
self.prev_corr = 0.0
def update(self, mean_diff: float, f: CutFeatures | None = None) -> bool:
score = min(mean_diff, mean_diff - self.prev)
self.prev = mean_diff
cut = score > self.threshold
if self.use_structure and f is not None:
jump = min(f.corr_dist, f.corr_dist - self.prev_corr)
self.prev_corr = f.corr_dist
cut = cut or (jump > self.STRUCTURE and mean_diff > self.MIN_DIFF)
return cut
class CadenceScheduler:
"""Pure state machine: (is_new, is_cut) per tick -> Action."""
def __init__(self) -> None:
self.started = False
self.pending = False # a new frame has been received but not yet displayed as itself
def step(self, is_new: bool, is_cut: bool = False) -> Action:
if not is_new:
self.pending = False
return Action.CURRENT # duplicate of the latest real frame
if not self.started:
self.started = True
return Action.CURRENT
if self.pending:
return Action.PENDING # back-to-back new frames: source is >30 fps here
self.pending = True
return Action.HOLD if is_cut else Action.INTERP
UNEVEN_ON = (39, 56) # new frames in the last second at which the even timing below switches on...
UNEVEN_OFF = (35, 58) # ...and outside which it switches off again
UNEVEN_DWELL = 60 # ticks (a second) the rate has to stay there first, so a 30 fps game's 60 fps menu doesn't
# flip it on and off
UNEVEN_MAX_DELAY = 2.0 # ticks
@dataclass
class TimedFrame:
"""A new frame on the timeline: its time in the game (ticks, see FrameTimeline), the tick it arrived on, whether
a scene cut (or a damaged frame) comes just before it, and the pipeline's own: the frame and its arrival time."""
id: int
t: float
arrival: int
cut: bool = False
frame: object = None
t_arrival: float = 0.0
reached: bool = False # its time has come on screen
@dataclass
class Place:
"""What to show at one display time: frame `a` itself, or (`b` not None) the frame at fraction t from a to b.
c: the game time shown. reached: frames whose time came with this one (for the delay stats)."""
a: TimedFrame
b: TimedFrame | None = None
t: float = 0.0
c: float = 0.0
reached: tuple = ()
waiting: bool = False # the game time shown is past the newest frame: the next one is late
class FrameTimeline:
"""Even timing for games whose frame rate is neither 30 nor 60: about 40 to 60 fps, as in unlocked "performance"
modes with VRR off. CadenceScheduler keeps working for 30 fps games; the pipeline uses this while `uneven`.
At 60 Hz such a game's frames arrive unevenly. At 45 fps it's new, repeat, new, new, new, repeat, ..., so frames
stay on screen for one tick or two and motion stutters. The game drew them evenly, though, and each one was
finished some time in the tick before it arrived. So the timeline gives each new frame a time in ticks: the last
one's plus the recent average spacing, kept within that tick. The pipeline then shows the game's time `delay`
ticks behind the display's (place()), drawing the in-between frame at the right fraction, so motion is even at
60, 90 or 120 fps.
The two frames either side of a display time can be older than the newest two (a frame can arrive while there's
still a frame to draw before the one before it), so the pipeline hands a frame to the interpolator only when
place() first asks for it. delay is the least that kept the game time shown from passing the newest frame over
the last dozen frames, so the next frame has nearly always arrived when it's needed.
"""
def __init__(self, k: int = 12) -> None:
self.n = -1 # ticks seen
self.frames: deque[TimedFrame] = deque() # the frame at or before the last game time shown, and later ones
self.delay = 1.0 # ticks between the display's time and the game time it shows
self.uneven = False
self._ids = 0
self._arrivals: deque = deque(maxlen=k + 1) # ticks at which the last few new frames arrived
self._need: deque = deque(maxlen=k) # for each of them: the least delay that would have waited for it
self._last: TimedFrame | None = None
self._recent: deque = deque(maxlen=60) # new (1) or repeat (0), over the last second
self._dwell = 0
self._hz, self._j = 0, 0 # slots(): the output rate, and the next output frame's number
@property
def period(self) -> float:
"""The recent average spacing of new frames, in ticks (a gap over 3 ticks, a hitch, counts as 3)."""
a = list(self._arrivals)
d = [min(3, y - x) for x, y in zip(a, a[1:])]
return sum(d) / len(d) if d else 1.0
def fps(self) -> int | None:
"""New frames in the last second (the last 60 ticks), or None until there's a second of them."""
return sum(self._recent) if len(self._recent) == self._recent.maxlen else None
def _want_delay(self) -> float:
return min(UNEVEN_MAX_DELAY, max(self._need, default=1.0) + 0.05)
def tick(self, is_new: bool, is_cut: bool = False, frame=None, t_arrival: float = 0.0) -> TimedFrame | None:
"""One tick of the stream; a new frame goes on the timeline (and is returned)."""
self.n += 1
self._recent.append(1 if is_new else 0)
added = None
if is_new:
self._arrivals.append(self.n)
last = self._last
if last is None:
t = float(self.n)
elif self.n - last.arrival > 3: # after a hitch: as it comes
t = max(self.n - 0.95, last.t + 0.05)
else:
# Finished in the tick before it arrived: (n - 1, n]. (The 0.05 keeps two frames' times apart.)
t = min(float(self.n), max(self.n - 0.95, last.t + self.period))
# Until it came (the tick before), the game time shown had to stay at or before the last frame's.
self._need.append(self.n - 1 - last.t)
added = TimedFrame(self._ids, t, self.n, is_cut, frame, t_arrival)
self._ids += 1
self.frames.append(added)
self._last = added
while len(self.frames) > 4: # (only when they come much faster than they're shown)
self.frames.popleft()
want = self._want_delay()
self.delay += (0.3 if want > self.delay else 0.05) * (want - self.delay)
fps = self.fps()
want_on = self.uneven
if fps is not None:
if UNEVEN_ON[0] <= fps <= UNEVEN_ON[1]:
want_on = True
elif fps <= UNEVEN_OFF[0] or fps >= UNEVEN_OFF[1]:
want_on = False
self._dwell = self._dwell + 1 if want_on != self.uneven else 0
if self._dwell >= UNEVEN_DWELL:
self.uneven, self._dwell = want_on, 0
if want_on:
self.delay = self._want_delay()
return added
def slots(self, hz: int) -> list[float]:
"""The display times (in ticks) of the output frames due this tick: one at 60 fps, one or two at 90, two
at 120."""
step = 60 / hz
if hz != self._hz or self._j * step <= self.n - 1: # a new rate, or not called for a while: start afresh
self._hz, self._j = hz, math.floor((self.n - 1) / step + 1e-9) + 1
out = []
while self._j * step <= self.n + 1e-9:
out.append(self._j * step)
self._j += 1
return out
def place(self, phi: float) -> Place | None:
"""What to show at display time phi (ticks); None before the first frame."""
c = phi - self.delay
fr = self.frames
if not fr:
return None
while len(fr) >= 2 and fr[1].t <= c: # frames whose time has passed (the last of them stays)
fr.popleft()
reached = tuple(f for f in fr if not f.reached and f.t <= c)
for f in reached:
f.reached = True
a = fr[0]
if len(fr) == 1 or c <= a.t:
return Place(a, c=c, reached=reached, waiting=len(fr) == 1 and c > a.t + 1e-6)
b = fr[1]
t = (c - a.t) / (b.t - a.t)
if b.cut or t < 0.04: # across a cut, the frame before it until the new one's time comes
return Place(a, c=c, reached=reached)
if t > 0.96:
return Place(b, c=c, reached=reached)
return Place(a, b, t, c, reached)
+610
View File
@@ -0,0 +1,610 @@
"""Capture cards (Experimental): a console's HDMI output through a capture card, read with FFmpeg's DirectShow input
(PyAV, already installed), so nothing extra to download.
How (research_notes/Expansion planning/sources.md, section 2):
- Raw frames. The card's own NV12 or YUY2, straight off USB with no decoding, timed by the card's clock. MJPEG
(compressed; most cheap cards offer it) only when the card has nothing else at the size and rate asked for: it's
decoded on the GPU (NVDEC) where it can be, else on the CPU, which can stutter.
- Converted to BGR on the GPU: one upload of the raw frame (3-4 MB at 1080p), then a few tensor operations, so the
pipeline gets CUDA frames as it does from Remote Play's GPU decoder, and RTX VSR works too. Without CUDA, OpenCV
converts on the CPU (BT.601, a slight colour shift on HD video).
- Colours: HDMI video is limited range (16-235) unless the card says it's full range; BT.709 at 720 lines and up,
BT.601 below, as video players assume.
- Sound: the card's own audio device, opened with the video (one DirectShow graph, so both are timed by the same
clock) and played on this PC through framegen/audio.py, held back to meet the picture. pick_audio() finds it by
name; --capture-audio names another, or "off".
Untested with real cards. Written from FFmpeg's documentation and source and other viewers' notes (NitLink, MIT;
CapturePlay and Veyra, GPL, ideas only), and tested with a raw video file standing in for a card
(tests/test_capture.py). The launcher marks capture cards Experimental.
python -m framegen.capture --list [--json] # the video and audio capture devices Windows has
python -m framegen.capture --formats NAME # what a device offers, and the format SmoovPlay would pick
"""
from __future__ import annotations
import argparse
import json
import queue
import re
import sys
import threading
import time
from collections import deque
from dataclasses import asdict, dataclass
import numpy as np
# Raw formats, best first: NV12 is the smallest uncompressed format (4:2:0), YUY2/UYVY are 4:2:2 (more USB bandwidth,
# same picture after 4:2:0 HDMI sources). Anything compressed comes after all of them, MJPEG last but one.
RAW_RANK = {"nv12": 0, "yuyv422": 1, "uyvy422": 2, "yuv420p": 3, "bgr24": 4, "bgr0": 4, "rgb24": 4}
COMPRESSED_RANK = {"mjpeg": 10}
BYTES_PER_PIXEL = {"nv12": 1.5, "yuv420p": 1.5, "yuyv422": 2, "uyvy422": 2, "bgr24": 3, "rgb24": 3, "bgr0": 4}
CONVERTIBLE = ("nv12", "yuyv422", "uyvy422") # converted here; anything else raw goes through PyAV's own conversion
@dataclass(frozen=True)
class Device:
name: str # what Windows calls it, and what to open it by
kind: str # "video", "audio" or "unknown" (a device whose type FFmpeg couldn't tell, e.g. a virtual camera that
# isn't running)
alt: str = "" # DirectShow's unique name, for when two devices share a name
@dataclass(frozen=True)
class Mode:
"""One way a device can send video, as DirectShow lists it."""
fmt: str # pixel format for raw video ("nv12", "yuyv422", ...), or the codec ("mjpeg", "h264")
raw: bool
w: int
h: int
fps_min: float
fps_max: float
range: str = "" # "tv" (limited) or "pc" (full) when the card says; "" when it doesn't
space: str = "" # colour matrix, when the card says ("bt709", "bt470bg", ...)
def label(self) -> str:
fps = f"{self.fps_max:g}" if abs(self.fps_max - self.fps_min) < 0.01 else f"{self.fps_min:g}-{self.fps_max:g}"
return f"{self.w}x{self.h} {fps} fps {self.fmt.upper() if not self.raw else self.fmt}"
# ----------------------------------------------------------------------------- what Windows has
def _dshow_log(url: str, options: dict) -> str:
"""FFmpeg's DirectShow listings come out in its log, not as data: open with a listing option and read the log."""
import av
import av.logging
old = av.logging.get_level()
av.logging.set_level(av.logging.INFO)
try:
with av.logging.Capture() as logs:
try:
av.open(url, format="dshow", options=options).close()
except Exception: # noqa: BLE001 - a listing always "fails": FFmpeg exits after printing it
pass
finally:
av.logging.set_level(old)
return "".join(msg for _, name, msg in logs if name == "dshow")
def parse_devices(text: str) -> list[Device]:
"""Devices from `-list_devices true` output. FFmpeg 5+ tags each device '"Name" (video)'; older versions put
them under "DirectShow video devices" / "DirectShow audio devices" headings. Both are read."""
out: list[Device] = []
heading = "unknown"
for line in text.splitlines():
line = re.sub(r"^\[dshow @ [0-9A-Fa-fx]+\]\s?", "", line)
if "DirectShow video devices" in line:
heading = "video"
elif "DirectShow audio devices" in line:
heading = "audio"
elif m := re.match(r'\s*Alternative name "(.*)"\s*$', line):
if out:
out[-1] = Device(out[-1].name, out[-1].kind, m.group(1))
elif m := re.match(r'\s*"(.*)"\s*(?:\((video|audio|none|video,audio|audio,video)\))?\s*$', line):
kind = m.group(2) or heading
kind = {"none": "unknown", "video,audio": "video", "audio,video": "video"}.get(kind, kind)
out.append(Device(m.group(1), kind))
return out
def list_devices() -> list[Device]:
return parse_devices(_dshow_log("dummy", {"list_devices": "true"}))
# Words in device names that say nothing about which card it is.
_GENERIC = {"usb", "usb2", "usb3", "audio", "video", "capture", "device", "digital", "interface", "input", "hdmi",
"line", "microphone", "mic", "camera", "webcam", "stream", "streaming", "game", "high", "definition",
"the", "and", "for", "with", "pro", "plus"}
def _words(name: str) -> set[str]:
return {w for w in re.findall(r"[a-z0-9]+", name.lower()) if len(w) >= 3 and w not in _GENERIC}
def pick_audio(video: str, devices: list[Device]) -> str | None:
"""The capture card's own sound device: one named like the video device (e.g. "USB3.0 Capture" and "Digital
Audio Interface (USB3.0 Capture)", or "Cam Link 4K" for both), else None. A device whose name says nothing (only
generic words) matches only on the whole name."""
audio = [d.name for d in devices if d.kind == "audio"]
v = video.lower().strip()
whole = [a for a in audio if v and (v in a.lower() or a.lower() in v)]
if whole:
return min(whole, key=len)
vw = _words(video)
scored = [(len(vw & _words(a)), a) for a in audio]
best = max(scored, default=(0, None))
return best[1] if best[0] > 0 and sum(n == best[0] for n, _ in scored) == 1 else None
_MODE = re.compile(r"(?:pixel_format=(?P<pix>\S+)|vcodec=(?P<codec>\S+))\s+"
r"min s=(?P<w0>\d+)x(?P<h0>\d+) fps=(?P<f0>[\d.e+-]+)\s+"
r"max s=(?P<w1>\d+)x(?P<h1>\d+) fps=(?P<f1>[\d.e+-]+)"
r"(?:\s*\((?P<color>[^)]*)\))?")
def parse_modes(text: str) -> list[Mode]:
"""Video modes from `-list_options true` output, e.g.
pixel_format=nv12 min s=1920x1080 fps=60 max s=1920x1080 fps=60 (tv, bt709/bt709/bt709, topleft)
vcodec=mjpeg min s=1920x1080 fps=30 max s=1920x1080 fps=60
Each line becomes one Mode at its largest size (cards list one line per size). Duplicates are dropped."""
modes: list[Mode] = []
for m in _MODE.finditer(text):
raw = m.group("pix") is not None
rng = space = ""
if m.group("color"):
parts = [p.strip() for p in m.group("color").split(",")]
rng = parts[0] if parts and parts[0] in ("tv", "pc") else ""
if len(parts) > 1:
space = parts[1].split("/")[0]
space = "" if space == "unknown" else space
mode = Mode(m.group("pix") or m.group("codec"), raw, int(m.group("w1")), int(m.group("h1")),
float(m.group("f0")), float(m.group("f1")), rng, space)
if mode not in modes:
modes.append(mode)
return modes
def list_modes(device: str) -> list[Mode]:
return parse_modes(_dshow_log(f"video={device}", {"list_options": "true"}))
def pick_mode(modes: list[Mode], w: int = 1920, h: int = 1080, fps: float = 60.0) -> tuple[Mode | None, str]:
"""The mode to ask for, and a note for the log when it isn't what we'd want ("" when it is).
The size asked for if the card has it (else the largest at or under it, else the smallest), at a rate that
reaches `fps` if possible, in the best format: raw before compressed, NV12 first."""
if not modes:
return None, "the card listed no video formats"
usable = [m for m in modes if m.fmt in RAW_RANK or m.fmt in COMPRESSED_RANK]
if not usable:
return None, "the card offers no format SmoovPlay can read (" + ", ".join(sorted({m.fmt for m in modes})) + ")"
sizes = {(m.w, m.h) for m in usable}
if (w, h) in sizes:
size = (w, h)
else:
under = [s for s in sizes if s[0] <= w and s[1] <= h]
size = max(under, key=lambda s: s[0] * s[1]) if under else min(sizes, key=lambda s: s[0] * s[1])
at = [m for m in usable if (m.w, m.h) == size]
fast = [m for m in at if m.fps_max >= fps - 0.5]
pool = fast or at
best = min(pool, key=lambda m: (RAW_RANK.get(m.fmt, COMPRESSED_RANK.get(m.fmt, 99)), -m.fps_max))
notes = []
if size != (w, h):
notes.append(f"no {w}x{h} mode, using {size[0]}x{size[1]}")
if not fast:
notes.append(f"no mode reaches {fps:g} fps at that size (best {best.fps_max:g})")
if not best.raw:
notes.append(f"only {best.fmt.upper()} (compressed) at that size and rate: decoded on the GPU where it can be")
return best, "; ".join(notes)
def open_options(mode: Mode, fps: float = 60.0, queue_frames: int = 4) -> dict:
"""av.open options for a mode. rtbufsize caps DirectShow's own queue at a few frames: it only fills when we fall
behind, and frames dropped there are counted by FFmpeg ("real-time buffer too full")."""
rate = min(fps, mode.fps_max) if mode.fps_max >= fps - 0.5 else mode.fps_max
opts = {"video_size": f"{mode.w}x{mode.h}", "framerate": f"{rate:g}",
"rtbufsize": str(int(mode.w * mode.h * BYTES_PER_PIXEL.get(mode.fmt, 3) * queue_frames))}
opts["pixel_format" if mode.raw else "vcodec"] = mode.fmt
return opts
# ----------------------------------------------------------------------------- colour conversion
def ycbcr_to_bgr(y, u, v, bt709: bool, full_range: bool):
"""Full-resolution Y, Cb, Cr (float tensors, 0-255 scale) -> HxWx3 uint8 BGR, on whatever device they're on.
The same maths as framegen.chiaki_tap.cuda_frame_to_bgr (FFmpeg's)."""
import torch
kr, kb = (0.2126, 0.0722) if bt709 else (0.299, 0.114)
kg = 1.0 - kr - kb
ys, yo, cs = (1.0, 0.0, 1.0) if full_range else (255 / 219, 16.0, 255 / 224)
lum = (y - yo) * ys
u, v = (u - 128.0) * cs, (v - 128.0) * cs
b = lum + 2 * (1 - kb) * u
g = lum - (2 * kb * (1 - kb) / kg) * u - (2 * kr * (1 - kr) / kg) * v
r = lum + 2 * (1 - kr) * v
return torch.stack([b, g, r], -1).clamp_(0, 255).round_().to(torch.uint8)
def raw_to_bgr(raw, fmt: str, w: int, h: int, bt709: bool, full_range: bool):
"""One raw frame (a flat uint8 tensor: NV12, YUY2 or UYVY) -> HxWx3 uint8 BGR tensor on the same device."""
import torch.nn.functional as F
def up(c): # chroma to full size (bilinear, as FFmpeg's default scaler does near enough)
return F.interpolate(c[None, None].float(), size=(h, w), mode="bilinear", align_corners=False)[0, 0]
if fmt == "nv12":
y = raw[: w * h].view(h, w).float()
uv = raw[w * h: w * h * 3 // 2].view(h // 2, w // 2, 2)
return ycbcr_to_bgr(y, up(uv[..., 0]), up(uv[..., 1]), bt709, full_range)
if fmt in ("yuyv422", "uyvy422"):
p = raw[: w * h * 2].view(h, w // 2, 4)
iy0, iu, iy1, iv = (0, 1, 2, 3) if fmt == "yuyv422" else (1, 0, 3, 2)
y = p[..., [iy0, iy1]].reshape(h, w).float()
return ycbcr_to_bgr(y, up(p[..., iu]), up(p[..., iv]), bt709, full_range)
raise ValueError(f"can't convert {fmt}")
def raw_to_bgr_cpu(raw: np.ndarray, fmt: str, w: int, h: int) -> np.ndarray:
"""The CPU fallback (no CUDA): OpenCV's converters, which are BT.601 limited range."""
import cv2
if fmt == "nv12":
return cv2.cvtColor(raw[: w * h * 3 // 2].reshape(h * 3 // 2, w), cv2.COLOR_YUV2BGR_NV12)
if fmt == "yuyv422":
return cv2.cvtColor(raw[: w * h * 2].reshape(h, w, 2), cv2.COLOR_YUV2BGR_YUY2)
if fmt == "uyvy422":
return cv2.cvtColor(raw[: w * h * 2].reshape(h, w, 2), cv2.COLOR_YUV2BGR_UYVY)
raise ValueError(f"can't convert {fmt}")
# ----------------------------------------------------------------------------- the source
class CardSource:
"""Frames from a capture card as Ticks: read on a thread and queued (not "latest only", which would break repeat
detection); when the pipeline falls behind, the oldest frame goes and is counted in `dropped`.
Open a card with CardSource.open(name). Two kinds of file stand in for one, played at their own rate from when
the pipeline starts reading: CardSource.raw_file(path, w, h, fmt, fps), raw frames read exactly as a card's are
(every line of the card path but the av.open call), and CardSource.video_file(path), any video, decoded and
turned into NV12 first. test: a framegen.sources.TestMode, applied before the queue.
device: "cuda" (default when there is CUDA), "cpu" (torch on the CPU, for tests) or None (numpy and OpenCV).
colour: "auto", or (bt709, full_range) to override.
audio: what plays the sound, if the container has any: audio(rate, channels) -> an object with push(pcm bytes),
set_delay(seconds) and close() (framegen.audio.Player; a fake in tests), or None for no sound.
"""
def __init__(self, container, name: str, live: bool, test=None, device: str | None = "auto",
colour="auto", range_hint: str = "", queue_size: int = 3, decode_to: str = "", audio=None) -> None:
from .sources import source_info
self.container, self.live, self.test = container, live, test
self.stream = container.streams.video[0]
self.astream = container.streams.audio[0] if audio is not None and container.streams.audio else None
self._audio_out, self.player, self._resampler = audio, None, None
self._audio_wait: list = [] # a file's sound, held until the picture gets to it: (time, pcm)
self._replay_sound: deque = deque(maxlen=2000) # the sound as it's played, for instant replay (read_sound)
# How late each stream arrives after its own timestamps (the same clock in one DirectShow graph), so the
# sound can be held back by the picture's delay less however much later it already comes.
self._late_v: list[float] = []
self._late_a: list[float] = []
cc = self.stream.codec_context
self.w, self.h = cc.width, cc.height
self.raw = cc.name == "rawvideo"
self.fmt = (cc.format.name if cc.format is not None else "") if self.raw else cc.name
self.decode_to = decode_to # a video file standing in: decoded, then sent on as raw frames of this format
if decode_to:
self.raw, self.fmt = True, decode_to
rate = self.stream.average_rate or self.stream.base_rate or self.stream.guessed_rate
self.fps = float(rate) if rate else 60.0
if device == "auto":
device = _cuda_device()
self.device = device
self.bt709, self.full_range = (self.h >= 720, range_hint == "pc") if colour == "auto" else colour
self.info = source_info("capture", hz=self.fps, name=name)
self.dropped = 0
self._stop = False
self._go = threading.Event()
self.q: queue.Queue = queue.Queue(maxsize=queue_size)
self._host = None # a reusable (pinned, with CUDA) buffer for raw frames on their way to the GPU
# MJPEG on the GPU: NVDEC decodes it and the frame stays there (as Remote Play's do). Made on the reader's
# thread, in PyTorch's CUDA context; if it fails, the CPU decodes instead.
self._gpu_jpeg = not self.raw and self.fmt == "mjpeg" and device == "cuda"
self._hw = None
how = (("GPU" if device == "cuda" else "CPU (torch)" if device else "CPU (OpenCV)")
if self.raw and self.fmt in CONVERTIBLE else "GPU (NVDEC)" if self._gpu_jpeg else "PyAV, CPU")
print(f"[capture] {name}: {self.w}x{self.h} {self.fmt} at {self.fps:g} fps; decoded and converted on {how}"
f" ({'BT.709' if self.bt709 else 'BT.601'}, {'full' if self.full_range else 'limited'} range)")
if not self.raw and not self._gpu_jpeg:
print(f"[capture] {self.fmt.upper()} is compressed: each frame is decoded on the CPU, which can stutter. "
"If the card offers NV12 or YUY2 at this size, that's better.")
if self.astream is not None:
cc = self.astream.codec_context
print(f"[capture] sound: {cc.sample_rate} Hz, {cc.channels} channel(s), played on this PC, held back to "
"meet the picture")
threading.Thread(target=self._reader, daemon=True, name="capture").start()
# ---- opening
@classmethod
def open(cls, device: str, w: int = 1920, h: int = 1080, fps: float = 60.0, mode: Mode | None = None,
audio_device: str | None = None, audio=None, **kw) -> "CardSource":
"""audio_device: the card's sound device (pick_audio), opened with the video; audio: what plays it."""
import av
note = ""
if mode is None:
mode, note = pick_mode(list_modes(device), w, h, fps)
if mode is None:
raise RuntimeError(f"capture card {device!r}: {note}")
if note:
print(f"[capture] {note}")
opts = open_options(mode, fps)
container = None
if audio_device and audio is not None:
try: # a small sound buffer: DirectShow's default is half a second or more
container = av.open(f"video={device}:audio={audio_device}", format="dshow",
options={**opts, "audio_buffer_size": "20"})
except Exception as e: # noqa: BLE001 - busy or gone: the picture on its own
print(f"[capture] couldn't open the sound device ({str(e)[:120]}); playing without sound")
if container is None:
container = av.open(f"video={device}", format="dshow", options=opts)
return cls(container, f"Capture card ({device})", live=True, range_hint=mode.range, audio=audio, **kw)
@classmethod
def raw_file(cls, path: str, w: int, h: int, fmt: str, fps: float = 60.0, **kw) -> "CardSource":
import av
container = av.open(path, format="rawvideo",
options={"video_size": f"{w}x{h}", "pixel_format": fmt, "framerate": f"{fps:g}"})
return cls(container, "Capture card (a raw file standing in)", live=False, **kw)
@classmethod
def video_file(cls, path: str, **kw) -> "CardSource":
import av
container = av.open(path)
container.streams.video[0].thread_type = "AUTO"
return cls(container, "Capture card (a recording standing in)", live=False, decode_to="nv12", **kw)
# ---- reading
def _gpu_decoder(self):
import av
import torch
from av.codec.hwaccel import HWAccel
torch.zeros(1, device="cuda") # PyTorch's CUDA context, current on this thread (see ChiakiSource._new_decoder)
ctx = av.CodecContext.create("mjpeg", "r", hwaccel=HWAccel(
"cuda", options={"primary_ctx": "0", "current_ctx": "1"}, is_hw_owned=True))
ctx.flags |= av.codec.context.Flags.low_delay
return ctx
def _convert_gpu(self, packet):
"""MJPEG through NVDEC; None (and the CPU from then on) if this card's JPEGs don't go that way."""
from .chiaki_tap import cuda_frame_to_bgr
try:
if self._hw is None:
self._hw = self._gpu_decoder()
frames = self._hw.decode(packet)
return cuda_frame_to_bgr(frames[-1]) if frames else None
except Exception as e: # noqa: BLE001 - e.g. 4:2:2 JPEGs the GPU path can't hand over
print(f"[capture] MJPEG on the GPU didn't work ({str(e)[:120]}); decoding on the CPU instead")
self._gpu_jpeg, self._hw = False, None
return None
def _convert(self, packet):
if self._gpu_jpeg:
frame = self._convert_gpu(packet)
if frame is not None or self._gpu_jpeg:
return frame
if not self.raw or self.fmt not in CONVERTIBLE:
frames = self.stream.codec_context.decode(packet)
if not frames:
return None
bgr = frames[-1].to_ndarray(format="bgr24")
if self.device:
import torch
return torch.from_numpy(bgr).to(self.device)
return bgr
return self._convert_raw(np.frombuffer(packet, dtype=np.uint8))
def _convert_raw(self, data: np.ndarray):
n = int(self.w * self.h * BYTES_PER_PIXEL[self.fmt])
if data.size < n:
return None # a short packet (a format change mid-stream): skip it
if self.device is None:
return raw_to_bgr_cpu(data, self.fmt, self.w, self.h)
import torch
if self._host is None:
t = torch.empty(n, dtype=torch.uint8, pin_memory=self.device == "cuda")
self._host = (t, t.numpy())
t, a = self._host
a[:] = data[:n] # the one copy on the CPU; the upload below finishes before the next frame reuses it
return raw_to_bgr(t.to(self.device), self.fmt, self.w, self.h, self.bt709, self.full_range)
def _reader(self) -> None:
from .io import Tick
if not self.live:
self._go.wait()
t0, n = time.perf_counter(), 0
try:
for frame, t_arrival, t_src in self._frames():
if self._stop:
break
if not self.live and (wait := t0 + n / self.fps - time.perf_counter()) > 0:
time.sleep(wait) # a card delivers on the HDMI clock
t_arrival = time.perf_counter()
if self._audio_wait: # a file: its sound goes out as the picture gets to it
now_s = (t_src if t_src is not None else n / self.fps) + 1 / self.fps
while self._audio_wait and self._audio_wait[0][0] <= now_s:
self._play(self._audio_wait.pop(0)[1])
tick = Tick(frame, t_arrival, 0, t_source=t_src, t_ready=time.perf_counter())
n += 1
if self.test is not None and (tick := self.test(tick)) is None:
continue
try:
self.q.put_nowait(tick)
except queue.Full:
self.q.get_nowait()
self.dropped += 1
self.q.put_nowait(tick)
except Exception as e: # noqa: BLE001 - the card went away, or the file ended badly: end the stream
print(f"[capture] stopped: {str(e)[:200]}")
self.q.put(None)
def _frames(self):
"""(frame, arrival time, the source's own time in seconds) for each frame, as it comes. Sound packets on the
way go to the player (a file's wait for the picture: _reader)."""
streams = [self.stream] + ([self.astream] if self.astream is not None else [])
if self.decode_to:
from av.video.reformatter import ColorRange, Colorspace
# into the colours the raw path will read them as (an MJPEG file is full range, a card's NV12 isn't)
space = Colorspace.ITU709 if self.bt709 else Colorspace.ITU601
rng = ColorRange.JPEG if self.full_range else ColorRange.MPEG
start = None
for packet in self.container.demux(*streams):
if packet.stream is not self.stream:
self._sound(packet, time.perf_counter())
continue
for fr in packet.decode():
t_arrival = time.perf_counter()
start = fr.time if start is None else start
raw = fr.reformat(format=self.decode_to, dst_colorspace=space, dst_color_range=rng)
frame = self._convert_raw(raw.to_ndarray().ravel())
if frame is not None:
yield frame, t_arrival, fr.time
return
for packet in self.container.demux(*streams):
if packet.size == 0:
continue
t_arrival = time.perf_counter()
if packet.stream is not self.stream:
self._sound(packet, t_arrival)
continue
frame = self._convert(packet)
if frame is not None:
t_src = float(packet.pts * packet.time_base) if packet.pts is not None else None
if t_src is not None:
self._late_v = (self._late_v + [t_arrival - t_src])[-120:]
yield frame, t_arrival, t_src
# ---- sound
def _sound(self, packet, t_arrival: float) -> None:
"""A sound packet: decoded to 16-bit PCM, then played (a card) or held for the picture (a file)."""
import av
if packet.size == 0:
return
try:
frames = packet.decode()
except Exception: # noqa: BLE001 - a damaged packet: skip it
return
for fr in frames:
if self._resampler is None:
channels = min(2, fr.layout.nb_channels if hasattr(fr.layout, "nb_channels") else len(fr.layout.channels))
self._resampler = av.AudioResampler(format="s16", layout="stereo" if channels == 2 else "mono",
rate=fr.sample_rate)
self._rate, self._channels = fr.sample_rate, channels
pcm = b"".join(o.to_ndarray().tobytes() for o in self._resampler.resample(fr))
if not pcm:
continue
if self.live:
if fr.time is not None:
self._late_a = (self._late_a + [t_arrival - (fr.time + fr.samples / fr.sample_rate)])[-120:]
self._play(pcm)
else:
self._audio_wait.append((fr.time if fr.time is not None else 0.0, pcm))
def _play(self, pcm: bytes) -> None:
from .io import Sound
# Timed like the picture it goes with: a card's sound comes this much later than its picture.
self._replay_sound.append(Sound(time.perf_counter() - self.sound_late_s(), pcm, self._rate, self._channels))
if self._audio_out is None:
return
if self.player is None:
try:
self.player = self._audio_out(self._rate, self._channels)
except Exception as e: # noqa: BLE001 - no output device: the picture on its own
print(f"[capture] can't play the sound ({str(e)[:120]}); playing without it")
self._audio_out, self.astream = None, None
return
if self._delay_s is not None:
self.player.set_delay(self._delay_s)
self.player.push(pcm)
_delay_s: float | None = None
_rate, _channels = 48000, 2
def read_sound(self) -> list:
"""The sound played since the last call (framegen.io.Sound chunks), for instant replay."""
out = []
while self._replay_sound:
out.append(self._replay_sound.popleft())
return out
def sound_late_s(self) -> float:
"""How much later the sound arrives than the picture, after their own timestamps (0 if not known)."""
if len(self._late_v) < 10 or len(self._late_a) < 10:
return 0.0
return float(np.median(self._late_a) - np.median(self._late_v))
# The pipeline's side (as for chiaki-ng, framegen.chiaki_tap.ChiakiSource): the sound is held back to meet the
# picture (Sound in sync); the delay test needs Remote Play.
def can_press(self) -> bool:
return False
def can_delay_audio(self) -> bool:
return self.astream is not None and self._audio_out is not None
def set_audio_delay(self, ms: float) -> None:
self._delay_s = max(0.0, ms / 1000 - self.sound_late_s())
if self.player is not None:
self.player.set_delay(self._delay_s)
def __iter__(self):
self.dropped = 0 # frames dropped while the pipeline was loading don't count
self._go.set()
from .io import queue_ticks
yield from queue_ticks(self.q, "the capture card")
def close(self) -> None:
self._stop = True
self._go.set()
try:
self.container.close()
except Exception: # noqa: BLE001 - closing
pass
if self.player is not None:
self.player.close()
print(f"[capture] dropped frames: {self.dropped}")
def _cuda_device() -> str | None:
try:
import torch
return "cuda" if torch.cuda.is_available() else None
except Exception: # noqa: BLE001 - no torch: OpenCV on the CPU
return None
# ----------------------------------------------------------------------------- command line
def main(argv: list[str] | None = None) -> int:
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--list", action="store_true", help="the capture devices Windows has")
ap.add_argument("--formats", metavar="NAME", help="what a video device offers, and what SmoovPlay would pick")
ap.add_argument("--json", action="store_true")
a = ap.parse_args(argv)
if a.formats:
modes = list_modes(a.formats)
best, note = pick_mode(modes)
if a.json:
print(json.dumps({"modes": [asdict(m) for m in modes], "pick": asdict(best) if best else None,
"note": note}))
else:
for m in modes:
print(("* " if m == best else " ") + m.label())
print(note or ("would use " + best.label() if best else "nothing usable"))
return 0
devices = list_devices()
if a.json:
print(json.dumps({"video": [asdict(d) for d in devices if d.kind in ("video", "unknown")],
"audio": [asdict(d) for d in devices if d.kind == "audio"]}))
else:
for d in devices:
print(f"{d.kind:7} {d.name}")
if not devices:
print("no capture devices found")
return 0
if __name__ == "__main__":
sys.exit(main())
+741
View File
@@ -0,0 +1,741 @@
"""Frames from chiaki-ng (PS5 Remote Play) through its frame tap: see chiaki_tap/frametap.h for the layout.
chiaki-ng, built with the tap and started with CHIAKI_FRAMETAP=1, copies every compressed video frame the PS5
sends into a shared-memory ring. FrameTap reads that ring; ChiakiSource decodes it into Ticks for the pipeline.
Compared with a capture card, each frame also carries what the stream knows about it:
- size: bytes of the compressed frame. After compression a repeated frame isn't an exact copy (the encoder
spends its few bytes sharpening the picture), so the image-based duplicate detector calls most repeats
new. Size doesn't have that problem: a repeat costs the encoder almost nothing (in tests ~3 KB against
~60 KB for a new frame), so `new_hint` comes from size and the pipeline uses it instead of the image check.
- damaged: frames were lost before this one, or it's the PS5's recovery frame after a loss. The pipeline
holds instead of interpolating, so a broken frame isn't smeared into the generated one.
Windows only (named file mapping + named event).
"""
from __future__ import annotations
import csv
import ctypes
import mmap
import queue
import struct
import sys
import tempfile
import threading
import time
from dataclasses import dataclass
from pathlib import Path
import numpy as np
from .io import Tick
from .streamcheck import StreamCheck
from .sync import CAPTURE_LOCK
NAME = "Local\\chiaki-frametap"
EVENT_NAME = "Local\\chiaki-frametap-frame"
MAGIC = 0x50544643 # 'CFTP'
VERSION = 1
HEADER = 4096
SLOT_HEADER = 64
SLOTS = 32
SLOT_SIZE = 2 * 1024 * 1024
TOTAL = HEADER + SLOTS * SLOT_SIZE
CODECS = {0: "h264", 1: "hevc", 2: "hevc"} # ChiakiCodec: H264, H265, H265_HDR
CODEC_NAMES = {0: "H.264", 1: "H.265", 2: "H.265 HDR"}
DAMAGE_HOLD = 6 # frames held (not interpolated) after a gap in the stream, while the picture repairs itself
U64_MAX = 2**64 - 1
FEATURE_PRESS, FEATURE_AUDIO_DELAY, FEATURE_AUDIO_TAP = 1, 2, 4 # header `features` bits (frametap.h)
# The game's sound, in a mapping of its own (frametap.h, "Sound ring")
AUDIO_SUFFIX = "-audio"
AUDIO_MAGIC = 0x41544643 # 'CFTA'
AUDIO_HEADER, AUDIO_SLOT_HEADER, AUDIO_SLOTS, AUDIO_SLOT_SIZE = 64, 32, 512, 8192
AUDIO_TOTAL = AUDIO_HEADER + AUDIO_SLOTS * AUDIO_SLOT_SIZE
BUTTON_OPTIONS, BUTTON_PS = 1 << 12, 1 << 15 # ChiakiControllerButton
if sys.platform == "win32":
_k32 = ctypes.WinDLL("kernel32", use_last_error=True)
_k32.CreateEventW.restype = ctypes.c_void_p
_k32.CreateEventW.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_int, ctypes.c_wchar_p]
_k32.WaitForSingleObject.argtypes = [ctypes.c_void_p, ctypes.c_uint32]
_k32.SetEvent.argtypes = [ctypes.c_void_p]
_k32.CloseHandle.argtypes = [ctypes.c_void_p]
def qpc() -> int:
v = ctypes.c_int64()
_k32.QueryPerformanceCounter(ctypes.byref(v))
return v.value
@dataclass
class Header:
magic: int
version: int
codec: int
width: int
height: int
max_fps: int
write_seq: int
session: int
qpc_freq: int
@property
def live(self) -> bool:
return self.magic == MAGIC
@dataclass
class Packet:
seq: int
t_arrival: float # time.perf_counter() timebase
data: bytes
frames_lost: int
recovered: bool
truncated: bool
class FrameTap:
"""The shared ring. Either side may create it first; both see the same memory."""
def __init__(self, name: str = NAME, event_name: str = EVENT_NAME) -> None:
if sys.platform != "win32":
raise RuntimeError("the chiaki frame tap is Windows-only")
self.mm = mmap.mmap(-1, TOTAL, tagname=name)
self.event = _k32.CreateEventW(None, 0, 0, event_name)
def header(self) -> Header:
magic, version, _n, _size, codec, w, h, fps = struct.unpack_from("<8I", self.mm, 0)
(write_seq,) = struct.unpack_from("<Q", self.mm, 32)
(session,) = struct.unpack_from("<I", self.mm, 44)
(freq,) = struct.unpack_from("<Q", self.mm, 48)
return Header(magic, version, codec, w, h, fps, write_seq, session, freq)
def request_idr(self) -> None:
struct.pack_into("<I", self.mm, 40, 1)
def heartbeat(self) -> None:
struct.pack_into("<Q", self.mm, 56, qpc())
# The delay test's button presses and the sound delay (frametap.h, offsets 64-91). A chiaki-ng built from an
# older patch leaves `features` at 0 and ignores both.
def features(self) -> int:
return struct.unpack_from("<I", self.mm, 64)[0] if self.header().live else 0
def press(self, buttons: int, hold_ms: int = 100) -> int:
"""Ask chiaki-ng to press `buttons` (a ChiakiControllerButton mask) for hold_ms. Returns a token for
press_sent()."""
(count,) = struct.unpack_from("<I", self.mm, 76)
struct.pack_into("<I", self.mm, 72, hold_ms)
struct.pack_into("<I", self.mm, 68, buttons)
return count
def press_sent(self, token: int, qpc_freq: int) -> float | None:
"""When chiaki-ng sent the press to the PS5 (time.perf_counter() timebase), or None if it hasn't yet."""
(count,) = struct.unpack_from("<I", self.mm, 76)
if count == token or not qpc_freq:
return None
(q,) = struct.unpack_from("<Q", self.mm, 80)
return time.perf_counter() - (qpc() - q) / qpc_freq
def set_audio_delay(self, ms: int) -> None:
struct.pack_into("<I", self.mm, 88, max(0, min(500, int(ms))))
def wait(self, timeout_s: float) -> None:
_k32.WaitForSingleObject(self.event, int(timeout_s * 1000))
def read(self, seq: int, qpc_freq: int) -> Packet | None:
"""Copy frame `seq` out of its slot, or None if the writer has already reused the slot."""
off = HEADER + (seq % SLOTS) * SLOT_SIZE
s0, q, size, lost, rec, flags = struct.unpack_from("<QQIiII", self.mm, off)
if s0 != seq:
return None
data = self.mm[off + SLOT_HEADER: off + SLOT_HEADER + size]
if struct.unpack_from("<Q", self.mm, off)[0] != seq: # rewritten while we copied
return None
age = (qpc() - q) / qpc_freq if qpc_freq else 0.0
return Packet(seq, time.perf_counter() - age, data, lost, bool(rec), bool(flags & 1))
# Writer side, for tests and the fake PS5 (scripts/frametap_fake.py); chiaki-ng uses frametap.c.
def begin(self, codec: int, width: int, height: int, max_fps: int = 60) -> None:
struct.pack_into("<I", self.mm, 0, 0)
freq = ctypes.c_int64()
_k32.QueryPerformanceFrequency(ctypes.byref(freq))
struct.pack_into("<7I", self.mm, 4, VERSION, SLOTS, SLOT_SIZE, codec, width, height, max_fps)
struct.pack_into("<QI", self.mm, 32, 0, 0)
struct.pack_into("<Q", self.mm, 48, freq.value)
(session,) = struct.unpack_from("<I", self.mm, 44)
struct.pack_into("<I", self.mm, 44, session + 1)
struct.pack_into("<I", self.mm, 0, MAGIC)
def push(self, data: bytes, frames_lost: int = 0, recovered: bool = False) -> None:
(seq,) = struct.unpack_from("<Q", self.mm, 32)
off = HEADER + (seq % SLOTS) * SLOT_SIZE
size = min(len(data), SLOT_SIZE - SLOT_HEADER)
struct.pack_into("<Q", self.mm, off, U64_MAX)
struct.pack_into("<QIiII", self.mm, off + 8, qpc(), size, frames_lost, int(recovered),
int(size < len(data)))
self.mm[off + SLOT_HEADER: off + SLOT_HEADER + size] = data[:size]
struct.pack_into("<Q", self.mm, off, seq)
struct.pack_into("<Q", self.mm, 32, seq + 1)
_k32.SetEvent(self.event)
def take_idr_request(self) -> bool:
(r,) = struct.unpack_from("<I", self.mm, 40)
if r:
struct.pack_into("<I", self.mm, 40, 0)
return bool(r)
def set_features(self, features: int) -> None:
struct.pack_into("<I", self.mm, 64, features)
def take_press_request(self) -> int:
(buttons,) = struct.unpack_from("<I", self.mm, 68)
if buttons:
struct.pack_into("<I", self.mm, 68, 0)
return buttons
def press_done(self) -> None:
"""The press went to the (fake) PS5 now."""
struct.pack_into("<Q", self.mm, 80, qpc())
(count,) = struct.unpack_from("<I", self.mm, 76)
struct.pack_into("<I", self.mm, 76, count + 1)
def audio_delay_ms(self) -> int:
return struct.unpack_from("<I", self.mm, 88)[0]
def end(self) -> None:
struct.pack_into("<I", self.mm, 0, 0)
_k32.SetEvent(self.event)
def close(self) -> None:
_k32.CloseHandle(self.event)
self.mm.close()
class AudioTap:
"""The game's sound from chiaki-ng (frametap.h, "Sound ring"): 16-bit PCM chunks timed by their arrival, for
instant replay. A chiaki-ng from before this ring never writes it (its `features` lack FEATURE_AUDIO_TAP)."""
def __init__(self, name: str = NAME + AUDIO_SUFFIX) -> None:
if sys.platform != "win32":
raise RuntimeError("the chiaki frame tap is Windows-only")
self.mm = mmap.mmap(-1, AUDIO_TOTAL, tagname=name)
self.next: int | None = None # the next chunk to read; None: from wherever the writer is now
def live(self) -> bool:
return struct.unpack_from("<I", self.mm, 0)[0] == AUDIO_MAGIC
def reset(self, from_start: bool = False) -> None:
"""Forget the read position (a new stream): the next read starts at the writer's position, or at its first
chunk."""
self.next = 0 if from_start else None
def read_new(self) -> list:
"""Every chunk written since the last call (at most the ring's worth), as framegen.io.Sound."""
from .io import Sound
magic = struct.unpack_from("<I", self.mm, 0)[0]
write_seq, freq = struct.unpack_from("<QQ", self.mm, 24)
if magic != AUDIO_MAGIC or not freq:
self.next = None
return []
if self.next is None or self.next > write_seq: # first read, or the writer started over
self.next = write_seq
self.next = max(self.next, write_seq - AUDIO_SLOTS + 1) # fell a whole ring behind: what's left
out = []
now_q, now_t = qpc(), time.perf_counter()
while self.next < write_seq:
seq = self.next
self.next += 1
off = AUDIO_HEADER + (seq % AUDIO_SLOTS) * AUDIO_SLOT_SIZE
s0, q, size, rate, channels = struct.unpack_from("<QQIII", self.mm, off)
if s0 != seq or size > AUDIO_SLOT_SIZE - AUDIO_SLOT_HEADER:
continue
data = self.mm[off + AUDIO_SLOT_HEADER: off + AUDIO_SLOT_HEADER + size]
if struct.unpack_from("<Q", self.mm, off)[0] != seq: # rewritten while we copied
continue
out.append(Sound(now_t - (now_q - q) / freq, data, rate, channels))
return out
# Writer side, for tests and the fake PS5 (scripts/frametap_fake.py); chiaki-ng uses frametap.c.
def begin(self, rate: int = 48000, channels: int = 2) -> None:
freq = ctypes.c_int64()
_k32.QueryPerformanceFrequency(ctypes.byref(freq))
struct.pack_into("<I", self.mm, 0, 0)
struct.pack_into("<5I", self.mm, 4, 1, AUDIO_SLOTS, AUDIO_SLOT_SIZE, rate, channels)
struct.pack_into("<QQ", self.mm, 24, 0, freq.value)
struct.pack_into("<I", self.mm, 0, AUDIO_MAGIC)
def push(self, pcm: bytes, t_qpc: int | None = None) -> None:
rate, channels = struct.unpack_from("<II", self.mm, 16)
cap = (AUDIO_SLOT_SIZE - AUDIO_SLOT_HEADER) // (2 * channels) * (2 * channels)
q0 = qpc() if t_qpc is None else t_qpc
(freq,) = struct.unpack_from("<Q", self.mm, 32)
for i in range(0, len(pcm), cap):
part = pcm[i:i + cap]
(seq,) = struct.unpack_from("<Q", self.mm, 24)
off = AUDIO_HEADER + (seq % AUDIO_SLOTS) * AUDIO_SLOT_SIZE
struct.pack_into("<Q", self.mm, off, U64_MAX)
struct.pack_into("<QIII", self.mm, off + 8, q0 + round(i // (2 * channels) * freq / rate), len(part),
rate, channels)
self.mm[off + AUDIO_SLOT_HEADER: off + AUDIO_SLOT_HEADER + len(part)] = part
struct.pack_into("<Q", self.mm, off, seq)
struct.pack_into("<Q", self.mm, 24, seq + 1)
def end(self) -> None:
struct.pack_into("<I", self.mm, 0, 0)
def close(self) -> None:
self.mm.close()
def _nal_types(data: bytes, codec: str):
"""NAL unit types in an Annex-B access unit."""
i, n = 0, len(data)
while True:
i = data.find(b"\x00\x00\x01", i)
if i < 0 or i + 3 >= n:
return
b = data[i + 3]
yield (b >> 1) & 0x3F if codec == "hevc" else b & 0x1F
i += 3
def is_keyframe(data: bytes, codec: str) -> bool:
# H.264: IDR slice (5). HEVC: IRAP pictures, BLA/IDR/CRA (16-21).
return any((t == 5) if codec == "h264" else (16 <= t <= 21) for t in _nal_types(data, codec))
PARAM_NALS = {"hevc": {32, 33, 34}, "h264": {7, 8}} # VPS/SPS/PPS, SPS/PPS
def nal_units(data: bytes, codec: str):
"""(type, unit with a 3-byte start code) for each NAL unit in an Annex-B access unit."""
starts, i = [], 0
while (i := data.find(b"\x00\x00\x01", i)) >= 0:
starts.append(i)
i += 3
for k, s in enumerate(starts):
if s + 3 >= len(data):
return
b = data[s + 3]
end = starts[k + 1] if k + 1 < len(starts) else len(data)
yield ((b >> 1) & 0x3F if codec == "hevc" else b & 0x1F), b"\x00\x00\x01" + data[s + 3:end]
def param_sets(data: bytes, codec: str) -> bytes:
"""The codec header NAL units in an access unit, or b"" if none.
chiaki-ng sends these once, as a packet of their own at the start of a stream (the PS5 delivers them out of
band), so a decoder that missed them can't decode anything until the next stream.
"""
return b"".join(u for t, u in nal_units(data, codec) if t in PARAM_NALS[codec])
class SizeRepeatDetector:
"""New frame or repeat, from compressed size alone.
A frame is new if it's at least `ratio` of a typical recent new frame (the 75th percentile of the last 16
non-keyframe sizes: in a 30 fps game at 60 Hz half the frames are new, so that lands on a new one).
Unsure cases lean towards "repeat": that only shows a real frame without a generated one before it,
while calling a repeat new makes the scheduler stall a tick. Keyframes are big whatever they contain: if
the recent frames alternate new/repeat (a 30 fps game), a keyframe gets the opposite of the frame before
it; otherwise it returns None and the pipeline falls back to the image check.
"""
def __init__(self, ratio: float = 0.4, window: int = 16) -> None:
from collections import deque
self.ratio = ratio
self.sizes: deque[int] = deque(maxlen=window)
self.decisions: deque[bool] = deque(maxlen=6)
self.ref: float | None = None # the last update's typical new frame size (None: keyframe or warming up)
self.big = False # the last update was treated as a keyframe for its size
def update(self, size: int, keyframe: bool) -> bool | None:
# The PS5's refresh frames are ordinary slices by NAL type, but far bigger than anything recent.
self.big = not keyframe and len(self.sizes) >= 8 and size > 4 * float(np.percentile(self.sizes, 75))
self.ref = None
if keyframe or self.big:
d = list(self.decisions)
alternating = len(d) >= 4 and all(a != b for a, b in zip(d, d[1:]))
decision = (not d[-1]) if alternating else None
else:
self.sizes.append(size)
if len(self.sizes) >= 4:
self.ref = float(np.percentile(self.sizes, 75))
decision = (size >= self.ratio * self.ref) if self.ref is not None else None
if decision is not None:
self.decisions.append(decision)
return decision
def cuda_frame_to_bgr(fr):
"""A decoded NVDEC frame (NV12, still on the GPU) -> HxWx3 uint8 BGR CUDA tensor, without leaving the GPU.
Matches FFmpeg's CPU conversion: BT.709 when the stream says so, else BT.601; limited range unless tagged full.
Runs on PyTorch's default stream, which is also where FFmpeg copied the frame out, so no extra sync is needed.
"""
import torch
import torch.nn.functional as F
if fr.format.name != "cuda": # the decoder fell back to software for this stream
return torch.from_numpy(fr.to_ndarray(format="bgr24")).cuda()
y = torch.from_dlpack(fr.planes[0].__dlpack__()) # H x W
uv = torch.from_dlpack(fr.planes[1].__dlpack__()) # H/2 x W/2 x 2
kr, kb = (0.2126, 0.0722) if fr.colorspace == 1 else (0.299, 0.114)
kg = 1.0 - kr - kb
ys, yo, cs = (1.0, 0.0, 1.0) if fr.color_range == 2 else (255 / 219, 16.0, 255 / 224)
lum = (y.float() - yo) * ys
c = F.interpolate(uv.permute(2, 0, 1).unsqueeze(0).float() - 128.0, size=y.shape, mode="bilinear",
align_corners=False)[0] * cs
u, v = c[0], c[1]
b = lum + 2 * (1 - kb) * u
g = lum - (2 * kb * (1 - kb) / kg) * u - (2 * kr * (1 - kr) / kg) * v
r = lum + 2 * (1 - kr) * v
return torch.stack([b, g, r], -1).clamp_(0, 255).round_().to(torch.uint8)
class ChiakiSource:
"""Decoded frames from the tap, as Ticks. Waits for chiaki-ng to start streaming.
Joins the live stream (never replays old frames) and asks the PS5 for a keyframe whenever it can't decode:
at start, after falling more than the ring's 32 frames behind, or after a decode error.
"""
def __init__(self, decoder: str = "sw", wait_s: float = 120.0, log_path: str | None = None,
tap_name: str = NAME, test=None) -> None:
"""test: a framegen.sources.TestMode ("Simulate a 30 fps game"), applied as frames are decoded, before
the queue, so a frame dropped from a full queue never shifts which frames it keeps."""
from .sources import source_info
self.tap = FrameTap(tap_name, tap_name + "-frame")
self.sound = AudioTap(tap_name + AUDIO_SUFFIX) # the game's sound, for instant replay
self._sound_session: int | None = None
self.test = test
self._last_idr = 0.0
self._header_file = Path(tempfile.gettempdir()) / (tap_name.split("\\")[-1] + "-header.bin")
self.decoder_kind = decoder
t_end = time.perf_counter() + wait_s
printed = False
while not (h := self.tap.header()).live:
if not printed:
print("[chiaki] waiting for chiaki-ng to start a stream (run it with CHIAKI_FRAMETAP=1)...")
printed = True
if time.perf_counter() > t_end:
raise TimeoutError("no chiaki-ng stream on the frame tap")
self.tap.wait(0.25)
self.w, self.h, self.codec_id = h.width, h.height, h.codec
self.info = source_info("chiaki", hz=float(h.max_fps))
print(f"[chiaki] stream: {CODEC_NAMES.get(h.codec, h.codec)} {h.width}x{h.height}, up to {h.max_fps} fps")
if h.max_fps < 60:
print("[chiaki] WARNING: the stream is set to 30 fps. Set chiaki-ng's frame rate to 60 so the "
"pipeline sees the PS5's 60 Hz output (it expects repeats, not every other frame missing).")
if h.codec == 2:
print("[chiaki] WARNING: HDR stream; the pipeline is 8-bit SDR, colours will be off. Turn HDR off.")
self.q: queue.Queue = queue.Queue(maxsize=3)
self.dropped = 0 # decoded frames dropped because the pipeline fell behind
self.skipped = 0 # stream frames never decoded (ring overrun or waiting for a keyframe)
self.idr_requests = 0
self.check = StreamCheck() # how well the size check read this game: reported when the session ends
self._stop = False
self._log = None
if log_path:
f = open(log_path, "w", newline="")
self._log = (f, csv.writer(f))
self._log[1].writerow(["tick", "seq", "t_arrival_ms", "size", "frames_lost", "recovered", "keyframe",
"decode_ms", "queue_ms", "size_says_new", "image_says_new", "max_diff",
"mean_diff", "action", "proc_ms"])
self._t0 = time.perf_counter()
self._beat = self._t0 # when the reader's loop last went round (why() says if it stopped)
self._no_header = False # joined a running stream whose codec header went past, and none was saved
self._ring = (-1, self._t0) # why(): the ring's write count when it last moved, and when
# The reader starts right away, not when the pipeline is ready: a new stream's first packet is its codec
# header, and the ring only holds half a second. But until the pipeline asks for frames (self._go: its loop
# has started) it only watches for that header, with no GPU work, so the decoder never starts up on the GPU
# alongside the pipeline's own set-up (TensorRT, VFG, the window's GPU sharing). Frames decoded then would
# be dropped anyway. hold() stops it decoding again while the pipeline restarts.
self._go = threading.Event()
self._thread = threading.Thread(target=self._reader, daemon=True)
self._thread.start()
def _new_decoder(self, codec: str):
import av
from av.codec.hwaccel import HWAccel
if self.decoder_kind == "sw":
ctx = av.CodecContext.create(codec, "r")
ctx.thread_type = "SLICE" # frame threading would delay output by a frame per thread
elif self.decoder_kind == "cuda":
# NVDEC, and the frames stay on the GPU (handed to PyTorch through DLPack). current_ctx: decode in
# PyTorch's context, made current on this thread in _reader. FFmpeg's default would be a second context,
# which takes turns on the GPU with RIFE; primary_ctx refuses because PyTorch set it up differently.
ctx = av.CodecContext.create(codec, "r", hwaccel=HWAccel(
"cuda", options={"primary_ctx": "0", "current_ctx": "1"}, is_hw_owned=True))
else:
ctx = av.CodecContext.create(codec, "r", hwaccel=HWAccel(self.decoder_kind))
ctx.flags |= av.codec.context.Flags.low_delay
return ctx
def _reader(self) -> None:
import av
from .winutil import boost_thread
boost_thread() # the decoder thread feeds every frame, so it gets the same treatment as the pipeline's
on_gpu = False # PyTorch's CUDA context made current on this thread, for NVDEC (once going)
session, seq, dec, codec = None, 0, None, None
params = b"" # this stream's codec header, once seen
pending = b"" # the header, still to go into the decoder (with the next picture: not every decoder
# takes it on its own)
decoded = False # a picture has come out of this stream
damaged_left = 0 # frames still treated as damaged after a gap
errors = 0 # decode errors in a row
passed = False # frames went by undecoded (joined late, the pipeline not ready yet, or held)
held = -1 # the frame the reader waits at for the pipeline to be ready (see below)
late = False
t_join, told = 0.0, False
sizes = SizeRepeatDetector()
while not self._stop:
self._beat = time.perf_counter()
h = self.tap.header()
if not h.live:
if decoded: # the stream we were showing ended
print("[chiaki] stream ended")
self.q.put(None)
return
self.tap.wait(0.25) # not started yet, or being reconnected
continue
if h.session != session: # a new stream
session, codec = h.session, CODECS.get(h.codec, "h264")
if (h.width, h.height) != (self.w, self.h):
print(f"[chiaki] stream size changed to {h.width}x{h.height}; restart run.py", file=sys.stderr)
self.q.put(None)
return
dec, params, pending, decoded, damaged_left, errors, held = None, b"", b"", False, 0, 0, -1
sizes = SizeRepeatDetector()
# Read it from its first packet (the codec header) while that's still in the ring.
seq = 0 if h.write_seq <= SLOTS - 4 else h.write_seq
late = passed = seq > 0
if late: # joining a running stream: an earlier run.py may have saved its header
params = self._load_header(session, h.codec)
if params:
print("[chiaki] joined a running stream, using its saved codec header")
else:
self._ask_idr()
self._no_header = late and not params
t_join, told = time.perf_counter(), False
going = self._go.is_set()
if going and dec is None:
if self.decoder_kind == "cuda" and not on_gpu:
import torch
torch.zeros(1, device="cuda") # PyTorch's CUDA context, current on this thread for the decoder
on_gpu = True
dec, pending = self._new_decoder(codec), params
if going and passed and params:
# Frames went by undecoded: ask the PS5 for a refresh frame and hold what comes out until the
# picture is whole again.
passed, damaged_left = False, 60
self._ask_idr()
if late and not params and not told and time.perf_counter() - t_join > 3:
print("[chiaki] this stream was already running, so its codec header went past before the pipeline "
"started. In chiaki-ng press Ctrl+O, click the x to end the stream, then connect again: the "
"pipeline picks up the new stream from its start.")
told = True
if h.write_seq == seq:
self.tap.heartbeat()
self.tap.wait(0.1)
continue
if h.write_seq - seq > SLOTS - 4: # fell behind: the oldest slots are being overwritten
if going:
self.skipped += h.write_seq - seq
damaged_left = DAMAGE_HOLD
self._ask_idr()
else:
passed = True
seq = h.write_seq
continue
if not going and seq == held: # at the stream's first picture, waiting for the pipeline (see below)
self.tap.heartbeat()
self.tap.wait(0.1)
continue
p = self.tap.read(seq, h.qpc_freq)
seq += 1
if p is None:
if going:
self.skipped += 1
damaged_left = DAMAGE_HOLD
self._ask_idr()
else:
passed = True
continue
ps = param_sets(p.data, codec)
if ps:
if ps != params:
self._save_header(session, h.codec, ps)
params, self._no_header = ps, False
if all(t in PARAM_NALS[codec] for t, _ in nal_units(p.data, codec)): # the header on its own
pending = ps
continue
elif not params: # nothing is decodable without the header
if going:
self.skipped += 1
continue
if not going: # the pipeline isn't ready: only the header was wanted
if not passed:
# A picture: leave it in the ring, which holds half a second, and start decoding there once the
# pipeline is ready, as if it had been all along. If it takes longer, the ring moves on (passed)
# and the PS5 is asked for a refresh frame instead.
seq = held = p.seq
continue
key = is_keyframe(p.data, codec)
t = time.perf_counter()
try:
with CAPTURE_LOCK: # no GPU decoding while the pipeline captures its CUDA graphs (startup only)
frames = dec.decode(av.Packet(pending + p.data if pending else p.data))
images = [self._image(fr) for fr in frames]
pending, errors = b"", 0
except av.error.FFmpegError as e:
# Keep the decoder (it holds the header and reference frames) and hold the next few frames; the
# PS5 answers a keyframe request with a refresh frame.
print(f"[chiaki] decode error at frame {p.seq}: {e}", file=sys.stderr)
damaged_left, errors = DAMAGE_HOLD, errors + 1
if errors >= 30: # stuck: start a decoder afresh from the saved header
dec, errors, pending = self._new_decoder(codec), 0, params
self._ask_idr()
continue
if not frames: # (a decoder that holds a frame back)
continue
decoded = True
new_hint = sizes.update(len(p.data), key)
damaged = bool(p.frames_lost > 0 or p.recovered or p.truncated or damaged_left > 0)
for img in images:
decode_ms = (time.perf_counter() - t) * 1000
# Ready = arrival + decode time: what the pipeline's "behind" check has always measured from.
tick = Tick(img, p.t_arrival, 0, new_hint=new_hint, damaged=damaged,
t_ready=p.t_arrival + decode_ms / 1000,
extra={"seq": p.seq, "size": len(p.data), "frames_lost": p.frames_lost,
"recovered": p.recovered, "keyframe": key, "decode_ms": decode_ms,
# for the stream check: test mode replaces new_hint, these stay as the stream said
"size_new": new_hint, "size_ref": sizes.ref, "big": sizes.big})
if self.test is not None and (tick := self.test(tick)) is None:
continue
try:
self.q.put_nowait(tick)
except queue.Full:
self.q.get_nowait()
self.dropped += 1
self.q.put_nowait(tick)
damaged_left = max(0, damaged_left - 1)
def _image(self, fr):
return cuda_frame_to_bgr(fr) if self.decoder_kind == "cuda" else fr.to_ndarray(format="bgr24")
def _ask_idr(self) -> None:
now = time.perf_counter()
if now - self._last_idr < 0.5: # chiaki-ng re-asks by itself; don't flood the PS5
return
self._last_idr = now
self.tap.request_idr()
self.idr_requests += 1
def _save_header(self, session: int, codec: int, params: bytes) -> None:
try:
self._header_file.write_bytes(struct.pack("<II", session, codec) + params)
except OSError:
pass
def _load_header(self, session: int, codec: int) -> bytes:
"""The codec header an earlier run.py saved for this same stream, if any."""
try:
b = self._header_file.read_bytes()
except OSError:
return b""
return b[8:] if len(b) > 8 and struct.unpack_from("<II", b) == (session, codec) else b""
# The delay test and the sound delay go through chiaki-ng (frametap.h). Both need a chiaki-ng from this version
# of the patch; can_press()/can_delay_audio() say whether the one streaming is.
def can_press(self) -> bool:
return bool(self.tap.features() & FEATURE_PRESS)
def can_delay_audio(self) -> bool:
return bool(self.tap.features() & FEATURE_AUDIO_DELAY)
def press(self, buttons: int, hold_ms: int = 100) -> int:
return self.tap.press(buttons, hold_ms)
def press_sent(self, token: int) -> float | None:
return self.tap.press_sent(token, self.tap.header().qpc_freq)
def set_audio_delay(self, ms: float) -> None:
self.tap.set_audio_delay(round(ms))
# Instant replay's sound: chiaki-ng copies the game's sound into a ring of its own (a chiaki-ng from before that
# leaves it empty, and replays are silent).
def has_sound(self) -> bool:
return bool(self.tap.features() & FEATURE_AUDIO_TAP) and self.sound.live()
def read_sound(self) -> list:
"""The game's sound that arrived since the last call (framegen.io.Sound chunks); [] if there's none."""
h = self.tap.header()
if not h.live:
return []
if h.session != self._sound_session: # a new stream: start from its current sound
self._sound_session = h.session
self.sound.reset()
return self.sound.read_new()
def hold(self, on: bool) -> None:
"""Stop decoding while the pipeline restarts (on), and start again from a fresh frame (off)."""
if on:
self._go.clear()
return
while True: # frames from before the restart are stale by now
try:
self.q.get_nowait()
except queue.Empty:
break
self._go.set()
def why(self) -> str:
"""What the ring says about a wait for frames: a hint under the window's "No picture" note ("" if none)."""
now = time.perf_counter()
h = self.tap.header()
if h.write_seq != self._ring[0]:
self._ring = (h.write_seq, now)
if not h.live:
return "chiaki-ng isn't streaming. Connect to the PS5 in chiaki-ng (or wait while it reconnects)"
if now - self._beat > 3:
return "SmoovPlay's video decoder has stopped. Press Q, then Play again"
if now - self._ring[1] > 1:
return "chiaki-ng isn't sending any frames. Is its stream still running?"
if self._no_header:
return ("This stream started before SmoovPlay, so its start is missing.\n"
"In chiaki-ng press Ctrl+O, click the x to end the stream, then connect again")
return ""
def __iter__(self):
self.dropped = 0 # frames dropped while RIFE was loading don't count
self._go.set() # the pipeline is ready: start decoding
from .io import queue_ticks
yield from queue_ticks(self.q, "the PS5", self.why)
def log_tick(self, tick: Tick, diff, action, proc_ms: float, t_start: float) -> None:
"""Per-tick CSV row: stream facts next to the pipeline's decisions, for tuning after a real session."""
self.check.add_tick(tick, diff)
if self._log is None:
return
e = tick.extra
hint = tick.new_hint
self._log[1].writerow([tick.index, e.get("seq"), f"{(tick.t_arrival - self._t0) * 1000:.2f}", e.get("size"),
e.get("frames_lost"), int(bool(e.get("recovered"))), int(bool(e.get("keyframe"))),
f"{e.get('decode_ms', 0):.2f}", f"{(t_start - tick.t_arrival) * 1000:.2f}",
"" if hint is None else int(hint), int(diff.is_new), f"{diff.max_diff:.2f}",
f"{diff.mean_diff:.3f}", action.value, f"{proc_ms:.2f}"])
def close(self) -> None:
self._stop = True
if self._log is not None:
self._log[0].close()
try:
self.sound.close()
except (BufferError, ValueError): # still being read: it goes with the process
pass
print(f"[chiaki] decoded frames dropped: {self.dropped}, stream frames skipped: {self.skipped}, "
f"keyframe requests: {self.idr_requests}")
+249
View File
@@ -0,0 +1,249 @@
"""Window capture on the GPU: Desktop Duplication of one monitor, the window's part copied on the graphics card and
handed to CUDA, so frames never go through the CPU (framegen/window.py; FFmpeg's ddagrab is the CPU fallback).
Each time the screen changes, Windows hands over the monitor's picture as a Direct3D 11 texture
(IDXGIOutputDuplication::AcquireNextFrame). If the window's part changed (Windows says which parts did), it's copied
into a texture of ours that CUDA can read (cudaGraphicsD3D11RegisterResource), then into a PyTorch tensor: BGR at the
source's size, scaled on the GPU if the window isn't that size. When Windows last updated the screen
(LastPresentTime) comes with it, on the same clock as time.perf_counter.
Needs the monitor on the graphics card CUDA runs on (a desktop PC with the monitor plugged into the NVIDIA card),
not rotated, and not in Windows HDR mode; otherwise GpuCaptureUnavailable says why and window.py uses ddagrab.
"""
from __future__ import annotations
import ctypes
from ctypes import POINTER, byref, c_int, c_long, c_size_t, c_uint, c_void_p
from .dxgi_present import (D3D11_BIND_SHADER_RESOURCE, D3D11_SDK_VERSION, D3D11_USAGE_DEFAULT,
D3D_DRIVER_TYPE_UNKNOWN, DEVICE_CREATE_TEXTURE2D, DXGI_FORMAT_B8G8R8A8_UNORM,
FACTORY_ENUM_ADAPTERS1, IID_ID3D11Texture2D, IID_IDXGIFactory1, GUID, Texture2DDesc,
_check, _com, _query, _release)
IID_IDXGIOutput1 = "00cddea8-939b-4b83-a340-a685226666cc"
ADAPTER_ENUM_OUTPUTS = 7
OUTPUT1_DUPLICATE_OUTPUT = 22
DUP_GET_DESC, DUP_ACQUIRE_NEXT_FRAME, DUP_GET_DIRTY_RECTS, DUP_GET_MOVE_RECTS, DUP_RELEASE_FRAME = 7, 8, 9, 10, 14
CONTEXT_COPY_SUBRESOURCE_REGION = 46
DXGI_ERROR_WAIT_TIMEOUT = ctypes.c_long(0x887A0027).value
DXGI_ERROR_ACCESS_LOST = ctypes.c_long(0x887A0026).value
DXGI_ERROR_MORE_DATA = ctypes.c_long(0x887A0003).value
_CUDA_MAP_READ_ONLY = 1
_MEMCPY_DEVICE_TO_DEVICE = 3
class GpuCaptureUnavailable(RuntimeError):
"""The GPU path can't run on this PC or monitor (the reason is the message): use the CPU path instead."""
class CaptureLost(RuntimeError):
"""Windows took the duplication away (a mode change, a UAC prompt, a fullscreen app): start again."""
class _Rect(ctypes.Structure):
_fields_ = [("left", c_long), ("top", c_long), ("right", c_long), ("bottom", c_long)]
class _MoveRect(ctypes.Structure): # DXGI_OUTDUPL_MOVE_RECT
_fields_ = [("x", c_long), ("y", c_long), ("dest", _Rect)]
class _DuplDesc(ctypes.Structure): # DXGI_OUTDUPL_DESC
_fields_ = [("Width", c_uint), ("Height", c_uint), ("RefreshNum", c_uint), ("RefreshDen", c_uint),
("Format", c_uint), ("ScanlineOrdering", c_uint), ("Scaling", c_uint), ("Rotation", c_uint),
("InSystemMemory", c_int)]
class _FrameInfo(ctypes.Structure): # DXGI_OUTDUPL_FRAME_INFO
_fields_ = [("LastPresentTime", ctypes.c_longlong), ("LastMouseUpdateTime", ctypes.c_longlong),
("AccumulatedFrames", c_uint), ("RectsCoalesced", c_int), ("ProtectedContentMaskedOut", c_int),
("PointerX", c_long), ("PointerY", c_long), ("PointerVisible", c_int),
("TotalMetadataBufferSize", c_uint), ("PointerShapeBufferSize", c_uint)]
class _Box(ctypes.Structure): # D3D11_BOX
_fields_ = [("left", c_uint), ("top", c_uint), ("front", c_uint), ("right", c_uint), ("bottom", c_uint),
("back", c_uint)]
def _overlaps(r: _Rect, x: int, y: int, w: int, h: int) -> bool:
return r.left < x + w and r.right > x and r.top < y + h and r.bottom > y
class DdaCapture:
"""The part (x, y, w, h) of output `output` of DXGI adapter 0 (window.plan_grab's Grab), as HxWx3 uint8 BGR CUDA
tensors of out_w x out_h. Use it from one thread; close() it when done (a monitor allows only a few)."""
def __init__(self, output: int, x: int, y: int, w: int, h: int, out_w: int, out_h: int) -> None:
import torch
from .glcuda import cudart_path
self.x, self.y, self.w, self.h, self.out_w, self.out_h = x, y, w, h, out_w, out_h
self.factory = self.adapter = self.output = self.device = self.context = self.dup = None
self.texture, self.res, self._held = None, c_void_p(), False
self.copies = self.skipped = 0 # frames copied; screen changes elsewhere on the monitor, skipped
freq = ctypes.c_longlong()
ctypes.windll.kernel32.QueryPerformanceFrequency(byref(freq))
self._qpf = float(freq.value)
try:
if not torch.cuda.is_available():
raise GpuCaptureUnavailable("no CUDA")
self.rt = rt = ctypes.CDLL(cudart_path())
p, u, s = c_void_p, c_uint, c_size_t
rt.cudaD3D11GetDevice.argtypes = [POINTER(c_int), p]
rt.cudaGraphicsD3D11RegisterResource.argtypes = [POINTER(p), p, u]
rt.cudaGraphicsResourceSetMapFlags.argtypes = [p, u]
rt.cudaGraphicsMapResources.argtypes = [c_int, POINTER(p), p]
rt.cudaGraphicsUnmapResources.argtypes = [c_int, POINTER(p), p]
rt.cudaGraphicsSubResourceGetMappedArray.argtypes = [POINTER(p), p, u, u]
rt.cudaMemcpy2DFromArrayAsync.argtypes = [p, s, p, s, s, s, s, c_int, p]
rt.cudaGraphicsUnregisterResource.argtypes = [p]
torch.cuda.current_device() # the runtime initialised, PyTorch's context current on this thread
self._open(output)
except Exception:
self.close()
raise
def _open(self, output: int) -> None:
import torch
self.factory = c_void_p()
_check(ctypes.windll.dxgi.CreateDXGIFactory1(byref(GUID.of(IID_IDXGIFactory1)), byref(self.factory)),
"CreateDXGIFactory1")
self.adapter = c_void_p()
_check(_com(self.factory, FACTORY_ENUM_ADAPTERS1, [c_uint, POINTER(c_void_p)], 0, byref(self.adapter)),
"EnumAdapters1")
cuda_dev = c_int(-1)
if self.rt.cudaD3D11GetDevice(byref(cuda_dev), self.adapter) or cuda_dev.value != torch.cuda.current_device():
raise GpuCaptureUnavailable("the monitor isn't on the graphics card CUDA runs on")
out = c_void_p()
_check(_com(self.adapter, ADAPTER_ENUM_OUTPUTS, [c_uint, POINTER(c_void_p)], output, byref(out)),
"EnumOutputs")
self.output = _query(out, IID_IDXGIOutput1)
_release(out)
if self.output is None:
raise GpuCaptureUnavailable("Desktop Duplication needs Windows 8 or newer")
self.device, self.context, level = c_void_p(), c_void_p(), c_uint()
_check(ctypes.windll.d3d11.D3D11CreateDevice(self.adapter, D3D_DRIVER_TYPE_UNKNOWN, None, 0, None, 0,
D3D11_SDK_VERSION, byref(self.device), byref(level),
byref(self.context)), "D3D11CreateDevice")
self.dup = c_void_p()
hr = _com(self.output, OUTPUT1_DUPLICATE_OUTPUT, [c_void_p, POINTER(c_void_p)], self.device, byref(self.dup))
if hr < 0: # e.g. DXGI_ERROR_UNSUPPORTED in Windows HDR mode, or too many duplications of this monitor
raise GpuCaptureUnavailable(f"DuplicateOutput failed (HRESULT 0x{hr & 0xFFFFFFFF:08X})")
desc = _DuplDesc()
_com(self.dup, DUP_GET_DESC, [POINTER(_DuplDesc)], byref(desc), restype=None)
if desc.Rotation not in (0, 1):
raise GpuCaptureUnavailable("the monitor is rotated")
if desc.InSystemMemory or desc.Format != DXGI_FORMAT_B8G8R8A8_UNORM:
raise GpuCaptureUnavailable(f"the screen's picture isn't 8-bit on the GPU (format {desc.Format})")
if self.x + self.w > desc.Width or self.y + self.h > desc.Height:
raise GpuCaptureUnavailable("the region is outside the monitor")
td = Texture2DDesc(self.w, self.h, 1, 1, DXGI_FORMAT_B8G8R8A8_UNORM, 1, 0, D3D11_USAGE_DEFAULT,
D3D11_BIND_SHADER_RESOURCE, 0, 0)
self.texture = c_void_p()
_check(_com(self.device, DEVICE_CREATE_TEXTURE2D, [POINTER(Texture2DDesc), c_void_p, POINTER(c_void_p)],
byref(td), None, byref(self.texture)), "CreateTexture2D")
err = self.rt.cudaGraphicsD3D11RegisterResource(byref(self.res), self.texture, 0)
if err:
self.res = c_void_p()
raise GpuCaptureUnavailable(f"CUDA can't read a Direct3D texture here (cudaError {err})")
self.rt.cudaGraphicsResourceSetMapFlags(self.res, _CUDA_MAP_READ_ONLY)
self.bgra = torch.empty((self.h, self.w, 4), dtype=torch.uint8, device="cuda")
def _changed(self, info: _FrameInfo) -> bool:
"""Whether this screen update touched our part of the monitor (Windows lists the parts it redrew)."""
if info.TotalMetadataBufferSize == 0:
return True
buf = (ctypes.c_ubyte * info.TotalMetadataBufferSize)()
need = c_uint()
for slot, item in ((DUP_GET_MOVE_RECTS, _MoveRect), (DUP_GET_DIRTY_RECTS, _Rect)):
hr = _com(self.dup, slot, [c_uint, c_void_p, POINTER(c_uint)], len(buf), buf, byref(need))
if hr < 0:
return True # can't tell: copy it
rects = (item * (need.value // ctypes.sizeof(item))).from_buffer(buf)
for r in rects:
if _overlaps(r.dest if item is _MoveRect else r, self.x, self.y, self.w, self.h):
return True
return False
def grab(self, timeout_ms: int = 100):
"""(frame, t_acquired, t_present) when our part of the screen has changed, else None (no change within the
timeout, or a change elsewhere). Raises CaptureLost when Windows takes the duplication away."""
import time
import torch
self._release_frame()
info, resource = _FrameInfo(), c_void_p()
hr = _com(self.dup, DUP_ACQUIRE_NEXT_FRAME, [c_uint, POINTER(_FrameInfo), POINTER(c_void_p)], timeout_ms,
byref(info), byref(resource))
if hr == DXGI_ERROR_WAIT_TIMEOUT:
return None
if hr == DXGI_ERROR_ACCESS_LOST:
raise CaptureLost("Desktop Duplication lost access")
_check(hr, "AcquireNextFrame")
self._held = True
t_acquired = time.perf_counter()
try:
if info.LastPresentTime == 0 or not self._changed(info): # only the mouse moved, or another part changed
self.skipped += info.LastPresentTime != 0
return None
tex = _query(resource, IID_ID3D11Texture2D)
if tex is None:
raise GpuCaptureUnavailable("the screen's picture isn't a Direct3D texture")
try:
box = _Box(self.x, self.y, 0, self.x + self.w, self.y + self.h, 1)
_com(self.context, CONTEXT_COPY_SUBRESOURCE_REGION,
[c_void_p, c_uint, c_uint, c_uint, c_uint, c_void_p, c_uint, POINTER(_Box)],
self.texture, 0, 0, 0, 0, tex, 0, byref(box), restype=None)
finally:
_release(tex)
finally:
_release(resource)
stream = torch.cuda.current_stream()
s = c_void_p(stream.cuda_stream)
res = byref(self.res)
_cuda(self.rt.cudaGraphicsMapResources(1, res, s), "map") # waits for the copy above
try:
arr = c_void_p()
_cuda(self.rt.cudaGraphicsSubResourceGetMappedArray(byref(arr), self.res, 0, 0), "mapped array")
_cuda(self.rt.cudaMemcpy2DFromArrayAsync(c_void_p(self.bgra.data_ptr()), self.w * 4, arr, 0, 0,
self.w * 4, self.h, _MEMCPY_DEVICE_TO_DEVICE, s), "copy")
finally:
_cuda(self.rt.cudaGraphicsUnmapResources(1, res, s), "unmap")
self._release_frame() # Windows can reuse its picture now: ours is copied
frame = to_bgr(self.bgra, self.out_w, self.out_h)
stream.synchronize() # the frame is complete before another thread (the pipeline's) reads it
self.copies += 1
t_present = info.LastPresentTime / self._qpf # QueryPerformanceCounter, as time.perf_counter on Windows
return frame, t_acquired, (t_present if abs(t_present - t_acquired) < 1.0 else None)
def _release_frame(self) -> None:
if self._held:
self._held = False
_com(self.dup, DUP_RELEASE_FRAME, [])
def close(self) -> None:
if self.dup:
self._release_frame()
if self.res:
self.rt.cudaGraphicsUnregisterResource(self.res)
self.res = c_void_p()
for name in ("texture", "dup", "context", "device", "output", "adapter", "factory"):
_release(getattr(self, name))
setattr(self, name, None)
def to_bgr(bgra, out_w: int, out_h: int):
"""HxWx4 BGRA -> out_h x out_w x 3 BGR, on the GPU (bilinear, smoothed when shrinking, as FFmpeg's scale is
near enough)."""
import torch.nn.functional as F
h, w = bgra.shape[:2]
if (w, h) == (out_w, out_h):
return bgra[..., :3].contiguous()
x = bgra[..., :3].permute(2, 0, 1).unsqueeze(0).float()
x = F.interpolate(x, size=(out_h, out_w), mode="bilinear", align_corners=False, antialias=out_w < w)
return x.squeeze(0).permute(1, 2, 0).round_().clamp_(0, 255).to(dtype=bgra.dtype).contiguous()
def _cuda(err: int, what: str) -> None:
if err:
raise CaptureLost(f"CUDA {what} failed (cudaError {err})")
+126
View File
@@ -0,0 +1,126 @@
"""The delay test (L in the video window, PS5 Remote Play): chiaki-ng presses a button on the PS5 a few times, and
each time the pipeline times how long the answer takes to reach this PC, from the moment chiaki-ng sent the press
to the first frame that shows it. That's the controller's trip to the PS5, the game's own response, encoding and
the stream back. Add SmoovPlay's time (measured as it plays) and it's button to screen, all but the controller's
own link (a few ms) and the monitor.
It presses Options: in most games that opens the pause menu, a big change on screen that the game draws at its
own frame rate, so frame generation's delay is included. Best done standing still. (The PS button's control centre
is drawn at 60 fps over the game, so with frame generation on it would pass straight through.)
The picture is compared in 32x18 blocks of brightness: a press is answered when at least a quarter of the blocks
change by much more than the picture moved on its own in the second before the test.
"""
from __future__ import annotations
import time
import numpy as np
import torch
import torch.nn.functional as F
BUTTON_OPTIONS = 1 << 12 # ChiakiControllerButton
PRESSES = 6 # an even number, so a menu that opens and closes ends closed
HOLD_MS = 100
SETTLE_S = 1.0 # watch the picture this long first, to learn how much it moves on its own
SPAN = 10 # ...comparing frames this many ticks apart (about as long as an answer takes)
WAIT_S = 1.0 # the longest wait for an answer
SEND_S = 0.5 # the longest wait for chiaki-ng to send the press
GAP_S = 1.2 # from an answer (or giving up) to the next press
MIN_CHANGE = 6.0 # brightness levels: the smallest change that counts as an answer, however still the picture
def small(frame_u8: torch.Tensor) -> np.ndarray:
"""A frame (HxWx3 uint8 BGR, any device) as 18x32 blocks of brightness."""
grey = frame_u8.float() @ torch.tensor([0.114, 0.587, 0.299], device=frame_u8.device)
return F.adaptive_avg_pool2d(grey[None, None], (18, 32))[0, 0].cpu().numpy()
def change(a: np.ndarray, b: np.ndarray) -> float:
"""How much of the picture changed: the 75th percentile of the blocks' change, so at least a quarter of it."""
return float(np.percentile(np.abs(a - b), 75))
class DelayTest:
"""press(buttons, hold_ms) -> token and press_sent(token) -> time or None are chiaki-ng's (ChiakiSource).
Feed it every frame with feed(); it presses, watches and times by itself until `done`."""
def __init__(self, press, press_sent, presses: int = PRESSES, button: int = BUTTON_OPTIONS,
now: float | None = None) -> None:
self._press, self._press_sent = press, press_sent
self.presses, self.button = presses, button
self.state, self.t_state = "settle", time.perf_counter() if now is None else now
self.recent: list[np.ndarray] = [] # the last few frames' blocks
self.motion: list[float] = []
self.threshold = MIN_CHANGE
self.ms: list[float] = [] # each answered press: sent -> the first frame showing it arrived
self.pressed = self.missed = 0
self.error = ""
self._ref: np.ndarray | None = None
self._token = 0
self._t_sent = 0.0
@property
def done(self) -> bool:
return self.state == "done"
def _to(self, state: str, now: float) -> None:
self.state, self.t_state = state, now
def feed(self, blocks: np.ndarray, t_arrival: float, now: float) -> None:
"""One frame (small()), when it reached this PC, and the time now."""
self.recent = (self.recent + [blocks])[-SPAN - 1:]
if self.state == "settle":
if len(self.recent) > SPAN:
self.motion.append(change(self.recent[0], blocks))
if now - self.t_state >= SETTLE_S and self.motion:
self.threshold = max(MIN_CHANGE, 2.5 * float(np.percentile(self.motion, 95)))
self._to("gap", now - GAP_S)
if self.state == "gap" and now - self.t_state >= GAP_S:
if self.pressed >= self.presses:
self._to("done", now)
return
self._ref, self.pressed = blocks, self.pressed + 1
self._token = self._press(self.button, HOLD_MS)
self._to("sending", now)
if self.state == "sending":
sent = self._press_sent(self._token)
if sent is not None:
self._t_sent = sent
self._to("waiting", now)
elif now - self.t_state > SEND_S:
self.error = "chiaki-ng didn't send the press"
self._to("done", now)
return
if self.state == "waiting":
if t_arrival > self._t_sent and change(self._ref, blocks) > self.threshold:
self.ms.append((t_arrival - self._t_sent) * 1000)
self._to("gap", now)
elif now - self._t_sent > WAIT_S:
self.missed += 1
if self.missed >= 2 and not self.ms:
self.error = "nothing changed on screen after pressing Options"
self._to("done", now)
return
self._to("gap", now)
def status(self) -> str:
"""The overlay's line while it runs."""
if self.state == "settle":
return "DELAY TEST: stand still; it presses Options a few times (a menu opening is what it times)"
return f"DELAY TEST: press {self.pressed} of {self.presses}" + (
f" PS5 answered in {np.median(self.ms):.0f} ms" if self.ms else "")
def result(self, smoovplay_ms: float | None) -> str:
"""The answer, in a line: the PS5 and Remote Play's part, SmoovPlay's, and the two together."""
if self.error and not self.ms:
return (f"Delay test: {self.error}. Try where Options opens a menu, standing still"
if "nothing changed" in self.error else
f"Delay test: {self.error}. Close chiaki-ng and open it from SmoovPlay")
remote = float(np.median(self.ms))
text = (f"Delay test: PS5 and Remote Play {remote:.0f} ms (button sent to the answer arriving, median of "
f"{len(self.ms)})")
if smoovplay_ms is not None:
text += (f", SmoovPlay {smoovplay_ms:.0f} ms: {remote + smoovplay_ms:.0f} ms from button to "
"SmoovPlay's screen, plus your controller's link and your monitor")
return text
+286
View File
@@ -0,0 +1,286 @@
"""DirectML engine: RIFE on any DirectX 12 graphics card (AMD, Intel or NVIDIA) through ONNX Runtime.
For PCs without an NVIDIA card; NVIDIA cards keep the CUDA/TensorRT engine (framegen/interpolator.py, trt.py).
`DmlInterpolator` is a drop-in for `RifeInterpolator`: the same load / prepare / interpolate calls on HxWx3 uint8
BGR frames, here CPU tensors.
The model runs as two ONNX graphs, converted from the RIFE weights once per resolution and flow scale (about 30 s
with PyTorch on the CPU; no NVIDIA card needed) and cached in models/dml/:
* encode: uint8 BGR frame -> [image | features] (fp32, padded), kept on the GPU in one of two ping-pong slots.
* flow: two slots + timestep -> the in-between frame as uint8 BGR, written straight into `out_u8`.
The uint8 conversions are inside the graphs, so only 6 MB frames cross between the CPU and the GPU. The math is
FastIFNet's (framegen/fastrife.py): fp16 convolutions, fp32 warps. The one change is that the warp grid is built
from a row and a column at run time, since an exported full-size grid is a 17 MB constant copied into every warp.
"""
from __future__ import annotations
import ctypes
import os
import time
from ctypes import wintypes
from pathlib import Path
import numpy as np
import torch
import torch.nn.functional as F
from .fastrife import FastIFNet
from .interpolator import DEFAULT_MODEL_DIR
EXPORT_VERSION = 1 # bump when the exported graphs change, so cached files are rebuilt
MODEL_DIR = DEFAULT_MODEL_DIR / "dml"
VENDORS = {0x10DE: "NVIDIA", 0x1002: "AMD", 0x8086: "Intel"}
# ------------------------------------------------------------------------------------------------ graphics cards
class _LUID(ctypes.Structure):
_fields_ = [("LowPart", wintypes.DWORD), ("HighPart", wintypes.LONG)]
class _AdapterDesc1(ctypes.Structure): # DXGI_ADAPTER_DESC1
_fields_ = [("Description", wintypes.WCHAR * 128), ("VendorId", wintypes.UINT), ("DeviceId", wintypes.UINT),
("SubSysId", wintypes.UINT), ("Revision", wintypes.UINT),
("DedicatedVideoMemory", ctypes.c_size_t), ("DedicatedSystemMemory", ctypes.c_size_t),
("SharedSystemMemory", ctypes.c_size_t), ("AdapterLuid", _LUID), ("Flags", wintypes.UINT)]
class _GUID(ctypes.Structure):
_fields_ = [("Data1", wintypes.DWORD), ("Data2", wintypes.WORD), ("Data3", wintypes.WORD),
("Data4", ctypes.c_ubyte * 8)]
_IID_IDXGIFactory1 = _GUID(0x770AAE78, 0xF26F, 0x4DBA, (ctypes.c_ubyte * 8)(0xA8, 0x29, 0x25, 0x3C, 0x83, 0xD1, 0xB3, 0x87))
def _com(obj: ctypes.c_void_p, index: int, *argtypes):
"""Method `index` of a COM object's vtable, callable with the object as its first argument."""
vtbl = ctypes.cast(obj, ctypes.POINTER(ctypes.POINTER(ctypes.c_void_p))).contents
return ctypes.WINFUNCTYPE(ctypes.c_long, ctypes.c_void_p, *argtypes)(vtbl[index])
def adapters() -> list[dict]:
"""The graphics adapters in DXGI order, which is what DirectML's device_id counts (software adapters skipped)."""
factory = ctypes.c_void_p()
if ctypes.windll.dxgi.CreateDXGIFactory1(ctypes.byref(_IID_IDXGIFactory1), ctypes.byref(factory)) < 0:
return []
found = []
try:
for i in range(16):
adapter = ctypes.c_void_p()
if _com(factory, 12, wintypes.UINT, ctypes.POINTER(ctypes.c_void_p))(factory, i, ctypes.byref(adapter)) < 0:
break # DXGI_ERROR_NOT_FOUND: no more adapters
desc = _AdapterDesc1()
_com(adapter, 10, ctypes.POINTER(_AdapterDesc1))(adapter, ctypes.byref(desc))
_com(adapter, 2)(adapter) # Release
if desc.Flags & 2: # DXGI_ADAPTER_FLAG_SOFTWARE (Microsoft Basic Render Driver)
continue
found.append({"index": i, "name": desc.Description, "vendor": VENDORS.get(desc.VendorId, "other"),
"vram_gb": desc.DedicatedVideoMemory / 2**30})
finally:
_com(factory, 2)(factory)
return found
def unavailable_reason() -> str | None:
"""Why the DirectML engine can't run here, or None if it can."""
try:
import onnxruntime as ort
except Exception as e: # noqa: BLE001
return f"ONNX Runtime isn't installed ({str(e)[:80]})"
if "DmlExecutionProvider" not in ort.get_available_providers():
return "this ONNX Runtime has no DirectML (it needs the onnxruntime-directml package)"
if not adapters():
return "no DirectX 12 graphics adapter found"
return None
def pick_adapter() -> dict:
"""The adapter with the most dedicated memory (the graphics card, not integrated graphics).
SMOOVPLAY_DML_ADAPTER=<index> picks one instead (e.g. to try integrated graphics)."""
found = adapters()
if not found:
raise RuntimeError("no DirectX 12 graphics adapter found")
forced = os.environ.get("SMOOVPLAY_DML_ADAPTER")
if forced is not None:
for a in found:
if a["index"] == int(forced):
return a
raise RuntimeError(f"SMOOVPLAY_DML_ADAPTER={forced}: no such adapter ({[a['index'] for a in found]})")
return max(found, key=lambda a: a["vram_gb"])
# ------------------------------------------------------------------------------------------------ conversion
class _DmlIFNet(FastIFNet):
"""FastIFNet with the warp grid built from a row and a column, so the export stays small (same math)."""
def __init__(self, net, ph: int, pw: int, dtype: torch.dtype, device: torch.device) -> None:
super().__init__(net, ph, pw, dtype, device)
del self.base_grid
self.gx = torch.linspace(-1.0, 1.0, pw, device=device).view(1, 1, 1, pw)
self.gy = torch.linspace(-1.0, 1.0, ph, device=device).view(1, 1, ph, 1)
self.sx, self.sy = 2.0 / (pw - 1), 2.0 / (ph - 1)
def _warp(self, src: torch.Tensor, flow: torch.Tensor) -> torch.Tensor:
f = flow.float()
grid = torch.cat([f[:, 0:1] * self.sx + self.gx, f[:, 1:2] * self.sy + self.gy], 1).permute(0, 2, 3, 1)
return F.grid_sample(src, grid, mode="bilinear", padding_mode="border", align_corners=True)
class _EncodeGraph(torch.nn.Module):
def __init__(self, encode: torch.nn.Module, pad: tuple, dtype: torch.dtype) -> None:
super().__init__()
self.encode, self.pad, self.dtype = encode, pad, dtype
self.register_buffer("rgb", torch.tensor([2, 1, 0]))
def forward(self, frame: torch.Tensor) -> torch.Tensor: # (H, W, 3) uint8 BGR
x = frame.to(self.dtype).permute(2, 0, 1).index_select(0, self.rgb).unsqueeze(0) / 255.0
if self.pad[1] or self.pad[3]:
x = F.pad(x, self.pad)
return FastIFNet.make_src(x, self.encode(x))
class _FlowGraph(torch.nn.Module):
def __init__(self, fast: _DmlIFNet, h: int, w: int) -> None:
super().__init__()
self.fast, self.h, self.w = fast, h, w
self.blocks = torch.nn.ModuleList(fast.blocks) # registers the weights
self.register_buffer("bgr", torch.tensor([2, 1, 0]))
def forward(self, src0: torch.Tensor, src1: torch.Tensor, t: torch.Tensor) -> torch.Tensor:
mid = self.fast(src0, src1, t)[0, :, : self.h, : self.w].index_select(0, self.bgr).permute(1, 2, 0)
return mid.clamp(0.0, 1.0).mul(255.0).round().to(torch.uint8) # (H, W, 3) uint8 BGR
def model_paths(version: str, scale: float, width: int, height: int) -> tuple[Path, Path]:
tag = f"rife{version}_{width}x{height}"
return (MODEL_DIR / f"{tag}_encode_v{EXPORT_VERSION}.onnx",
MODEL_DIR / f"{tag}_s{scale}_flow_v{EXPORT_VERSION}.onnx")
def convert(version: str, scale: float, width: int, height: int) -> tuple[Path, Path]:
"""Converts RIFE to the two ONNX graphs (skipping any that are already cached). Runs on the CPU."""
from .interpolator import RifeInterpolator
enc_path, flow_path = model_paths(version, scale, width, height)
if enc_path.exists() and flow_path.exists():
return enc_path, flow_path
print(f"[dml] preparing RIFE {version} for {width}x{height} (once, about 30 s)...")
t0 = time.perf_counter()
MODEL_DIR.mkdir(parents=True, exist_ok=True)
cpu = torch.device("cpu")
it = RifeInterpolator(width, height, version, scale, fp16=True, cuda_graph=False, device="cpu")
frame = torch.zeros((height, width, 3), dtype=torch.uint8)
with torch.no_grad():
if not enc_path.exists():
_export(_EncodeGraph(it.encode, it.pad, it.dtype), (frame,), enc_path, ["frame"], ["src"])
if not flow_path.exists():
fast = _DmlIFNet(it.flownet, it.ph, it.pw, it.dtype, cpu)
src = torch.rand(tuple(it.src[0].shape))
t = torch.full((1, 1, 1, 1), 0.5)
_export(_FlowGraph(fast, height, width), (src, src.clone(), t), flow_path, ["src0", "src1", "t"], ["frame"])
print(f"[dml] prepared in {time.perf_counter() - t0:.0f} s")
return enc_path, flow_path
def _export(module: torch.nn.Module, args: tuple, path: Path, inputs: list[str], outputs: list[str]) -> None:
part = path.with_suffix(".part")
torch.onnx.export(module, args, str(part), dynamo=False, opset_version=17, input_names=inputs,
output_names=outputs)
part.replace(path)
# ------------------------------------------------------------------------------------------------ engine
class DmlInterpolator:
"""RIFE through ONNX Runtime + DirectML. Same calls as RifeInterpolator; frames are CPU tensors."""
backend = "dml"
def __init__(self, width: int, height: int, version: str = "4.22.lite", scale: float = 1.0,
adapter: dict | None = None) -> None:
import onnxruntime as ort
self.ort = ort
self.w, self.h = width, height
self.version, self.scale = version, scale
self.device = torch.device("cpu") # where in_u8 / out_u8 live
self.adapter = adapter or pick_adapter()
dev = self.adapter["index"]
enc_path, flow_path = convert(version, scale, width, height)
self.encode = self._session(enc_path, dev)
self.flow = self._session(flow_path, dev)
self.in_u8 = torch.zeros((height, width, 3), dtype=torch.uint8)
self.out_u8 = torch.zeros((height, width, 3), dtype=torch.uint8)
self._t = np.full((1, 1, 1, 1), 0.5, dtype=np.float32)
# CPU OrtValues that share memory with these arrays. A bound output is written in place on every run, but a
# CPU input is copied to the GPU when it's *bound*, so the frame and the timestep are re-bound on each call.
self._frame_in = ort.OrtValue.ortvalue_from_numpy(self.in_u8.numpy())
self._t_in = ort.OrtValue.ortvalue_from_numpy(self._t)
frame_out = ort.OrtValue.ortvalue_from_numpy(self.out_u8.numpy())
shape = self.encode.get_outputs()[0].shape
self.slots = [ort.OrtValue.ortvalue_from_shape_and_type(shape, np.float32, "dml", dev) for _ in range(2)]
self._prep, self._interp = [], []
for slot in (0, 1):
b = self.encode.io_binding()
b.bind_ortvalue_output("src", self.slots[slot])
self._prep.append(b)
b = self.flow.io_binding() # newest frame in `slot`, the one before it in the other
b.bind_ortvalue_input("src0", self.slots[1 - slot])
b.bind_ortvalue_input("src1", self.slots[slot])
b.bind_ortvalue_output("frame", frame_out)
self._interp.append(b)
def _session(self, path: Path, device_id: int):
ort = self.ort
so = ort.SessionOptions()
so.enable_mem_pattern = False # DirectML requires these two
so.execution_mode = ort.ExecutionMode.ORT_SEQUENTIAL
so.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
s = ort.InferenceSession(str(path), so, providers=[("DmlExecutionProvider", {"device_id": device_id})])
if s.get_providers()[0] != "DmlExecutionProvider":
raise RuntimeError(f"DirectML isn't available (ONNX Runtime providers: {s.get_providers()})")
return s
def describe(self) -> str:
return f"DirectML on {self.adapter['name']}"
def load(self, frame) -> None:
"""Copy an HxWx3 uint8 BGR frame (CPU tensor or numpy array) into the static input."""
if torch.is_tensor(frame):
self.in_u8.copy_(frame)
else:
np.copyto(self.in_u8.numpy(), frame)
def prepare(self, slot: int) -> None:
"""Convert+encode `in_u8` into ping-pong slot `slot` (0/1), on the GPU."""
b = self._prep[slot]
b.bind_ortvalue_input("frame", self._frame_in) # uploads in_u8 as it is now
self.encode.run_with_iobinding(b)
def interpolate(self, newest_slot: int, t: float = 0.5) -> torch.Tensor:
"""Frame at fraction t from slot (1-newest_slot) to newest_slot -> `out_u8` (overwritten by each call)."""
self._t.fill(t)
b = self._interp[newest_slot]
b.bind_ortvalue_input("t", self._t_in)
self.flow.run_with_iobinding(b)
return self.out_u8
def speed_test(self, iters: int = 60, warmup_s: float = 1.0) -> tuple[float, float]:
"""Milliseconds for prepare (once per real frame) and interpolate (once per generated frame).
Timed as whole cycles: prepare's output stays on the GPU, so it may finish after the call returns, while
interpolate waits for its frame. The warm-up lets an idle card raise its clocks first."""
end = time.perf_counter() + warmup_s
while time.perf_counter() < end:
self.prepare(0)
self.interpolate(0)
t0 = time.perf_counter()
for i in range(iters):
self.interpolate(i % 2, 1 / 3 if i % 2 else 2 / 3)
interp = (time.perf_counter() - t0) * 1000 / iters
t0 = time.perf_counter()
for i in range(iters):
self.prepare(i % 2)
self.interpolate(i % 2)
cycle = (time.perf_counter() - t0) * 1000 / iters
return max(cycle - interp, 0.0), interp
+399
View File
@@ -0,0 +1,399 @@
"""Window presentation through a DXGI flip-model swap chain: settings "present" = "dxgi" (Experimental).
Why: OpenGL's own SwapBuffers in a window goes through the Windows compositor as a copy. PresentMon on an RTX 4070
Ti SUPER (scripts/presentmon_check.ps1) showed "Composed: Copy with GPU GDI": about 12 ms more until a frame is on
screen than fullscreen, 3-4% of frames never shown, and frames snapped to the display's refresh, so no G-Sync or
FreeSync in a window. A flip-model swap chain (what games use) lets Windows hand frames to the display directly
("Independent Flip"), in a window too.
How: WGL_NV_DX_interop2 shares the swap chain's back buffer with OpenGL as a renderbuffer. The window still draws
everything with OpenGL, into an offscreen framebuffer (fbo); present() copies that into the back buffer, flipped
(Direct3D's rows run top-down, OpenGL's bottom-up), and calls IDXGISwapChain::Present. The visible window has no
OpenGL context of its own (GLFW NO_API), so OpenGL and DXGI never both present to it; the caller keeps OpenGL on a
hidden window.
NVIDIA only (the interop extension), with Direct3D 11 on the NVIDIA adapter OpenGL runs on. Any failure while
setting up raises, and the caller falls back to OpenGL's own presentation. COM is called through ctypes; the vtable
slots below are from the Windows SDK headers (dxgi.h, dxgi1_2.h, dxgi1_5.h, d3d11.h).
Testing: FRAMEGEN_PRESENT_SNAP=<folder> saves the back buffer as Direct3D is about to show it (read back, so it's
what the window gets, upright or not) every SNAP_EVERY presents and after each resize (scripts/dxgi_smoke.py).
Under test (the fullscreen stall: going fullscreen could block for 2 s or more):
FRAMEGEN_DXGI_MODE=direct OpenGL draws straight into the swap chain's back buffer (shared with the interop).
copy OpenGL draws into a texture of our own (shared instead), and Direct3D copies that into
the back buffer before Present. The interop then never holds a swap chain buffer, which
Windows may be scanning out in fullscreen (Independent Flip). One extra GPU copy.
FRAMEGEN_DXGI_BUFFERS=2|3 the swap chain's buffer count.
A lock or Present over 250 ms is logged separately, to show which one waits.
"""
from __future__ import annotations
import ctypes
import os
import time
import uuid
from ctypes import POINTER, WINFUNCTYPE, byref, c_char_p, c_int, c_long, c_size_t, c_uint, c_ulong, c_void_p
# ---------------------------------------------------------------------------------------------- Windows constants
DXGI_FORMAT_UNKNOWN = 0
DXGI_FORMAT_B8G8R8A8_UNORM = 87
DXGI_USAGE_RENDER_TARGET_OUTPUT = 0x20
DXGI_SCALING_STRETCH = 0
DXGI_SWAP_EFFECT_FLIP_DISCARD = 4
DXGI_ALPHA_MODE_IGNORE = 3
DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING = 2048
DXGI_PRESENT_ALLOW_TEARING = 0x200
DXGI_FEATURE_PRESENT_ALLOW_TEARING = 0
DXGI_MWA_NO_ALT_ENTER = 2
DXGI_ERROR_NOT_FOUND = ctypes.c_long(0x887A0002).value
D3D_DRIVER_TYPE_UNKNOWN = 0 # an adapter is given
D3D11_CREATE_DEVICE_BGRA_SUPPORT = 0x20
D3D11_SDK_VERSION = 7
NVIDIA = 0x10DE
WGL_ACCESS_WRITE_DISCARD_NV = 0x0002
GL_RENDERBUFFER = 0x8D41
D3D11_USAGE_DEFAULT = 0
D3D11_USAGE_STAGING = 3
D3D11_BIND_SHADER_RESOURCE = 0x8
D3D11_BIND_RENDER_TARGET = 0x20
D3D11_CPU_ACCESS_READ = 0x20000
D3D11_MAP_READ = 1
SNAP_DIR = os.environ.get("FRAMEGEN_PRESENT_SNAP")
SNAP_EVERY, SNAP_MAX = 90, 80
MODE = os.environ.get("FRAMEGEN_DXGI_MODE", "direct") # see the module docstring
BUFFERS = min(3, max(2, int(os.environ.get("FRAMEGEN_DXGI_BUFFERS", "2") or 2)))
SLOW_MS = 250.0
IID_IDXGIFactory1 = "770aae78-f26f-4dba-a829-253c83d1b387"
IID_IDXGIFactory2 = "50c83a1c-e072-4c48-87b0-3630fa36a6d0"
IID_IDXGIFactory5 = "7632e1f5-ee65-4dca-87fd-84cd75f8838d"
IID_IDXGIDevice1 = "77db970f-6276-48ba-ba28-070143b4392c"
IID_ID3D11Texture2D = "6f15aaf2-d208-4e89-9ab4-489535d34f9c"
# vtable slots (0-2 are IUnknown's QueryInterface, AddRef, Release)
QUERY_INTERFACE, RELEASE = 0, 2
FACTORY_ENUM_ADAPTERS1, FACTORY_MAKE_WINDOW_ASSOCIATION = 12, 8
FACTORY2_CREATE_SWAP_CHAIN_FOR_HWND = 15
FACTORY5_CHECK_FEATURE_SUPPORT = 28
ADAPTER1_GET_DESC1 = 10
DEVICE1_SET_MAXIMUM_FRAME_LATENCY = 12
SWAP_CHAIN_PRESENT, SWAP_CHAIN_GET_BUFFER, SWAP_CHAIN_RESIZE_BUFFERS = 8, 9, 13
DEVICE_CREATE_TEXTURE2D = 5
CONTEXT_MAP, CONTEXT_UNMAP, CONTEXT_COPY_RESOURCE = 14, 15, 47
class GUID(ctypes.Structure):
_fields_ = [("data", ctypes.c_ubyte * 16)]
@classmethod
def of(cls, text: str) -> "GUID":
return cls.from_buffer_copy(uuid.UUID(text).bytes_le)
class SwapChainDesc1(ctypes.Structure): # DXGI_SWAP_CHAIN_DESC1
_fields_ = [("Width", c_uint), ("Height", c_uint), ("Format", c_uint), ("Stereo", c_int),
("SampleCount", c_uint), ("SampleQuality", c_uint), ("BufferUsage", c_uint), ("BufferCount", c_uint),
("Scaling", c_uint), ("SwapEffect", c_uint), ("AlphaMode", c_uint), ("Flags", c_uint)]
class Texture2DDesc(ctypes.Structure): # D3D11_TEXTURE2D_DESC
_fields_ = [("Width", c_uint), ("Height", c_uint), ("MipLevels", c_uint), ("ArraySize", c_uint), ("Format", c_uint),
("SampleCount", c_uint), ("SampleQuality", c_uint), ("Usage", c_uint), ("BindFlags", c_uint),
("CPUAccessFlags", c_uint), ("MiscFlags", c_uint)]
class MappedSubresource(ctypes.Structure): # D3D11_MAPPED_SUBRESOURCE
_fields_ = [("pData", c_void_p), ("RowPitch", c_uint), ("DepthPitch", c_uint)]
class Luid(ctypes.Structure):
_fields_ = [("LowPart", c_uint), ("HighPart", c_long)]
class AdapterDesc1(ctypes.Structure): # DXGI_ADAPTER_DESC1
_fields_ = [("Description", ctypes.c_wchar * 128), ("VendorId", c_uint), ("DeviceId", c_uint),
("SubSysId", c_uint), ("Revision", c_uint), ("DedicatedVideoMemory", c_size_t),
("DedicatedSystemMemory", c_size_t), ("SharedSystemMemory", c_size_t), ("AdapterLuid", Luid),
("Flags", c_uint)]
def _com(obj: c_void_p, slot: int, argtypes: list, *args, restype=c_long):
"""Calls method `slot` of a COM object. HRESULTs come back as numbers (negative: failed)."""
vtbl = ctypes.cast(obj, POINTER(POINTER(c_void_p)))[0]
return WINFUNCTYPE(restype, c_void_p, *argtypes)(vtbl[slot])(obj, *args)
def _check(hr: int, what: str) -> None:
if hr < 0:
raise OSError(f"{what} failed (HRESULT 0x{hr & 0xFFFFFFFF:08X})")
def _release(obj: c_void_p | None) -> None:
if obj:
_com(obj, RELEASE, [], restype=c_ulong)
def _query(obj: c_void_p, iid: str) -> c_void_p | None:
out = c_void_p()
return out if _com(obj, QUERY_INTERFACE, [POINTER(GUID), POINTER(c_void_p)], byref(GUID.of(iid)),
byref(out)) >= 0 else None
class _Wgl:
"""The WGL_NV_DX_interop2 functions, from the current OpenGL context."""
def __init__(self) -> None:
gl = ctypes.WinDLL("opengl32")
gl.wglGetProcAddress.restype, gl.wglGetProcAddress.argtypes = c_void_p, [c_char_p]
gl.wglGetCurrentDC.restype = c_void_p
def fn(name: str, restype, *argtypes):
p = gl.wglGetProcAddress(name.encode())
if not p:
raise OSError(f"{name} isn't available")
return WINFUNCTYPE(restype, *argtypes)(p)
ext = fn("wglGetExtensionsStringARB", c_char_p, c_void_p)(gl.wglGetCurrentDC()) or b""
if b"WGL_NV_DX_interop2" not in ext.split():
raise OSError("the graphics driver doesn't offer WGL_NV_DX_interop2")
HANDLE = c_void_p
self.open_device = fn("wglDXOpenDeviceNV", HANDLE, c_void_p)
self.close_device = fn("wglDXCloseDeviceNV", c_int, HANDLE)
self.register = fn("wglDXRegisterObjectNV", HANDLE, HANDLE, c_void_p, c_uint, c_uint, c_uint)
self.unregister = fn("wglDXUnregisterObjectNV", c_int, HANDLE, HANDLE)
self.lock = fn("wglDXLockObjectsNV", c_int, HANDLE, c_int, POINTER(HANDLE))
self.unlock = fn("wglDXUnlockObjectsNV", c_int, HANDLE, c_int, POINTER(HANDLE))
def _nvidia_adapter(factory: c_void_p) -> c_void_p:
"""The first NVIDIA adapter: the interop works only with a Direct3D device on the GPU OpenGL runs on (on a
laptop the default adapter is often the integrated one)."""
i = 0
while True:
adapter = c_void_p()
hr = _com(factory, FACTORY_ENUM_ADAPTERS1, [c_uint, POINTER(c_void_p)], i, byref(adapter))
if hr == DXGI_ERROR_NOT_FOUND:
raise OSError("no NVIDIA graphics card found by DXGI")
_check(hr, "EnumAdapters1")
desc = AdapterDesc1()
if _com(adapter, ADAPTER1_GET_DESC1, [POINTER(AdapterDesc1)], byref(desc)) >= 0 and desc.VendorId == NVIDIA:
return adapter
_release(adapter)
i += 1
class DxgiPresenter:
"""A flip-model swap chain on `hwnd`, fed by OpenGL. Draw into `fbo` (sized with resize()), then present().
Needs the OpenGL context that will draw to be current. Raises OSError (or RuntimeError) if anything is missing.
"""
def __init__(self, GL, hwnd: int, w: int, h: int) -> None:
self.GL, self.hwnd = GL, hwnd
self.w = self.h = 0
self.factory = self.factory2 = self.adapter = self.device = self.context = self.swap_chain = None
self.back = self.shared = self.obj = self.hdev = None
self.tex = self.fbo = self.rb = self.back_fbo = None
self.presents, self.snaps, self.snap_next = 0, 0, False
self.mode = MODE if MODE in ("direct", "copy") else "direct"
try:
self._open(w, h)
except BaseException:
self.close()
raise
def _open(self, w: int, h: int) -> None:
GL = self.GL
self.wgl = _Wgl()
dxgi, d3d11 = ctypes.WinDLL("dxgi"), ctypes.WinDLL("d3d11")
self.factory = c_void_p()
_check(dxgi.CreateDXGIFactory1(byref(GUID.of(IID_IDXGIFactory1)), byref(self.factory)), "CreateDXGIFactory1")
self.adapter = _nvidia_adapter(self.factory)
self.device, self.context, level = c_void_p(), c_void_p(), c_uint()
d3d11.D3D11CreateDevice.argtypes = [c_void_p, c_uint, c_void_p, c_uint, c_void_p, c_uint, c_uint,
POINTER(c_void_p), POINTER(c_uint), POINTER(c_void_p)]
_check(d3d11.D3D11CreateDevice(self.adapter, D3D_DRIVER_TYPE_UNKNOWN, None, D3D11_CREATE_DEVICE_BGRA_SUPPORT,
None, 0, D3D11_SDK_VERSION, byref(self.device), byref(level),
byref(self.context)), "D3D11CreateDevice")
self.factory2 = _query(self.factory, IID_IDXGIFactory2)
if self.factory2 is None:
raise OSError("DXGI 1.2 isn't available")
# Tearing (vsync off, in a window) needs DXGI 1.5 and a driver that allows it; without it, vsync off still
# presents at once but Windows waits for the next refresh to show it.
self.tearing = False
factory5 = _query(self.factory, IID_IDXGIFactory5)
if factory5 is not None:
allow = c_int(0)
if _com(factory5, FACTORY5_CHECK_FEATURE_SUPPORT, [c_uint, c_void_p, c_uint],
DXGI_FEATURE_PRESENT_ALLOW_TEARING, byref(allow), ctypes.sizeof(allow)) >= 0:
self.tearing = bool(allow.value)
_release(factory5)
self.flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING if self.tearing else 0
desc = SwapChainDesc1(Width=max(w, 1), Height=max(h, 1), Format=DXGI_FORMAT_B8G8R8A8_UNORM, SampleCount=1,
BufferUsage=DXGI_USAGE_RENDER_TARGET_OUTPUT, BufferCount=BUFFERS,
Scaling=DXGI_SCALING_STRETCH,
SwapEffect=DXGI_SWAP_EFFECT_FLIP_DISCARD, AlphaMode=DXGI_ALPHA_MODE_IGNORE,
Flags=self.flags)
self.swap_chain = c_void_p()
_check(_com(self.factory2, FACTORY2_CREATE_SWAP_CHAIN_FOR_HWND,
[c_void_p, c_void_p, POINTER(SwapChainDesc1), c_void_p, c_void_p, POINTER(c_void_p)],
self.device, c_void_p(hwnd_value(self.hwnd)), byref(desc), None, None, byref(self.swap_chain)),
"CreateSwapChainForHwnd")
_com(self.factory2, FACTORY_MAKE_WINDOW_ASSOCIATION, [c_void_p, c_uint], c_void_p(hwnd_value(self.hwnd)),
DXGI_MWA_NO_ALT_ENTER) # Alt+Enter is ours (F), not DXGI's exclusive fullscreen
device1 = _query(self.device, IID_IDXGIDevice1)
if device1 is not None: # at most one frame queued ahead: no extra delay when the GPU is ahead
_com(device1, DEVICE1_SET_MAXIMUM_FRAME_LATENCY, [c_uint], 1)
_release(device1)
self.hdev = self.wgl.open_device(self.device)
if not self.hdev:
raise OSError("wglDXOpenDeviceNV failed")
self.tex, self.fbo = GL.glGenTextures(1), GL.glGenFramebuffers(1)
self.rb, self.back_fbo = GL.glGenRenderbuffers(1), GL.glGenFramebuffers(1)
self.resize(max(w, 1), max(h, 1))
self.present(True, check=True) # fails here, not mid-session, if the driver can't do it
def _attach(self, w: int, h: int) -> None:
"""Shares a w x h buffer with OpenGL: the swap chain's back buffer ("direct"), or a texture of our own that
present() copies into it ("copy"). Direct3D 11 keeps buffer 0 as the one to draw into next, whichever buffer
that is, so this lasts until the next resize."""
GL = self.GL
self.back = c_void_p()
_check(_com(self.swap_chain, SWAP_CHAIN_GET_BUFFER, [c_uint, POINTER(GUID), POINTER(c_void_p)], 0,
byref(GUID.of(IID_ID3D11Texture2D)), byref(self.back)), "GetBuffer")
target = self.back
if self.mode == "copy":
desc = Texture2DDesc(Width=w, Height=h, MipLevels=1, ArraySize=1, Format=DXGI_FORMAT_B8G8R8A8_UNORM,
SampleCount=1, Usage=D3D11_USAGE_DEFAULT,
BindFlags=D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE)
self.shared = c_void_p()
_check(_com(self.device, DEVICE_CREATE_TEXTURE2D, [POINTER(Texture2DDesc), c_void_p, POINTER(c_void_p)],
byref(desc), None, byref(self.shared)), "CreateTexture2D (shared)")
target = self.shared
self.obj = self.wgl.register(self.hdev, target, int(self.rb), GL_RENDERBUFFER, WGL_ACCESS_WRITE_DISCARD_NV)
if not self.obj:
raise OSError("wglDXRegisterObjectNV failed")
GL.glBindFramebuffer(GL.GL_DRAW_FRAMEBUFFER, self.back_fbo)
GL.glFramebufferRenderbuffer(GL.GL_DRAW_FRAMEBUFFER, GL.GL_COLOR_ATTACHMENT0, GL.GL_RENDERBUFFER, self.rb)
def _detach(self) -> None:
if self.obj:
self.wgl.unregister(self.hdev, self.obj)
self.obj = None
_release(self.shared)
_release(self.back)
self.back = self.shared = None
def resize(self, w: int, h: int) -> None:
"""Matches the swap chain and `fbo` to the window's size (in pixels); cheap when it hasn't changed."""
if (w, h) == (self.w, self.h) or w <= 0 or h <= 0:
return
GL = self.GL
self._detach()
if self.w: # not the first time: the buffers were made at the old size
_check(_com(self.swap_chain, SWAP_CHAIN_RESIZE_BUFFERS, [c_uint, c_uint, c_uint, c_uint, c_uint], 0, w, h,
DXGI_FORMAT_UNKNOWN, self.flags), "ResizeBuffers")
self._attach(w, h)
GL.glBindTexture(GL.GL_TEXTURE_2D, self.tex)
GL.glTexImage2D(GL.GL_TEXTURE_2D, 0, GL.GL_RGBA8, w, h, 0, GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, None)
GL.glBindFramebuffer(GL.GL_DRAW_FRAMEBUFFER, self.fbo)
GL.glFramebufferTexture2D(GL.GL_DRAW_FRAMEBUFFER, GL.GL_COLOR_ATTACHMENT0, GL.GL_TEXTURE_2D, self.tex, 0)
GL.glClear(GL.GL_COLOR_BUFFER_BIT) # black until the first frame, not whatever the memory held
self.snap_next = self.w > 0 # (testing) the first frame at the new size, after it's drawn
self.w, self.h = w, h
def present(self, vsync: bool, check: bool = False) -> None:
"""Copies `fbo` into the back buffer (upright) and shows it. vsync off: at once, tearing if allowed."""
GL, handles = self.GL, (c_void_p * 1)(self.obj)
t0 = time.perf_counter()
if not self.wgl.lock(self.hdev, 1, handles):
raise OSError("wglDXLockObjectsNV failed")
self._say_if_slow("lock", t0)
try:
GL.glBindFramebuffer(GL.GL_READ_FRAMEBUFFER, self.fbo)
GL.glBindFramebuffer(GL.GL_DRAW_FRAMEBUFFER, self.back_fbo)
if check and GL.glCheckFramebufferStatus(GL.GL_DRAW_FRAMEBUFFER) != GL.GL_FRAMEBUFFER_COMPLETE:
raise OSError("the shared back buffer can't be drawn into")
GL.glBlitFramebuffer(0, 0, self.w, self.h, 0, self.h, self.w, 0, GL.GL_COLOR_BUFFER_BIT, GL.GL_NEAREST)
finally:
t0 = time.perf_counter()
self.wgl.unlock(self.hdev, 1, handles)
self._say_if_slow("unlock", t0)
if self.shared is not None: # "copy": our texture into the back buffer, on the GPU (after OpenGL's blit)
_com(self.context, CONTEXT_COPY_RESOURCE, [c_void_p, c_void_p], self.back, self.shared, restype=None)
self.presents += 1
if SNAP_DIR and not check and self.snaps < SNAP_MAX and (self.snap_next or self.presents % SNAP_EVERY == 0):
self._snap(vsync)
sync, flags = (1, 0) if vsync else (0, DXGI_PRESENT_ALLOW_TEARING if self.tearing else 0)
t0 = time.perf_counter()
hr = _com(self.swap_chain, SWAP_CHAIN_PRESENT, [c_uint, c_uint], sync, flags)
self._say_if_slow("Present call", t0)
_check(hr, "Present")
def _say_if_slow(self, what: str, t0: float) -> None:
ms = (time.perf_counter() - t0) * 1000
if ms > SLOW_MS:
print(f"[display] DXGI {what} took {ms:.0f} ms ({self.mode}, {BUFFERS} buffers, {self.w}x{self.h})")
def read_back(self):
"""The back buffer as Direct3D will show it (rows top-down), as BGR. Waits for the GPU: for testing only, between
drawing and Present."""
import numpy as np
desc = Texture2DDesc(Width=self.w, Height=self.h, MipLevels=1, ArraySize=1, Format=DXGI_FORMAT_B8G8R8A8_UNORM,
SampleCount=1, Usage=D3D11_USAGE_STAGING, CPUAccessFlags=D3D11_CPU_ACCESS_READ)
staging = c_void_p()
_check(_com(self.device, DEVICE_CREATE_TEXTURE2D, [POINTER(Texture2DDesc), c_void_p, POINTER(c_void_p)],
byref(desc), None, byref(staging)), "CreateTexture2D")
try:
_com(self.context, CONTEXT_COPY_RESOURCE, [c_void_p, c_void_p], staging, self.back, restype=None)
m = MappedSubresource()
_check(_com(self.context, CONTEXT_MAP, [c_void_p, c_uint, c_uint, c_uint, POINTER(MappedSubresource)],
staging, 0, D3D11_MAP_READ, 0, byref(m)), "Map")
try:
buf = (ctypes.c_ubyte * (m.RowPitch * self.h)).from_address(m.pData)
return np.frombuffer(buf, np.uint8).reshape(self.h, m.RowPitch // 4, 4)[:, :self.w, :3].copy()
finally:
_com(self.context, CONTEXT_UNMAP, [c_void_p, c_uint], staging, 0, restype=None)
finally:
_release(staging)
def _snap(self, vsync: bool) -> None:
import cv2
self.snap_next = False
try:
os.makedirs(SNAP_DIR, exist_ok=True)
name = f"dxgi_{self.presents:06d}_{self.w}x{self.h}_vsync-{'on' if vsync else 'off'}.png"
cv2.imwrite(os.path.join(SNAP_DIR, name), self.read_back())
self.snaps += 1
except Exception as e: # noqa: BLE001 - testing aid: say so, keep presenting
print(f"[display] couldn't save the back buffer: {e}")
self.snaps = SNAP_MAX
def close(self) -> None:
GL = self.GL
try:
self._detach()
if self.hdev:
self.wgl.close_device(self.hdev)
self.hdev = None
except Exception: # noqa: BLE001 - closing: free what we can
pass
for fb in (self.fbo, self.back_fbo):
if fb:
GL.glDeleteFramebuffers(1, [fb])
if self.rb:
GL.glDeleteRenderbuffers(1, [self.rb])
if self.tex:
GL.glDeleteTextures([self.tex])
self.fbo = self.back_fbo = self.rb = self.tex = None
for name in ("swap_chain", "factory2", "context", "device", "adapter", "factory"):
_release(getattr(self, name))
setattr(self, name, None)
def hwnd_value(hwnd) -> int:
"""glfw.get_win32_window gives an int or a ctypes pointer, depending on the pyGLFW version."""
if isinstance(hwnd, int):
return hwnd
return ctypes.cast(hwnd, c_void_p).value or 0
+88
View File
@@ -0,0 +1,88 @@
"""Streaming-optimised forward pass for the RIFE v4.2x IFNet family.
Same math as `IFNet.forward` in framegen/rife/*, restructured to cut full-resolution
memory traffic (which, not convolution FLOPs, dominates at 1080p+):
1. One warp per direction instead of two: the original warps `img` with flow_i at the
end of step i and warps `f` with the same flow_i at the start of step i+1, so we warp
a pre-concatenated [img | f] tensor once.
2. Each block's inputs are downsampled *before* concatenation (bilinear resize is
per-channel, so this is exact) rather than concatenating ~28 channels at full res.
3. The fp32 copy needed for accurate grid_sample is made once per frame (`make_src`),
not twice per warp.
4. Resizes by a factor of 1 are skipped.
Results match the reference forward to fp16 rounding (checked by scripts/check_fast.py).
"""
from __future__ import annotations
import torch
import torch.nn.functional as F
def _resize(t: torch.Tensor, factor: float) -> torch.Tensor:
return t if factor == 1 else F.interpolate(t, scale_factor=factor, mode="bilinear")
class FastIFNet:
def __init__(self, net: torch.nn.Module, ph: int, pw: int, dtype: torch.dtype, device: torch.device) -> None:
# NHWC conv weights: cuDNN's fast fp16 kernels are NHWC, so NCHW would pay a layout
# transpose around every conv.
self.blocks = [getattr(net, f"block{i}").to(memory_format=torch.channels_last)
for i in range(len(net.scale_list))]
self.scales = list(net.scale_list)
self.dtype = dtype
gx = torch.linspace(-1.0, 1.0, pw, device=device).view(1, 1, pw).expand(1, ph, pw)
gy = torch.linspace(-1.0, 1.0, ph, device=device).view(1, ph, 1).expand(1, ph, pw)
self.base_grid = torch.stack([gx, gy], dim=-1).contiguous() # (1,H,W,2) for grid_sample
self.flow_to_grid = torch.tensor([2.0 / (pw - 1), 2.0 / (ph - 1)], device=device)
# Timestep is a constant plane (0.5 = midpoint); its bilinear downsample is the same constant.
# Static tensors, so CUDA graphs read whatever set_timestep last wrote.
self.timestep = {}
for s in self.scales:
probe = _resize(torch.zeros(1, 1, ph, pw, device=device), 1.0 / s)
self.timestep[s] = torch.full(probe.shape, 0.5, dtype=dtype, device=device)
def set_timestep(self, t: float) -> None:
for plane in self.timestep.values():
plane.fill_(t)
@staticmethod
def make_src(img: torch.Tensor, feat: torch.Tensor) -> torch.Tensor:
"""Per-frame [img(3) | encoder features] in fp32, ready for warping."""
return torch.cat([img, feat], 1).float()
def _warp(self, src: torch.Tensor, flow: torch.Tensor) -> torch.Tensor:
grid = flow.permute(0, 2, 3, 1).float() * self.flow_to_grid + self.base_grid
return F.grid_sample(src, grid, mode="bilinear", padding_mode="border", align_corners=True)
@torch.no_grad()
def __call__(self, src0: torch.Tensor, src1: torch.Tensor, t: torch.Tensor | None = None) -> torch.Tensor:
"""Frame at the current timestep (1,3,H,W) fp32 in 0..1 (unclamped) between two `make_src` tensors.
t: optional (1,1,1,1) timestep tensor (the ONNX/TensorRT export takes it as an input) instead of the
planes set by set_timestep."""
dt = self.dtype
flow = mask = feat = None
w0, w1 = src0, src1 # at step 0 nothing is warped yet
n = len(self.blocks)
for i, (blk, s) in enumerate(zip(self.blocks, self.scales)):
a = _resize(w0, 1.0 / s).to(dt)
b = _resize(w1, 1.0 / s).to(dt)
ts = self.timestep[s] if t is None else t.to(dt).expand(1, 1, a.shape[2], a.shape[3])
parts = [a[:, :3], b[:, :3], a[:, 3:], b[:, 3:], ts]
if flow is not None:
parts += [_resize(mask, 1.0 / s), _resize(feat, 1.0 / s), _resize(flow, 1.0 / s) / s]
x = torch.cat(parts, 1).contiguous(memory_format=torch.channels_last)
tmp = blk.lastconv(blk.convblock(blk.conv0(x))).contiguous()
tmp = _resize(tmp, s)
fd = tmp[:, :4] * s
flow = fd if flow is None else flow + fd
mask, feat = tmp[:, 4:5], tmp[:, 5:]
last = i == n - 1
# On the final step only the images are needed, not the warped features.
w0 = self._warp(src0[:, :3] if last else src0, flow[:, :2])
w1 = self._warp(src1[:, :3] if last else src1, flow[:, 2:4])
m = torch.sigmoid(mask.float())
return w0 * m + w1 * (1 - m)
+178
View File
@@ -0,0 +1,178 @@
"""AMD FidelityFX Super Resolution 1 (FSR 1) for the display window.
Two OpenGL fragment-shader passes where the frame is drawn to the screen:
EASU (edge-adaptive upscale to the window size) and RCAS (sharpening).
Because it runs at draw time it scales real and generated frames alike, and it doesn't touch the
interpolation's CUDA work. The shader code is AMD's own (framegen/shaders/fsr1, MIT licence).
"""
from __future__ import annotations
from pathlib import Path
SHADER_DIR = Path(__file__).resolve().parent / "shaders" / "fsr1"
_VERT = """#version 450
void main() { // one triangle covering the viewport
vec2 p = vec2((gl_VertexID << 1) & 2, gl_VertexID & 2);
gl_Position = vec4(p * 2.0 - 1.0, 0.0, 1.0);
}
"""
_EASU = """
layout(binding = 0) uniform sampler2D src;
uniform vec2 in_size; // source image, pixels
uniform vec2 out_size; // upscaled image, pixels
out vec4 color;
AF4 FsrEasuRF(AF2 p) { return textureGather(src, p, 0); }
AF4 FsrEasuGF(AF2 p) { return textureGather(src, p, 1); }
AF4 FsrEasuBF(AF2 p) { return textureGather(src, p, 2); }
void main() {
AU4 c0, c1, c2, c3;
FsrEasuCon(c0, c1, c2, c3, in_size.x, in_size.y, in_size.x, in_size.y, out_size.x, out_size.y);
AF3 c;
FsrEasuF(c, AU2(gl_FragCoord.xy), c0, c1, c2, c3);
color = vec4(c, 1.0);
}
"""
# Images keep row 0 at the top (texture row 0); the window's row 0 is the bottom, so RCAS flips while it draws.
_RCAS = """
layout(binding = 0) uniform sampler2D mid;
uniform ivec2 origin; // window pixel of the image's bottom-left corner
uniform float sharpness; // stops below maximum sharpness: 0 = max, each +1 halves it
out vec4 color;
AF4 FsrRcasLoadF(ASU2 p) { return texelFetch(mid, clamp(p, ASU2(0), textureSize(mid, 0) - 1), 0); }
void FsrRcasInputF(inout AF1 r, inout AF1 g, inout AF1 b) {}
void main() {
ivec2 q = ivec2(gl_FragCoord.xy) - origin;
AU2 ip = AU2(q.x, textureSize(mid, 0).y - 1 - q.y);
AU4 con;
FsrRcasCon(con, sharpness);
AF1 r, g, b;
FsrRcasF(r, g, b, ip, con);
color = vec4(r, g, b, 1.0);
}
"""
def _source(defines: str, body: str) -> str:
a = (SHADER_DIR / "ffx_a.h").read_text(encoding="utf-8")
f = (SHADER_DIR / "ffx_fsr1.h").read_text(encoding="utf-8")
return "#version 450\n#define A_GPU 1\n#define A_GLSL 1\n" + a + defines + f + body
class FsrScaler:
"""FSR 1 upscaling of a GL texture into a rectangle of a framebuffer. Needs a current GL 4.5 context."""
def __init__(self, GL, sharpness: float = 0.5, denoise: bool = True) -> None:
self.GL, self.sharpness = GL, float(sharpness)
rcas_defs = "#define FSR_RCAS_F 1\n" + ("#define FSR_RCAS_DENOISE 1\n" if denoise else "")
self.easu = self._program(_source("#define FSR_EASU_F 1\n", _EASU))
self.rcas = self._program(_source(rcas_defs, _RCAS))
self.u_in = GL.glGetUniformLocation(self.easu, "in_size")
self.u_out = GL.glGetUniformLocation(self.easu, "out_size")
self.u_origin = GL.glGetUniformLocation(self.rcas, "origin")
self.u_sharp = GL.glGetUniformLocation(self.rcas, "sharpness")
self.vao = GL.glGenVertexArrays(1)
self.mid_tex = self.mid_fbo = None
self.mid_size = (0, 0)
def _program(self, frag: str) -> int:
from OpenGL.GL import shaders
GL = self.GL
return shaders.compileProgram(shaders.compileShader(_VERT, GL.GL_VERTEX_SHADER),
shaders.compileShader(frag, GL.GL_FRAGMENT_SHADER), validate=False)
def _mid(self, w: int, h: int) -> None:
"""The EASU output: an RGBA8 texture at the upscaled size, re-made when the window size changes."""
GL = self.GL
if self.mid_size == (w, h):
return
if self.mid_tex is not None:
GL.glDeleteFramebuffers(1, [self.mid_fbo])
GL.glDeleteTextures([self.mid_tex])
self.mid_tex = GL.glGenTextures(1)
GL.glBindTexture(GL.GL_TEXTURE_2D, self.mid_tex)
for p, v in ((GL.GL_TEXTURE_MIN_FILTER, GL.GL_NEAREST), (GL.GL_TEXTURE_MAG_FILTER, GL.GL_NEAREST),
(GL.GL_TEXTURE_WRAP_S, GL.GL_CLAMP_TO_EDGE), (GL.GL_TEXTURE_WRAP_T, GL.GL_CLAMP_TO_EDGE)):
GL.glTexParameteri(GL.GL_TEXTURE_2D, p, v)
GL.glTexImage2D(GL.GL_TEXTURE_2D, 0, GL.GL_RGBA8, w, h, 0, GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, None)
self.mid_fbo = GL.glGenFramebuffers(1)
GL.glBindFramebuffer(GL.GL_FRAMEBUFFER, self.mid_fbo)
GL.glFramebufferTexture2D(GL.GL_FRAMEBUFFER, GL.GL_COLOR_ATTACHMENT0, GL.GL_TEXTURE_2D, self.mid_tex, 0)
self.mid_size = (w, h)
def draw(self, src_tex: int, sw: int, sh: int, dst_fbo: int, x0: int, y0: int, dw: int, dh: int) -> None:
"""Upscale src_tex (sw x sh, row 0 = image top) into dst_fbo's rectangle at (x0, y0) of size dw x dh,
upright on screen. Leaves dst_fbo bound as the framebuffer."""
GL = self.GL
self._mid(dw, dh)
GL.glBindVertexArray(self.vao)
GL.glActiveTexture(GL.GL_TEXTURE0)
GL.glBindFramebuffer(GL.GL_FRAMEBUFFER, self.mid_fbo)
GL.glViewport(0, 0, dw, dh)
GL.glUseProgram(self.easu)
GL.glUniform2f(self.u_in, float(sw), float(sh))
GL.glUniform2f(self.u_out, float(dw), float(dh))
GL.glBindTexture(GL.GL_TEXTURE_2D, src_tex)
GL.glDrawArrays(GL.GL_TRIANGLES, 0, 3)
GL.glBindFramebuffer(GL.GL_FRAMEBUFFER, dst_fbo)
GL.glViewport(x0, y0, dw, dh)
GL.glUseProgram(self.rcas)
GL.glUniform2i(self.u_origin, x0, y0)
GL.glUniform1f(self.u_sharp, self.sharpness)
GL.glBindTexture(GL.GL_TEXTURE_2D, self.mid_tex)
GL.glDrawArrays(GL.GL_TRIANGLES, 0, 3)
GL.glUseProgram(0)
GL.glBindVertexArray(0)
def close(self) -> None:
GL = self.GL
if self.mid_tex is not None:
GL.glDeleteFramebuffers(1, [self.mid_fbo])
GL.glDeleteTextures([self.mid_tex])
GL.glDeleteProgram(self.easu)
GL.glDeleteProgram(self.rcas)
GL.glDeleteVertexArrays(1, [self.vao])
class GpuTimer:
"""Time GL work with timer queries, read back a few frames later so it never stalls the pipeline."""
def __init__(self, GL, ring: int = 4) -> None:
self.GL, self.ring = GL, ring
self.queries = list(GL.glGenQueries(ring))
self.pending: list[tuple[int, str]] = [] # (query, label) in flight
self.ms: dict[str, list[float]] = {}
def begin(self) -> int | None:
GL = self.GL
self._collect()
if len(self.pending) >= self.ring:
return None # all in flight: skip timing this frame
busy = {q for q, _ in self.pending}
q = next(q for q in self.queries if q not in busy)
GL.glBeginQuery(GL.GL_TIME_ELAPSED, q)
return q
def end(self, q: int | None, label: str) -> None:
if q is not None:
self.GL.glEndQuery(self.GL.GL_TIME_ELAPSED)
self.pending.append((q, label))
def _collect(self) -> None:
GL = self.GL
while self.pending:
q, label = self.pending[0]
if not GL.glGetQueryObjectiv(q, GL.GL_QUERY_RESULT_AVAILABLE):
return
ns = GL.glGetQueryObjectuiv(q, GL.GL_QUERY_RESULT) # 32-bit: fine below 4 s (PyOpenGL's ui64v is broken)
self.ms.setdefault(label, []).append(int(ns) / 1e6)
self.pending.pop(0)
def close(self) -> None:
self.GL.glDeleteQueries(len(self.queries), self.queries)
+167
View File
@@ -0,0 +1,167 @@
"""CUDA -> OpenGL texture copy, so frames already on the GPU are shown without a trip through the CPU.
The usual path downloads each frame to the CPU (~0.5-1 ms) and uploads it again with glTexSubImage2D
(~1.5-2 ms for 1080p BGR). Here the GL texture is registered with CUDA once and each frame is a
device-to-device copy into it (~0.05 ms). Uses the CUDA runtime that PyTorch already loaded, so it shares
PyTorch's context and stream ordering.
"""
from __future__ import annotations
import ctypes
import glob
import os
import torch
_GRAPHICS_REGISTER_WRITE_DISCARD = 2
_MEMCPY_DEVICE_TO_DEVICE = 3
_GL_TEXTURE_2D = 0x0DE1
def cudart_path() -> str:
"""PyTorch's CUDA runtime DLL (cudart64_*.dll)."""
libdir = os.path.join(os.path.dirname(torch.__file__), "lib")
for path in sorted(glob.glob(os.path.join(libdir, "cudart64_*.dll"))):
return path
raise OSError("PyTorch's CUDA runtime (cudart64_*.dll) not found")
def _cudart() -> ctypes.CDLL:
return ctypes.CDLL(cudart_path())
class CudaGLTexture:
"""Copies HxWx3 uint8 BGR CUDA tensors into an existing GL_RGBA8 texture of the same size.
Create it, and call `upload`, on the thread whose GL context owns the texture.
"""
def __init__(self, tex: int, w: int, h: int) -> None:
self.w, self.h = w, h
self.rt = rt = _cudart()
p, i, u, s = ctypes.c_void_p, ctypes.c_int, ctypes.c_uint, ctypes.c_size_t
rt.cudaGraphicsGLRegisterImage.argtypes = [ctypes.POINTER(p), u, u, u]
rt.cudaGraphicsMapResources.argtypes = [i, ctypes.POINTER(p), p]
rt.cudaGraphicsUnmapResources.argtypes = [i, ctypes.POINTER(p), p]
rt.cudaGraphicsSubResourceGetMappedArray.argtypes = [ctypes.POINTER(p), p, u, u]
rt.cudaMemcpy2DToArrayAsync.argtypes = [p, s, s, p, s, s, s, i, p]
rt.cudaGraphicsUnregisterResource.argtypes = [p]
torch.cuda.current_device() # make sure the runtime is initialised on this thread
self.res = p()
self._check(rt.cudaGraphicsGLRegisterImage(ctypes.byref(self.res), tex, _GL_TEXTURE_2D,
_GRAPHICS_REGISTER_WRITE_DISCARD), "register texture")
# RGBA staging tensor (the texture is RGBA8; CUDA can't map 3-channel GL textures). Alpha stays 255.
self.rgba = torch.full((h, w, 4), 255, dtype=torch.uint8, device="cuda")
def _check(self, err: int, what: str) -> None:
if err:
raise RuntimeError(f"CUDA-GL interop: {what} failed (cudaError {err})")
def upload(self, bgr: torch.Tensor) -> None:
stream = ctypes.c_void_p(torch.cuda.current_stream().cuda_stream)
self.rgba[..., :3].copy_(bgr.flip(-1))
res = ctypes.byref(self.res)
self._check(self.rt.cudaGraphicsMapResources(1, res, stream), "map")
try:
arr = ctypes.c_void_p()
self._check(self.rt.cudaGraphicsSubResourceGetMappedArray(ctypes.byref(arr), self.res, 0, 0), "get array")
self._check(self.rt.cudaMemcpy2DToArrayAsync(arr, 0, 0, ctypes.c_void_p(self.rgba.data_ptr()),
self.w * 4, self.w * 4, self.h,
_MEMCPY_DEVICE_TO_DEVICE, stream), "copy")
finally:
# Unmapping orders GL's use of the texture after the copy (stream semantics), no CPU wait needed.
self._check(self.rt.cudaGraphicsUnmapResources(1, res, stream), "unmap")
def close(self) -> None:
if self.res:
self.rt.cudaGraphicsUnregisterResource(self.res)
self.res = ctypes.c_void_p()
_GRAPHICS_REGISTER_SURFACE_LOAD_STORE = 4
class CudaGLImage:
"""A GL_RGBA8 texture that CUDA kernels write through a surface object (e.g. RTX VSR's output).
map() gives the texture's CUDA array; unmap() hands it back to GL, ordered on the same stream.
"""
def __init__(self, tex: int) -> None:
self.rt = rt = _cudart()
p, i, u = ctypes.c_void_p, ctypes.c_int, ctypes.c_uint
rt.cudaGraphicsGLRegisterImage.argtypes = [ctypes.POINTER(p), u, u, u]
rt.cudaGraphicsMapResources.argtypes = [i, ctypes.POINTER(p), p]
rt.cudaGraphicsUnmapResources.argtypes = [i, ctypes.POINTER(p), p]
rt.cudaGraphicsSubResourceGetMappedArray.argtypes = [ctypes.POINTER(p), p, u, u]
rt.cudaGraphicsUnregisterResource.argtypes = [p]
self.res, self.array = p(), p()
err = rt.cudaGraphicsGLRegisterImage(ctypes.byref(self.res), tex, _GL_TEXTURE_2D,
_GRAPHICS_REGISTER_SURFACE_LOAD_STORE)
if err:
raise RuntimeError(f"CUDA-GL interop: register output texture failed (cudaError {err})")
def map(self, stream: int) -> ctypes.c_void_p:
s = ctypes.c_void_p(stream)
err = self.rt.cudaGraphicsMapResources(1, ctypes.byref(self.res), s)
if not err:
err = self.rt.cudaGraphicsSubResourceGetMappedArray(ctypes.byref(self.array), self.res, 0, 0)
if err:
self.rt.cudaGraphicsUnmapResources(1, ctypes.byref(self.res), s)
if err:
raise RuntimeError(f"CUDA-GL interop: map output texture failed (cudaError {err})")
return self.array
def unmap(self, stream: int) -> None:
self.rt.cudaGraphicsUnmapResources(1, ctypes.byref(self.res), ctypes.c_void_p(stream))
def close(self) -> None:
if self.res:
self.rt.cudaGraphicsUnregisterResource(self.res)
self.res = ctypes.c_void_p()
_GRAPHICS_REGISTER_READ_ONLY = 1
class CudaGLReader:
"""Copies a GL_RGBA8 texture (w x h) into an (h, w, 4) uint8 CUDA tensor: a look drawn for instant replay
(framegen/looks_gl.py). Texture row 0 lands in tensor row 0. Create and use it on the GL context's thread."""
def __init__(self, tex: int, w: int, h: int) -> None:
self.w, self.h = w, h
self.rt = rt = _cudart()
p, i, u, s = ctypes.c_void_p, ctypes.c_int, ctypes.c_uint, ctypes.c_size_t
rt.cudaGraphicsGLRegisterImage.argtypes = [ctypes.POINTER(p), u, u, u]
rt.cudaGraphicsMapResources.argtypes = [i, ctypes.POINTER(p), p]
rt.cudaGraphicsUnmapResources.argtypes = [i, ctypes.POINTER(p), p]
rt.cudaGraphicsSubResourceGetMappedArray.argtypes = [ctypes.POINTER(p), p, u, u]
rt.cudaMemcpy2DFromArrayAsync.argtypes = [p, s, p, s, s, s, s, i, p]
rt.cudaGraphicsUnregisterResource.argtypes = [p]
torch.cuda.current_device()
self.res = p()
err = rt.cudaGraphicsGLRegisterImage(ctypes.byref(self.res), tex, _GL_TEXTURE_2D, _GRAPHICS_REGISTER_READ_ONLY)
if err:
raise RuntimeError(f"CUDA-GL interop: register texture for reading failed (cudaError {err})")
def read(self, out: torch.Tensor) -> None:
"""Into `out` (contiguous (h, w, 4) uint8 on the GPU), ordered on the current stream after GL's drawing."""
stream = ctypes.c_void_p(torch.cuda.current_stream().cuda_stream)
res = ctypes.byref(self.res)
err = self.rt.cudaGraphicsMapResources(1, res, stream)
if err:
raise RuntimeError(f"CUDA-GL interop: map failed (cudaError {err})")
try:
arr = ctypes.c_void_p()
err = (self.rt.cudaGraphicsSubResourceGetMappedArray(ctypes.byref(arr), self.res, 0, 0)
or self.rt.cudaMemcpy2DFromArrayAsync(ctypes.c_void_p(out.data_ptr()), self.w * 4, arr, 0, 0,
self.w * 4, self.h, _MEMCPY_DEVICE_TO_DEVICE, stream))
if err:
raise RuntimeError(f"CUDA-GL interop: copy failed (cudaError {err})")
finally:
self.rt.cudaGraphicsUnmapResources(1, res, stream)
def close(self) -> None:
if self.res:
self.rt.cudaGraphicsUnregisterResource(self.res)
self.res = ctypes.c_void_p()
+291
View File
@@ -0,0 +1,291 @@
"""RIFE frame interpolator tuned for a live stream: 1 to 3 in-between frames per real frame (60, 90 or 120 fps).
Design notes
------------
* Every buffer is pre-allocated at a fixed resolution, so the per-frame work can
be captured once as CUDA graphs and replayed (removes Python/launch overhead,
which matters more than FLOPs for these small networks).
* RIFE v4.2x splits work into `encode(frame) -> features` and
`flownet(img0, img1, f0, f1) -> middle frame`. In a stream each real frame is
the "next" frame of one pair and the "previous" frame of the following pair,
so we encode it exactly once into one of two ping-pong slots.
* Frames enter and leave as HxWx3 uint8 BGR (OpenCV / capture-card layout).
"""
from __future__ import annotations
import importlib
import math
import os
import subprocess
import urllib.error
import urllib.request
from pathlib import Path
import torch
import torch.nn.functional as F
from .fastrife import FastIFNet
from .sync import CAPTURE_LOCK
# version -> (module name, padding modulo). Modulo values match vs-rife.
MODELS: dict[str, tuple[str, int]] = {
"4.22.lite": ("IFNet_HDv3_v4_22_lite", 32),
"4.25.lite": ("IFNet_HDv3_v4_25_lite", 128),
"4.25": ("IFNet_HDv3_v4_25", 64),
"4.26": ("IFNet_HDv3_v4_26", 64),
}
WEIGHTS_URL = "https://github.com/HolyWu/vs-rife/releases/download/model/flownet_v{version}.pkl"
DEFAULT_MODEL_DIR = Path(__file__).resolve().parent.parent / "models"
# Steady HUD: the largest difference between the two real frames (0..1 per colour channel) at which a pixel still
# counts as unchanged. 0.03 is about 8 of 255 levels: above Remote Play's compression noise on a still HUD.
STEADY_HUD_THRESHOLD = float(os.environ.get("FRAMEGEN_STEADY_THRESHOLD", "0.03")) # env: for tuning only
# ...and only within this many pixels of an edge: Sobel L1 of brightness (0..1) above STEADY_HUD_EDGE, about a
# 32-level step. See _steady.
STEADY_HUD_EDGE = 128.0 / 255.0
STEADY_HUD_EDGE_R = 1
def ensure_weights(version: str, model_dir: Path = DEFAULT_MODEL_DIR) -> Path:
model_dir.mkdir(parents=True, exist_ok=True)
path = model_dir / f"flownet_v{version}.pkl"
if not path.exists():
url = WEIGHTS_URL.format(version=version)
print(f"[rife] downloading {url}")
tmp = path.with_suffix(".part")
try:
urllib.request.urlretrieve(url, tmp)
except urllib.error.URLError: # e.g. Python's CA bundle can't verify; Windows curl uses the OS store
subprocess.run(["curl", "-sfL", "-o", str(tmp), url], check=True)
tmp.replace(path)
return path
class RifeInterpolator:
def __init__(
self,
width: int,
height: int,
version: str = "4.22.lite",
scale: float = 1.0,
fp16: bool = True,
cuda_graph: bool = True,
device: str = "cuda",
reference: bool = False,
backend: str = "torch",
build_engine: bool = True,
) -> None:
"""`reference=True` runs the unmodified vs-rife forward (for validating FastIFNet).
backend="trt" runs the flow network as a TensorRT engine (built and cached on first use; with
build_engine=False a missing engine raises FileNotFoundError instead)."""
if version not in MODELS:
raise ValueError(f"unknown model {version!r}; choose from {list(MODELS)}")
if scale not in (0.25, 0.5, 1.0, 2.0):
raise ValueError("scale must be 0.25, 0.5, 1.0 or 2.0")
self.w, self.h = width, height
self.version, self.scale = version, scale
self.device = torch.device(device)
self.dtype = torch.half if fp16 else torch.float
torch.backends.cudnn.benchmark = True
module_name, modulo = MODELS[version]
mod = importlib.import_module(f"framegen.rife.{module_name}")
state = torch.load(ensure_weights(version), map_location="cpu", weights_only=True)
state = {k.replace("module.", ""): v for k, v in state.items() if k.startswith("module.")}
self.flownet = mod.IFNet(scale=scale)
# Checkpoints also carry training-only weights (teacher/caltime); ignore those, but every
# parameter the inference model has must be present.
missing = self.flownet.load_state_dict(state, strict=False).missing_keys
if missing:
raise RuntimeError(f"RIFE {version}: checkpoint is missing {missing[:5]}...")
self.encode = mod.Head()
self.encode.load_state_dict({k[len("encode."):]: v for k, v in state.items() if k.startswith("encode.")})
for m in (self.flownet, self.encode):
m.eval().to(self.device, self.dtype)
# Pad to a multiple the pyramid can divide cleanly.
step = max(modulo, int(modulo / scale))
self.pw = math.ceil(width / step) * step
self.ph = math.ceil(height / step) * step
self.pad = (0, self.pw - width, 0, self.ph - height)
dev, dt, ph, pw = self.device, self.dtype, self.ph, self.pw
self.flow_div = torch.tensor([(pw - 1.0) / 2.0, (ph - 1.0) / 2.0], dtype=torch.float, device=dev)
gx = torch.linspace(-1.0, 1.0, pw, device=dev).view(1, 1, 1, pw).expand(1, 1, ph, pw)
gy = torch.linspace(-1.0, 1.0, ph, device=dev).view(1, 1, ph, 1).expand(1, 1, ph, pw)
self.grid = torch.cat([gx, gy], 1).contiguous()
self.timestep = torch.full((1, 1, ph, pw), 0.5, dtype=dt, device=dev)
self._t = 0.5
# Steady HUD (see _steady): read by the captured graphs, so changing them needs no recapture.
self.steady = 0.0
self.t_now = torch.full((1, 1, 1, 1), 0.5, device=dev)
self.still_thr = torch.full((1, 1, 1, 1), STEADY_HUD_THRESHOLD, device=dev)
gx = torch.tensor([[-1.0, 0.0, 1.0], [-2.0, 0.0, 2.0], [-1.0, 0.0, 1.0]], device=dev)
self.sobel = torch.stack([gx, gx.t()]).unsqueeze(1).half() # (2, 1, 3, 3): x and y gradients
self.luma = torch.tensor([0.299, 0.587, 0.114], device=dev).view(1, 3, 1, 1).half() # RGB
self.edge = [torch.zeros((1, 1, ph, pw), dtype=torch.half, device=dev) for _ in range(2)] # see _edges
self.steady_w = torch.zeros((1, 1, ph, pw), device=dev) # see _steady_mask
self._slot: int | None = None # the newest prepared slot
# Static I/O buffers (graph inputs/outputs).
self.in_u8 = torch.zeros((height, width, 3), dtype=torch.uint8, device=dev)
self.out_u8 = torch.zeros((height, width, 3), dtype=torch.uint8, device=dev)
with torch.no_grad():
fshape = self.encode(torch.zeros((1, 3, ph, pw), dtype=dt, device=dev)).shape
self.fast = None if reference else FastIFNet(self.flownet, ph, pw, dt, dev)
if self.fast is not None: # per slot: fp32 [img | features]
self.src = [torch.zeros((1, 3 + fshape[1], ph, pw), device=dev) for _ in range(2)]
else:
self.img = [torch.zeros((1, 3, ph, pw), dtype=dt, device=dev) for _ in range(2)]
self.feat = [torch.zeros(fshape, dtype=dt, device=dev) for _ in range(2)]
self.trt = None
if backend == "trt":
if self.fast is None:
raise ValueError("backend='trt' needs the fast path (reference=False)")
from .trt import TrtIFNet
self.trt = TrtIFNet(self.fast, tuple(self.src[0].shape), f"{version}_s{scale}", dev, build=build_engine)
elif backend != "torch":
raise ValueError(f"unknown backend {backend!r}")
self._graphs: dict[tuple, torch.cuda.CUDAGraph] = {}
self.cuda_graph = cuda_graph
if cuda_graph:
for slot in (0, 1):
self._graphs[("prep", slot)] = self._capture(lambda s=slot: self._prepare_eager(s))
self._graphs[("mask", slot)] = self._capture(lambda s=slot: self._steady_mask(1 - s, s))
for steady in (False, True): # two variants, so Steady HUD costs nothing when it's off
self._graphs[("interp", slot, steady)] = self._capture(
lambda s=slot, st=steady: self._interp_eager(1 - s, s, st))
# ---- eager kernels (also what gets captured into graphs) -----------------
@torch.no_grad()
def _prepare_eager(self, slot: int) -> None:
x = self.in_u8.permute(2, 0, 1).flip(0).unsqueeze(0).to(self.dtype).div_(255.0) # BGR->RGB, 0..1
if self.pad[1] or self.pad[3]:
x = F.pad(x, self.pad)
if self.fast is not None:
self.src[slot].copy_(FastIFNet.make_src(x, self.encode(x)))
else:
self.img[slot].copy_(x)
self.feat[slot].copy_(self.encode(x))
@torch.no_grad()
def _interp_eager(self, a: int, b: int, steady: bool = False) -> None:
if self.trt is not None:
mid = self.trt(self.src[a], self.src[b])
elif self.fast is not None:
mid = self.fast(self.src[a], self.src[b])
else:
mid = self.flownet(
self.img[a], self.img[b], self.timestep, self.flow_div, self.grid, self.feat[a], self.feat[b]
)
if steady:
mid = self._steady(mid, a, b)
mid = mid[0, :, : self.h, : self.w].flip(0).permute(1, 2, 0) # RGB->BGR, HWC
self.out_u8.copy_(mid.clamp(0.0, 1.0).mul(255.0).round_().to(torch.uint8))
def _rgb(self, slot: int) -> torch.Tensor:
"""Slot's real frame, (1, 3, ph, pw) RGB 0..1."""
return (self.src[slot][:, :3] if self.fast is not None else self.img[slot]).float()
def _steady(self, mid: torch.Tensor, a: int, b: int) -> torch.Tensor:
"""Steady HUD: where a pixel is (almost) the same in both real frames, like a map, health bar or subtitle
over a moving scene, the AI frame takes the real pixel (blended at t, so fades still fade) instead of the
model's, which can drag it along with the motion behind it. The edge is soft: fully real below half the
threshold, fully the model's above it, so there's no speckle where the difference hovers near it.
Only near edges (within STEADY_HUD_EDGE_R pixels of a brightness step of about 32 levels, in either real
frame): text, icons and map lines, where wobble shows. On a flat background the model's pixel is kept, so a
pole or a car crossing a sky or road that matches before and after isn't painted over. On eight 60 fps
gameplay clips (scripts/steady_hud_eval.py) that keeps 96% of the fix on HUD-like pixels at a quarter of the
cost elsewhere.
Where it acts (steady_w) depends only on the two real frames, so _steady_mask works it out once per real
frame (after prepare) and each in-between frame just blends."""
return torch.lerp(mid.float(), torch.lerp(self._rgb(a), self._rgb(b), self.t_now), self.steady_w)
@torch.no_grad()
def _edges(self, slot: int) -> None:
"""edge[slot]: 1 on a brightness edge of that real frame (worked out once per frame, in half precision)."""
lum = F.conv2d(self._rgb(slot).half(), self.luma)
g = F.conv2d(lum, self.sobel, padding=1).abs_().sum(1, keepdim=True)
self.edge[slot].copy_(g > STEADY_HUD_EDGE)
@torch.no_grad()
def _steady_mask(self, a: int, b: int) -> None:
"""steady_w for real frames a -> b: 1 where Steady HUD takes the real pixels, 0 where the model's stay.
The newest frame's edges are worked out here; the older one's were, when it was the newest."""
self._edges(b)
ia, ib = self._rgb(a).half(), self._rgb(b).half()
d = (ib - ia).abs_().amax(1, keepdim=True)
thr = self.still_thr.half()
w = ((thr - d) * (2.0 / thr)).clamp_(0.0, 1.0)
r = STEADY_HUD_EDGE_R
self.steady_w.copy_(w * F.max_pool2d(torch.maximum(self.edge[a], self.edge[b]), 2 * r + 1, 1, r))
def set_steady(self, threshold: float) -> None:
"""Steady HUD on (threshold: largest real-frame difference, 0..1, that counts as still) or off (0)."""
if threshold > 0:
self.still_thr.fill_(threshold)
if self.steady <= 0 and self._slot is not None: # turned on mid-pair: the current pair's mask now
self._edges(1 - self._slot) # (the older frame's edges weren't worked out while it was off)
self._steady_mask(1 - self._slot, self._slot)
self.steady = threshold
def _capture(self, fn) -> torch.cuda.CUDAGraph:
with CAPTURE_LOCK:
return self._capture_locked(fn)
def _capture_locked(self, fn) -> torch.cuda.CUDAGraph:
side = torch.cuda.Stream()
side.wait_stream(torch.cuda.current_stream())
with torch.cuda.stream(side):
for _ in range(3): # warm-up (cudnn autotune, allocator) before capture
fn()
torch.cuda.current_stream().wait_stream(side)
g = torch.cuda.CUDAGraph()
# thread_local, and CAPTURE_LOCK: the Remote Play reader decodes on the GPU in another thread. With the
# default ("global") its CUDA calls fail during capture, and FFmpeg's decoder crashes on that.
with torch.cuda.graph(g, capture_error_mode="thread_local"):
fn()
return g
# ---- public API ----------------------------------------------------------
def prepare(self, slot: int) -> None:
"""Convert+encode `in_u8` into ping-pong slot `slot` (0/1); with Steady HUD on, also where it acts between
the previous real frame and this one."""
if self.cuda_graph:
self._graphs[("prep", slot)].replay()
if self.steady > 0:
self._graphs[("mask", slot)].replay()
else:
self._prepare_eager(slot)
if self.steady > 0:
self._steady_mask(1 - slot, slot)
self._slot = slot
def interpolate(self, newest_slot: int, t: float = 0.5) -> torch.Tensor:
"""Frame at fraction t (0.5 = midpoint) from slot (1-newest_slot) to newest_slot -> `out_u8`.
Each call overwrites `out_u8`, so for several timesteps copy each result out before the next."""
if t != self._t: # the graphs read these static planes, so no recapture is needed
if self.trt is not None:
self.trt.set_timestep(t)
if self.fast is not None:
self.fast.set_timestep(t)
else:
self.timestep.fill_(t)
self.t_now.fill_(t)
self._t = t
steady = self.steady > 0
if self.cuda_graph:
self._graphs[("interp", newest_slot, steady)].replay()
else:
self._interp_eager(1 - newest_slot, newest_slot, steady)
return self.out_u8
def load(self, frame_u8: torch.Tensor) -> None:
"""Copy an HxWx3 uint8 frame (GPU or pinned CPU) into the static input."""
self.in_u8.copy_(frame_u8, non_blocking=True)
+1176
View File
File diff suppressed because it is too large. Load diff
+1128
View File
File diff suppressed because it is too large. Load diff
+465
View File
@@ -0,0 +1,465 @@
"""Draws a look (framegen/looks.py) with OpenGL, after upscaling, in the video window's last step.
looks.stages() splits the look into passes. Each pass is one fragment shader made for that run of nodes, so a run
of per-pixel nodes (color, wheels, grain, vignette...) costs one full-screen pass however many there are; a node
that reads other pixels (blur, bloom, sharpen...) starts a new pass, which reads the pass before it from a
half-float texture of the output's size. Bloom, halation, blur and clarity also build a blurred copy of that
input: six halvings (a 4x4 box each, the first with bloom's bright pass), then back up, mixing each level with the
one below (looks.glow()). The first pass reads the picture (FSR's or VSR's result, or the stream's own frame,
which it resizes) and the last one writes to the window, upright, or to a texture for instant replay ("Looks in
clips", at the stream's size).
Programs are made once per look's layout (adding, removing or switching off a node remakes them, in a few ms);
setting changes only change uniforms. Everything here is held to looks.render(), the NumPy reference, by
tests/test_looks.py.
"""
from __future__ import annotations
from . import looks
_VERT = """#version 450
void main() { // one triangle covering the viewport
vec2 p = vec2((gl_VertexID << 1) & 2, gl_VertexID & 2);
gl_Position = vec4(p * 2.0 - 1.0, 0.0, 1.0);
}
"""
# Every pass: where this pixel is in the output image (Q: pixel center, row 0 at the top; UV: 0..1), then the nodes.
_HEAD = """#version 450
layout(binding = 0) uniform sampler2D src; // the pass's input
layout(binding = 1) uniform sampler2D glow; // its blurred copy (bloom, halation, blur, clarity)
uniform vec2 out_size; // the output image, pixels
uniform ivec2 origin; // the framebuffer pixel of its first column and its bottom row
uniform int flip_out; // 1: the framebuffer's row 0 is the image's bottom (the window); 0: its top (a texture)
uniform int flip_in; // 1: the input's row 0 is the image's bottom (FSR's result)
uniform uint frame_no; // moves the grain
out vec4 color;
const vec3 W = vec3(0.2126, 0.7152, 0.0722);
vec2 Q;
vec2 UV;
uint pcg(uint v) {
uint s = v * 747796405u + 2891336453u;
uint w = ((s >> ((s >> 28u) + 4u)) ^ s) * 277803737u;
return (w >> 22u) ^ w;
}
float hash3(uint x, uint y, uint z) { return float(pcg(x + pcg(y + pcg(z)))) * (1.0 / 4294967296.0); }
float vnoise(uint x, uint y, vec2 f, uint z) {
float a = hash3(x, y, z), b = hash3(x + 1u, y, z), c = hash3(x, y + 1u, z), d = hash3(x + 1u, y + 1u, z);
float top = a * (1.0 - f.x) + b * f.x;
float bot = c * (1.0 - f.x) + d * f.x;
return (top * (1.0 - f.y) + bot * f.y - 0.5) * 2.0;
}
vec3 n_color(vec3 c, vec3 wb, float gain, float k, float sh, float hi, float fade, float sat, float vib) {
c = clamp(c * wb, 0.0, 1.0);
c = clamp(c * gain, 0.0, 1.0);
vec3 s = c * c * (3.0 - 2.0 * c);
c = c + k * (s - c);
vec3 x1 = 1.0 - c;
c = c + sh * c * x1 * x1 + hi * c * c * x1;
x1 = 1.0 - c;
c = c + fade * x1 * x1;
float y = dot(c, W);
float spread = max(max(c.r, c.g), c.b) - min(min(c.r, c.g), c.b);
float f = sat * max(0.0, 1.0 + vib * (1.0 - spread));
return y + (c - y) * f;
}
vec3 n_wheels(vec3 c, vec3 lift, vec3 gain, vec3 power) {
return pow(max(gain * (c + lift * (1.0 - c)), 0.0), power);
}
vec3 n_split(vec3 c, vec3 sh, vec3 hi, float bal) {
float y = dot(c, W);
float t = clamp(y + 0.5 * bal, 0.0, 1.0);
float wh = t * t * (3.0 - 2.0 * t);
return c + (1.0 - wh) * smoothstep(0.0, 0.25, y) * sh + wh * (1.0 - smoothstep(0.9, 1.0, y)) * hi;
}
vec3 n_mono(vec3 c, vec3 w, vec3 tone) {
float y = clamp(dot(c, w), 0.0, 1.0);
return vec3(y) + tone * (4.0 * y * (1.0 - y));
}
vec3 n_lut(vec3 c, sampler3D t, vec3 dmin, vec3 dscale, float n) {
vec3 x = clamp((c - dmin) * dscale, 0.0, 1.0);
return texture(t, (x * (n - 1.0) + 0.5) / n).rgb;
}
vec3 n_grain(vec3 c, float a, float size, float col) {
float px = max(0.5, size * out_size.y / 1080.0);
vec2 g = Q / px;
vec2 fl = floor(g);
vec2 f = g - fl;
f = f * f * (3.0 - 2.0 * f);
uint x = uint(int(fl.x)), y = uint(int(fl.y)), z = frame_no * 4u;
vec3 n3 = vec3(vnoise(x, y, f, z), vnoise(x, y, f, z + 1u), vnoise(x, y, f, z + 2u));
float nm = vnoise(x, y, f, z + 3u);
vec3 nn = nm * (1.0 - col) + n3 * col;
float yl = clamp(dot(c, W), 0.0, 1.0);
return c + a * nn * (0.25 + 3.0 * yl * (1.0 - yl));
}
vec3 n_vignette(vec3 c, float a, float r0, float soft, float rnd) {
float ax = 1.0 + (out_size.x / out_size.y - 1.0) * rnd;
vec2 d2 = (UV - 0.5) * 2.0 * vec2(ax, 1.0);
float d = length(d2) / length(vec2(ax, 1.0));
return c * (1.0 - a * smoothstep(r0 - soft, r0 + soft, d));
}
vec3 n_scanlines(vec3 c, float a, float size) {
float period = max(2.0, size * out_size.y / 1080.0); // (lines need 2 pixels or more: at 1 every row is alike)
return c * (1.0 - a * (0.5 + 0.5 * cos(6.2831853 * fract(Q.y / period))));
}
vec3 n_letterbox(vec3 c, float aspect) {
float e = out_size.x / out_size.y < aspect ? abs(Q.y - 0.5 * out_size.y) - 0.5 * out_size.x / aspect
: abs(Q.x - 0.5 * out_size.x) - 0.5 * out_size.y * aspect;
return c * (1.0 - clamp(e + 0.5, 0.0, 1.0));
}
vec3 n_assist(vec3 c, mat3 m) {
return pow(clamp(m * pow(c, vec3(2.2)), 0.0, 1.0), vec3(1.0 / 2.2));
}
vec3 s_bloom(vec3 c, float amount, vec3 tint) { return c + amount * texture(glow, UV).rgb * tint; }
vec3 s_halation(vec3 c, float amount, vec3 tint) { return c + amount * texture(glow, UV).rgb * tint; }
vec3 s_blur(vec3 c) { return texture(glow, UV).rgb; }
vec3 s_clarity(vec3 c, float amount) { return c + amount * (c - texture(glow, UV).rgb); }
vec3 s_ca(vec3 c, float k) {
vec2 off = (UV - 0.5) * k;
return vec3(texture(src, UV + off).r, c.g, texture(src, UV - off).b);
}
vec3 s_sharpen(vec3 c, float amount) {
ivec2 p = ivec2(Q), m = textureSize(src, 0) - 1;
vec3 nb = texelFetch(src, clamp(p + ivec2(1, 0), ivec2(0), m), 0).rgb
+ texelFetch(src, clamp(p - ivec2(1, 0), ivec2(0), m), 0).rgb
+ texelFetch(src, clamp(p + ivec2(0, 1), ivec2(0), m), 0).rgb
+ texelFetch(src, clamp(p - ivec2(0, 1), ivec2(0), m), 0).rgb;
return c + amount * (c - 0.25 * nb);
}
"""
_DOWN = """#version 450
layout(binding = 0) uniform sampler2D src;
uniform float thr; // bloom's bright pass; below 0: none
out vec4 color;
vec3 bright(vec3 c) {
float br = max(max(c.r, c.g), c.b);
float knee = 0.1;
float soft = clamp(br - thr + knee, 0.0, 2.0 * knee);
soft = soft * soft / (4.0 * knee + 1e-5);
return c * (max(soft, br - thr) / max(br, 1e-4));
}
void main() { // a 4x4 box, centered on this pixel's 2x2 of the level above
ivec2 p = ivec2(gl_FragCoord.xy) * 2 - 1, m = textureSize(src, 0) - 1;
vec3 s = vec3(0.0);
for (int y = 0; y < 4; y++)
for (int x = 0; x < 4; x++) {
vec3 c = texelFetch(src, clamp(p + ivec2(x, y), ivec2(0), m), 0).rgb;
s += thr >= 0.0 ? bright(c) : c;
}
color = vec4(s / 16.0, 1.0);
}
"""
_UP = """#version 450
layout(binding = 0) uniform sampler2D level;
layout(binding = 1) uniform sampler2D below; // the next smaller level, already mixed
uniform float r;
out vec4 color;
void main() {
ivec2 p = ivec2(gl_FragCoord.xy);
vec2 uv = (vec2(p) + 0.5) / vec2(textureSize(level, 0));
color = vec4(mix(texelFetch(level, p, 0).rgb, texture(below, uv).rgb, r), 1.0);
}
"""
def _gl_type(v) -> str:
if isinstance(v, (int, float)):
return "float"
return {3: "vec3", 9: "mat3"}[len(v)]
def stage_source(stage: looks.Stage, first: bool) -> str:
"""The fragment shader for one pass (uniforms u<i>_<name> for its i-th node, LUTs lut<j> from binding 2)."""
decl, body = [], []
luts = 0
nodes = ([stage.start] if stage.start is not None else []) + list(stage.nodes)
for i, n in enumerate(nodes):
args = ["c"]
if n["type"] == "lut":
decl.append(f"layout(binding = {2 + luts}) uniform sampler3D lut{luts};")
args.append(f"lut{luts}")
luts += 1
for name, v in looks.uniforms(n):
decl.append(f"uniform {_gl_type(v)} u{i}_{name};")
args.append(f"u{i}_{name}")
decl.append(f"uniform float u{i}_mix;")
fn = ("s_" if i == 0 and stage.start is not None else "n_") + n["type"]
body.append(f" {{ vec3 o = {fn}({', '.join(args)}); c = clamp(mix(c, o, u{i}_mix), 0.0, 1.0); }}")
read = ("texture(src, flip_in == 1 ? vec2(UV.x, 1.0 - UV.y) : UV).rgb" if first
else "texelFetch(src, ivec2(Q), 0).rgb")
return (_HEAD + "\n".join(decl) + "\nvoid main() {\n"
" Q = gl_FragCoord.xy - vec2(origin);\n"
" if (flip_out == 1) Q.y = out_size.y - Q.y;\n"
" UV = Q / out_size;\n"
f" vec3 c = {read};\n" + "\n".join(body) + "\n color = vec4(c, 1.0);\n}\n")
class _Tex:
"""A 2D texture with its framebuffer."""
def __init__(self, GL, w: int, h: int, fmt) -> None:
self.GL, self.w, self.h = GL, w, h
self.tex = GL.glGenTextures(1)
GL.glBindTexture(GL.GL_TEXTURE_2D, self.tex)
for p, v in ((GL.GL_TEXTURE_MIN_FILTER, GL.GL_LINEAR), (GL.GL_TEXTURE_MAG_FILTER, GL.GL_LINEAR),
(GL.GL_TEXTURE_WRAP_S, GL.GL_CLAMP_TO_EDGE), (GL.GL_TEXTURE_WRAP_T, GL.GL_CLAMP_TO_EDGE)):
GL.glTexParameteri(GL.GL_TEXTURE_2D, p, v)
GL.glTexImage2D(GL.GL_TEXTURE_2D, 0, fmt, w, h, 0, GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, None)
self.fbo = GL.glGenFramebuffers(1)
GL.glBindFramebuffer(GL.GL_FRAMEBUFFER, self.fbo)
GL.glFramebufferTexture2D(GL.GL_FRAMEBUFFER, GL.GL_COLOR_ATTACHMENT0, GL.GL_TEXTURE_2D, self.tex, 0)
def close(self) -> None:
self.GL.glDeleteFramebuffers(1, [self.fbo])
self.GL.glDeleteTextures([self.tex])
class _Targets:
"""What a look needs at one output size: two half-float images to pass between passes, and the blur levels."""
def __init__(self, GL, w: int, h: int) -> None:
self.GL, self.size = GL, (w, h)
self.ping = [_Tex(GL, w, h, GL.GL_RGBA16F) for _ in range(2)]
self.down: list[_Tex] = []
self.up: list[_Tex] = []
def levels(self) -> tuple[list[_Tex], list[_Tex]]:
if not self.down:
sizes = looks.pyramid_sizes(*self.size)
self.down = [_Tex(self.GL, w, h, self.GL.GL_RGBA16F) for w, h in sizes]
self.up = [_Tex(self.GL, w, h, self.GL.GL_RGBA16F) for w, h in sizes[:-1]]
return self.down, self.up
def close(self) -> None:
for t in self.ping + self.down + self.up:
t.close()
class LookRenderer:
"""Needs a current GL 4.5 context, the one the window draws with. lut_of(name) -> looks.Lut or None."""
def __init__(self, GL, lut_of) -> None:
self.GL, self.lut_of = GL, lut_of
self.vao = GL.glGenVertexArrays(1)
self._programs: dict[tuple, tuple[int, dict]] = {}
self._down = self._compile(_DOWN)
self._up = self._compile(_UP)
self._u_thr = GL.glGetUniformLocation(self._down, "thr")
self._u_r = GL.glGetUniformLocation(self._up, "r")
self._targets: dict[str, _Targets] = {}
self._lut_tex: dict[str, tuple[object, int]] = {} # name -> (the Lut it was made from, 3D texture)
self._plan_for: tuple | None = None # (look id, rev) the plan below is for
self._plan: list | None = None
self._set: dict[int, int] = {} # program -> the plan serial its node uniforms were last set for
self._serial = 0
self.broken: str | None = None # why looks can't be drawn here (a shader didn't compile), or None
def _compile(self, frag: str) -> int:
from OpenGL.GL import shaders
GL = self.GL
return shaders.compileProgram(shaders.compileShader(_VERT, GL.GL_VERTEX_SHADER),
shaders.compileShader(frag, GL.GL_FRAGMENT_SHADER), validate=False)
# ---- what to draw
def plan(self, look: dict | None, rev: int):
"""The passes for this look (cached until `rev` changes), or None if it does nothing."""
if look is None or self.broken:
return None
key = (id(look), rev)
if key != self._plan_for:
self._plan_for, self._plan = key, self._make_plan(look)
self._serial += 1
return self._plan
def _make_plan(self, look: dict):
passes = looks.stages(look, lambda name: self.lut_of(name) is not None)
if not passes:
return None
plan = []
for i, st in enumerate(passes):
nodes = ([st.start] if st.start is not None else []) + list(st.nodes)
layout = (i, st.start["type"] if st.start else None, tuple(n["type"] for n in st.nodes))
try:
prog, locs = self._program(layout, st, i == 0)
except Exception as e: # noqa: BLE001 - a driver that can't compile it: no looks, the video goes on
self.broken = f"a shader didn't compile ({str(e)[:300]})"
print(f"[looks] can't draw looks on this graphics card: {self.broken}")
return None
values, luts = [], []
for k, n in enumerate(nodes):
lut = self.lut_of(n["file"]) if n["type"] == "lut" else None
if lut is not None:
luts.append(self._lut_texture(n["file"], lut))
for name, v in looks.uniforms(n, lut):
values.append((locs.get(f"u{k}_{name}", -1), v))
values.append((locs.get(f"u{k}_mix", -1), float(n["mix"])))
plan.append((prog, locs, values, luts, st.start))
return plan
def _program(self, layout: tuple, st: looks.Stage, first: bool):
got = self._programs.get(layout)
if got is None:
GL = self.GL
prog = self._compile(stage_source(st, first))
n_uniforms = GL.glGetProgramiv(prog, GL.GL_ACTIVE_UNIFORMS)
locs = {}
for j in range(n_uniforms):
name = GL.glGetActiveUniform(prog, j)[0]
name = name.decode() if isinstance(name, bytes) else str(name)
locs[name] = GL.glGetUniformLocation(prog, name)
got = self._programs[layout] = (prog, locs)
return got
def _lut_texture(self, name: str, lut) -> int:
import numpy as np
GL = self.GL
got = self._lut_tex.get(name)
if got is not None and got[0] is lut:
return got[1]
if got is not None:
GL.glDeleteTextures([got[1]])
tex = GL.glGenTextures(1)
GL.glBindTexture(GL.GL_TEXTURE_3D, tex)
for p, v in ((GL.GL_TEXTURE_MIN_FILTER, GL.GL_LINEAR), (GL.GL_TEXTURE_MAG_FILTER, GL.GL_LINEAR),
(GL.GL_TEXTURE_WRAP_S, GL.GL_CLAMP_TO_EDGE), (GL.GL_TEXTURE_WRAP_T, GL.GL_CLAMP_TO_EDGE),
(GL.GL_TEXTURE_WRAP_R, GL.GL_CLAMP_TO_EDGE)):
GL.glTexParameteri(GL.GL_TEXTURE_3D, p, v)
n = lut.size
GL.glTexImage3D(GL.GL_TEXTURE_3D, 0, GL.GL_RGBA16F, n, n, n, 0, GL.GL_RGB, GL.GL_FLOAT,
np.ascontiguousarray(lut.table, np.float32))
GL.glBindTexture(GL.GL_TEXTURE_3D, 0)
self._lut_tex[name] = (lut, tex)
return tex
# ---- drawing
def targets(self, purpose: str, w: int, h: int) -> _Targets:
t = self._targets.get(purpose)
if t is None or t.size != (w, h):
if t is not None:
t.close()
t = self._targets[purpose] = _Targets(self.GL, w, h)
return t
def input_target(self, w: int, h: int, purpose: str = "screen") -> tuple[int, int]:
"""(texture, framebuffer) at the output's size for the upscaler to draw into; draw() then reads it."""
t = self.targets(purpose, w, h).ping[0]
return t.tex, t.fbo
def draw(self, plan, src_tex: int, flip_in: bool, dst_fbo: int, x0: int, y0: int, w: int, h: int,
flip_out: bool = True, frame: int = 0, purpose: str = "screen") -> None:
"""The look from src_tex (any size; flip_in: its row 0 is the image's bottom) into dst_fbo's rectangle at
(x0, y0), w x h: upright on screen with flip_out, else image row 0 in framebuffer row 0. Leaves dst_fbo bound;
the caller sets its viewport back."""
GL = self.GL
tg = self.targets(purpose, w, h)
GL.glBindVertexArray(self.vao)
cur = src_tex
# the passes alternate between the two images; one that's being read is never written
out_i = 1 if src_tex == tg.ping[0].tex else 0
last = len(plan) - 1
for i, (prog, locs, values, luts, start) in enumerate(plan):
if start is not None and looks.TYPES[start["type"]].kind in ("glow", "blur", "clarity"):
glow_tex = self._pyramid(tg, cur, *looks.glow(start))
else:
glow_tex = cur
if i == last:
GL.glBindFramebuffer(GL.GL_FRAMEBUFFER, dst_fbo)
GL.glViewport(x0, y0, w, h)
origin, flip = (x0, y0), flip_out
else:
out = tg.ping[out_i]
GL.glBindFramebuffer(GL.GL_FRAMEBUFFER, out.fbo)
GL.glViewport(0, 0, w, h)
origin, flip = (0, 0), False
GL.glUseProgram(prog)
if self._set.get(prog) != self._serial:
for loc, v in values:
self._uniform(loc, v)
self._set[prog] = self._serial
if "out_size" in locs:
GL.glUniform2f(locs["out_size"], float(w), float(h))
if "origin" in locs:
GL.glUniform2i(locs["origin"], *origin)
if "flip_out" in locs:
GL.glUniform1i(locs["flip_out"], int(flip))
if "flip_in" in locs:
GL.glUniform1i(locs["flip_in"], int(flip_in and i == 0))
if "frame_no" in locs:
GL.glUniform1ui(locs["frame_no"], frame & 0x3FFFFFFF)
GL.glActiveTexture(GL.GL_TEXTURE0)
GL.glBindTexture(GL.GL_TEXTURE_2D, cur)
GL.glActiveTexture(GL.GL_TEXTURE1)
GL.glBindTexture(GL.GL_TEXTURE_2D, glow_tex)
for j, tex in enumerate(luts):
GL.glActiveTexture(GL.GL_TEXTURE2 + j)
GL.glBindTexture(GL.GL_TEXTURE_3D, tex)
GL.glDrawArrays(GL.GL_TRIANGLES, 0, 3)
if i != last:
cur = tg.ping[out_i].tex
out_i ^= 1
for j in range(max((len(p[3]) for p in plan), default=0)):
GL.glActiveTexture(GL.GL_TEXTURE2 + j)
GL.glBindTexture(GL.GL_TEXTURE_3D, 0)
GL.glActiveTexture(GL.GL_TEXTURE0)
GL.glUseProgram(0)
GL.glBindVertexArray(0)
def _uniform(self, loc: int, v) -> None:
if loc < 0:
return
GL = self.GL
if isinstance(v, (int, float)):
GL.glUniform1f(loc, float(v))
elif len(v) == 3:
GL.glUniform3f(loc, *(float(c) for c in v))
else:
GL.glUniformMatrix3fv(loc, 1, GL.GL_TRUE, [float(c) for c in v])
def _pyramid(self, tg: _Targets, src: int, thr: float | None, r: float) -> int:
"""The blurred copy of src (output-sized): its first level, half the size, as a texture."""
GL = self.GL
down, up = tg.levels()
if not down:
return src
GL.glUseProgram(self._down)
GL.glActiveTexture(GL.GL_TEXTURE0)
cur = src
for k, lv in enumerate(down):
GL.glUniform1f(self._u_thr, thr if (k == 0 and thr is not None) else -1.0)
GL.glBindFramebuffer(GL.GL_FRAMEBUFFER, lv.fbo)
GL.glViewport(0, 0, lv.w, lv.h)
GL.glBindTexture(GL.GL_TEXTURE_2D, cur)
GL.glDrawArrays(GL.GL_TRIANGLES, 0, 3)
cur = lv.tex
GL.glUseProgram(self._up)
GL.glUniform1f(self._u_r, r)
below = down[-1].tex
for k in range(len(up) - 1, -1, -1):
GL.glBindFramebuffer(GL.GL_FRAMEBUFFER, up[k].fbo)
GL.glViewport(0, 0, up[k].w, up[k].h)
GL.glActiveTexture(GL.GL_TEXTURE0)
GL.glBindTexture(GL.GL_TEXTURE_2D, down[k].tex)
GL.glActiveTexture(GL.GL_TEXTURE1)
GL.glBindTexture(GL.GL_TEXTURE_2D, below)
GL.glDrawArrays(GL.GL_TRIANGLES, 0, 3)
below = up[k].tex
GL.glActiveTexture(GL.GL_TEXTURE0)
return below
def close(self) -> None:
GL = self.GL
for t in self._targets.values():
t.close()
for _, tex in self._lut_tex.values():
GL.glDeleteTextures([tex])
for prog, _ in self._programs.values():
GL.glDeleteProgram(prog)
GL.glDeleteProgram(self._down)
GL.glDeleteProgram(self._up)
GL.glDeleteVertexArrays(1, [self.vao])
+210
View File
@@ -0,0 +1,210 @@
"""The launcher's Looks page preview: a look drawn on a sample game picture, the way the video window draws it.
`python -m framegen.looks_preview` runs while the Looks page is open. It reads one JSON request per line on stdin and
answers with one JSON line on stdout:
-> {"id": 7, "look": {...}, "sample": "gta6-beach", "width": 640, "height": 360, "out": "C:\\...\\preview-1.bmp"}
<- {"id": 7, "file": "C:\\...\\preview-1.bmp", "sample": "gta6-beach", "ms": 2.1} (or {"id": 7, "error": "..."})
Its first line is {"ready": true, "gl": true|false, "samples": [...]}. It ends when stdin closes (the launcher went).
A request is drawn at the size the launcher shows it, so effects measured in pixels (grain, scanlines) look as they
will on screen.
The drawing is the video window's own (framegen/looks_gl.py) in a hidden OpenGL context: under a millisecond.
Without OpenGL it falls back to looks.render(), the NumPy reference: the same picture, about 0.1 to 0.2 s at 640x360.
The sample pictures (framegen/samples, listed in samples.json) are screenshots from games, credited in samples.json,
on the Looks page and in THIRD_PARTY_NOTICES.txt. They belong to their publishers and aren't covered by SmoovPlay's
MIT licence.
"""
from __future__ import annotations
import json
import sys
import time
from pathlib import Path
import numpy as np
from . import looks
SAMPLES_DIR = Path(__file__).resolve().parent / "samples"
MAX_SIZE = (1920, 1080)
def samples(folder: Path = SAMPLES_DIR) -> list[dict]:
"""The sample pictures: id, game, scene, credit, and path (absolute). Missing files are left out."""
try:
listed = json.loads((folder / "samples.json").read_text(encoding="utf-8"))["samples"]
except (OSError, ValueError, KeyError):
return []
out = []
for s in listed:
path = folder / s["file"]
if path.is_file():
out.append({"id": s["id"], "game": s["game"], "scene": s["scene"], "credit": s["credit"],
"path": str(path)})
return out
class _Gl:
"""A hidden OpenGL context with the video window's look renderer, drawing into an offscreen picture."""
def __init__(self, lut_of) -> None:
import glfw
from OpenGL import GL
from .looks_gl import LookRenderer
if not glfw.init():
raise RuntimeError("no OpenGL")
glfw.window_hint(glfw.VISIBLE, glfw.FALSE)
self.win = glfw.create_window(64, 64, "SmoovPlay look preview", None, None)
glfw.default_window_hints()
if not self.win:
glfw.terminate()
raise RuntimeError("no OpenGL context")
glfw.make_context_current(self.win)
GL.glPixelStorei(GL.GL_UNPACK_ALIGNMENT, 1)
GL.glPixelStorei(GL.GL_PACK_ALIGNMENT, 1)
self.glfw, self.GL = glfw, GL
self.r = LookRenderer(GL, lut_of)
self.rev = 0
self.src: dict[tuple, int] = {} # (sample, w, h) -> texture
self.dst: tuple | None = None # (w, h, texture, framebuffer)
def _texture(self, img: np.ndarray | None, w: int, h: int) -> int:
GL = self.GL
t = GL.glGenTextures(1)
GL.glBindTexture(GL.GL_TEXTURE_2D, t)
for p, v in ((GL.GL_TEXTURE_MIN_FILTER, GL.GL_LINEAR), (GL.GL_TEXTURE_MAG_FILTER, GL.GL_LINEAR),
(GL.GL_TEXTURE_WRAP_S, GL.GL_CLAMP_TO_EDGE), (GL.GL_TEXTURE_WRAP_T, GL.GL_CLAMP_TO_EDGE)):
GL.glTexParameteri(GL.GL_TEXTURE_2D, p, v)
GL.glTexImage2D(GL.GL_TEXTURE_2D, 0, GL.GL_RGBA8, w, h, 0, GL.GL_BGR, GL.GL_UNSIGNED_BYTE,
None if img is None else np.ascontiguousarray(img))
return t
def render(self, look: dict, img: np.ndarray, key: tuple, frame: int = 0) -> np.ndarray:
GL = self.GL
h, w = img.shape[:2]
self.rev += 1
plan = self.r.plan(look, self.rev)
if plan is None:
if self.r.broken:
raise RuntimeError("the look shaders didn't build")
return img
if key not in self.src:
if len(self.src) > 8: # (a few sizes of a few pictures)
GL.glDeleteTextures(list(self.src.values()))
self.src.clear()
self.src[key] = self._texture(img, w, h)
if self.dst is None or self.dst[:2] != (w, h):
if self.dst is not None:
GL.glDeleteFramebuffers(1, [self.dst[3]])
GL.glDeleteTextures([self.dst[2]])
t = self._texture(None, w, h)
fbo = GL.glGenFramebuffers(1)
GL.glBindFramebuffer(GL.GL_FRAMEBUFFER, fbo)
GL.glFramebufferTexture2D(GL.GL_FRAMEBUFFER, GL.GL_COLOR_ATTACHMENT0, GL.GL_TEXTURE_2D, t, 0)
self.dst = (w, h, t, fbo)
# Row 0 of the picture is the top, in and out (as tests/test_looks.py checks against the reference).
self.r.draw(plan, self.src[key], False, self.dst[3], 0, 0, w, h, flip_out=False, frame=frame,
purpose="preview")
GL.glBindFramebuffer(GL.GL_READ_FRAMEBUFFER, self.dst[3])
data = GL.glReadPixels(0, 0, w, h, GL.GL_BGR, GL.GL_UNSIGNED_BYTE)
return np.frombuffer(data, np.uint8).reshape(h, w, 3).copy()
def close(self) -> None:
try:
self.r.close()
self.glfw.destroy_window(self.win)
self.glfw.terminate()
except Exception: # noqa: BLE001 - closing anyway
pass
class Previewer:
"""Looks drawn on the sample pictures, at any size."""
def __init__(self, library: looks.Library | None = None, use_gl: bool = True, folder: Path = SAMPLES_DIR):
self.lib = library or looks.Library()
self.samples = {s["id"]: s for s in samples(folder)}
self.gl: _Gl | None = None
if use_gl:
try:
self.gl = _Gl(self.lib.lut)
except Exception as e: # noqa: BLE001 - no OpenGL here: the NumPy path draws the same picture
print(f"[looks] preview without OpenGL ({str(e)[:120]}): slower", file=sys.stderr)
self._pictures: dict[tuple, np.ndarray] = {}
def picture(self, sample: str, w: int, h: int) -> np.ndarray:
import cv2
key = (sample, w, h)
if key not in self._pictures:
if sample not in self.samples:
raise ValueError(f"there's no sample picture called {sample!r}")
img = cv2.imread(self.samples[sample]["path"])
if img is None:
raise ValueError(f"couldn't read the sample picture {sample!r}")
if len(self._pictures) > 16:
self._pictures.clear()
self._pictures[key] = cv2.resize(img, (w, h), interpolation=cv2.INTER_AREA)
return self._pictures[key]
def render(self, look: dict, sample: str, w: int, h: int, frame: int = 0) -> np.ndarray:
w = max(16, min(MAX_SIZE[0], int(w)))
h = max(16, min(MAX_SIZE[1], int(h)))
img = self.picture(sample, w, h)
look = looks.normalize(look)
if self.gl is not None:
try:
return self.gl.render(look, img, (sample, w, h), frame)
except Exception as e: # noqa: BLE001 - fall back for good
print(f"[looks] OpenGL preview failed ({str(e)[:160]}): using the slower one", file=sys.stderr)
self.gl.close()
self.gl = None
return looks.render(look, img, frame, self.lib)
def close(self) -> None:
if self.gl is not None:
self.gl.close()
self.gl = None
def serve(inp=None, out=None, previewer: Previewer | None = None) -> int:
import cv2
inp = inp or sys.stdin
if out is None:
out = sys.stdout
sys.stdout = sys.stderr # stdout carries the answers: anything else printed goes to stderr
pv = previewer or Previewer()
def say(obj: dict) -> None:
out.write(json.dumps(obj) + "\n") # (ASCII)
out.flush()
say({"ready": True, "gl": pv.gl is not None, "samples": list(pv.samples.values())})
try:
for line in inp:
line = line.strip()
if not line:
continue
rid = None
try:
req = json.loads(line)
rid = req.get("id")
t = time.perf_counter()
img = pv.render(req["look"], req["sample"], req.get("width", 640), req.get("height", 360),
int(req.get("frame", 0)))
if not cv2.imwrite(req["out"], img):
raise OSError(f"couldn't write {req['out']}")
say({"id": rid, "file": req["out"], "sample": req["sample"],
"ms": round((time.perf_counter() - t) * 1000, 1)})
except (ValueError, KeyError, TypeError, OSError) as e:
say({"id": rid, "error": str(e)[:300]})
finally:
pv.close()
return 0
if __name__ == "__main__":
raise SystemExit(serve())
+177
View File
@@ -0,0 +1,177 @@
"""In-video settings menu: keyboard-driven, drawn as an image that the GL window blits over the video.
Rows come from settings.SPECS, so a new setting shows up here without changes to this file. Drawing happens
only when something on the menu changes (the window caches the image), so an open menu costs nothing per frame.
"""
from __future__ import annotations
from typing import Callable
import cv2
import numpy as np
from .settings import SPECS, Settings, Spec
FONT = cv2.FONT_HERSHEY_SIMPLEX
TITLE_FONT = cv2.FONT_HERSHEY_DUPLEX
# BGR
BG = (34, 30, 28)
ROW_SEL = (70, 58, 48)
ACCENT = (40, 170, 255)
TEXT = (238, 238, 238)
MUTED = (150, 150, 150)
IMPACT = (200, 200, 200)
DIM = (95, 95, 95)
RULE = (70, 66, 62)
class Menu:
"""allowed(key, value): whether a choice can be picked now (e.g. RTX VSR when the SDK isn't installed).
disabled(key): a reason to grey out a whole row, or None. restart_reasons(): labels of settings changed
since start that need a restart. Changes go through Settings, whose watchers apply them."""
def __init__(self, settings: Settings, specs: tuple[Spec, ...] = SPECS,
allowed: Callable[[str, object], bool] | None = None,
disabled: Callable[[str], str | None] | None = None,
restart_reasons: Callable[[], list[str]] | None = None) -> None:
self.settings, self.specs = settings, specs
self.allowed = allowed or (lambda k, v: True)
self.disabled = disabled or (lambda k: None)
self.restart_reasons = restart_reasons or (lambda: [])
self.open = False
self.index = 0
self._sel: str | None = None # the highlighted setting's key, and the index it was at (see _follow)
self._at = 0
def rows(self) -> list[tuple[str, Spec | None]]:
"""The settings that apply right now (VFG quality only while NVIDIA VFG is picked, and so on)."""
values = self.settings.values()
rows: list[tuple[str, Spec | None]] = [("setting", s) for s in self.specs if s.applies_to(values)]
if self.restart_reasons():
rows.append(("restart", None))
return rows
def _follow(self, rows: list) -> None:
"""Keeps the highlight on the same setting when rows appear or go (a model or upscaler change)."""
keys = [s.key if s is not None else kind for kind, s in rows] # "restart" for the Restart now row
if self.index == self._at and self._sel in keys: # (index set from outside: that row, as given)
self.index = keys.index(self._sel)
self.index = min(self.index, len(rows) - 1)
self._sel, self._at = keys[self.index], self.index
def key(self, name: str) -> str | None:
"""name: up / down / left / right / enter / back. Returns "close", "restart" or None."""
rows = self.rows()
self._follow(rows)
if name == "back":
return "close"
if name in ("up", "down"):
self.index = (self.index + (-1 if name == "up" else 1)) % len(rows)
kind, spec = rows[self.index]
self._sel, self._at = (spec.key if spec is not None else kind), self.index
return None
kind, spec = rows[self.index]
if kind == "restart":
return "restart" if name == "enter" else None
if self.disabled(spec.key):
return None
if name in ("left", "right", "enter"):
self.settings.step(spec.key, -1 if name == "left" else 1, self.allowed)
return None
def state(self) -> tuple:
"""Everything the drawing depends on (the window redraws only when this changes)."""
return (self.index, tuple(self.settings.values().items()), tuple(self.restart_reasons()),
tuple(self.disabled(s.key) for s in self.specs))
def render(self, ui: float = 1.0) -> np.ndarray:
"""The menu as a BGR image; ui scales it (1.0 suits a 1080p-tall window)."""
def px(v: float) -> int:
return max(1, int(round(v * ui)))
w, pad, row_h, head_h = px(780), px(26), px(46), px(78)
fs, small = 0.66 * ui, 0.5 * ui
th = 1 if ui < 1.4 else 2
rows = self.rows()
self._follow(rows)
sel_kind, sel_spec = rows[self.index]
if sel_kind == "restart":
help_text = "Restarts the pipeline with the new settings. The stream keeps running; takes a few seconds."
else:
help_text = self.disabled(sel_spec.key) or sel_spec.help
help_lines = _wrap(help_text, w - 2 * pad, small, th)[:4]
impact_lines: list[str] = [] # under the help: its rough effect on the picture and on speed
if sel_kind != "restart" and not self.disabled(sel_spec.key):
for k, name in (("picture", "Picture"), ("speed", "Speed")):
if sel_spec.impact.get(k):
impact_lines += _wrap(f"{name}: {sel_spec.impact[k]}", w - 2 * pad, small, th)[:2]
foot_h = px(18) + (len(help_lines) + len(impact_lines)) * px(26) + (px(8) if impact_lines else 0) + px(46)
if head_h + len(rows) * row_h + foot_h > px(1040): # many rows: closer together, so it fits the window
row_h = max(px(32), (px(1040) - head_h - foot_h) // len(rows))
h = head_h + len(rows) * row_h + foot_h
img = np.full((h, w, 3), BG, np.uint8)
cv2.putText(img, "Settings", (pad, px(50)), TITLE_FONT, 1.05 * ui, TEXT, th + 1, cv2.LINE_AA)
_text_right(img, "M / Esc to close", w - pad, px(48), small, MUTED, th)
cv2.line(img, (pad, head_h - px(10)), (w - pad, head_h - px(10)), RULE, max(1, px(1.5)))
for i, (kind, spec) in enumerate(rows):
y0 = head_h + i * row_h
base = y0 + int(row_h * 0.66)
selected = i == self.index
if selected:
cv2.rectangle(img, (0, y0), (w, y0 + row_h - px(2)), ROW_SEL, -1)
cv2.rectangle(img, (0, y0), (px(6), y0 + row_h - px(2)), ACCENT, -1)
if kind == "restart":
reasons = ", ".join(self.restart_reasons())
cv2.putText(img, f"Restart now (applies: {reasons})", (pad, base), FONT, fs, ACCENT, th,
cv2.LINE_AA)
continue
off = self.disabled(spec.key) is not None
color = DIM if off else TEXT
cv2.putText(img, spec.label, (pad, base), FONT, fs, color, th, cv2.LINE_AA)
if not spec.live:
lw = cv2.getTextSize(spec.label, FONT, fs, th)[0][0]
cv2.putText(img, "restart", (pad + lw + px(12), base), FONT, small * 0.9, DIM if off else MUTED,
th, cv2.LINE_AA)
value = "not available" if off else spec.name(getattr(self.settings, spec.key))
right = w - pad
if selected and not off:
_text_right(img, ">", right, base, fs, ACCENT, th)
right -= px(30)
vw = _text_right(img, value, right, base, fs, TEXT, th)
_text_right(img, "<", right - vw - px(14), base, fs, ACCENT, th)
else:
_text_right(img, value, right - (px(30) if not off else 0), base, fs, MUTED if not off else DIM, th)
y = head_h + len(rows) * row_h
cv2.line(img, (pad, y + px(4)), (w - pad, y + px(4)), RULE, max(1, px(1.5)))
y += px(18)
for line in help_lines:
y += px(26)
cv2.putText(img, line, (pad, y), FONT, small, MUTED, th, cv2.LINE_AA)
y += px(8) if impact_lines else 0
for line in impact_lines:
y += px(26)
cv2.putText(img, line, (pad, y), FONT, small, IMPACT, th, cv2.LINE_AA)
cv2.putText(img, "Up/Down select Left/Right change M close Q quit",
(pad, h - px(16)), FONT, small * 0.9, DIM, th, cv2.LINE_AA)
return img
def _text_right(img: np.ndarray, text: str, right: int, base: int, scale: float, color, th: int) -> int:
tw = cv2.getTextSize(text, FONT, scale, th)[0][0]
cv2.putText(img, text, (right - tw, base), FONT, scale, color, th, cv2.LINE_AA)
return tw
def _wrap(text: str, width: int, scale: float, th: int) -> list[str]:
lines, line = [], ""
for word in text.split():
trial = f"{line} {word}".strip()
if line and cv2.getTextSize(trial, FONT, scale, th)[0][0] > width:
lines.append(line)
line = word
else:
line = trial
return lines + ([line] if line else [])
+767
View File
@@ -0,0 +1,767 @@
"""Source -> duplicate detection -> scheduler -> RIFE or NVIDIA VFG -> sink, with latency/quality stats."""
from __future__ import annotations
import time
from collections import Counter, deque
from dataclasses import dataclass, field
import numpy as np
import torch
from . import delaytest
from .cadence import Action, CadenceScheduler, CutDetector, DuplicateDetector, FrameTimeline
from .interpolator import STEADY_HUD_THRESHOLD, RifeInterpolator
from .io import TICK, Waiting
# --score's "still areas": pixels within this many levels (of 255) in both real frames, like a HUD or map.
STILL_LEVELS = 3
# --score's "HUD-like areas": still in both real frames *and* the real in-between one, on an edge (Sobel L1 of the
# real frame's brightness above HUD_EDGE, about a 32-level step), so text, icons and map lines rather than flat
# sky. A pixel there is "visibly off" when the AI frame misses the real one by more than HUD_OFF_LEVELS: the
# wobble a viewer sees, which a whole-frame score dilutes.
HUD_EDGE = 128.0
HUD_OFF_LEVELS = 12
def psnr(a: torch.Tensor, b: torch.Tensor) -> float:
return _db((a.float() - b.float()).pow_(2).mean().item())
_SOBEL: dict = {}
def hud_mask(a: torch.Tensor, b: torch.Tensor, gt: torch.Tensor, still: torch.Tensor | None = None) -> torch.Tensor:
"""HUD-like pixels for scoring (HxWx1 float 0/1): unchanged within STILL_LEVELS across the real frames a, gt
(the real in-between one) and b, all HxWx3 BGR 0..255, and on an edge of gt's brightness (see HUD_EDGE)."""
a, b, gt = a.float(), b.float(), gt.float()
if still is None:
still = ((b - a).abs().amax(-1, keepdim=True) <= STILL_LEVELS).float()
static = still * ((gt - a).abs().amax(-1, keepdim=True) <= STILL_LEVELS).float()
k = _SOBEL.get(gt.device)
if k is None:
gx = torch.tensor([[-1.0, 0.0, 1.0], [-2.0, 0.0, 2.0], [-1.0, 0.0, 1.0]], device=gt.device)
k = _SOBEL[gt.device] = torch.stack([gx, gx.t()]).unsqueeze(1) # (2, 1, 3, 3)
luma = (gt * torch.tensor([0.114, 0.587, 0.299], device=gt.device)).sum(-1)[None, None]
g = torch.nn.functional.conv2d(torch.nn.functional.pad(luma, (1, 1, 1, 1), mode="replicate"), k)
edge = (g.abs().sum(1)[0] > HUD_EDGE).float().unsqueeze(-1)
return static * edge
def _np(frame) -> np.ndarray:
"""A private numpy copy of a frame (numpy array or CUDA tensor)."""
return frame.cpu().numpy() if torch.is_tensor(frame) else frame.copy()
def _db(mse: float) -> float:
return float("inf") if mse == 0 else 10.0 * np.log10(255.0**2 / mse)
class GameRate:
"""The game's own frame rate: new frames among the last `n` ticks of a 60 Hz stream. Counted by ticks rather
than by the clock, so a file read faster than real time reads the same. None until `n` ticks are in."""
def __init__(self, n: int = 120) -> None:
self._new: deque = deque(maxlen=n)
def add(self, new: bool | None) -> None:
"""One tick: new content (True) or a repeat (False). None (the source can't say) is left out."""
if new is not None:
self._new.append(bool(new))
def clear(self) -> None:
self._new.clear()
def fps(self) -> float | None:
n = len(self._new)
return sum(self._new) / n / TICK if n and n == self._new.maxlen else None
class ShownRate:
"""Frames put on screen per second over the last `window` seconds: what a GPU overlay calls the frame rate."""
def __init__(self, window: float = 1.0) -> None:
self.window, self._t, self._start = window, deque(), None
def add(self, t: float) -> None:
self._start = t if self._start is None else self._start
self._t.append(t)
while self._t[0] <= t - self.window:
self._t.popleft()
def fps(self) -> float | None:
if self._start is None or self._t[-1] - self._start < self.window:
return None
return len(self._t) / self.window
# How long the game has to stay off the rate that's needed before the overlay says so, and before the one-off message
RATE_NOTE_S, RATE_TOAST_S = 3.0, 10.0
def rate_advice(game_fps: float | None, test: bool, even: bool = False) -> str:
"""One line for someone whose game isn't at the rate that's needed, or "" when it is (or it isn't known yet).
test: "Simulate a 30 fps game" is on, which needs a game at a steady 60 fps. Otherwise frame generation, which
fills a 30 fps game's gaps: a faster game's frames mostly pass through as they are, unless `even` (Even out
40-60 fps is on), which spaces a 40-60 fps game's frames evenly."""
if game_fps is None:
return ""
g = round(game_fps)
if test:
if g >= 50:
return ""
if g <= 38:
return f"Simulate is for 60 fps games. This one is at {g} fps already: turn Simulate off (menu: M)"
return f"Simulate needs a steady 60 fps game. This one is at about {g}, so quality isn't measured"
if g <= 38 or (even and g <= 56):
return ""
if g >= 55:
return f"Game at {g} fps: no gaps to fill. Frame generation is for 30 fps modes (Quality/Fidelity)"
return f"Game at about {g} fps, not 30: few gaps to fill. Its 30 fps mode (Quality/Fidelity) is smoother"
@dataclass
class Stats:
proc_interp_ms: list[float] = field(default_factory=list) # tick processing when we interpolate
proc_other_ms: list[float] = field(default_factory=list) # tick processing otherwise
sink_ms: list[float] = field(default_factory=list) # time spent in display/encode
queue_ms: list[float] = field(default_factory=list) # arrival -> processing starts (backlog)
score_ms: list[float] = field(default_factory=list) # --score, done after the frame is shown
busy_ms: list[float] = field(default_factory=list) # processing + display per tick
# Arrival of each real (new) frame -> it is first presented. Passthrough would be ~upload+present;
# interpolation adds one 60 Hz tick on top, because the midpoint must go out first.
real_delay_ms: list[float] = field(default_factory=list)
actions: Counter = field(default_factory=Counter)
dedup: Counter = field(default_factory=Counter) # tp/tn/fp/fn vs ground truth
psnr_interp: list[float] = field(default_factory=list)
psnr_repeat: list[float] = field(default_factory=list) # what you'd see without interpolation
psnr_blend: list[float] = field(default_factory=list) # naive 50/50 crossfade
# The same, only over pixels that are (almost) unchanged between the two real frames: HUD, maps, still
# backgrounds. Where Steady HUD acts; for tuning it (--score), not shown to users.
psnr_still: list[float] = field(default_factory=list)
psnr_still_repeat: list[float] = field(default_factory=list)
still_frac: list[float] = field(default_factory=list)
psnr_hud: list[float] = field(default_factory=list) # HUD-like areas (see HUD_EDGE)
hud_off: list[float] = field(default_factory=list) # share of them visibly off (see HUD_OFF_LEVELS)
hud_frac: list[float] = field(default_factory=list)
worst: tuple | None = None # (psnr, tick, prev, interp, gt, next)
quarter_shown: int = 0 # 90/120 Hz: extra in-between frames shown (1/4 and 3/4, or 1/3)
quarter_skipped: int = 0 # ones skipped because the pipeline was behind (shown at 60 Hz instead)
behind: int = 0 # ticks whose frame waited for the pipeline to finish earlier ones (more than 60% of a tick)
hz_used: set = field(default_factory=set) # output rates used during the run
simulated: int = 0 # ticks played with "Simulate a 30 fps game" on
# Frames played in test mode, by the source's word on whether the game itself drew each one new or repeated one.
# Test mode needs a game at a steady 60 fps, with next to no repeats; only frames with new ones on both sides
# are scored (TestMode.gt).
test_game_new: int = 0
test_game_repeat: int = 0
delay_tests: list = field(default_factory=list) # the delay test's results (L), a line each
# Even out 40-60 fps (FrameTimeline): ticks played that way, its game's frame rate, and output frames that showed
# the newest frame again because the next one came late.
uneven_ticks: int = 0
uneven_fps: list = field(default_factory=list)
uneven_waits: int = 0
wall_s: float = 0.0
exit: str = "end" # why run() returned: "end" (source finished), "quit" or "restart" (asked by the sink)
stale: int = 0 # frames skipped because they arrived before run() started (queued during a restart)
# The engine's numbers mustn't be shared (NVIDIA VFG: its licence forbids publishing benchmark results), and the
# log goes into Copy diagnostics, so summary() leaves out timings and scores. The overlay and test mode's report
# (results(); Copy diagnostics leaves it out, see run.write_results) still show them on this PC.
private: bool = False
PRIVATE_NOTE = ("NVIDIA VFG: timings and quality scores are left out of the log, because NVIDIA's licence doesn't "
"allow sharing them and the log goes into Copy diagnostics. The stats overlay (S) and test mode's "
"report show them on this PC.")
def summary(self) -> str:
def pct(xs, p):
return float(np.percentile(xs, p)) if xs else float("nan")
n = len(self.proc_interp_ms) + len(self.proc_other_ms)
lines = [
f"ticks={n} wall={self.wall_s:.1f}s",
f"actions: {dict(self.actions)}",
]
tg = self.test_game_new + self.test_game_repeat
if tg:
lines.append(f"test mode: {self.test_game_repeat} of {tg} frames were repeats in the game itself (a steady "
"60 fps game has next to none); only frames with new ones on both sides are scored")
if self.uneven_ticks:
lines.append(f"even timing (a game at about {np.median(self.uneven_fps):.0f} fps): {self.uneven_ticks} "
f"ticks, {self.uneven_waits} output frames waited for a late frame")
if self.private:
if self.dedup:
lines.append(f"dedup vs truth: {dict(self.dedup)}")
return "\n".join(lines + [self.PRIVATE_NOTE])
lines += self.delay_tests
lines[0] += f" ({n / max(self.wall_s, 1e-9):.1f} ticks/s)"
rows = (("processing, interp ticks", self.proc_interp_ms), ("processing, other ticks", self.proc_other_ms),
("display/encode", self.sink_ms), ("scoring, after display", self.score_ms),
("queueing (backlog)", self.queue_ms),
("real frame arrival->presented", self.real_delay_ms))
for name, xs in rows:
if xs:
lines.append("{:<30} ms p50={:6.2f} p95={:6.2f} p99={:6.2f} max={:6.2f}".format(
name, pct(xs, 50), pct(xs, 95), pct(xs, 99), max(xs)))
if self.stale:
lines.append(f"stale frames skipped at start (queued before this run): {self.stale}")
lines.append(f"ticks over the {TICK * 1000:.1f} ms budget (processing + display): "
f"{sum(b > TICK * 1000 for b in self.busy_ms)}")
if self.quarter_shown or self.quarter_skipped:
due = self.quarter_shown + self.quarter_skipped
lines.append(f"extra in-between frames (90/120 Hz) shown {self.quarter_shown} of {due} "
f"({100 * self.quarter_shown / due:.0f}%); the rest fell back to 60 Hz because it was behind")
if self.dedup:
lines.append(f"dedup vs truth: {dict(self.dedup)}")
if self.psnr_interp:
fin = lambda xs: [x for x in xs if np.isfinite(x)] # noqa: E731
lines.append(
"PSNR vs real in-between frame (dB, higher=better): RIFE {:.2f} | blend {:.2f} | repeat {:.2f}"
" (n={}, RIFE worst {:.2f})".format(
np.mean(fin(self.psnr_interp)), np.mean(fin(self.psnr_blend)),
np.mean(fin(self.psnr_repeat)), len(self.psnr_interp), min(self.psnr_interp)))
if self.psnr_still:
fin = lambda xs: [x for x in xs if np.isfinite(x)] # noqa: E731
lines.append(" still areas ({:.0f}% of pixels): RIFE {:.2f} | repeat {:.2f}".format(
100 * np.mean(self.still_frac), np.mean(fin(self.psnr_still)), np.mean(fin(self.psnr_still_repeat))))
if self.psnr_hud:
fin = lambda xs: [x for x in xs if np.isfinite(x)] # noqa: E731
lines.append(" HUD-like areas ({:.1f}% of pixels): RIFE {:.2f} dB, {:.2f}% visibly off".format(
100 * np.mean(self.hud_frac), np.mean(fin(self.psnr_hud)) if fin(self.psnr_hud) else float("inf"),
100 * np.mean(self.hud_off)))
return "\n".join(lines)
def results(self, full_motion: bool | None = None) -> list[str]:
"""Test mode's plain-language report: can this PC keep up, and how close are the AI frames to the real
ones. Safe to call from another thread while run() is still adding to the lists. full_motion: whether
motion ran at full resolution (None: unknown), so the advice doesn't suggest what's already on."""
budget = TICK * 1000
interp, busy, delay = list(self.proc_interp_ms), list(self.busy_ms), list(self.real_delay_ms)
ai = [x for x in list(self.psnr_interp) if np.isfinite(x)]
repeat = [x for x in list(self.psnr_repeat) if np.isfinite(x)]
rates = sorted(set(self.hz_used)) or [60]
lines = ["Output: " + " and ".join(f"{h} fps" for h in rates)]
if interp:
lines.append(f"AI frame time: {np.mean(interp):.1f} ms on average, {np.percentile(interp, 95):.1f} ms "
f"for the slowest 5% (a 60 fps frame lasts {budget:.1f} ms)")
# Behind, not "took over 16.7 ms": at 90/120 fps the pacer sleeps between a tick's two frames on purpose.
n, behind = len(busy), self.behind
if n:
lines.append(f"Running behind: {100 * behind / n:.1f}% of frames ({behind} of {n}) arrived while the PC "
"was still busy with earlier ones")
due = self.quarter_shown + self.quarter_skipped
if due:
lines.append(f"Extra frames for 90/120 fps: {100 * self.quarter_shown / due:.0f}% shown; the rest fell "
"back to 60 fps because the PC was behind")
if delay:
lines.append(f"Delay: a real frame reached the screen {np.median(delay):.0f} ms after it arrived (median)")
# Test mode needs a game at a steady 60 fps: where the game itself repeated a frame, there's no real
# in-between frame, so those aren't scored (TestMode.gt), and it's said when the game wasn't at 60.
tg = self.test_game_new + self.test_game_repeat
not_60 = tg >= 120 and self.test_game_repeat / tg > 0.1
if not_60:
fps = 60 * self.test_game_new / tg
lines.append(f"Game: it ran at about {fps:.0f} fps, not a steady 60. Simulate a 30 fps game is for 60 fps "
"games; a 30 fps game doesn't need it, as frame generation works on it as it is")
if len(ai) >= (30 if not_60 else 1):
lines.append(f"Quality: AI frames scored {np.mean(ai):.1f} dB against the real frames they stood in for; "
f"repeating the last frame instead (no AI) scores {np.mean(repeat):.1f} dB. Higher is "
f"closer to the real thing; slow scenes score high either way, the gap shows in motion "
f"({len(ai)} frames measured, worst {min(ai):.1f} dB"
+ ("; only where the game drew every frame)" if not_60 else ")"))
elif not_60:
lines.append("Quality: not measured, as the game wasn't at a steady 60 fps")
elif interp:
lines.append("Quality: not measured yet (it's measured at 60 and 120 fps output; 90 fps has no real "
"frame to compare with)")
if self.uneven_ticks:
lines.append(f"Game: for {self.uneven_ticks / 60:.0f} s it ran at about {np.median(self.uneven_fps):.0f} "
"fps, between 30 and 60, and its frames were evened out (Even out 40-60 fps)")
lines += list(self.delay_tests)
if not interp:
lines.append("Verdict: frame generation was off, so there's nothing to judge")
else:
late, shown = behind / max(n, 1), self.quarter_shown / due if due else 1.0
top = f"{max(rates)} fps"
lighter = (["a lower output rate"] if max(rates) > 60 else []) + (
["Motion detail: Half"] if full_motion is not False else [])
either = " or ".join(lighter)
# At 90 and 120 fps the extra frames say it: a tick that arrives while the PC is still busy only costs
# something when it has to skip one (a repeat tick waiting a moment loses nothing on screen). At 60 fps
# there are no extra frames, so frames that waited are what's left to go by.
ok, mostly = (shown >= 0.95, shown >= 0.8) if due else (late < 0.01, late < 0.05)
if ok:
lines.append(f"Verdict: this PC keeps up at {top}")
elif mostly:
lines.append(f"Verdict: this PC mostly keeps up at {top}, but falls behind now and then"
+ (f". {either[:1].upper()}{either[1:]} would smooth that out" if lighter else ""))
else:
lines.append(f"Verdict: this PC is falling behind at {top}"
+ (f". Try {either}" if lighter else ", even on the lightest settings"))
return lines
class Pipeline:
def __init__(self, interp: RifeInterpolator, detector: DuplicateDetector | None = None,
cut_threshold: float = 25.0) -> None:
self.interp = interp
self.detector = detector or DuplicateDetector()
self.cut_threshold = cut_threshold # see CutDetector
h, w = interp.h, interp.w
pin = torch.cuda.is_available() # (pinned memory needs CUDA; DirectML's frames are plain CPU tensors)
self._in_pinned = torch.empty((h, w, 3), dtype=torch.uint8, pin_memory=pin)
self._out_pinned = torch.empty((h, w, 3), dtype=torch.uint8, pin_memory=pin)
self._in_np = self._in_pinned.numpy()
self._out_np = self._out_pinned.numpy()
self.stats: Stats | None = None # the running session's, for reports written while it plays
self.beat = time.perf_counter() # when run()'s loop last went round (run.py's watchdog reads it)
self.waiting = None # the source's Waiting while no frame is coming, else None (the watchdog reads it too)
def run(self, source, sink=None, enabled: bool = True, score: bool = False, label: str = "",
on_tick=None, hz: int = 60, settings=None, gt=None, remote=None, replay=None) -> Stats:
"""on_tick(tick, diff, action, proc_ms, t_start), if given, is called after each tick is processed.
remote: the source, when it can press a button for the delay test (L: PS5 Remote Play's chiaki-ng,
framegen.chiaki_tap.ChiakiSource) or hold its sound back to meet the picture (settings.audio_sync: chiaki-ng,
or a capture card's sound, framegen.capture.CardSource); None for other sources.
gt(content) -> the real frame that was left out, for scoring; default `source.gt` (pass it when `source`
is an iterator over the real source, which doesn't have it).
settings (framegen.settings.Settings): if given, its `interp` and `hz` are followed live instead of
`enabled` and `hz`.
replay (framegen.replay.Recorder): instant replay. It gets every frame shown, each new frame from the game
and the pipeline's delay, and the window's R and B keys save it.
hz=120 or 90 (needs a sink): more generated frames per 30 fps frame, shown at least 1/hz apart.
120: a new frame B after A shows A->B at 1/4 then 1/2; its repeat tick shows 3/4 then B.
90: the new frame's tick shows 1/3 then 2/3; its repeat tick shows B.
When the pipeline is running behind, a tick skips the extra frame(s) and shows what 60 Hz would (the 1/2
frame, or B), so it never builds a backlog.
"""
if settings is not None:
enabled, hz = settings.interp, settings.hz if sink is not None else 60
it, sched, st = self.interp, CadenceScheduler(), Stats(private=bool(getattr(self.interp, "private", False)))
steady = None # Steady HUD as last applied to the interpolator (followed live from settings)
self.stats = st
quarter_due = False # 120 Hz: the previous tick interpolated, so this repeat tick owes the 3/4 frame
behind_ms = 1000 * TICK * 0.6 # start-of-tick lag above which the extra frames are skipped
gap = 0.95 / hz # time between two presents, 5% short so the schedule has slack to catch up
next_due = 0.0
cuts = CutDetector(self.cut_threshold)
slot = 0
key_frame: np.ndarray | None = None # last frame that arrived as new content
key_content: int | None = None
# Scoring: --score, or live while "Simulate a 30 fps game" is on (the source keeps the left-out frames).
scoring = score or bool(settings is not None and settings.simulate_30)
gt = gt or getattr(source, "gt", None)
gt_fn = gt if scoring else None
st.hz_used.add(hz)
key_gpu: torch.Tensor | None = None # GPU copy of key_frame, for scoring
# A sink that takes CUDA tensors (the GL window with CUDA-GL interop) gets generated frames without a
# GPU->CPU->GPU round trip; otherwise they're downloaded into pinned memory as before.
gpu_out = bool(getattr(sink, "gpu", False))
last_proc = 0.0
unshown: float | None = None # arrival time of the newest real frame not yet presented as itself
t_start = time.perf_counter()
# Overlay: one line for every frame shown (real and in-between), refreshed a few times a second with
# averages since the last refresh, so it reads steadily instead of changing every frame.
ov_text, ov_next, ov_mark = label, 0.0, (0, 0, 0)
# What's really happening, next to what's set: the game's frame rate as the pipeline sees it (30 in test
# mode), the game's own (test mode reads it from the source's hints), and frames shown per second. A game
# that isn't at the rate frame generation (or test mode) needs gets a line on the overlay and, once, a
# message (see rate_advice).
seen_rate, game_rate, shown_rate = GameRate(), GameRate(), ShownRate()
delay_test, test_mark = None, 0 # the delay test while it runs, and where its stretch of real_delay_ms starts
# A 40-60 fps game: its frames' own timing, and evenly spaced frames from it (FrameTimeline). in_slot: which
# frame (TimedFrame.id) is in each of the interpolator's two slots; timed frames go in only when needed.
timeline, timed, in_slot = FrameTimeline(), False, [-1, -1]
reached: tuple = () # timed: the frames whose time came with the frame about to be shown
audio_next, audio_ms = 0.0, None # when the sound delay is next looked at, and what chiaki-ng was last told
replay_next = 0.0 # when instant replay is next told the delay
off_since: float | None = None # since when the game has been off the rate that's needed
note, toasted = "", set()
def overlay_text() -> str:
nonlocal ov_mark
n0, s0, k0 = ov_mark
ov_mark = (len(st.proc_interp_ms), st.quarter_shown, st.quarter_skipped)
g, s = seen_rate.fps(), shown_rate.fps()
rates = (f"game {g:.0f} fps{' evened out' if timed else ''}, showing {s:.0f}"
if g is not None and s is not None else "")
if not enabled:
text = f"{label} INTERP OFF" + (f" {rates}" if rates else "")
else:
proc = st.proc_interp_ms[n0:]
text = f"{label} INTERP ON {rates or f'{hz} Hz'} interp {np.mean(proc) if proc else 0.0:5.1f} ms"
shown, skipped = st.quarter_shown - s0, st.quarter_skipped - k0
if hz > 60 and shown + skipped:
text += f" extra frames {100 * shown / (shown + skipped):3.0f}%"
if delay_test is not None: # the delay test, while it runs, is the second line
text += "\n" + delay_test.status()
elif note: # the game isn't at the rate that's needed: that's the second line
text += "\n" + note
elif settings is not None and settings.simulate_30:
# A second line: the test badge, and quality over the last ~30 scored frames (about a second).
# 90 fps draws frames at 1/3 and 2/3, where a 60 fps game has no real frame to compare against.
text += "\nTEST: 60 fps game played as 30 fps"
q = [(x, y) for x, y in zip(st.psnr_interp[-30:], st.psnr_repeat[-30:])
if np.isfinite(x) and np.isfinite(y)]
if enabled and hz == 90:
text += " quality: measured at 60 and 120 fps"
elif enabled and q:
text += (f" quality {np.mean([x for x, _ in q]):.1f} dB vs real frames"
f" (no AI {np.mean([y for _, y in q]):.1f} dB)")
return text
for tick in source:
self.beat = time.perf_counter()
if isinstance(tick, Waiting): # no frame for a moment: keep the window answering until one comes
self.waiting = tick
if sink is not None and hasattr(sink, "wait"):
cmd = sink.wait(tick)
if cmd in ("quit", "restart"):
st.exit = cmd
break
continue
self.waiting = None
if tick.t_arrival < t_start: # queued while the previous session was restarting: show live frames only
st.stale += 1
continue
if settings is not None: # changed in the menu (or by a hotkey) since the last tick?
want_hz = settings.hz if sink is not None else 60
if want_hz != hz:
hz, gap, quarter_due, ov_next = want_hz, 0.95 / want_hz, False, 0.0
st.hz_used.add(hz)
print(f"[pipeline] output {hz} Hz")
if (score or settings.simulate_30) != scoring:
scoring = not scoring
gt_fn = gt if scoring else None
key_gpu, ov_next = None, 0.0
seen_rate.clear() # test mode changes what the pipeline sees; the game's own rate stays
off_since, note = None, ""
print(f"[pipeline] test mode (simulated 30 fps game) {'ON' if settings.simulate_30 else 'OFF'}")
if settings.simulate_30:
st.simulated += 1
if settings.interp != enabled:
enabled, sched, quarter_due, ov_next = settings.interp, CadenceScheduler(), False, 0.0
print(f"[pipeline] interpolation {'ON' if enabled else 'OFF'}")
if settings.steady_hud != steady:
steady = settings.steady_hud
if hasattr(it, "set_steady"):
it.set_steady(STEADY_HUD_THRESHOLD if steady else 0.0)
print(f"[pipeline] steady HUD {'ON' if steady else 'OFF'}")
t0 = time.perf_counter()
st.queue_ms.append((t0 - tick.t_arrival) * 1000)
if torch.is_tensor(tick.frame): # already on the GPU (hardware decoder)
it.load(tick.frame)
else:
np.copyto(self._in_np, tick.frame)
it.load(self._in_pinned)
diff = self.detector.update(it.in_u8)
# A source that knows better (Remote Play: compressed frame size) overrides the image check.
is_new = diff.is_new if tick.new_hint is None else tick.new_hint
seen_rate.add(is_new)
# In test mode the source's own word on the game's frame (TestMode puts it in extra["game_new"]).
game_new = tick.extra["game_new"] if "game_new" in tick.extra else is_new
game_rate.add(game_new)
if "game_new" in tick.extra and game_new is not None:
if game_new:
st.test_game_new += 1
else:
st.test_game_repeat += 1
if delay_test is not None:
delay_test.feed(delaytest.small(it.in_u8), tick.t_arrival, time.perf_counter())
if delay_test.done:
ours = st.real_delay_ms[test_mark:]
result = delay_test.result(float(np.median(ours)) if ours else None)
st.delay_tests.append(result)
if not st.private: # with NVIDIA VFG it stays on screen and in test mode's report
print(f"[pipeline] {result}")
if hasattr(sink, "toast"):
sink.toast(result.replace("Delay test: ", "", 1), 15.0)
delay_test, ov_next = None, 0.0
# Sound: chiaki-ng plays it as it arrives, while the picture spends a while in SmoovPlay. Every 2 s,
# chiaki-ng is told to hold the sound back by that while (the median of the last ~2 s of real frames).
sync = settings is None or getattr(settings, "audio_sync", True)
if remote is not None and t0 >= audio_next and (st.real_delay_ms or not sync):
audio_next = t0 + 2.0
want = round(float(np.median(st.real_delay_ms[-120:]))) if sync else 0
if (audio_ms is None or abs(want - audio_ms) >= 4) and remote.can_delay_audio():
if want and (audio_ms is None or abs(want - audio_ms) >= 10):
print(f"[pipeline] sound held back {want} ms to meet the picture")
elif not want and audio_ms:
print("[pipeline] sound no longer held back (Sound in sync is off)")
remote.set_audio_delay(want)
audio_ms = want
# Instant replay times the game's own frames and its sound by the same delay, to line up with the picture.
if replay is not None and t0 >= replay_next and st.real_delay_ms:
replay_next = t0 + 2.0
replay.set_delay(float(np.median(st.real_delay_ms[-120:])))
if tick.truth_new is not None:
st.dedup[("t" if is_new == tick.truth_new else "f") + ("p" if is_new else "n")] += 1
to_score = None
early_cmd = None # 90/120 Hz: the first of this tick's two frames, already shown
mid_t = 0.5 # the generated frame this tick ends on
# Behind = waiting frames, not decode time: a Remote Play frame's arrival is before its ~3-11 ms decode.
t_avail = tick.t_arrival if tick.t_ready is None else tick.t_ready
behind = (t0 - t_avail) * 1000 >= behind_ms
st.behind += behind
extra_ok = hz > 60 and sink is not None and not behind
def present(frame, text: str):
# Frame pacer: each present is due one gap after the previous one was *due*, so sleep overshoot and
# present time don't accumulate; when late it goes straight away and the schedule restarts from now.
nonlocal next_due
if hz > 60:
now = time.perf_counter()
if next_due > now:
time.sleep(next_due - now)
next_due = max(next_due, now) + gap
cmd = sink.write(frame, text)
t_now = time.perf_counter()
shown_rate.add(t_now)
if replay is not None:
replay.frame(frame, t_now) # after it's on screen, so it adds no delay
return cmd
def show_early(t: float) -> bool:
nonlocal early_cmd
if not extra_ok:
st.quarter_skipped += 1
return False
early_cmd = present(self._generated(it.interpolate(slot, t), gpu_out), ov_text)
st.quarter_shown += 1
return True
if not enabled:
action, out = Action.CURRENT, tick.frame
quarter_due = timed = False
else:
# A frame the source flags as damaged (e.g. Remote Play packet loss) is held like a cut, so its
# corruption isn't blended into the generated frame. `|` so the cut detector still sees every frame.
is_cut = is_new and (cuts.update(diff.mean_diff, diff.cut) | tick.damaged)
action = sched.step(is_new, is_cut)
added = timeline.tick(is_new, is_cut, tick.frame, tick.t_arrival)
was_timed = timed
timed = (timeline.uneven and sink is not None and gt_fn is None
and (settings is None or getattr(settings, "even_out", True)))
if timed != was_timed:
if timed:
unshown = None
print(f"[pipeline] game at about {timeline.fps()} fps: evening out its frames")
if hasattr(sink, "toast") and "even" not in toasted:
toasted.add("even")
sink.toast(f"Game at about {timeline.fps()} fps: SmoovPlay is spacing its frames evenly "
"(Even out 40-60 fps)", 6.0)
else:
sched = CadenceScheduler() # starts afresh, from the next new frame
action = sched.step(is_new, is_cut)
print("[pipeline] even timing off")
if is_new and not timed:
slot = 1 - slot
it.prepare(slot) # (in_u8 holds this tick's frame)
in_slot[slot] = added.id
if timed:
st.uneven_ticks += 1
if is_new:
st.uneven_fps.append(timeline.fps())
quarter_due = False
phases = timeline.slots(hz)
if len(phases) > 1 and not extra_ok:
st.quarter_skipped += len(phases) - 1
phases = phases[-1:]
else:
st.quarter_shown += len(phases) - 1
for k, phi in enumerate(phases):
pl = timeline.place(phi)
if pl.b is None:
frame = pl.a.frame
else:
slot = self._timed_pair(pl.a, pl.b, slot, in_slot)
frame = self._generated(it.interpolate(slot, pl.t), gpu_out)
st.uneven_waits += pl.waiting
if k < len(phases) - 1:
early_cmd = present(frame, ov_text) or early_cmd
t_now = time.perf_counter()
st.real_delay_ms.extend((t_now - f.t_arrival) * 1000 for f in pl.reached)
else:
out, reached = frame, pl.reached
action = Action.INTERP if pl.b is not None else Action.CURRENT
elif hz == 120 and action is Action.INTERP:
show_early(0.25)
elif hz == 120 and quarter_due and action is Action.CURRENT and not is_new:
show_early(0.75)
elif hz == 90 and action is Action.INTERP and show_early(1 / 3):
mid_t = 2 / 3
quarter_due = action is Action.INTERP
if timed:
pass # shown above
elif action is Action.INTERP:
out = self._generated(it.interpolate(slot, mid_t), gpu_out)
# --score has ground truth only at the midpoint
if gt_fn is not None and key_gpu is not None and mid_t == 0.5:
to_score = (key_frame, key_content) # scored once the frame is on screen
elif action in (Action.PENDING, Action.HOLD):
out = key_frame
else:
out = tick.frame
prev_key = key_gpu
if is_new:
key_frame, key_content = tick.frame, tick.content
if gt_fn is not None:
key_gpu = it.in_u8.clone()
t_ready = time.perf_counter()
last_proc = (t_ready - t0) * 1000
(st.proc_interp_ms if action is Action.INTERP else st.proc_other_ms).append(last_proc)
st.actions[action.value] += 1
if on_tick is not None:
on_tick(tick, diff, action, last_proc, t0)
cmd = None
if sink is not None:
if t_ready >= ov_next:
test = settings is not None and settings.simulate_30
even = sink is not None and (settings is None or getattr(settings, "even_out", True))
advice = rate_advice(game_rate.fps(), test, even) if enabled or test else ""
if not advice:
off_since, note = None, ""
else:
off_since = t_ready if off_since is None else off_since
note = advice if t_ready - off_since >= RATE_NOTE_S else ""
if t_ready - off_since >= RATE_TOAST_S and test not in toasted: # once a session for each
toasted.add(test)
print(f"[pipeline] {advice}")
if hasattr(sink, "toast"):
sink.toast(advice, 8.0)
ov_text, ov_next = overlay_text(), t_ready + 0.25
cmd = present(out, ov_text) or early_cmd
t_shown = time.perf_counter()
st.busy_ms.append((t_shown - t0) * 1000)
if sink is not None:
st.sink_ms.append((t_shown - t_ready) * 1000)
# Track when each real frame first reaches the screen (timed: when the game time shown reaches it).
if timed:
st.real_delay_ms.extend((t_shown - f.t_arrival) * 1000 for f in reached)
reached = ()
elif action is Action.PENDING and unshown is not None:
st.real_delay_ms.append((t_shown - unshown) * 1000)
unshown = None
elif is_new:
if action is Action.CURRENT:
st.real_delay_ms.append((t_shown - tick.t_arrival) * 1000)
else:
unshown = tick.t_arrival
elif unshown is not None:
st.real_delay_ms.append((t_shown - unshown) * 1000)
unshown = None
if replay is not None and is_new: # the game's own frame, for a before & after video
replay.real_frame(tick.frame, tick.t_arrival)
if to_score is not None:
self._score(st, tick, prev_key, *to_score, gt_fn, keep_worst=score)
st.score_ms.append((time.perf_counter() - t_shown) * 1000)
if sink is not None:
if cmd in ("quit", "restart"):
st.exit = cmd
break
if cmd == "delay_test" and delay_test is None:
if remote is None or not remote.can_press():
msg = ("The delay test works with PS5 Remote Play, through the chiaki-ng that comes with this "
"SmoovPlay" if remote is None or not hasattr(remote, "press") else
"The delay test needs the chiaki-ng that comes with this SmoovPlay: open it from there")
print(f"[pipeline] {msg}")
if hasattr(sink, "toast"):
sink.toast(msg, 6.0)
else:
delay_test, test_mark, ov_next = delaytest.DelayTest(remote.press, remote.press_sent), len(
st.real_delay_ms), 0.0
print("[pipeline] delay test started")
if cmd in ("save_replay", "save_compare"): # R and B
if replay is not None:
replay.save("compare" if cmd == "save_compare" else None)
elif hasattr(sink, "toast"):
sink.toast("Instant replay isn't available here", 4.0)
if cmd == "toggle_interp": # the OpenCV window's i key (the GL window changes settings itself)
if settings is not None:
settings.override("interp", not settings.interp) # picked up at the next tick
else:
enabled = not enabled
sched = CadenceScheduler()
print(f"[pipeline] interpolation {'ON' if enabled else 'OFF'}")
st.wall_s = time.perf_counter() - t_start
return st
def _load(self, frame) -> None:
"""A frame (GPU tensor or HxWx3 uint8 array) into the interpolator's input."""
if torch.is_tensor(frame):
self.interp.load(frame)
else:
np.copyto(self._in_np, frame)
self.interp.load(self._in_pinned)
def _timed_pair(self, a, b, slot: int, in_slot: list) -> int:
"""Even timing: frames a then b (TimedFrames) in the interpolator's two slots, b the newer, putting in what
isn't there yet. Returns b's slot. (Overwrites the input: only after this tick's frame has been looked at.)"""
if in_slot[slot] == b.id and in_slot[1 - slot] == a.id:
return slot
if in_slot[slot] != a.id:
if in_slot[1 - slot] == a.id: # a is the older of the two already: b goes in after it
slot = 1 - slot
else:
slot = 1 - slot
self._load(a.frame)
self.interp.prepare(slot)
in_slot[slot] = a.id
slot = 1 - slot
self._load(b.frame)
self.interp.prepare(slot)
in_slot[slot] = b.id
return slot
def _generated(self, frame: torch.Tensor, gpu_out: bool):
"""A generated frame for the sink, waited for (a sync point, so timings are real)."""
if gpu_out:
torch.cuda.current_stream().synchronize()
return frame
self._out_pinned.copy_(frame) # blocking D2H copy
return self._out_np
def _score(self, st: Stats, tick, a: torch.Tensor, prev, prev_content, gt_fn, keep_worst: bool = True) -> None:
"""a: the previous real frame on the GPU (prev is the same frame on the CPU, kept for --save-worst).
keep_worst: copy the worst frame's images to the CPU (--save-worst); test mode skips that hitch."""
if prev_content is None or tick.content is None or tick.content - prev_content != 2:
return # only score clean 2-tick steps, where the in-between source frame exists
gt_np = gt_fn(prev_content + 1)
if gt_np is None:
return
gt = (gt_np if torch.is_tensor(gt_np) else torch.from_numpy(gt_np).to(self.interp.device)).float()
b = self.interp.in_u8
out = self.interp.out_u8
blend = ((a.float() + b.float()) * 0.5).round_()
still = ((b.float() - a.float()).abs().amax(-1, keepdim=True) <= STILL_LEVELS).float()
n_still = still.sum().clamp_min(1.0) * 3
errs = [(x - gt).pow_(2) for x in (out.float(), a.float(), blend)]
mse = torch.stack([e.mean() for e in errs] + [(errs[0] * still).sum() / n_still,
(errs[1] * still).sum() / n_still, still.mean()]).tolist()
p, p_repeat, p_blend = map(_db, mse[:3])
if mse[5] > 0:
st.psnr_still.append(_db(mse[3]))
st.psnr_still_repeat.append(_db(mse[4]))
st.still_frac.append(mse[5])
st.psnr_interp.append(p)
st.psnr_repeat.append(p_repeat)
st.psnr_blend.append(p_blend)
hud = hud_mask(a, b, gt, still)
n_hud = hud.sum().item()
if n_hud:
off = ((out.float() - gt).abs().amax(-1, keepdim=True) > HUD_OFF_LEVELS).float()
st.psnr_hud.append(_db((errs[0] * hud).sum().item() / (3 * n_hud)))
st.hud_off.append((off * hud).sum().item() / n_hud)
st.hud_frac.append(n_hud / hud.numel())
if keep_worst and (st.worst is None or p < st.worst[0]):
st.worst = (p, tick.index, _np(prev), self.interp.out_u8.cpu().numpy(), _np(gt_np), _np(tick.frame))
+107
View File
@@ -0,0 +1,107 @@
"""One-time preparation after install: RIFE weights, the TensorRT engine for a 1080p stream, and (on a new install)
settings picked for this PC by framegen.autodetect.
python -m framegen.prepare # what the SmoovPlay installer runs
Building an engine takes a minute or two, so doing it here means the first stream starts at once. Only full motion
detail gets one: that's where the "Auto" engine uses TensorRT (trt.auto_engine). Without an NVIDIA card (AMD or
Intel), RIFE is converted for DirectML instead, at full and half motion detail (framegen/dml.py, Experimental).
Progress goes to stdout as "[prepare] ..." lines (the launcher shows them). Exit code 0 = ready (PyTorch is used when
TensorRT isn't available), 2 = neither an NVIDIA card nor DirectML can run RIFE here.
"""
from __future__ import annotations
import argparse
import gc
import sys
import time
def main() -> int:
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--width", type=int, default=1920)
ap.add_argument("--height", type=int, default=1080)
ap.add_argument("--model", default="4.22.lite")
ap.add_argument("--scales", default="1.0", help="flow scales to build engines for (1.0 = full motion detail)")
ap.add_argument("--no-detect", action="store_true", help="don't pick settings for this PC (framegen.autodetect)")
a = ap.parse_args()
print("[prepare] checking the graphics card", flush=True)
import torch
if not torch.cuda.is_available():
return prepare_dml(a)
name = torch.cuda.get_device_name(0)
major, minor = torch.cuda.get_device_capability(0)
print(f"[prepare] {name} (compute {major}.{minor}), PyTorch {torch.__version__}", flush=True)
from .interpolator import ensure_weights
ensure_weights(a.model)
print(f"[prepare] RIFE {a.model} weights ready", flush=True)
from .trt import trt_available
if trt_available():
build_engines(a)
else:
print("[prepare] TensorRT isn't available, so the PyTorch engine will be used (about 12% slower)", flush=True)
if not a.no_detect:
pick_settings()
print("[prepare] done", flush=True)
return 0
def prepare_dml(a: argparse.Namespace) -> int:
"""No NVIDIA CUDA here: RIFE through DirectML (an AMD or Intel card), converted once on the CPU."""
from . import dml
why = dml.unavailable_reason()
if why:
print(f"[prepare] ERROR: no NVIDIA card PyTorch can use, and DirectML can't run here either ({why}). "
"Update the graphics driver, then repair SmoovPlay on the Help page", flush=True)
return 2
print(f"[prepare] {dml.pick_adapter()['name']}: no NVIDIA card, so RIFE runs through DirectML (Experimental)",
flush=True)
from .interpolator import ensure_weights
ensure_weights(a.model)
print(f"[prepare] RIFE {a.model} weights ready", flush=True)
scales = (1.0, 0.5) # Auto uses half motion detail at 120 fps
for i, scale in enumerate(scales, 1):
label = {1.0: "full", 0.5: "half"}[scale]
print(f"[prepare] preparing RIFE for DirectML, step {i} of {len(scales)} ({label} motion detail); "
"takes about half a minute", flush=True)
t0 = time.perf_counter()
dml.convert(a.model, scale, a.width, a.height)
print(f"[prepare] step {i} of {len(scales)} ready ({time.perf_counter() - t0:.0f} s)", flush=True)
if not a.no_detect:
pick_settings()
print("[prepare] done", flush=True)
return 0
def pick_settings() -> None:
"""A new install starts with settings picked for this PC; an existing settings file is left alone."""
print("[prepare] picking settings for this PC", flush=True)
from .autodetect import main as autodetect
try:
autodetect(["--apply", "--if-new"])
except Exception as e: # noqa: BLE001 - the defaults work everywhere; Auto-detect is on the Settings page
print(f"[prepare] couldn't pick settings ({e}); the defaults are used", flush=True)
def build_engines(a: argparse.Namespace) -> None:
import torch
from .interpolator import RifeInterpolator
scales = [float(s) for s in a.scales.split(",") if s.strip()]
for i, scale in enumerate(scales, 1):
label = {1.0: "full", 0.5: "half"}.get(scale, str(scale))
print(f"[prepare] optimising for this GPU, step {i} of {len(scales)} ({label} motion detail); "
"takes a minute or two", flush=True)
t0 = time.perf_counter()
interp = RifeInterpolator(a.width, a.height, a.model, scale, cuda_graph=False, backend="trt")
del interp
gc.collect()
torch.cuda.empty_cache()
print(f"[prepare] step {i} of {len(scales)} ready ({time.perf_counter() - t0:.0f} s)", flush=True)
if __name__ == "__main__":
sys.exit(main())
+106
View File
@@ -0,0 +1,106 @@
"""The launcher's live link to a running session (run.py --control), so its Settings page works while you play.
The launcher writes one command per line to our stdin:
set <key> <json value> change a setting and save it, as if it were picked in the video window's menu
restart apply restart-only settings now (the menu's "Restart now")
state print the current state again
look-show <look JSON> show this look (the Looks page is editing it), whatever the Look settings say
look-hide back to the Look settings' look
looks-reload the user's looks changed on disk: read them again (the list of looks is in the state)
and reads a `[settings-state] {json}` line on our stdout at the start of every session and after every change,
whoever made it (this link, the menu or a hotkey): the current values, which choices can be picked right now,
rows that are unavailable and why, and the restart-only changes still waiting. Commands are read on a thread but
applied on the window's thread (poll()), the thread the menu's keys run on, so they act exactly like menu changes.
"""
from __future__ import annotations
import json
import queue
import sys
import threading
from typing import Callable, TextIO
from .settings import BY_KEY, SPECS, Settings
PREFIX = "[settings-state] "
class Remote:
"""allowed(key, value) and disabled(key) are the window's (the same rules as its menu); restart_reasons() lists
the labels of restart-only settings changed since the session started."""
def __init__(self, settings: Settings, allowed: Callable[[str, object], bool],
disabled: Callable[[str], str | None], restart_reasons: Callable[[], list[str]],
commands: TextIO | None = None, out: TextIO | None = None,
handlers: dict[str, Callable[[str], None]] | None = None) -> None:
self.settings, self.allowed, self.disabled, self.restart_reasons = settings, allowed, disabled, restart_reasons
self._out = out
self.handlers = dict(handlers or {}) # more commands: name -> fn(the rest of the line), e.g. the looks'
self._q: queue.Queue[str] = queue.Queue()
threading.Thread(target=self._read, args=(commands or sys.stdin,), name="remote", daemon=True).start()
settings.watch(lambda key: self.publish())
def _read(self, commands: TextIO) -> None:
for line in commands: # ends when the launcher closes our stdin, or exits
line = line.strip().lstrip("") # in case a writer starts with a byte-order mark
if line:
self._q.put(line)
def poll(self) -> str | None:
"""Apply the commands that arrived since the last call (on the window's thread). Returns "restart" if one
asked for it."""
out = None
while True:
try:
line = self._q.get_nowait()
except queue.Empty:
return out
cmd, _, rest = line.partition(" ")
if cmd == "restart":
out = "restart"
elif cmd == "state":
self.publish()
elif cmd == "set":
key, _, text = rest.partition(" ")
self._set(key, text)
elif cmd in self.handlers:
try:
self.handlers[cmd](rest)
except Exception as e: # noqa: BLE001 - a bad command must never take the video down
print(f"[remote] {cmd} failed: {str(e)[:200]}")
else:
print(f"[remote] unknown command: {line[:80]}")
def _set(self, key: str, text: str) -> None:
spec = BY_KEY.get(key)
try:
value = json.loads(text)
except ValueError:
value = None
why = ("unknown setting" if spec is None else
f"{text[:40]!r} isn't one of its choices" if value not in spec.choices else
self.disabled(key) or (None if self.allowed(key, value) else "not available right now"))
if why:
print(f"[remote] can't set {key}: {why}")
self.publish() # so the launcher shows the real value again
return
value = spec.choices[spec.choices.index(value)] # the spec's own type (JSON 1 -> 1.0)
if value == getattr(self.settings, key):
self.publish() # nothing changes, so no watcher would answer
else:
self.settings.set(key, value) # saved; the watchers apply it (window, pipeline) and publish()
def state(self) -> dict:
return {
"values": self.settings.values(),
"choices": {s.key: [v for v in s.choices if self.allowed(s.key, v)] for s in SPECS},
"disabled": {s.key: why for s in SPECS if (why := self.disabled(s.key))},
"restart": list(self.restart_reasons()),
}
def publish(self) -> None:
out = self._out or sys.stdout
out.write(PREFIX + json.dumps(self.state()) + "\n") # one write, so other threads' lines don't split it
out.flush()
+1117
View File
File diff suppressed because it is too large. Load diff
+129
View File
@@ -0,0 +1,129 @@
import torch
import torch.nn as nn
import torch.nn.functional as F
from .warplayer import warp
def conv(in_planes, out_planes, kernel_size=3, stride=1, padding=1, dilation=1):
return nn.Sequential(
nn.Conv2d(
in_planes, out_planes, kernel_size=kernel_size, stride=stride, padding=padding, dilation=dilation, bias=True
),
nn.LeakyReLU(0.2, True),
)
class Head(nn.Module):
def __init__(self):
super(Head, self).__init__()
self.cnn0 = nn.Conv2d(3, 16, 3, 2, 1)
self.cnn1 = nn.Conv2d(16, 16, 3, 1, 1)
self.cnn2 = nn.Conv2d(16, 16, 3, 1, 1)
self.cnn3 = nn.ConvTranspose2d(16, 4, 4, 2, 1)
self.relu = nn.LeakyReLU(0.2, True)
def forward(self, x, feat=False):
x = x.clamp(0.0, 1.0)
x0 = self.cnn0(x)
x = self.relu(x0)
x1 = self.cnn1(x)
x = self.relu(x1)
x2 = self.cnn2(x)
x = self.relu(x2)
x3 = self.cnn3(x)
if feat:
return [x0, x1, x2, x3]
return x3
class ResConv(nn.Module):
def __init__(self, c, dilation=1):
super(ResConv, self).__init__()
self.conv = nn.Conv2d(c, c, 3, 1, dilation, dilation=dilation, groups=1)
self.beta = nn.Parameter(torch.ones((1, c, 1, 1)), requires_grad=True)
self.relu = nn.LeakyReLU(0.2, True)
def forward(self, x):
return self.relu(self.conv(x) * self.beta + x)
class IFBlock(nn.Module):
def __init__(self, in_planes, c=64):
super(IFBlock, self).__init__()
self.conv0 = nn.Sequential(
conv(in_planes, c // 2, 3, 2, 1),
conv(c // 2, c, 3, 2, 1),
)
self.convblock = nn.Sequential(
ResConv(c),
ResConv(c),
ResConv(c),
ResConv(c),
ResConv(c),
ResConv(c),
ResConv(c),
ResConv(c),
)
self.lastconv = nn.Sequential(nn.ConvTranspose2d(c, 4 * 13, 4, 2, 1), nn.PixelShuffle(2))
def forward(self, x, flow=None, scale=1):
x = F.interpolate(x, scale_factor=1.0 / scale, mode="bilinear")
if flow is not None:
flow = F.interpolate(flow, scale_factor=1.0 / scale, mode="bilinear") / scale
x = torch.cat((x, flow), 1)
feat = self.conv0(x)
feat = self.convblock(feat)
tmp = self.lastconv(feat)
tmp = F.interpolate(tmp, scale_factor=scale, mode="bilinear")
flow = tmp[:, :4] * scale
mask = tmp[:, 4:5]
feat = tmp[:, 5:]
return flow, mask, feat
class IFNet(nn.Module):
def __init__(self, scale=1, ensemble=False):
super(IFNet, self).__init__()
self.block0 = IFBlock(7 + 8, c=192)
self.block1 = IFBlock(8 + 4 + 8 + 8, c=128)
self.block2 = IFBlock(8 + 4 + 8 + 8, c=64)
self.block3 = IFBlock(8 + 4 + 8 + 8, c=32)
self.encode = Head()
self.scale_list = [8 / scale, 4 / scale, 2 / scale, 1 / scale]
if ensemble:
raise ValueError("rife: ensemble is not supported in v4.22.lite")
def forward(self, img0, img1, timestep, tenFlow_div, backwarp_tenGrid, f0, f1):
img0 = img0.clamp(0.0, 1.0)
img1 = img1.clamp(0.0, 1.0)
flow_list = []
merged = []
mask_list = []
warped_img0 = img0
warped_img1 = img1
flow = None
mask = None
block = [self.block0, self.block1, self.block2, self.block3]
for i in range(4):
if flow is None:
flow, mask, feat = block[i](
torch.cat((img0, img1, f0, f1, timestep), 1), None, scale=self.scale_list[i]
)
else:
wf0 = warp(f0, flow[:, :2], tenFlow_div, backwarp_tenGrid)
wf1 = warp(f1, flow[:, 2:4], tenFlow_div, backwarp_tenGrid)
fd, m0, feat = block[i](
torch.cat((warped_img0, warped_img1, wf0, wf1, timestep, mask, feat), 1),
flow,
scale=self.scale_list[i],
)
mask = m0
flow = flow + fd
mask_list.append(mask)
flow_list.append(flow)
warped_img0 = warp(img0, flow[:, :2], tenFlow_div, backwarp_tenGrid)
warped_img1 = warp(img1, flow[:, 2:4], tenFlow_div, backwarp_tenGrid)
merged.append((warped_img0, warped_img1))
mask = torch.sigmoid(mask)
return warped_img0 * mask + warped_img1 * (1 - mask)
+130
View File
@@ -0,0 +1,130 @@
import torch
import torch.nn as nn
import torch.nn.functional as F
from .warplayer import warp
def conv(in_planes, out_planes, kernel_size=3, stride=1, padding=1, dilation=1):
return nn.Sequential(
nn.Conv2d(
in_planes, out_planes, kernel_size=kernel_size, stride=stride, padding=padding, dilation=dilation, bias=True
),
nn.LeakyReLU(0.2, True),
)
class Head(nn.Module):
def __init__(self):
super(Head, self).__init__()
self.cnn0 = nn.Conv2d(3, 16, 3, 2, 1)
self.cnn1 = nn.Conv2d(16, 16, 3, 1, 1)
self.cnn2 = nn.Conv2d(16, 16, 3, 1, 1)
self.cnn3 = nn.ConvTranspose2d(16, 4, 4, 2, 1)
self.relu = nn.LeakyReLU(0.2, True)
def forward(self, x, feat=False):
x = x.clamp(0.0, 1.0)
x0 = self.cnn0(x)
x = self.relu(x0)
x1 = self.cnn1(x)
x = self.relu(x1)
x2 = self.cnn2(x)
x = self.relu(x2)
x3 = self.cnn3(x)
if feat:
return [x0, x1, x2, x3]
return x3
class ResConv(nn.Module):
def __init__(self, c, dilation=1):
super(ResConv, self).__init__()
self.conv = nn.Conv2d(c, c, 3, 1, dilation, dilation=dilation, groups=1)
self.beta = nn.Parameter(torch.ones((1, c, 1, 1)), requires_grad=True)
self.relu = nn.LeakyReLU(0.2, True)
def forward(self, x):
return self.relu(self.conv(x) * self.beta + x)
class IFBlock(nn.Module):
def __init__(self, in_planes, c=64):
super(IFBlock, self).__init__()
self.conv0 = nn.Sequential(
conv(in_planes, c // 2, 3, 2, 1),
conv(c // 2, c, 3, 2, 1),
)
self.convblock = nn.Sequential(
ResConv(c),
ResConv(c),
ResConv(c),
ResConv(c),
ResConv(c),
ResConv(c),
ResConv(c),
ResConv(c),
)
self.lastconv = nn.Sequential(nn.ConvTranspose2d(c, 4 * 13, 4, 2, 1), nn.PixelShuffle(2))
def forward(self, x, flow=None, scale=1):
x = F.interpolate(x, scale_factor=1.0 / scale, mode="bilinear")
if flow is not None:
flow = F.interpolate(flow, scale_factor=1.0 / scale, mode="bilinear") / scale
x = torch.cat((x, flow), 1)
feat = self.conv0(x)
feat = self.convblock(feat)
tmp = self.lastconv(feat)
tmp = F.interpolate(tmp, scale_factor=scale, mode="bilinear")
flow = tmp[:, :4] * scale
mask = tmp[:, 4:5]
feat = tmp[:, 5:]
return flow, mask, feat
class IFNet(nn.Module):
def __init__(self, scale=1, ensemble=False):
super(IFNet, self).__init__()
self.block0 = IFBlock(7 + 8, c=192)
self.block1 = IFBlock(8 + 4 + 8 + 8, c=128)
self.block2 = IFBlock(8 + 4 + 8 + 8, c=96)
self.block3 = IFBlock(8 + 4 + 8 + 8, c=64)
self.block4 = IFBlock(8 + 4 + 8 + 8, c=32)
self.encode = Head()
self.scale_list = [16 / scale, 8 / scale, 4 / scale, 2 / scale, 1 / scale]
if ensemble:
raise ValueError("rife: ensemble is not supported in v4.25")
def forward(self, img0, img1, timestep, tenFlow_div, backwarp_tenGrid, f0, f1):
img0 = img0.clamp(0.0, 1.0)
img1 = img1.clamp(0.0, 1.0)
flow_list = []
merged = []
mask_list = []
warped_img0 = img0
warped_img1 = img1
flow = None
mask = None
block = [self.block0, self.block1, self.block2, self.block3, self.block4]
for i in range(5):
if flow is None:
flow, mask, feat = block[i](
torch.cat((img0, img1, f0, f1, timestep), 1), None, scale=self.scale_list[i]
)
else:
wf0 = warp(f0, flow[:, :2], tenFlow_div, backwarp_tenGrid)
wf1 = warp(f1, flow[:, 2:4], tenFlow_div, backwarp_tenGrid)
fd, m0, feat = block[i](
torch.cat((warped_img0, warped_img1, wf0, wf1, timestep, mask, feat), 1),
flow,
scale=self.scale_list[i],
)
mask = m0
flow = flow + fd
mask_list.append(mask)
flow_list.append(flow)
warped_img0 = warp(img0, flow[:, :2], tenFlow_div, backwarp_tenGrid)
warped_img1 = warp(img1, flow[:, 2:4], tenFlow_div, backwarp_tenGrid)
merged.append((warped_img0, warped_img1))
mask = torch.sigmoid(mask)
return warped_img0 * mask + warped_img1 * (1 - mask)
+130
View File
@@ -0,0 +1,130 @@
import torch
import torch.nn as nn
import torch.nn.functional as F
from .warplayer import warp
def conv(in_planes, out_planes, kernel_size=3, stride=1, padding=1, dilation=1):
return nn.Sequential(
nn.Conv2d(
in_planes, out_planes, kernel_size=kernel_size, stride=stride, padding=padding, dilation=dilation, bias=True
),
nn.LeakyReLU(0.2, True),
)
class Head(nn.Module):
def __init__(self):
super(Head, self).__init__()
self.cnn0 = nn.Conv2d(3, 16, 3, 2, 1)
self.cnn1 = nn.Conv2d(16, 16, 3, 1, 1)
self.cnn2 = nn.Conv2d(16, 16, 3, 1, 1)
self.cnn3 = nn.ConvTranspose2d(16, 4, 4, 2, 1)
self.relu = nn.LeakyReLU(0.2, True)
def forward(self, x, feat=False):
x = x.clamp(0.0, 1.0)
x0 = self.cnn0(x)
x = self.relu(x0)
x1 = self.cnn1(x)
x = self.relu(x1)
x2 = self.cnn2(x)
x = self.relu(x2)
x3 = self.cnn3(x)
if feat:
return [x0, x1, x2, x3]
return x3
class ResConv(nn.Module):
def __init__(self, c, dilation=1):
super(ResConv, self).__init__()
self.conv = nn.Conv2d(c, c, 3, 1, dilation, dilation=dilation, groups=1)
self.beta = nn.Parameter(torch.ones((1, c, 1, 1)), requires_grad=True)
self.relu = nn.LeakyReLU(0.2, True)
def forward(self, x):
return self.relu(self.conv(x) * self.beta + x)
class IFBlock(nn.Module):
def __init__(self, in_planes, c=64):
super(IFBlock, self).__init__()
self.conv0 = nn.Sequential(
conv(in_planes, c // 2, 3, 2, 1),
conv(c // 2, c, 3, 2, 1),
)
self.convblock = nn.Sequential(
ResConv(c),
ResConv(c),
ResConv(c),
ResConv(c),
ResConv(c),
ResConv(c),
ResConv(c),
ResConv(c),
)
self.lastconv = nn.Sequential(nn.ConvTranspose2d(c, 4 * 13, 4, 2, 1), nn.PixelShuffle(2))
def forward(self, x, flow=None, scale=1):
x = F.interpolate(x, scale_factor=1.0 / scale, mode="bilinear")
if flow is not None:
flow = F.interpolate(flow, scale_factor=1.0 / scale, mode="bilinear") / scale
x = torch.cat((x, flow), 1)
feat = self.conv0(x)
feat = self.convblock(feat)
tmp = self.lastconv(feat)
tmp = F.interpolate(tmp, scale_factor=scale, mode="bilinear")
flow = tmp[:, :4] * scale
mask = tmp[:, 4:5]
feat = tmp[:, 5:]
return flow, mask, feat
class IFNet(nn.Module):
def __init__(self, scale=1, ensemble=False):
super(IFNet, self).__init__()
self.block0 = IFBlock(7 + 8, c=192)
self.block1 = IFBlock(8 + 4 + 8 + 8, c=128)
self.block2 = IFBlock(8 + 4 + 8 + 8, c=96)
self.block3 = IFBlock(8 + 4 + 8 + 8, c=64)
self.block4 = IFBlock(8 + 4 + 8 + 8, c=24)
self.encode = Head()
self.scale_list = [32 / scale, 16 / scale, 8 / scale, 4 / scale, 1 / scale]
if ensemble:
raise ValueError("rife: ensemble is not supported in v4.25.lite")
def forward(self, img0, img1, timestep, tenFlow_div, backwarp_tenGrid, f0, f1):
img0 = img0.clamp(0.0, 1.0)
img1 = img1.clamp(0.0, 1.0)
flow_list = []
merged = []
mask_list = []
warped_img0 = img0
warped_img1 = img1
flow = None
mask = None
block = [self.block0, self.block1, self.block2, self.block3, self.block4]
for i in range(5):
if flow is None:
flow, mask, feat = block[i](
torch.cat((img0, img1, f0, f1, timestep), 1), None, scale=self.scale_list[i]
)
else:
wf0 = warp(f0, flow[:, :2], tenFlow_div, backwarp_tenGrid)
wf1 = warp(f1, flow[:, 2:4], tenFlow_div, backwarp_tenGrid)
fd, m0, feat = block[i](
torch.cat((warped_img0, warped_img1, wf0, wf1, timestep, mask, feat), 1),
flow,
scale=self.scale_list[i],
)
mask = m0
flow = flow + fd
mask_list.append(mask)
flow_list.append(flow)
warped_img0 = warp(img0, flow[:, :2], tenFlow_div, backwarp_tenGrid)
warped_img1 = warp(img1, flow[:, 2:4], tenFlow_div, backwarp_tenGrid)
merged.append((warped_img0, warped_img1))
mask = torch.sigmoid(mask)
return warped_img0 * mask + warped_img1 * (1 - mask)
+130
View File
@@ -0,0 +1,130 @@
import torch
import torch.nn as nn
import torch.nn.functional as F
from .warplayer import warp
def conv(in_planes, out_planes, kernel_size=3, stride=1, padding=1, dilation=1):
return nn.Sequential(
nn.Conv2d(
in_planes, out_planes, kernel_size=kernel_size, stride=stride, padding=padding, dilation=dilation, bias=True
),
nn.LeakyReLU(0.2, True),
)
class Head(nn.Module):
def __init__(self):
super(Head, self).__init__()
self.cnn0 = nn.Conv2d(3, 16, 3, 2, 1)
self.cnn1 = nn.Conv2d(16, 16, 3, 1, 1)
self.cnn2 = nn.Conv2d(16, 16, 3, 1, 1)
self.cnn3 = nn.ConvTranspose2d(16, 4, 4, 2, 1)
self.relu = nn.LeakyReLU(0.2, True)
def forward(self, x, feat=False):
x = x.clamp(0.0, 1.0)
x0 = self.cnn0(x)
x = self.relu(x0)
x1 = self.cnn1(x)
x = self.relu(x1)
x2 = self.cnn2(x)
x = self.relu(x2)
x3 = self.cnn3(x)
if feat:
return [x0, x1, x2, x3]
return x3
class ResConv(nn.Module):
def __init__(self, c, dilation=1):
super(ResConv, self).__init__()
self.conv = nn.Conv2d(c, c, 3, 1, dilation, dilation=dilation, groups=1)
self.beta = nn.Parameter(torch.ones((1, c, 1, 1)), requires_grad=True)
self.relu = nn.LeakyReLU(0.2, True)
def forward(self, x):
return self.relu(self.conv(x) * self.beta + x)
class IFBlock(nn.Module):
def __init__(self, in_planes, c=64):
super(IFBlock, self).__init__()
self.conv0 = nn.Sequential(
conv(in_planes, c // 2, 3, 2, 1),
conv(c // 2, c, 3, 2, 1),
)
self.convblock = nn.Sequential(
ResConv(c),
ResConv(c),
ResConv(c),
ResConv(c),
ResConv(c),
ResConv(c),
ResConv(c),
ResConv(c),
)
self.lastconv = nn.Sequential(nn.ConvTranspose2d(c, 4 * 13, 4, 2, 1), nn.PixelShuffle(2))
def forward(self, x, flow=None, scale=1):
x = F.interpolate(x, scale_factor=1.0 / scale, mode="bilinear")
if flow is not None:
flow = F.interpolate(flow, scale_factor=1.0 / scale, mode="bilinear") / scale
x = torch.cat((x, flow), 1)
feat = self.conv0(x)
feat = self.convblock(feat)
tmp = self.lastconv(feat)
tmp = F.interpolate(tmp, scale_factor=scale, mode="bilinear")
flow = tmp[:, :4] * scale
mask = tmp[:, 4:5]
feat = tmp[:, 5:]
return flow, mask, feat
class IFNet(nn.Module):
def __init__(self, scale=1, ensemble=False):
super(IFNet, self).__init__()
self.block0 = IFBlock(7 + 8, c=192)
self.block1 = IFBlock(8 + 4 + 8 + 8, c=128)
self.block2 = IFBlock(8 + 4 + 8 + 8, c=96)
self.block3 = IFBlock(8 + 4 + 8 + 8, c=64)
self.block4 = IFBlock(8 + 4 + 8 + 8, c=32)
self.encode = Head()
self.scale_list = [16 / scale, 8 / scale, 4 / scale, 2 / scale, 1 / scale]
if ensemble:
raise ValueError("rife: ensemble is not supported in v4.26")
def forward(self, img0, img1, timestep, tenFlow_div, backwarp_tenGrid, f0, f1):
img0 = img0.clamp(0.0, 1.0)
img1 = img1.clamp(0.0, 1.0)
flow_list = []
merged = []
mask_list = []
warped_img0 = img0
warped_img1 = img1
flow = None
mask = None
block = [self.block0, self.block1, self.block2, self.block3, self.block4]
for i in range(5):
if flow is None:
flow, mask, feat = block[i](
torch.cat((img0, img1, f0, f1, timestep), 1), None, scale=self.scale_list[i]
)
else:
wf0 = warp(f0, flow[:, :2], tenFlow_div, backwarp_tenGrid)
wf1 = warp(f1, flow[:, 2:4], tenFlow_div, backwarp_tenGrid)
fd, m0, feat = block[i](
torch.cat((warped_img0, warped_img1, wf0, wf1, timestep, mask, feat), 1),
flow,
scale=self.scale_list[i],
)
mask = m0
flow = flow + fd
mask_list.append(mask)
flow_list.append(flow)
warped_img0 = warp(img0, flow[:, :2], tenFlow_div, backwarp_tenGrid)
warped_img1 = warp(img1, flow[:, 2:4], tenFlow_div, backwarp_tenGrid)
merged.append((warped_img0, warped_img1))
mask = torch.sigmoid(mask)
return warped_img0 * mask + warped_img1 * (1 - mask)
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2021 HolyWu
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+4
View File
@@ -0,0 +1,4 @@
"""RIFE IFNet architectures, vendored from HolyWu/vs-rife (MIT, see LICENSE).
Original model: Practical-RIFE by hzwer (MIT).
"""
+12
View File
@@ -0,0 +1,12 @@
import torch
import torch.nn.functional as F
def warp(tenInput, tenFlow, tenFlow_div, backwarp_tenGrid):
dtype = tenInput.dtype
tenInput = tenInput.to(torch.float)
tenFlow = tenFlow.to(torch.float)
tenFlow = torch.cat([tenFlow[:, 0:1] / tenFlow_div[0], tenFlow[:, 1:2] / tenFlow_div[1]], 1)
g = (backwarp_tenGrid + tenFlow).permute(0, 2, 3, 1)
return F.grid_sample(input=tenInput, grid=g, mode="bilinear", padding_mode="border", align_corners=True).to(dtype)
+204
View File
@@ -0,0 +1,204 @@
"""NVIDIA RTX Video Super Resolution (RTX VSR) on CUDA frames, through the RTX Video SDK.
The SDK is NVIDIA's (free developer download, NVIDIA RTX SDKs licence) and is not part of this repo:
unpack it and point NV_RTX_VIDEO_SDK at that folder, then build the small
ctypes wrapper with native\\rtxvsr\\build.bat. The model itself (nvngx_vsr.dll) is loaded from the SDK's
bin folder; NVIDIA's runtime in the driver may update it.
Input is an 8-bit RGBA CUDA tensor; output goes to any 8-bit RGBA CUDA array (e.g. a mapped GL texture),
on PyTorch's current stream, so it orders with the interpolation and display work without CPU waits.
"""
from __future__ import annotations
import ctypes
import os
from pathlib import Path
import torch
from .glcuda import _cudart, cudart_path
ROOT = Path(__file__).resolve().parent.parent
SDK_DIR = Path(os.environ["NV_RTX_VIDEO_SDK"]) if os.environ.get("NV_RTX_VIDEO_SDK") else None
WRAPPER = ROOT / "native" / "rtxvsr" / "build" / "rtxvsr.dll"
DATA_DIR = ROOT / "out" / "ngx" # NGX logs / caches
QUALITY = {"bicubic": 0, "low": 1, "medium": 2, "high": 3, "ultra": 4}
_MEMCPY_DEVICE_TO_DEVICE = 3
_ARRAY_SURFACE_LOAD_STORE = 0x02
_RESOURCE_TYPE_ARRAY = 0
class _ChannelDesc(ctypes.Structure):
_fields_ = [("x", ctypes.c_int), ("y", ctypes.c_int), ("z", ctypes.c_int), ("w", ctypes.c_int),
("f", ctypes.c_int)]
_RGBA8 = _ChannelDesc(8, 8, 8, 8, 1) # cudaChannelFormatKindUnsigned
def _array_resource_desc(array: ctypes.c_void_p) -> ctypes.Array:
"""cudaResourceDesc for a CUDA array: resType at offset 0, the array handle at offset 8, rest zero.
Over-allocated so newer, larger layouts of the struct read zeros."""
buf = (ctypes.c_ubyte * 256)()
ctypes.c_int.from_buffer(buf, 0).value = _RESOURCE_TYPE_ARRAY
ctypes.c_void_p.from_buffer(buf, 8).value = array.value
return buf
def _linear_texture_desc() -> ctypes.Array:
"""cudaTextureDesc: clamp addressing, linear filtering, normalised float reads, normalised coordinates
(what the SDK's own CUDA sample uses for its input)."""
buf = (ctypes.c_ubyte * 256)()
for i in range(3):
ctypes.c_int.from_buffer(buf, 4 * i).value = 1 # addressMode[i] = cudaAddressModeClamp
ctypes.c_int.from_buffer(buf, 12).value = 1 # filterMode = cudaFilterModeLinear
ctypes.c_int.from_buffer(buf, 16).value = 1 # readMode = cudaReadModeNormalizedFloat
ctypes.c_int.from_buffer(buf, 40).value = 1 # normalizedCoords
return buf
def unavailable_reason() -> str | None:
"""None if the SDK and the wrapper are in place, otherwise what is missing."""
if SDK_DIR is None:
# what people see (the installed app has no SDK); developers set NV_RTX_VIDEO_SDK to the unpacked SDK folder
return ("it's not in this version of SmoovPlay: it needs NVIDIA's RTX Video SDK, which can't be included "
"yet. AMD FSR 1 looks about the same")
if not (SDK_DIR / "bin" / "Windows" / "x64" / "rel" / "nvngx_vsr.dll").exists():
return f"RTX Video SDK not found at {SDK_DIR} (set NV_RTX_VIDEO_SDK)"
if not WRAPPER.exists():
return f"wrapper not built: run native\\rtxvsr\\build.bat ({WRAPPER} missing)"
return None
class RtxVsr:
"""Upscales src_w x src_h RGBA frames into a caller-provided RGBA CUDA array with RTX VSR.
Create it, and call it, on one thread (NGX isn't thread-safe), after PyTorch has initialised CUDA there.
The CUDA stream current at creation is the one VSR runs on.
"""
def __init__(self, src_w: int, src_h: int, quality: int = QUALITY["high"]) -> None:
why = unavailable_reason()
if why:
raise RuntimeError(why)
self.w, self.h, self.quality = src_w, src_h, int(quality)
torch.zeros(1, device="cuda") # CUDA context current on this thread
self.rt = rt = _cudart()
p, i, u, s = ctypes.c_void_p, ctypes.c_int, ctypes.c_uint, ctypes.c_size_t
rt.cudaMallocArray.argtypes = [ctypes.POINTER(p), ctypes.POINTER(_ChannelDesc), s, s, u]
rt.cudaFreeArray.argtypes = [p]
rt.cudaCreateTextureObject.argtypes = [ctypes.POINTER(ctypes.c_ulonglong), p, p, p]
rt.cudaDestroyTextureObject.argtypes = [ctypes.c_ulonglong]
rt.cudaCreateSurfaceObject.argtypes = [ctypes.POINTER(ctypes.c_ulonglong), p]
rt.cudaDestroySurfaceObject.argtypes = [ctypes.c_ulonglong]
rt.cudaMemcpy2DToArrayAsync.argtypes = [p, s, s, p, s, s, s, i, p]
rt.cudaMemcpy2DFromArrayAsync.argtypes = [p, s, p, s, s, s, s, i, p]
self.dll = dll = ctypes.CDLL(str(WRAPPER))
dll.rtxvsr_set_cudart.argtypes = [ctypes.c_wchar_p]
dll.rtxvsr_create.argtypes = [p, p, ctypes.c_wchar_p, ctypes.c_wchar_p]
dll.rtxvsr_evaluate.argtypes = [ctypes.c_ulonglong, ctypes.c_ulonglong] + [u] * 6 + [i]
self._ngx(dll.rtxvsr_set_cudart(cudart_path()), "load CUDA runtime")
drv = ctypes.CDLL("nvcuda.dll")
ctx = p()
self._cuda(drv.cuCtxGetCurrent(ctypes.byref(ctx)), "get CUDA context")
self.stream = torch.cuda.current_stream()
DATA_DIR.mkdir(parents=True, exist_ok=True)
rc = dll.rtxvsr_create(ctx, p(self.stream.cuda_stream),
str(SDK_DIR / "bin" / "Windows" / "x64" / "rel"), str(DATA_DIR))
if rc == -1:
raise RuntimeError("RTX VSR is not available on this GPU/driver (needs an RTX 20-series or newer)")
if rc == -2:
raise RuntimeError("RTX VSR needs a newer NVIDIA driver")
self._ngx(rc, "create VSR")
self.in_array = p()
self._cuda(rt.cudaMallocArray(ctypes.byref(self.in_array), ctypes.byref(_RGBA8), src_w, src_h, 0),
"allocate input array")
self.tex = ctypes.c_ulonglong()
self._res_in, self._tex_desc = _array_resource_desc(self.in_array), _linear_texture_desc()
self._cuda(rt.cudaCreateTextureObject(ctypes.byref(self.tex), self._res_in, self._tex_desc, None),
"create input texture")
self._surfaces: dict[int, ctypes.c_ulonglong] = {} # output array handle -> surface object
self._events: list[tuple[torch.cuda.Event, torch.cuda.Event]] = []
self.gpu_ms: list[float] = []
def _cuda(self, err: int, what: str) -> None:
if err:
raise RuntimeError(f"RTX VSR: {what} failed (CUDA error {err})")
def _ngx(self, rc: int, what: str) -> None:
if rc:
raise RuntimeError(f"RTX VSR: {what} failed (code {rc & 0xFFFFFFFF:#x})")
def surface(self, array: ctypes.c_void_p) -> ctypes.c_ulonglong:
"""Surface object for an output array (cached; arrays must be 8-bit RGBA with surface load/store)."""
key = array.value
if key not in self._surfaces:
surf = ctypes.c_ulonglong()
self._cuda(self.rt.cudaCreateSurfaceObject(ctypes.byref(surf), _array_resource_desc(array)),
"create output surface")
self._surfaces[key] = surf
return self._surfaces[key]
def forget(self, array: ctypes.c_void_p) -> None:
"""Drop the cached surface of an output array that is about to be freed or re-registered."""
surf = self._surfaces.pop(array.value, None)
if surf is not None:
self.rt.cudaDestroySurfaceObject(surf)
def __call__(self, rgba: torch.Tensor, out_array: ctypes.c_void_p, out_w: int, out_h: int,
quality: int | None = None) -> None:
"""Upscale rgba (h x w x 4 uint8, contiguous CUDA) into out_array's top-left out_w x out_h."""
stream = ctypes.c_void_p(self.stream.cuda_stream)
self._cuda(self.rt.cudaMemcpy2DToArrayAsync(self.in_array, 0, 0, ctypes.c_void_p(rgba.data_ptr()),
self.w * 4, self.w * 4, self.h,
_MEMCPY_DEVICE_TO_DEVICE, stream), "copy input")
start, end = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)
start.record(self.stream)
self._ngx(self.dll.rtxvsr_evaluate(self.tex, self.surface(out_array), self.w, self.h, 0, 0, out_w, out_h,
self.quality if quality is None else int(quality)), "evaluate")
end.record(self.stream)
self._events.append((start, end))
self._collect()
def _collect(self) -> None:
"""GPU time of finished evaluations (read without waiting)."""
while self._events and self._events[0][1].query():
s, e = self._events.pop(0)
self.gpu_ms.append(s.elapsed_time(e))
def new_output_array(self, w: int, h: int) -> ctypes.c_void_p:
"""A CUDA-owned RGBA8 array usable as output (for tests and offscreen use)."""
arr = ctypes.c_void_p()
self._cuda(self.rt.cudaMallocArray(ctypes.byref(arr), ctypes.byref(_RGBA8), w, h,
_ARRAY_SURFACE_LOAD_STORE), "allocate output array")
return arr
def read_array(self, arr: ctypes.c_void_p, w: int, h: int) -> torch.Tensor:
"""Copy an RGBA8 array into a new h x w x 4 CUDA tensor (stream-ordered)."""
out = torch.empty((h, w, 4), dtype=torch.uint8, device="cuda")
self._cuda(self.rt.cudaMemcpy2DFromArrayAsync(ctypes.c_void_p(out.data_ptr()), w * 4, arr, 0, 0, w * 4, h,
_MEMCPY_DEVICE_TO_DEVICE,
ctypes.c_void_p(self.stream.cuda_stream)), "read output")
return out
def free_array(self, arr: ctypes.c_void_p) -> None:
self.forget(arr)
self.rt.cudaFreeArray(arr)
def close(self) -> None:
torch.cuda.synchronize()
self._collect()
for surf in self._surfaces.values():
self.rt.cudaDestroySurfaceObject(surf)
self._surfaces.clear()
if self.tex.value:
self.rt.cudaDestroyTextureObject(self.tex)
self.tex = ctypes.c_ulonglong()
if self.in_array.value:
self.rt.cudaFreeArray(self.in_array)
self.in_array = ctypes.c_void_p()
self.dll.rtxvsr_shutdown()
Binary file not shown.

After

Width:  |  Height:  |  Size: 133 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 108 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 110 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 108 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 139 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 97 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 117 KiB

+60
View File
@@ -0,0 +1,60 @@
{
"samples": [
{
"id": "gta6-beach",
"file": "gta6-beach.jpg",
"game": "Grand Theft Auto VI",
"scene": "Beach by day",
"credit": "Grand Theft Auto VI, © Rockstar Games"
},
{
"id": "gta6-night",
"file": "gta6-night.jpg",
"game": "Grand Theft Auto VI",
"scene": "City at night",
"credit": "Grand Theft Auto VI, © Rockstar Games"
},
{
"id": "gta6-sunset",
"file": "gta6-sunset.jpg",
"game": "Grand Theft Auto VI",
"scene": "Sunset",
"credit": "Grand Theft Auto VI, © Rockstar Games"
},
{
"id": "cyberpunk-2077",
"file": "cyberpunk-2077.jpg",
"game": "Cyberpunk 2077",
"scene": "Night City by day",
"credit": "Cyberpunk 2077, © CD PROJEKT RED"
},
{
"id": "forza-horizon-5",
"file": "forza-horizon-5.jpg",
"game": "Forza Horizon 5",
"scene": "Country road",
"credit": "Forza Horizon 5, © Microsoft"
},
{
"id": "gran-turismo-7",
"file": "gran-turismo-7.jpg",
"game": "Gran Turismo 7",
"scene": "Race at sunset",
"credit": "Gran Turismo 7, © Sony Interactive Entertainment"
},
{
"id": "gta5-night",
"file": "gta5-night.jpg",
"game": "Grand Theft Auto V",
"scene": "Firelight at night",
"credit": "Grand Theft Auto V, © Rockstar Games"
},
{
"id": "skate",
"file": "skate.jpg",
"game": "skate.",
"scene": "City plaza",
"credit": "skate., © Electronic Arts"
}
]
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 156 KiB

+341
View File
@@ -0,0 +1,341 @@
"""User settings: one registry (SPECS) that the in-video menu, the launcher's Settings page, the command line and
the saved file all share.
To add a setting: add a Spec here, then read `settings.<key>` where it matters (or `settings.watch(fn)` to hear
about changes). `live=False` settings are saved at once but take effect at the next in-app restart; the menu
offers "Restart now" when any are pending.
`python -m framegen.settings` prints the registry as JSON for the launcher (specs_json()), so it never keeps a copy.
"""
from __future__ import annotations
import json
import os
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Callable
from . import looks
DEFAULT_PATH = Path(os.environ.get("APPDATA", Path.home())) / "framegen" / "settings.json"
@dataclass(frozen=True)
class Spec:
key: str
label: str
choices: tuple
default: Any
names: dict = field(default_factory=dict) # value -> text shown; missing values are shown as str(value)
live: bool = True # applies immediately; False = on the next restart
help: str = ""
saved: bool = True # False: this session only, never written to the settings file (e.g. test modes)
group: str = "" # section on the launcher's Settings page; SPECS lists each section's rows together
quick: bool = False # one of the few big choices at the top of the launcher's Settings page
applies: tuple = () # (key, values): only used, and only shown, while setting `key` is one of `values`
later: str = "" # a note at the end of the launcher's dropdown, about choices that aren't offered yet
hints: dict = field(default_factory=dict) # value -> a line under that choice in the launcher's dropdown (only
# there, so no-break spaces keep "90 Hz" together; the in-video menu's font can't draw them, so help has none)
impact: dict = field(default_factory=dict) # "picture" and/or "speed": a rough line on what it does to the picture
# and to speed or delay, shown in the launcher and the in-video menu (plain ASCII). Numbers are measured (IMPACT_PC).
def name(self, value: Any) -> str:
return self.names.get(value, str(value))
def applies_to(self, values: dict) -> bool:
"""Whether this setting is used with these values (e.g. VFG quality only while NVIDIA VFG is picked)."""
return not self.applies or values.get(self.applies[0]) in self.applies[1]
ON_OFF = {True: "On", False: "Off"}
IMPACT_PC = "an RTX 4070 Ti SUPER" # where the numbers in `impact` and the hints were measured
# scripts/looks_timing.py: GPU time of the built-in looks on a 1440p window (0.02 to 0.34 ms) and at 1080p for clips
# (0.01 to 0.19 ms), measured while chiaki-ng streamed.
LOOK_SPEED = "About 0.02 to 0.35 ms a frame of graphics card time for SmoovPlay's looks (1440p)."
LOOK_CLIPS_SPEED = "Up to about 0.2 ms more a frame of graphics card time, to draw it again at 1080p."
SPECS: tuple[Spec, ...] = (
Spec("interp", "Frame generation", (True, False), True, ON_OFF, group="Smoothness", quick=True,
hints={False: "No new frames: the stream exactly as the game sends it, with the least delay."},
impact={"picture": "Smoother motion. Small, fast details can wobble a little.",
"speed": "Adds delay: about 20 ms at 60 fps, about 40 ms at 90 or 120 fps."},
help="Draws new frames between the ones the game sends, so a 30 fps game moves like 60, 90 or 120 fps. "
"Off shows the stream exactly as it arrives. In the video window, I turns it off and on for this "
"session only, to compare."),
Spec("hz", "Output frame rate", (60, 90, 120), 60, {60: "60 fps", 90: "90 fps", 120: "120 fps"},
group="Smoothness", quick=True,
hints={60: "One new frame for each real one. Any supported graphics card, any display. Adds about 20\u00a0ms of delay.",
90: "Two new frames for each real one. Needs a 90\u00a0Hz or faster display. Adds about 40\u00a0ms of "
"delay.",
120: "Three for each real one. Needs a 120\u00a0Hz display and a fast card. Adds about 40\u00a0ms of "
"delay."},
help="How many frames you see each second. Higher is smoother, but needs a faster graphics card and a "
"display that runs at least that fast (G-Sync or FreeSync helps). Auto-detect, on SmoovPlay's "
"Settings page, picks the most this PC keeps up with."),
# framegen/cadence.py FrameTimeline. Tried on simulated 40-55 fps games (tests/test_timeline.py), not a real one yet.
Spec("even_out", "Even out 40-60 fps", (True, False), True, ON_OFF, group="Smoothness",
applies=("interp", (True,)),
help="For games that run between about 40 and 60 fps, like unlocked performance modes. Their frames "
"arrive unevenly, some staying on screen twice as long as others, so motion stutters. SmoovPlay "
"times each one and draws evenly spaced frames from them at 60, 90 or 120 fps. 30 fps and 60 fps "
"games aren't affected. Experimental: not tried with a real game yet.",
impact={"picture": "Even motion in 40-60 fps games, instead of stutter.",
"speed": "About one frame (17 ms) more delay than showing their frames as they come."}),
# RIFE: only the model SmoovPlay is tuned and tested with (setup prepares it). interpolator.MODELS has more, for
# testing with run.py --model; one becomes a choice here once it's tested in real time and setup prepares it.
# NVIDIA VFG (framegen/vfg.py): offered once the user has set it up on the launcher's Settings page. Its licence
# forbids publishing benchmark results, so nothing here compares its speed or quality with RIFE's.
Spec("model", "Interpolation model", ("4.22.lite", "vfg"), "4.22.lite",
{"4.22.lite": "RIFE 4.22 lite", "vfg": "NVIDIA VFG"}, live=False,
group="Smoothness", quick=True, later="Support for other interpolation models may come in a later version.",
hints={"4.22.lite": "Fast and tested. The default.",
"vfg": "NVIDIA's own frame generation, for RTX 40 and 50 series cards. A separate download "
"from NVIDIA."},
help="The AI model that draws the in-between frames. RIFE 4.22 lite is the one SmoovPlay is tuned and "
"tested with, fast enough for 90 and 120 fps. NVIDIA VFG (Video Frame Generation) is NVIDIA's own, "
"for RTX 40 and 50 series cards: SmoovPlay's Settings page downloads it from NVIDIA once you accept "
"NVIDIA's licence."),
Spec("vfg_quality", "VFG quality", ("low", "medium", "high"), "medium",
{"low": "Low", "medium": "Medium", "high": "High"}, live=False, group="Smoothness", applies=("model", ("vfg",)),
hints={"low": "The lightest on your graphics card.", "medium": "Balanced. The default.",
"high": "The most careful, and the heaviest."},
help="How much work NVIDIA VFG puts into each in-between frame. Higher takes more of your graphics "
"card's time, which can cost in-between frames at 90 and 120 fps. Only used with NVIDIA VFG."),
# v2 (near edges only, interpolator._steady): on eight 60 fps gameplay clips (scripts/steady_hud_eval.py) it fixes
# 96% of the visibly wobbling HUD pixels for 0.06 dB over the whole frame, at about 0.5 ms per real frame plus
# 0.15 per AI frame. On three sections of PS5 GTA V it cost 0.1 to 1.2 dB over the whole frame. Off by default:
# judged by eye (scripts/steady_hud_compare.py), RIFE alone looked as good.
Spec("steady_hud", "Steady HUD", (False, True), False, ON_OFF, group="Smoothness", applies=("model", ("4.22.lite",)),
help="Keeps the parts of the picture that don't move, like the map, health bar and subtitles, exactly as "
"the game drew them, so they don't wobble when the scene behind them moves. Results vary by game, and "
"often there's no visible difference. If a small, fast object ever flickers, turn it off.",
impact={"picture": "Steadier HUD in some games; in others, slightly worse elsewhere.",
"speed": "About 0.5 ms more work per real frame, and a little more delay."}),
Spec("engine", "AI engine", ("auto", "trt", "torch"), "auto",
{"auto": "Auto", "trt": "TensorRT", "torch": "PyTorch"}, live=False, group="Smoothness", applies=("model", ("4.22.lite",)),
hints={"auto": "The faster one for your settings. Recommended.",
"trt": "Fastest at full motion detail. Its first start on a graphics card takes a minute or two.",
"torch": "Starts at once. Fastest at half motion detail."},
help="The software that runs the AI model on your graphics card. Both draw the same frames; only the "
"speed differs. Auto uses TensorRT at full motion detail, where it's about 12% faster, and PyTorch "
"at half, where PyTorch is faster. Only used with RIFE.",
impact={"picture": "None: both draw the same frames.",
"speed": "TensorRT is about 12% faster at full motion detail, PyTorch at half."}),
Spec("motion", "Motion detail", ("auto", "full", "half"), "auto",
{"auto": "Auto", "full": "Full", "half": "Half"}, live=False, group="Smoothness", applies=("model", ("4.22.lite",)),
hints={"auto": "Full, or Half at 120 fps. Recommended.", "full": "Sharpest on fast motion. The slowest.",
"half": "About 40% faster. A little softer on fast detail."},
help="How finely RIFE tracks movement. Full follows small, fast details best, like railings or distant "
"cars; Half takes about 40% less time but softens them a little. Auto uses Half at 120 fps (or for "
"a stream above 1440p) and Full otherwise. Only used with RIFE.",
impact={"picture": "Half is a little softer on small, fast details.",
"speed": "Half takes about 40% less time per AI frame."}),
Spec("scaler", "Upscaler", ("fsr", "vsr", "bilinear"), "fsr",
{"fsr": "AMD FSR 1", "vsr": "NVIDIA RTX VSR", "bilinear": "Bilinear"}, group="Picture", quick=True,
later="Support for other upscalers may come in a later version.",
hints={"fsr": "Sharp and almost free: about 0.1\u00a0ms a frame. Recommended.",
"vsr": "NVIDIA's AI upscaler. Also smooths compression blocks, but takes about 1.6\u00a0ms a frame, "
"which can cost in-between frames at 90 and 120 fps.",
"bilinear": "Plain resizing, the softest. For comparison."},
help="Enlarges the picture from the game (usually 1080p) to fill your window or screen, so it only "
"matters when that's bigger than 1080p, like a 1440p or 4K display. Key: U.",
impact={"picture": "Only matters on a display bigger than the stream, like 1440p or 4K.",
"speed": "About 0.1 ms a frame for FSR 1. RTX VSR (not in the installed app) takes about 1.6 ms."}),
Spec("fsr_sharpness", "FSR sharpening", (0.0, 0.25, 0.5, 1.0, 2.0), 0.5,
{0.0: "Max", 0.25: "High", 0.5: "Medium", 1.0: "Low", 2.0: "Minimal"}, group="Picture", applies=("scaler", ("fsr",)),
hints={0.0: "Crispest. Can make compression blocks stand out.", 0.5: "Balanced. The default.",
2.0: "Softest. Best for a blocky, low-quality stream."},
help="How strongly FSR 1 sharpens the enlarged picture. More looks crisper; less keeps the blocky patches "
"of a weak Wi-Fi stream from standing out. Only used with AMD FSR 1.",
impact={"picture": "More is crisper; less keeps a blocky stream calmer.", "speed": "No difference."}),
Spec("vsr_quality", "RTX VSR quality", (1, 2, 3, 4), 2, {1: "Low", 2: "Medium", 3: "High", 4: "Ultra"},
group="Picture", applies=("scaler", ("vsr",)),
help="How hard RTX VSR works to clean up and sharpen the picture. Higher looks cleaner but takes longer, "
"which can cost in-between frames at 90 and 120 fps. Only used with RTX VSR.",
impact={"picture": "Higher is cleaner and sharper.",
"speed": "Per frame at 1440p: Low 1.3 ms, Medium 1.6, High 3.6, Ultra 4.9."}),
# framegen/looks.py (the looks; "Which look" lists the built-in ones, then the user's, from looks.CHOICES, which
# the looks library keeps up to date) and framegen/looks_gl.py (drawing them, after the upscaler).
Spec("look_on", "Look", (False, True), False, ON_OFF, group="Looks",
help="Effects on top of the picture, like a color grade, film grain or bloom: one of SmoovPlay's looks, or "
"your own, made on SmoovPlay's Looks page. K turns the look on and off, J goes to the next one. Saved "
"clips stay as the game looked unless Looks in clips is on.",
impact={"picture": "Changes the colors and style of the picture, the way you choose.",
"speed": LOOK_SPEED}),
Spec("look", "Which look", looks.CHOICES, looks.DEFAULT_LOOK, looks.NAMES, group="Looks",
applies=("look_on", (True,)),
help="The look to use: SmoovPlay's own, then the ones you made or pasted on the Looks page. J goes to the "
"next one, Shift+J back."),
Spec("fullscreen", "Fullscreen", (False, True), False, ON_OFF, group="Display",
help="Fills the whole screen. It also skips the Windows desktop compositor, which removes about 12 ms "
"of delay, so it's the best way to play. Key: F.",
impact={"speed": "About 12 ms less delay than a window, and G-Sync or FreeSync works."}),
Spec("vsync", "VSync", (False, True), False, ON_OFF, group="Display",
help="Off: the lowest delay, but fast camera turns can show a tear line across the picture. On: no "
"tearing, with a little more delay. With a G-Sync or FreeSync display, On gives you both: no tearing "
"and low delay.",
impact={"picture": "On: no tear lines.", "speed": "On can add up to one refresh of delay: 8 ms at 120 Hz, 17 at 60."}),
# framegen/dxgi_present.py. Standard stays the default until Low delay has been measured on more PCs.
Spec("present", "Window presentation", ("gl", "dxgi"), "gl", {"gl": "Standard", "dxgi": "Low delay (Experimental)"},
live=False, group="Display", applies=("fullscreen", (False,)),
hints={"gl": "OpenGL's own way. Tested. In a window, Windows adds a copy of each frame.",
"dxgi": "Hands frames over the way games do, so a window is about as quick as fullscreen and G-Sync "
"works. Experimental."},
help="How the video reaches the screen. In a window, Standard goes through the Windows compositor, which "
"adds about 12 ms and keeps G-Sync and FreeSync from working (fullscreen doesn't). Low delay hands "
"frames over the way games do, for playing in a window; fullscreen always uses Standard, which is "
"already as quick there. Experimental; applies the next time you press Play.",
impact={"speed": "Low delay should save the 12 ms a window adds. Still being measured."}),
Spec("overlay", "Stats overlay", (True, False), True, ON_OFF, group="Display",
help="Shows the game's frame rate, how many frames a second are on screen, how long each AI frame takes "
"and the upscaler in a corner of the video. At 90 and 120 fps it also shows \"extra frames\": below "
"about 95%, your PC is falling behind, so try a lower frame rate. If the game isn't running at 30 fps, "
"a second line says so. Key: S."),
# framegen/replay.py. Memory in the hints: replay.memory_mb() for 1080p at 90 fps (tests/test_replay.py checks).
Spec("replay", "Instant replay", (0, 30, 60, 120, 300), 0,
{0: "Off", 30: "Last 30 seconds", 60: "Last minute", 120: "Last 2 minutes", 300: "Last 5 minutes"},
group="Instant replay",
hints={0: "Nothing is kept.", 30: "Keeps about 160 MB in memory (1080p at 90 fps).",
60: "Keeps about 310 MB in memory (1080p at 90 fps).",
120: "Keeps about 610 MB in memory (1080p at 90 fps).",
300: "Keeps about 1.5 GB in memory (1080p at 90 fps)."},
help="Keeps the last stretch of what you played, so you can save it after something good happens: press R "
"in the video window, or Ctrl+Alt+R from anywhere. Clips go to your Videos folder, in SmoovPlay, as "
"MP4 at the frame rate you see, with the game's own sound (PS5 Remote Play and capture cards; window "
"capture has none). B saves a before & after video instead.",
impact={"picture": "None.",
"speed": "About 0.3 ms of graphics card time a frame; the encoding is on its video encoder, not "
"the AI's part."}),
Spec("replay_save", "Saved clip", ("smoovplay", "compare", "both"), "smoovplay",
{"smoovplay": "SmoovPlay video", "compare": "Before & after", "both": "Both"},
group="Instant replay", applies=("replay", (30, 60, 120, 300)),
hints={"smoovplay": "What you saw, with the game's sound. Saved in a second or two.",
"compare": "The game's own frames next to SmoovPlay's, in one video. Made in the background, in "
"about as long as the clip.",
"both": "Both videos."},
help="What R saves. SmoovPlay video is what you saw, at 60, 90 or 120 fps. Before & after puts the game's "
"own frames next to SmoovPlay's in one video, to show the difference; it's made in the background "
"and takes about as long as the clip. B always saves a before & after video."),
Spec("replay_layout", "Before & after layout", ("split", "side"), "split",
{"split": "Split screen", "side": "Side by side"}, group="Instant replay",
applies=("replay", (30, 60, 120, 300)),
hints={"split": "One picture: the left half as the game sent it, the right half from SmoovPlay.",
"side": "Both whole pictures next to each other, in a video twice as wide."},
help="How a before & after video is laid out. Split screen is one picture: the left half as the game sent "
"it, the right half from SmoovPlay, with a line between. Side by side shows both whole pictures, in "
"a video twice as wide."),
Spec("look_clips", "Looks in clips", (False, True), False, ON_OFF, group="Instant replay",
applies=("replay", (30, 60, 120, 300)),
help="Puts the look you're using into saved clips too. Off keeps clips as the game looked, whatever look "
"you play with. In a before & after video, only the SmoovPlay side gets the look.",
impact={"picture": "Clips look like what you see, look included.", "speed": LOOK_CLIPS_SPEED}),
Spec("minimize_chiaki", "Minimise chiaki-ng", (True, False), True, ON_OFF, group="PS5 Remote Play",
help="Minimises chiaki-ng's own window while SmoovPlay's video is open, so your graphics card doesn't "
"spend time drawing a copy nobody sees. chiaki-ng keeps streaming, playing sound and reading your "
"controller, and its window comes back when you stop.",
impact={"speed": "Saves the time your graphics card spends drawing chiaki-ng's window."}),
Spec("audio_sync", "Sound in sync", (True, False), True, ON_OFF, group="PS5 Remote Play",
help="The sound (chiaki-ng's, or a capture card's, which SmoovPlay plays) would come as it arrives, while "
"the picture spends a little longer in SmoovPlay. On holds the sound back by that time (about 30 ms "
"at 90 fps, measured as you play), so they line up. Press L in the video window for a delay test: it "
"times the whole trip, from a button press to SmoovPlay's screen (PS5 Remote Play).",
impact={"speed": "None: only the sound waits, by as long as the picture does."}),
Spec("simulate_30", "Simulate a 30 fps game", (False, True), False, ON_OFF, saved=False, group="PS5 Remote Play",
help="For testing with a 60 fps game: every other frame is left out, so it plays like a 30 fps game. At "
"60 and 120 fps each AI frame is also scored against the real frame it replaced. This session "
"only."),
)
BY_KEY = {s.key: s for s in SPECS}
class Settings:
"""Current values, saved to JSON on every change. Values given on the command line (`override`) apply to
this run only and aren't saved unless changed in the menu."""
def __init__(self, values: dict | None = None, path: Path | None = None) -> None:
self.path = path
self._listeners: list[Callable[[str], None]] = []
self._v = {s.key: s.default for s in SPECS}
self._saved = dict(self._v) # what the file holds (or would)
for k, v in (values or {}).items():
if k in BY_KEY and BY_KEY[k].saved and v in BY_KEY[k].choices:
self._v[k] = self._saved[k] = v
@classmethod
def load(cls, path: Path = DEFAULT_PATH) -> "Settings":
try:
values = json.loads(Path(path).read_text(encoding="utf-8"))
except (OSError, ValueError):
values = {}
return cls(values if isinstance(values, dict) else {}, path)
def __getattr__(self, key: str) -> Any:
try:
return self.__dict__["_v"][key]
except KeyError:
raise AttributeError(key) from None
def values(self) -> dict:
return dict(self._v)
def watch(self, fn: Callable[[str], None]) -> Callable[[], None]:
"""fn(key) is called after any value changes. Returns a function that stops it."""
self._listeners.append(fn)
return lambda: self._listeners.remove(fn) if fn in self._listeners else None
def override(self, key: str, value: Any) -> None:
"""This run only (command-line flags, the I key)."""
self._put(key, value, save=False)
def set(self, key: str, value: Any) -> None:
self._put(key, value, save=True)
def _put(self, key: str, value: Any, save: bool) -> None:
if value not in BY_KEY[key].choices:
raise ValueError(f"{key}: {value!r} is not one of {BY_KEY[key].choices}")
changed = self._v[key] != value
self._v[key] = value
if save and BY_KEY[key].saved:
self._saved[key] = value
self.save()
if changed:
for fn in list(self._listeners):
fn(key)
def step(self, key: str, delta: int, allowed=None) -> Any:
"""Move to the next/previous choice (wrapping), skipping values `allowed(key, value)` rejects."""
choices = BY_KEY[key].choices
i = choices.index(self._v[key])
for _ in range(len(choices)):
i = (i + delta) % len(choices)
if allowed is None or allowed(key, choices[i]):
self.set(key, choices[i])
break
return self._v[key]
def save(self) -> None:
if self.path is None:
return
try:
self.path.parent.mkdir(parents=True, exist_ok=True)
self.path.write_text(json.dumps(self._saved, indent=2), encoding="utf-8")
except OSError as e:
print(f"[settings] couldn't save {self.path}: {e}")
def specs_json(specs: tuple[Spec, ...] = SPECS) -> dict:
"""The registry for the launcher's Settings page: every setting with its choices in display order, and where the
saved file is. Values are JSON types; the launcher sends a choice back exactly as given here."""
return {
"path": str(DEFAULT_PATH),
"impact_pc": IMPACT_PC,
"specs": [{"key": s.key, "label": s.label, "group": s.group, "help": s.help, "default": s.default,
"live": s.live, "saved": s.saved, "later": s.later, "quick": s.quick, "impact": s.impact,
"applies": {"key": s.applies[0], "values": list(s.applies[1])} if s.applies else None,
"choices": [{"value": v, "name": s.name(v), "hint": s.hints.get(v, "")} for v in s.choices]}
for s in specs],
}
if __name__ == "__main__":
print(json.dumps(specs_json()))
+19
View File
@@ -0,0 +1,19 @@
Copyright (c) 2021 Advanced Micro Devices, Inc. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+261
View File
@@ -0,0 +1,261 @@
"""Where frames come from: what each kind of source is like, and the pieces every source shares.
A source (framegen.io, framegen.chiaki_tap) yields Ticks: one frame for each refresh of the console's output,
new content or a repeat. It describes itself with `info` (a SourceInfo), so the pipeline and run.py read what it
is like instead of checking which class it is.
Shared pieces:
TestMode "Simulate a 30 fps game": a 60 fps game played as if it were 30 fps, with the frames it leaves
out kept to score the generated ones against. Works with any 60 Hz source.
Clock60 puts a source whose frames come at uneven times (window capture, a Moonlight stream) onto a
steady 60 Hz beat, the way a console's HDMI output delivers them.
make_detector the repeat detector that suits a source.
`python -m framegen.sources --json` (or `run.py --list-sources --json`) lists the sources for the launcher. It
imports nothing heavy, so it answers in well under a second.
"""
from __future__ import annotations
import json
import sys
import threading
import time
from dataclasses import asdict, dataclass, replace
# Sources that work but aren't offered in the launcher: video files are for testing. SMOOVPLAY_SOURCES=all shows
# them anyway.
HIDDEN = {"file"}
# Offered as Experimental: built from the best information available, without the hardware to test every setup. The
# launcher marks them and offers Send feedback (a GitHub issue form).
EXPERIMENTAL = {"capture", "window"}
@dataclass(frozen=True)
class SourceInfo:
kind: str # "chiaki" (PS5 Remote Play), "capture" (capture card), "window" (another app's window, framegen/window.py),
# "file" (a recording as-is), "sim" (simulated PS5)
name: str # shown to people
live: bool = True # frames come in real time; False: a file, read as fast as the pipeline takes them
rate: str = "fixed" # "fixed": a frame every refresh, repeats included (Remote Play, HDMI). "variable": frames
# come when the sender chooses (window capture, Moonlight), so Clock60 puts them on a 60 Hz beat
hz: float = 60.0 # refreshes per second, for a fixed rate
repeats: str = "pixels" # how a repeat is told from new content: "hint" (the source says, e.g. Remote Play from
# each frame's compressed size; the picture check is only a fallback) or "pixels" (pictures compared)
test_mode: bool = True # "Simulate a 30 fps game" works with it (False: built in, as for "sim")
full_range: bool = True # frames come as full-range RGB (0-255); False: limited range (16-235), to be expanded
audio: str = "" # who plays the sound, in words ("" = nobody yet)
controls: str = "" # where the controller goes, in words
KINDS = {
"chiaki": SourceInfo("chiaki", "PS5 Remote Play", repeats="hint", audio="chiaki-ng plays the sound",
controls="Your controller connects to this PC; chiaki-ng sends it to the PS5"),
"capture": SourceInfo("capture", "Capture card", audio="SmoovPlay plays the card's sound, in step with the picture",
controls="Your controller connects to the console as usual"),
"window": SourceInfo("window", "App window", rate="variable", test_mode=False,
audio="The app plays its own sound, a little ahead of the picture",
controls="Your controller connects to the app as usual"),
"file": SourceInfo("file", "Video file", live=False),
"sim": SourceInfo("sim", "Video file as a PS5 30 fps game", live=False, test_mode=False),
}
def source_info(kind: str, **changes) -> SourceInfo:
"""A kind's description, with what only the running source knows (its frame rate, ...) filled in."""
return replace(KINDS[kind], **changes)
# ----------------------------------------------------------------------------- test mode
class TestMode:
""""Simulate a 30 fps game", for any 60 Hz source: frames 0, 2, 4... of a 60 fps game arrive as new content,
and each odd frame is replaced by the one before it, so the stream looks like a 30 fps game (A A B B). The
frames left out are kept, so the pipeline can score each generated frame against the real one it replaced:
gt(content) is the frame left out at `content`.
It's a filter, tick -> tick or None (drop it). A source that queues frames on a thread of its own (Remote Play,
capture) applies it before the queue, so a frame dropped from a full queue never shifts which frames are kept;
a file applies it as it reads. Switching it on or off (set_on) takes effect from the next frame.
It needs a game running at a steady 60 fps. Each tick carries extra["game_new"], the source's own word on whether
the game drew a new frame there (Remote Play's size check; None for a source that doesn't say), so the pipeline
can tell when the game isn't at 60, and gt() won't offer a frame the game itself repeated.
"""
__test__ = False # not a pytest test class, despite the name
KEEP = 8 # left-out frames kept for scoring; the pipeline asks within a frame or two
def __init__(self, on: bool = False) -> None:
self.on = on
self._n = 0 # frames seen while on
self._last = None # the last kept frame
self._truth: dict = {}
self._game: dict = {} # the source's repeat hint for each recent frame: True new, False repeat, None unknown
def set_on(self, on: bool) -> None:
if on and not self.on:
self._last = None # don't repeat a frame from before it was switched on
self._truth.clear()
self._game.clear()
self.on = on
def gt(self, content: int):
"""The real frame left out at `content`, or None. None too when the game repeated a frame there or at the
kept frames either side (by the source's hint): below 60 fps the left-out frame isn't the real one halfway
between them, so there's nothing fair to compare with."""
if any(self._game.get(i) is False for i in (content - 1, content, content + 1)):
return None
return self._truth.get(content)
def __call__(self, tick):
if not self.on:
return tick
i = self._n
self._n += 1
self._game[i] = tick.extra["game_new"] = tick.new_hint
self._game.pop(i - self.KEEP, None)
if i % 2 == 0: # kept: arrives as new content
self._last = tick.frame
tick.content, tick.truth_new, tick.new_hint = i, True, True
elif self._last is not None: # left out: the kept frame again, the real one kept as truth
self._truth[i] = tick.frame
self._truth.pop(i - self.KEEP, None)
tick.frame = self._last
tick.content, tick.truth_new, tick.new_hint = i - 1, False, False
else: # switched on at an odd frame: nothing to repeat yet
return None
return tick
def wrap(self, ticks):
from .io import Waiting
for tick in ticks:
if isinstance(tick, Waiting): # (no frame yet: passed on, for the loop to keep the window answering)
yield tick
elif (tick := self(tick)) is not None:
yield tick
# ----------------------------------------------------------------------------- 60 Hz clock
class Clock60:
"""Puts a variable-rate source on a steady beat (60 Hz by default), the way a console's HDMI output delivers
frames: on each beat the newest frame is handed on, or the previous one again if nothing came since. The
source is read on a thread of its own, so a late frame never holds up the beat.
Each beat's tick: a fresh frame keeps the source's own repeat hint (usually None: the pipeline compares
pictures); a beat with no fresh frame is a repeat for certain (new_hint False). t_arrival stays when the frame
really arrived (so latency includes the wait for the beat); t_ready is when the beat handed it on, the first
moment the pipeline could have it. Frames overtaken by a newer one before their beat are counted in
`overtaken`.
"""
def __init__(self, source, hz: float = 60.0, clock=time.perf_counter, sleep=time.sleep) -> None:
self.source, self.period = source, 1.0 / hz
self._clock, self._sleep = clock, sleep
self._cond = threading.Condition()
self._latest = None
self._serial = 0 # frames received so far
self._done = False
self.overtaken = 0
def __getattr__(self, name: str): # w, h, info, close... come from the source
return getattr(self.source, name)
def _reader(self) -> None:
from .io import Waiting
try:
for tick in self.source:
if isinstance(tick, Waiting): # the beat goes on by itself: it repeats the last frame
continue
with self._cond:
if self._latest is not None and self._serial > self._taken:
self.overtaken += 1
self._latest, self._serial = tick, self._serial + 1
self._cond.notify_all()
finally:
with self._cond:
self._done = True
self._cond.notify_all()
def __iter__(self):
from .io import Tick
self._taken = 0 # the serial of the frame handed on last
threading.Thread(target=self._reader, name="clock60", daemon=True).start()
with self._cond: # the first beat is the first frame
self._cond.wait_for(lambda: self._latest is not None or self._done)
beat, index = self._clock(), 0
while True:
with self._cond:
latest, serial, done = self._latest, self._serial, self._done
fresh = serial != self._taken
self._taken = serial
if latest is None or (done and not fresh):
return
handed = self._clock() # the beat, or a moment after it if the sleep overshot
yield Tick(latest.frame, latest.t_arrival if fresh else handed, index, latest.content,
latest.truth_new if fresh else None,
new_hint=latest.new_hint if fresh else False, damaged=latest.damaged and fresh,
t_ready=handed, t_source=latest.t_source, extra=dict(latest.extra) if fresh else {})
index += 1
beat += self.period
now = self._clock()
if beat < now - self.period: # fell a whole beat behind (the pipeline stalled): restart the beat from now
beat = now
elif beat > now:
self._sleep(beat - now)
# ----------------------------------------------------------------------------- repeat detector
def make_detector(info: SourceInfo, threshold: float = 2.0):
"""The repeat detector for a source. Remote Play says which frames are repeats, so its detector is only the
fallback; files compare each frame with the previous one; a capture card compares with the last *new* frame,
so a slow change that stays under the threshold from frame to frame still adds up and is caught; an app's window
learns where the line between its repeats and new frames is (an app decodes its own stream, so its repeats are
never quite identical)."""
from .cadence import DuplicateDetector
return DuplicateDetector(threshold, reference="new" if info.kind == "capture" else "previous",
learn=info.kind == "window")
# ----------------------------------------------------------------------------- the list for the launcher
GUIDES = {
"chiaki": "Connect your PS5 with chiaki-ng (SmoovPlay sets it up), then press Play.",
"capture": "Connect the console's HDMI to the capture card and the card to this PC. On a PS5, turn off HDCP "
"while you use it (Settings > System > HDMI). Set the console to 1080p, 60 Hz, HDR off.",
"window": "Open the app you stream with (PS Remote Play, the Xbox app, Moonlight, or a browser) and start the "
"game, pick its window, then press Play. Keep the app's window on screen: SmoovPlay shows the smooth "
"picture on top of it, and the app keeps the controller.",
"file": "For testing: a video file played as a source.",
}
def describe(kind: str) -> dict:
"""One source for the launcher: its info, whether it's offered, and a line on setting it up."""
return {**asdict(KINDS[kind]), "hidden": kind in HIDDEN, "experimental": kind in EXPERIMENTAL,
"guide": GUIDES[kind]}
def list_sources(show_all: bool = False) -> list[dict]:
out = []
for kind in ("chiaki", "capture", "window", "file"):
d = describe(kind)
if show_all:
d["hidden"] = False
out.append(d)
return out
def main(argv: list[str] | None = None) -> int:
import os
argv = sys.argv[1:] if argv is None else argv
show_all = os.environ.get("SMOOVPLAY_SOURCES", "").lower() == "all" or "--all" in argv
sources = list_sources(show_all)
if "--json" in argv:
print(json.dumps({"sources": sources}))
else:
for s in sources:
print(f"{s['kind']:8s} {s['name']}{' (hidden)' if s['hidden'] else ''}\n {s['guide']}")
return 0
if __name__ == "__main__":
sys.exit(main())
+298
View File
@@ -0,0 +1,298 @@
"""Remote Play stream check: how well the size-based repeat check read a real game, in plain words.
The size check (chiaki_tap.SizeRepeatDetector) decides new frame or repeat from compressed size alone. This
records what it decided next to what the picture check measured, and reports, for one session:
- the game's frame rate, second by second, and the stream's;
- the rhythm: a 30 fps game on a 60 Hz stream alternates new / repeat (N r N r ...), so a break is either the
game itself (a hitch, a frame that came early) or a misread. Each break is tied to what was around it:
frames missing, packet loss, a keyframe (big whatever it shows), a size close to the threshold;
- the picture's view: in stretches where new frames and repeats clearly differ on screen, a "repeat" that
changed like a new frame, or a "new" frame that changed no more than a repeat, looks misread;
- how far apart the two sizes are, and when frames arrived.
One ~5 minute session of a native 30 fps game is enough to see whether the size check can be trusted.
Nothing here touches the GPU or the AI engine: it only keeps what the stream and the picture check already
measured, so it's safe in Copy diagnostics (no NVIDIA VFG numbers).
"""
from __future__ import annotations
from array import array
import numpy as np
TICK_MS = 1000 / 60
MAX_TICKS = 30 * 60 * 60 # the first 30 minutes; a check needs ~5
AMBIGUOUS = (0.25, 0.6) # size / typical new frame, around SizeRepeatDetector's 0.4: where size can't really tell
STRETCH = 60 # frames calibrated together for the picture's view (1 s)
def _mmss(seconds: float) -> str:
return f"{int(seconds) // 60}:{int(seconds) % 60:02d}"
def _n(mask) -> int:
return int(np.count_nonzero(mask))
def _pct(n: int, d: int) -> str:
return f"{100 * n / d:.1f}%" if d else "n/a"
class StreamCheck:
"""Collects one row per Remote Play frame the pipeline saw; report() turns them into plain-language lines."""
def __init__(self, max_ticks: int = MAX_TICKS) -> None:
self.max_ticks = max_ticks
self.t = array("d") # arrival, s
self.seq = array("q") # the tap's frame number: a jump means frames never reached the pipeline
self.size = array("q") # compressed bytes
self.ref = array("d") # the typical new frame size the check compared with (nan: keyframe, warm-up)
self.decision = array("b") # size check: 1 new, 0 repeat, -1 undecided (the picture check decided)
self.key = array("b") # keyframe, or a frame so big it was treated as one
self.lost = array("b") # frames were lost before it, or it's the PS5's recovery frame
self.mean_diff = array("d") # the picture check: average change from the frame before (0-255)
self.max_diff = array("d") # ... and the biggest change anywhere in the picture
self.simulated = 0 # frames played with "Simulate a 30 fps game" on: not part of the check
self.extra = 0 # frames past max_ticks
def add(self, t: float, seq: int, size: int, ref: float | None, decision: bool | None, key: bool,
lost: bool, mean_diff: float, max_diff: float) -> None:
if len(self.t) >= self.max_ticks:
self.extra += 1
return
self.t.append(t)
self.seq.append(seq)
self.size.append(size)
self.ref.append(float("nan") if ref is None else ref)
self.decision.append(-1 if decision is None else int(decision))
self.key.append(int(key))
self.lost.append(int(lost))
self.mean_diff.append(mean_diff if np.isfinite(mean_diff) else float("nan"))
self.max_diff.append(max_diff if np.isfinite(max_diff) else float("nan"))
def add_tick(self, tick, diff) -> None:
"""From the pipeline's on_tick: a Tick from ChiakiSource and the picture check's FrameDiff."""
if tick.truth_new is not None: # test mode replaced this frame
self.simulated += 1
return
e = tick.extra
self.add(tick.t_arrival, e.get("seq", 0), e.get("size", 0), e.get("size_ref"), e.get("size_new"),
bool(e.get("keyframe") or e.get("big")), bool(e.get("frames_lost") or e.get("recovered")),
float(diff.mean_diff), float(diff.max_diff))
# ------------------------------------------------------------------------------------------------- report
def report(self) -> list[str]:
n = len(self.t)
if n < 2:
return []
t = np.frombuffer(self.t, dtype=np.float64)
seq = np.frombuffer(self.seq, dtype=np.int64)
size = np.frombuffer(self.size, dtype=np.int64)
ref = np.frombuffer(self.ref, dtype=np.float64)
dec = np.frombuffer(self.decision, dtype=np.int8)
key = np.frombuffer(self.key, dtype=np.int8).astype(bool)
lost = np.frombuffer(self.lost, dtype=np.int8).astype(bool)
md = np.frombuffer(self.mean_diff, dtype=np.float64)
mx = np.frombuffer(self.max_diff, dtype=np.float64)
span = float(t[-1] - t[0])
new, rep = dec == 1, dec == 0
lines = [f"Stream check (Remote Play), {_mmss(span)} checked"
+ (" (the first 30 minutes; later frames weren't recorded)" if self.extra else "")]
if self.simulated:
lines[0] += f"; {_mmss(self.simulated * TICK_MS / 1000)} with \"Simulate a 30 fps game\" on left out"
# Frame rates, per whole second of play.
edges = t[0] + np.arange(int(span) + 1)
per_s = np.histogram(t[new], edges)[0] if len(edges) > 1 else np.zeros(0, dtype=np.int64)
pkt_s = np.histogram(t, edges)[0] if len(edges) > 1 else np.zeros(0, dtype=np.int64)
step = np.diff(seq)
missing = int((step[step > 1] - 1).sum())
stream_fps = float(np.median(pkt_s)) if len(per_s) else float("nan")
game_fps = float(np.median(per_s)) if len(per_s) else float("nan")
steady = int(np.count_nonzero((per_s >= 28) & (per_s <= 32)))
if len(per_s):
lines.append(f"Stream: {stream_fps:.0f} frames a second reached SmoovPlay"
+ (f"; {missing} never did (packet loss, or SmoovPlay fell behind)" if missing else ""))
lines.append(f"Game frame rate, by the size check: {game_fps:.0f} fps (median); "
f"{_pct(steady, len(per_s))} of seconds at 28-32 fps")
bands = [("under 25", per_s < 25), ("25-27", (per_s >= 25) & (per_s < 28)),
("28-32", (per_s >= 28) & (per_s <= 32)), ("33-45", (per_s > 32) & (per_s <= 45)),
("46-55", (per_s > 45) & (per_s <= 55)), ("56+", per_s > 55)]
lines.append(" seconds at: " + ", ".join(f"{name} fps {int(np.count_nonzero(m))}"
for name, m in bands if np.any(m)))
thirty = 25 <= game_fps <= 35
# The picture's view, calibrated per stretch: only where new frames and repeats clearly differ on screen.
miss, extra_new, checked = _picture_flags(dec, md, mx, key)
looks = miss | extra_new
# The rhythm: consecutive frames, both decided, nothing missing between them.
ok = (step == 1) & (dec[1:] >= 0) & (dec[:-1] >= 0)
a, b = dec[:-1], dec[1:]
pairs = int(np.count_nonzero(ok))
alt = int(np.count_nonzero(ok & (a != b)))
breaks = np.flatnonzero(ok & (a == b)) + 1 # the second frame of each break
nn, rr = int(np.count_nonzero(dec[breaks] == 1)), int(np.count_nonzero(dec[breaks] == 0))
lines.append(f"Rhythm (a 30 fps game alternates new / repeat): {_pct(alt, pairs)} of {pairs} frame pairs; "
f"{nn} new-new, {rr} repeat-repeat" + ("" if thirty else " (this game isn't at 30 fps, so "
"breaks are expected)"))
holds = _runs(rep, seq)
if holds:
longest = max(holds) + 1
n_long = sum(r >= 2 for r in holds)
lines.append(f" held frames: {n_long} times a frame stayed up 3 or more ticks (50 ms+), longest "
f"{longest} ticks ({longest * TICK_MS:.0f} ms)" if n_long else
" held frames: none longer than 2 ticks")
ratio = size / ref # nan where there was no reference
near = (ratio >= AMBIGUOUS[0]) & (ratio <= AMBIGUOUS[1])
if thirty and len(breaks):
causes = {"frames missing": 0, "packet loss": 0, "keyframe": 0, "size close to the threshold": 0,
"picture says misread": 0, "the game itself (the picture agrees)": 0, "can't tell": 0}
for i in breaks:
lo, hi = max(0, i - 2), min(n, i + 3)
if np.any(step[max(0, i - 3):min(n - 1, i + 2)] != 1):
causes["frames missing"] += 1
elif lost[lo:hi].any():
causes["packet loss"] += 1
elif key[i] or key[i - 1]:
causes["keyframe"] += 1
elif looks[i] or looks[i - 1]:
causes["picture says misread"] += 1
elif near[i] or near[i - 1]:
causes["size close to the threshold"] += 1
elif checked[i] and checked[i - 1]:
causes["the game itself (the picture agrees)"] += 1
else:
causes["can't tell"] += 1 # a near-still stretch: the picture can't separate them either
lines.append(" breaks: " + ", ".join(f"{k} {v}" for k, v in causes.items() if v))
n_checked = int(np.count_nonzero(checked))
n_looks = int(np.count_nonzero(looks))
if n_checked >= 600:
lines.append(f"Picture check, in stretches where the picture moves ({_pct(n_checked, n)} of frames): "
f"{n_looks} look misread ({_pct(n_looks, n_checked)}): {int(np.count_nonzero(miss))} "
f"\"repeats\" changed like a new frame, {int(np.count_nonzero(extra_new))} \"new\" frames "
"changed no more than a repeat")
else:
lines.append(f"Picture check: too few stretches where new frames and repeats clearly differ on screen "
f"({n_checked} frames; a still scene, or few repeats), so it can't confirm the size check")
# Does the PS5 send true copies? Then the picture alone could tell repeats apart, big or small, keyframes
# and still stretches included: for tuning the size check against this.
same = np.isfinite(mx) & (mx <= 0.01)
n_rep = int(np.count_nonzero(rep & ~key))
if n_rep:
lines.append(f" pixel-identical to the frame before: {_pct(_n(same & rep & ~key), n_rep)} of \"repeats\", "
f"{_pct(_n(same & new & ~key), _n(new & ~key))} of \"new\" frames")
if np.count_nonzero(same & rep & ~key) >= 0.9 * n_rep:
agree = int(np.count_nonzero((new & ~same) | (rep & same)))
lines.append(f" the picture alone (pixel-identical = repeat) agrees with the size check on "
f"{_pct(agree, int(np.count_nonzero(dec >= 0)))} of frames, and would also decide the "
f"{int(np.count_nonzero(dec < 0))} the size check left undecided")
# How far apart new frames and repeats are by size.
sized = ~key & np.isfinite(ratio)
rn, rp = ratio[sized & new], ratio[sized & rep]
if len(rn) and len(rp):
lines.append(f"Sizes: new frames {np.median(size[sized & new]) / 1000:.1f} KB, repeats "
f"{np.median(size[sized & rep]) / 1000:.1f} KB (medians). Against a typical new frame, the "
f"smallest 5% of new frames were {np.percentile(rn, 5):.2f}x and the biggest 5% of repeats "
f"{np.percentile(rp, 95):.2f}x (threshold 0.40x); {_pct(_n(near & sized), _n(sized))} "
f"of frames were close to it ({AMBIGUOUS[0]:.2f}-{AMBIGUOUS[1]:.2f}x)")
key_runs = _runs(key, seq)
lines.append(f"Undecided by size (the picture check decided): {int(np.count_nonzero(dec < 0))} frames; "
f"keyframes (or frames far bigger than recent ones) {int(np.count_nonzero(key))} "
f"({_pct(_n(key), n)})" + (f", longest run {max(key_runs)} in a row" if key_runs else ""))
# When frames arrived.
dt = np.diff(t)[step == 1] * 1000
if len(dt):
lines.append(f"Arrival: a frame every {np.median(dt):.1f} ms (median), 95% within "
f"{np.percentile(dt, 95):.1f} ms, slowest {dt.max():.0f} ms; "
f"{_pct(int(np.count_nonzero(dt > 25)), len(dt))} over 25 ms")
if np.count_nonzero(new) > 2:
dn = np.diff(t[new]) * 1000
lines.append(f" new frames: every {np.median(dn):.1f} ms (median), 95% within "
f"{np.percentile(dn, 95):.1f} ms")
lines.append(_verdict(span, stream_fps, game_fps, steady, len(per_s), alt, pairs,
int(np.count_nonzero(looks)), n_checked, float(np.count_nonzero(dec < 0)) / n))
return lines
def _picture_flags(dec, md, mx, key, stretch: int = STRETCH):
"""(miss, extra_new, checked) per frame, judged by the picture within each stretch of frames.
Calibrated on the picture alone, never on the size check's own answers (which may be what's wrong): in a
30 fps game half the frames are new, so the 75th percentile of the picture's change is a typical new frame
and the 25th a typical repeat (the encoder sharpening a still picture, or nothing). A stretch counts only if
those clearly differ: a typical new frame changes the picture by at least 0.5 on average, and 5 times more
than a typical repeat. Then a "repeat" that changed at least half as much as a typical new frame is a likely
miss, and a "new" frame that changed, on average and at its biggest, no more than twice a typical repeat is
a likely extra.
"""
n = len(dec)
miss, extra, checked = np.zeros(n, bool), np.zeros(n, bool), np.zeros(n, bool)
fin = np.isfinite(md) & np.isfinite(mx) # keyframes' pictures count for calibrating, not for judging
for s in range(0, n, stretch):
sl = slice(s, s + stretch)
d, m, x, f = dec[sl], md[sl], mx[sl], fin[sl]
if np.count_nonzero(f) < stretch // 3:
continue
lo, typ_new = (float(v) for v in np.percentile(m[f], [25, 75]))
typ_rep = max(lo, 0.02)
if typ_new < 0.5 or typ_new < 5 * typ_rep:
continue
quiet = f & (m <= 2 * typ_rep)
rep_max = max(float(np.median(x[quiet])) if np.any(quiet) else 0.0, 1.0)
o = f & ~key[sl] & (d >= 0)
checked[sl] = o
miss[sl] = o & (d == 0) & (m >= 0.5 * typ_new)
extra[sl] = o & (d == 1) & (m <= 2 * typ_rep) & (x <= 2 * rep_max)
return miss, extra, checked
def _runs(mask: np.ndarray, seq: np.ndarray) -> list[int]:
"""Lengths of runs of True in mask, split where frames are missing."""
out, run = [], 0
for i, m in enumerate(mask):
if i and seq[i] != seq[i - 1] + 1 and run:
out.append(run)
run = 0
if m:
run += 1
elif run:
out.append(run)
run = 0
if run:
out.append(run)
return out
def _verdict(span, stream_fps, game_fps, steady, seconds, alt, pairs, looks, checked, undecided) -> str:
"""undecided: the share of frames the size check left to the picture check."""
if span < 60 or not seconds:
return "Verdict: too short to judge; play for at least a minute (about 5 is best)"
if stream_fps < 45:
return ("Verdict: the stream itself is 30 fps, so there are no repeats to check. Set chiaki-ng's frame "
"rate to 60 and play again")
if checked < 600:
reads = "the picture couldn't confirm it (too little movement)"
else:
reads = f"{_pct(looks, checked)} of moving frames look misread" if looks else "no frame looks misread"
if game_fps >= 55:
return (f"Verdict: this game ran at about 60 fps here, so there were few repeats to fill; {reads}. For this "
"check, play a game (or a mode) that runs at 30 fps")
if steady / seconds < 0.8:
return (f"Verdict: this game's frame rate varied (about {game_fps:.0f} fps), so its rhythm can't be "
f"checked; {reads}")
rate = looks / checked if checked >= 600 else 0.0
if undecided > 0.05:
return (f"Verdict: the size check left {100 * undecided:.0f}% of this 30 fps game's frames undecided (the "
f"picture check stood in; {reads}). Please send this report")
if rate <= 0.005 and alt / max(pairs, 1) >= 0.97:
return f"Verdict: the size check read this 30 fps game correctly ({_pct(alt, pairs)} on rhythm; {reads})"
if rate <= 0.02:
return (f"Verdict: the size check mostly read this 30 fps game correctly ({_pct(alt, pairs)} on rhythm; "
f"{reads}). Please send this report")
return f"Verdict: the size check misread this 30 fps game too often ({reads}). Please send this report"
+7
View File
@@ -0,0 +1,7 @@
"""Cross-thread GPU coordination."""
import threading
# Held while the interpolator captures CUDA graphs. GPU work another thread puts on CUDA's legacy default stream
# during a capture (the Remote Play reader's NVDEC decode and colour conversion) breaks the capture and can hang
# both threads, so that work takes the lock too. Captures happen only at startup, so it's uncontended afterwards.
CAPTURE_LOCK = threading.Lock()
+129
View File
@@ -0,0 +1,129 @@
"""TensorRT backend for the RIFE flow network (FastIFNet): same math, faster kernels.
The PyTorch fp16 forward is exported to ONNX and built as a *strongly typed* engine, so TensorRT keeps
PyTorch's precision exactly (convolutions fp16, warps and blending fp32) instead of choosing its own.
Engines are built once per model / resolution / flow scale / GPU / TensorRT version (a minute or two)
and cached in models/trt/. They run on PyTorch's current CUDA stream, so they work inside the
interpolator's CUDA graphs.
TensorRT may be installed outside the venv (it's ~3 GB); if so, set FRAMEGEN_TRT_PATH to that folder.
"""
from __future__ import annotations
import hashlib
import os
import sys
import time
from pathlib import Path
import torch
from .fastrife import FastIFNet
TRT_PATH = os.environ.get("FRAMEGEN_TRT_PATH", "")
ENGINE_DIR = Path(__file__).resolve().parent.parent / "models" / "trt"
def import_trt():
if TRT_PATH and os.path.isdir(TRT_PATH) and TRT_PATH not in sys.path:
sys.path.append(TRT_PATH) # appended, so it never shadows the venv's own packages
import tensorrt as trt
return trt
_available: bool | None = None
def trt_available() -> bool:
"""Whether TensorRT can be imported (cached)."""
global _available
if _available is None:
try:
import_trt()
_available = True
except Exception: # noqa: BLE001 - missing or broken install: use PyTorch
_available = False
return _available
def auto_engine(scale: float) -> str:
"""What the "Auto" engine setting runs at a flow scale: TensorRT at full motion detail, where it's faster (7.9 vs
9.0 ms per 1080p in-between frame on an RTX 4070 Ti SUPER), PyTorch at half, where PyTorch is (5.5 vs 6.8 ms)."""
return "trt" if scale >= 1.0 and trt_available() else "torch"
class _Export(torch.nn.Module):
"""FastIFNet as an nn.Module with the timestep as an input, for torch.onnx.export."""
def __init__(self, fast: FastIFNet) -> None:
super().__init__()
self.fast = fast
self.blocks = torch.nn.ModuleList(fast.blocks) # registers the weights
def forward(self, src0: torch.Tensor, src1: torch.Tensor, t: torch.Tensor) -> torch.Tensor:
return self.fast(src0, src1, t)
class TrtIFNet:
"""Drop-in for FastIFNet.__call__ on fixed-size [img | features] inputs."""
def __init__(self, fast: FastIFNet, src_shape: tuple, tag: str, device: torch.device, build: bool = True) -> None:
"""build=False: raise FileNotFoundError instead of building an engine that isn't cached yet."""
trt = import_trt()
self.trt = trt
self.logger = trt.Logger(trt.Logger.WARNING)
gpu = torch.cuda.get_device_name(device)
key = hashlib.sha1(f"{tag}|{tuple(src_shape)}|{gpu}|{trt.__version__}".encode()).hexdigest()[:12]
ENGINE_DIR.mkdir(parents=True, exist_ok=True)
engine_path = ENGINE_DIR / f"ifnet_{tag}_{src_shape[2]}x{src_shape[3]}_{key}.engine"
if not engine_path.exists():
if not build:
raise FileNotFoundError(f"no TensorRT engine built yet: {engine_path.name}")
self._build(fast, src_shape, engine_path, device)
runtime = trt.Runtime(self.logger)
self.engine = runtime.deserialize_cuda_engine(engine_path.read_bytes())
if self.engine is None:
raise RuntimeError(f"could not load TensorRT engine {engine_path}")
self.ctx = self.engine.create_execution_context()
_, _, h, w = src_shape
self.t = torch.full((1, 1, 1, 1), 0.5, dtype=torch.float32, device=device)
self.out = torch.empty((1, 3, h, w), dtype=torch.float32, device=device)
self.ctx.set_tensor_address("t", self.t.data_ptr())
self.ctx.set_tensor_address("mid", self.out.data_ptr())
def _build(self, fast: FastIFNet, src_shape: tuple, engine_path: Path, device: torch.device) -> None:
trt = self.trt
onnx_path = engine_path.with_suffix(".onnx")
print(f"[trt] building {engine_path.name} (once, about a minute)...")
t0 = time.perf_counter()
src = torch.rand(src_shape, device=device)
t = torch.full((1, 1, 1, 1), 0.5, device=device)
with torch.no_grad():
torch.onnx.export(_Export(fast), (src, src.clone(), t), str(onnx_path), dynamo=False, opset_version=17,
input_names=["src0", "src1", "t"], output_names=["mid"])
builder = trt.Builder(self.logger)
network = builder.create_network(1 << int(trt.NetworkDefinitionCreationFlag.STRONGLY_TYPED))
parser = trt.OnnxParser(network, self.logger)
if not parser.parse_from_file(str(onnx_path)):
errs = "; ".join(str(parser.get_error(i)) for i in range(parser.num_errors))
raise RuntimeError(f"TensorRT could not parse the ONNX export: {errs}")
config = builder.create_builder_config()
config.set_memory_pool_limit(trt.MemoryPoolType.WORKSPACE, 2 << 30)
config.builder_optimization_level = 4
blob = builder.build_serialized_network(network, config)
if blob is None:
raise RuntimeError("TensorRT engine build failed")
engine_path.write_bytes(bytes(blob))
onnx_path.unlink(missing_ok=True)
print(f"[trt] built in {time.perf_counter() - t0:.0f} s")
def set_timestep(self, t: float) -> None:
self.t.fill_(t)
@torch.no_grad()
def __call__(self, src0: torch.Tensor, src1: torch.Tensor) -> torch.Tensor:
self.ctx.set_tensor_address("src0", src0.data_ptr())
self.ctx.set_tensor_address("src1", src1.data_ptr())
if not self.ctx.execute_async_v3(torch.cuda.current_stream().cuda_stream):
raise RuntimeError("TensorRT execution failed")
return self.out
+125
View File
@@ -0,0 +1,125 @@
"""NVIDIA Video Frame Generation (VFG) as an interpolation engine, in place of RIFE.
VFG is a filter in NVIDIA's Video Effects SDK, used here through NVIDIA's official `nvidia-vfx` Python package.
It is NOT part of this repo or of SmoovPlay's downloads: each user installs it from NVIDIA after accepting
NVIDIA's licence, through the launcher's Settings page or framegen/vfg_setup.py, into its own folder
(FRAMEGEN_VFX_PATH). It runs on RTX 40 and 50 series cards only (driver 570.65 or newer).
NVIDIA's licence for it forbids publishing its benchmark results without NVIDIA's written permission, and
using its output to train or tune other models. So: VFG timings and scores stay on the user's own PC (the
overlay, Auto-detect), never in the README, release notes, diagnostics or anything we publish.
The interface matches RifeInterpolator, so the pipeline and scheduler don't change: load() a frame into
`in_u8`, prepare() it into a slot, interpolate(newest_slot, t) into `out_u8`. Our own cut detector decides
when not to interpolate, so VFG's automatic shot-change detection is off.
"""
from __future__ import annotations
import torch
from .vfg_setup import MIN_COMPUTE, add_to_path, installed
QUALITY = {"low": 0, "medium": 1, "high": 2}
NOT_SET_UP = "NVIDIA VFG isn't set up on this PC. SmoovPlay's Settings page downloads it from NVIDIA."
def import_vfx():
add_to_path()
import nvvfx
return nvvfx
_available: str | None = None
def vfg_unavailable() -> str:
"""Why VFG can't run on this PC ("" if it can). Cached. Quick: it finds the package without importing it, so
a broken install shows up when a session builds VfgInterpolator (run.py then falls back to RIFE)."""
global _available
if _available is None:
_available = _check()
return _available
def _check() -> str:
try:
if not torch.cuda.is_available():
return "No NVIDIA graphics card was found."
if torch.cuda.get_device_capability(0) < MIN_COMPUTE:
return "NVIDIA VFG needs an RTX 40 or 50 series card."
return "" if installed() else NOT_SET_UP
except Exception as e: # noqa: BLE001 - a broken install must never stop RIFE from running
return f"NVIDIA VFG couldn't be checked: {e}"
class VfgInterpolator:
"""VFG behind RifeInterpolator's interface. encoding: "rgb10a2" (packed 10-bit, what NVIDIA recommends: no
float round trip, and the whole run stays on our stream) or "rgb8" (float32 planes, the simpler path)."""
def __init__(self, width: int, height: int, quality: str = "medium", device: str = "cuda",
encoding: str = "rgb10a2") -> None:
nvvfx = import_vfx()
self.w, self.h = width, height
self.device = torch.device(device)
self.quality, self.encoding = quality, encoding
self.version, self.scale, self.trt = f"VFG {quality}", 1.0, None # what run.py's label reads
self.private = True # the pipeline keeps timings and scores out of logs and reports (NVIDIA's licence)
enc = nvvfx.ImageEncoding.RGB10A2 if encoding == "rgb10a2" else nvvfx.ImageEncoding.RGB8
self.fx = nvvfx.VideoFrameGeneration(mode=QUALITY[quality], automatic_shot_change_detection_enabled=False,
device=self.device.index or 0, image_encoding=enc)
self.fx.input_width, self.fx.input_height = width, height
self.fx.load()
self.in_u8 = torch.zeros((height, width, 3), dtype=torch.uint8, device=self.device)
self.out_u8 = torch.zeros((height, width, 3), dtype=torch.uint8, device=self.device)
if encoding == "rgb10a2":
self.slots = [torch.zeros((height, width), dtype=torch.int32, device=self.device) for _ in range(2)]
else:
self.slots = [torch.zeros((3, height, width), dtype=torch.float32, device=self.device) for _ in range(2)]
# ---- the RifeInterpolator interface --------------------------------------------------------------------
def load(self, frame_u8: torch.Tensor) -> None:
"""Copy an HxWx3 uint8 BGR frame (GPU or pinned CPU) into the static input."""
self.in_u8.copy_(frame_u8, non_blocking=True)
@torch.no_grad()
def prepare(self, slot: int) -> None:
"""Convert `in_u8` into slot `slot` (0/1) in VFG's input format."""
if self.encoding == "rgb10a2":
self.slots[slot].copy_(pack_rgb10a2(self.in_u8))
else:
self.slots[slot].copy_(self.in_u8.permute(2, 0, 1).flip(0).float().div_(255.0))
@torch.no_grad()
def interpolate(self, newest_slot: int, t: float = 0.5) -> torch.Tensor:
"""Frame at fraction t from slot (1-newest_slot) to newest_slot -> `out_u8` (overwritten each call)."""
prev, cur = self.slots[1 - newest_slot], self.slots[newest_slot]
stream = torch.cuda.current_stream(self.device).cuda_stream
if self.encoding == "rgb10a2":
prev, cur = prev.view(torch.uint32), cur.view(torch.uint32)
out = self.fx.run_at_timestep(prev, cur, t, stream_ptr=stream)
img = torch.from_dlpack(out.image) # SDK-owned memory: converted (copied) into out_u8 before the next run
if self.encoding == "rgb10a2":
self.out_u8.copy_(unpack_rgb10a2(img.view(torch.int32)))
else:
self.out_u8.copy_(img.clamp(0.0, 1.0).mul(255.0).round_().to(torch.uint8).flip(0).permute(1, 2, 0))
return self.out_u8
def close(self) -> None:
close = getattr(self.fx, "close", None)
if close is not None:
close()
# ---- packed 10-bit RGB: R in bits 0-9, G 10-19, B 20-29, alpha 30-31 (left 0, so it fits a signed int32) ------
def pack_rgb10a2(bgr: torch.Tensor) -> torch.Tensor:
"""HxWx3 uint8 BGR -> HxW int32 holding packed RGB10A2 (8-bit values widened exactly: v10 = v8 * 1023 / 255)."""
v = bgr.to(torch.int32)
v = (v << 2) | (v >> 6) # 8 -> 10 bits, 255 -> 1023
return v[..., 2] | (v[..., 1] << 10) | (v[..., 0] << 20)
def unpack_rgb10a2(packed: torch.Tensor) -> torch.Tensor:
"""HxW int32 (packed RGB10A2) -> HxWx3 uint8 BGR, rounded."""
r, g, b = packed & 1023, (packed >> 10) & 1023, (packed >> 20) & 1023
bgr = torch.stack([b, g, r], -1).float().mul_(255.0 / 1023.0).round_()
return bgr.to(torch.uint8)
+217
View File
@@ -0,0 +1,217 @@
"""Setting up NVIDIA VFG (see framegen/vfg.py): NVIDIA's `nvidia-vfx` package, downloaded from NVIDIA's own package
index into a folder of its own, only after the user accepts NVIDIA's licence. Nothing here imports torch, so the
launcher can ask quickly.
python -m framegen.vfg_setup --status --json # installed? supported on this graphics card?
python -m framegen.vfg_setup --install --accept-nvidia-licence [--target DIR] [--proxy URL]
python -m framegen.vfg_setup --remove [--target DIR] # only a folder this script installed
The folder is FRAMEGEN_VFX_PATH (the launcher sets it to <install>\\runtime\\vfx) unless --target is given. The
package is pinned by version and by the SHA-256 of NVIDIA's Windows wheel, so pip installs exactly that file or
nothing. A marker file in the folder records the version and when the licence was accepted; --remove deletes only
folders that have it.
"""
from __future__ import annotations
import argparse
import importlib.machinery
import importlib.util
import json
import os
import shutil
import subprocess
import sys
import tempfile
import time
from pathlib import Path
PACKAGE, VERSION = "nvidia-vfx", "0.2.0.0"
# nvidia_vfx-0.2.0.0-cp312-abi3-win_amd64.whl on https://pypi.nvidia.com (pypi.org only has an empty placeholder)
WHEEL_SHA256 = "cebaa12411f7e22b39293205c5c4d07b8073d14ca1e0e7727ee4375207a36445"
INDEX = "https://pypi.nvidia.com"
SIZE_MB = 540 # installed size, for the launcher's "about 540 MB"
MARKER = "smoovplay-vfg.json"
MIN_COMPUTE = (8, 9) # Ada (RTX 40) and newer. NVIDIA doesn't support VFG on RTX 20/30; nothing here works around it.
LICENCES = {
"NVIDIA Software License Agreement":
"https://www.nvidia.com/en-us/agreements/enterprise-software/nvidia-software-license-agreement/",
"Product-Specific Terms for NVIDIA AI Products":
"https://www.nvidia.com/en-us/agreements/enterprise-software/product-specific-terms-for-ai-products/",
"NVIDIA Open Model License":
"https://www.nvidia.com/en-us/agreements/enterprise-software/nvidia-open-model-license/",
}
def vfx_path() -> str:
return os.environ.get("FRAMEGEN_VFX_PATH", "")
def add_to_path(folder: str | None = None) -> None:
"""Make the VFG folder importable. Appended, so it never shadows the venv's or runtime's own packages."""
folder = vfx_path() if folder is None else folder
if folder and os.path.isdir(folder) and folder not in sys.path:
sys.path.append(folder)
def installed(folder: str | None = None) -> bool:
"""Whether `nvvfx` is in `folder`, or (no folder given) in FRAMEGEN_VFX_PATH or anywhere Python looks. Doesn't
import it, so it's quick and loads no NVIDIA libraries."""
try:
if folder is not None:
return bool(folder) and importlib.machinery.PathFinder.find_spec("nvvfx", [folder]) is not None
add_to_path()
return importlib.util.find_spec("nvvfx") is not None
except (ImportError, ValueError):
return False
def gpu() -> tuple[str, tuple[int, int] | None]:
"""(name, compute capability) of the first NVIDIA graphics card, from nvidia-smi; ("", None) if none."""
try:
out = subprocess.run(["nvidia-smi", "--query-gpu=name,compute_cap", "--format=csv,noheader"],
capture_output=True, text=True, timeout=10,
creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0)).stdout
name, _, cap = out.splitlines()[0].rpartition(",")
major, _, minor = cap.strip().partition(".")
return name.strip(), (int(major), int(minor or 0))
except (OSError, subprocess.SubprocessError, IndexError, ValueError):
return "", None
def supported_reason(cap: tuple[int, int] | None) -> str:
"""Why VFG can't run on a card with this compute capability ("" if it can)."""
if cap is None:
return "No NVIDIA graphics card was found."
if cap < MIN_COMPUTE:
return "NVIDIA VFG needs an RTX 40 or 50 series card."
return ""
def read_marker(folder: str) -> dict | None:
try:
return json.loads((Path(folder) / MARKER).read_text(encoding="utf-8"))
except (OSError, ValueError):
return None
def status(folder: str) -> dict:
name, cap = gpu()
marker = read_marker(folder) if folder else None
return {
"path": folder,
"installed": bool(folder) and installed(folder),
"ours": marker is not None, # installed by --install, so --remove may delete it
"version": (marker or {}).get("version", ""),
"gpu": name,
"unsupported": supported_reason(cap),
"size_mb": SIZE_MB,
"licences": [{"name": k, "url": v} for k, v in LICENCES.items()],
}
def install(folder: str, proxy: str = "") -> int:
"""Download and install the pinned package into `folder` (replacing an earlier install of ours). pip's output
goes to stdout as it comes (--progress-bar raw: "Progress <bytes> of <total>" lines for the launcher)."""
name, cap = gpu()
why = supported_reason(cap)
if why:
print(f"[vfg] {why}" + (f" This PC has: {name}." if name else ""))
return 2
target = Path(folder)
if target.exists() and read_marker(folder) is None and any(target.iterdir()):
print(f"[vfg] {folder} already has files that SmoovPlay didn't put there; not touching it")
return 2
staging = target.with_name(target.name + ".partial")
sentinel = staging / ".smoovplay-staging"
if staging.exists():
if not sentinel.exists():
print(f"[vfg] {staging} is in the way and isn't SmoovPlay's; move it and try again")
return 2
shutil.rmtree(staging) # a stopped earlier attempt
staging.mkdir(parents=True)
sentinel.write_text("SmoovPlay is installing NVIDIA VFG here; deleted when it's done\n", encoding="utf-8")
with tempfile.TemporaryDirectory(dir=target.parent) as tmp:
req = Path(tmp) / "vfg-requirements.txt"
req.write_text(f"{PACKAGE}=={VERSION} --hash=sha256:{WHEEL_SHA256}\n", encoding="utf-8")
cmd = [sys.executable, "-m", "pip", "install", "--target", str(staging), "--only-binary", ":all:",
"--no-deps", "--require-hashes", "--index-url", INDEX, "--no-cache-dir", "--progress-bar", "raw",
"--disable-pip-version-check", "--no-warn-script-location", "-r", str(req)]
if proxy:
cmd += ["--proxy", proxy]
print(f"[vfg] downloading {PACKAGE} {VERSION} from {INDEX} (about {SIZE_MB} MB)", flush=True)
rc = subprocess.run(cmd).returncode
if rc != 0:
shutil.rmtree(staging, ignore_errors=True)
print(f"[vfg] pip failed (exit code {rc})")
return rc
# Check it loads, in another process: a loaded DLL would keep the folder from being renamed or removed.
check = subprocess.run([sys.executable, "-c", f"import sys; sys.path.append({str(staging)!r}); import nvvfx"],
capture_output=True, text=True)
if check.returncode != 0:
shutil.rmtree(staging, ignore_errors=True)
print(f"[vfg] installed, but it doesn't load: {(check.stderr or check.stdout).strip()[-400:]}")
return 3
sentinel.unlink()
(staging / MARKER).write_text(json.dumps({
"package": PACKAGE, "version": VERSION, "sha256": WHEEL_SHA256, "index": INDEX,
"licence_accepted": time.strftime("%Y-%m-%d %H:%M:%S"), "licences": LICENCES,
}, indent=2), encoding="utf-8")
if target.exists():
shutil.rmtree(target)
staging.rename(target)
print(f"[vfg] installed into {folder}")
return 0
def remove(folder: str) -> int:
target = Path(folder)
if not target.exists():
print("[vfg] not installed")
return 0
if read_marker(folder) is None:
print(f"[vfg] {folder} wasn't installed by SmoovPlay; not removing it")
return 2
try:
shutil.rmtree(target)
except OSError as e: # e.g. a running session still has its DLLs loaded
print(f"[vfg] couldn't remove it ({e}). Close SmoovPlay's video window and try again.")
return 1
print(f"[vfg] removed {folder}")
return 0
def main(argv: list[str] | None = None) -> int:
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
act = ap.add_mutually_exclusive_group(required=True)
act.add_argument("--status", action="store_true")
act.add_argument("--install", action="store_true")
act.add_argument("--remove", action="store_true")
ap.add_argument("--accept-nvidia-licence", action="store_true",
help="required by --install: you have read and accept NVIDIA's licence terms (--status lists them)")
ap.add_argument("--target", default=None, help="folder (default: FRAMEGEN_VFX_PATH)")
ap.add_argument("--proxy", default="", help="passed to pip")
ap.add_argument("--json", action="store_true", help="--status as JSON")
a = ap.parse_args(argv)
folder = a.target or vfx_path()
if a.status:
st = status(folder)
if a.json:
print(json.dumps(st))
else:
print(f"folder: {folder or '(FRAMEGEN_VFX_PATH not set)'}\ninstalled: {st['installed']}"
f"{' (by SmoovPlay, ' + st['version'] + ')' if st['ours'] else ''}\n"
f"graphics card: {st['gpu'] or 'none found'}{' - ' + st['unsupported'] if st['unsupported'] else ''}")
return 0
if not folder:
ap.error("give --target or set FRAMEGEN_VFX_PATH")
if a.remove:
return remove(folder)
if not a.accept_nvidia_licence:
print("[vfg] NVIDIA VFG is NVIDIA's software, under NVIDIA's licence. Read it, then add "
"--accept-nvidia-licence if you accept it:\n" + "\n".join(f" {k}: {v}" for k, v in LICENCES.items()))
return 2
return install(folder, a.proxy)
if __name__ == "__main__":
sys.exit(main())
+503
View File
@@ -0,0 +1,503 @@
"""Window capture (Experimental): frames from another app's window, such as Sony's PS Remote Play app, the Xbox app,
Moonlight's window, or a browser playing a cloud game.
python -m framegen.window --list [--json] # the app windows it could capture (for the launcher's picker)
python run.py --source window --window "exe:RemotePlay.exe" --display
How it works:
- The window is picked by its program ("exe:RemotePlay.exe"), a preset ("ps-remote-play", "xbox", "moonlight"), its
handle ("hwnd:123", as the launcher's picker passes it) or part of its title. Its picture area (the client area,
without the title bar) is found on screen.
- Desktop Duplication copies that part of the monitor when it changes. With CUDA it's copied on the graphics card
and stays there (framegen/dda.py), as Remote Play's frames do; otherwise, or if that can't start (the monitor on
another graphics card, Windows HDR mode), FFmpeg's ddagrab brings it to the CPU as BGR (through PyAV: no extra
package).
- SmoovPlay's own window sits on top as a click-through overlay that never takes the focus (the app keeps it:
some apps stop updating without it), and is left out of the capture (io.py, exclude_from_capture: Windows'
WDA_EXCLUDEFROMCAPTURE, Windows 10 2004 or newer), so the capture sees the app underneath.
- Frames come when the app draws, not on a fixed beat: run.py puts them on a 60 Hz beat (sources.Clock60). An app
decodes its own stream, so its repeats are never quite identical: they're told from new frames by a rule learned
from the last few frames (cadence.DuplicateDetector(learn=True)).
- Frames are scaled to 1920x1080 (SIZE), whatever the window's size: the size Remote Play's stream has, so the
TensorRT engines setup builds are used (a new size would build one, about a minute) and the settings fit. The
overlay shows the result at the window's own size.
- The window is looked at twice a second. If it moved or changed size, capture restarts there. If it's minimised,
the last frame stays up until it's back.
Limits (Experimental, not tried with a real app yet):
- The app's window must stay on screen, not minimised, and not covered by other windows (SmoovPlay's aside).
- The monitor it's on has to be one the main graphics adapter drives (DXGI adapter 0, where ddagrab looks).
- The app plays its own sound, which comes a little ahead of the picture.
- Without the GPU path, frames go through the CPU (about 2-4 ms more at 1080p).
"""
from __future__ import annotations
import argparse
import ctypes
import json
import os
import sys
import time
from ctypes import wintypes as wt
from dataclasses import asdict, dataclass
# Apps people stream games through, by program name: preset -> (exe, what it's called). Browsers come with no preset
# (a cloud game is one tab among many): pick their window from the list.
PRESETS = {
"ps-remote-play": ("remoteplay.exe", "PS Remote Play"),
"xbox": ("xboxpcapp.exe", "Xbox app"),
"moonlight": ("moonlight.exe", "Moonlight"),
}
KNOWN = {exe: name for exe, name in PRESETS.values()} | {
"chrome.exe": "Chrome", "msedge.exe": "Edge", "firefox.exe": "Firefox", "geforcenow.exe": "GeForce NOW"}
MIN_SIZE = (320, 180) # smaller windows aren't game streams
SKIP_EXE = {"explorer.exe", "textinputhost.exe", "applicationframehost.exe", "shellexperiencehost.exe",
"searchhost.exe", "startmenuexperiencehost.exe", "systemsettings.exe", "smoovplay.exe"}
CHECK_S = 0.5 # how often the window's place is looked at
SIZE = (1920, 1080) # what frames are scaled to, for the pipeline
@dataclass(frozen=True)
class Rect:
x: int
y: int
w: int
h: int
def clamp(self, other: "Rect") -> "Rect":
"""The part of this rectangle inside `other` (zero size if none)."""
x0, y0 = max(self.x, other.x), max(self.y, other.y)
x1, y1 = min(self.x + self.w, other.x + other.w), min(self.y + self.h, other.y + other.h)
return Rect(x0, y0, max(0, x1 - x0), max(0, y1 - y0))
@dataclass(frozen=True)
class AppWindow:
hwnd: int
title: str
exe: str # the program's file name, lower case
w: int # client area size, in pixels
h: int
@property
def app(self) -> str:
"""What the app is called, for people: a known app's name, else its program name."""
return KNOWN.get(self.exe, self.exe.removesuffix(".exe"))
# ----------------------------------------------------------------------------- Windows calls
class _RECT(ctypes.Structure):
_fields_ = [("left", wt.LONG), ("top", wt.LONG), ("right", wt.LONG), ("bottom", wt.LONG)]
class _MONITORINFOEX(ctypes.Structure):
_fields_ = [("cbSize", wt.DWORD), ("rcMonitor", _RECT), ("rcWork", _RECT), ("dwFlags", wt.DWORD),
("szDevice", wt.WCHAR * 32)]
class _DEVMODE(ctypes.Structure): # DEVMODEW, display fields
_fields_ = [("dmDeviceName", wt.WCHAR * 32), ("dmSpecVersion", wt.WORD), ("dmDriverVersion", wt.WORD),
("dmSize", wt.WORD), ("dmDriverExtra", wt.WORD), ("dmFields", wt.DWORD),
("dmPositionX", wt.LONG), ("dmPositionY", wt.LONG), ("dmDisplayOrientation", wt.DWORD),
("dmDisplayFixedOutput", wt.DWORD), ("dmColor", ctypes.c_short), ("dmDuplex", ctypes.c_short),
("dmYResolution", ctypes.c_short), ("dmTTOption", ctypes.c_short), ("dmCollate", ctypes.c_short),
("dmFormName", wt.WCHAR * 32), ("dmLogPixels", wt.WORD), ("dmBitsPerPel", wt.DWORD),
("dmPelsWidth", wt.DWORD), ("dmPelsHeight", wt.DWORD), ("dmDisplayFlags", wt.DWORD),
("dmDisplayFrequency", wt.DWORD), ("dmICMMethod", wt.DWORD), ("dmICMIntent", wt.DWORD),
("dmMediaType", wt.DWORD), ("dmDitherType", wt.DWORD), ("dmReserved1", wt.DWORD),
("dmReserved2", wt.DWORD), ("dmPanningWidth", wt.DWORD), ("dmPanningHeight", wt.DWORD)]
class _GUID(ctypes.Structure):
_fields_ = [("Data1", wt.DWORD), ("Data2", wt.WORD), ("Data3", wt.WORD), ("Data4", ctypes.c_ubyte * 8)]
class _OUTPUT_DESC(ctypes.Structure): # DXGI_OUTPUT_DESC
_fields_ = [("DeviceName", wt.WCHAR * 32), ("DesktopCoordinates", _RECT), ("AttachedToDesktop", wt.BOOL),
("Rotation", ctypes.c_uint), ("Monitor", wt.HMONITOR)]
_IID_IDXGIFactory1 = _GUID(0x770AAE78, 0xF26F, 0x4DBA, (ctypes.c_ubyte * 8)(0xA8, 0x29, 0x25, 0x3C, 0x83, 0xD1, 0xB3, 0x87))
_ready = False
def _api():
"""user32 / kernel32 / dwmapi with their argument types set, once; the process made DPI aware (per monitor) first,
so window positions are real pixels, as Desktop Duplication's are."""
global _ready
u32, k32, dwm = ctypes.windll.user32, ctypes.windll.kernel32, ctypes.windll.dwmapi
if not _ready:
try:
u32.SetProcessDpiAwarenessContext(ctypes.c_void_p(-4)) # PER_MONITOR_AWARE_V2 (fails harmlessly if set)
except Exception: # noqa: BLE001 - before Windows 10 1703
pass
u32.EnumWindows.argtypes = [ctypes.c_void_p, wt.LPARAM]
for f in ("IsWindowVisible", "IsIconic", "IsWindow", "GetWindowTextLengthW"):
getattr(u32, f).argtypes = [wt.HWND]
u32.GetWindowTextW.argtypes = [wt.HWND, wt.LPWSTR, ctypes.c_int]
u32.GetWindowThreadProcessId.argtypes = [wt.HWND, ctypes.POINTER(wt.DWORD)]
u32.GetWindow.argtypes, u32.GetWindow.restype = [wt.HWND, wt.UINT], wt.HWND
u32.GetWindowLongW.argtypes = [wt.HWND, ctypes.c_int]
u32.GetClientRect.argtypes = [wt.HWND, ctypes.POINTER(_RECT)]
u32.ClientToScreen.argtypes = [wt.HWND, ctypes.POINTER(wt.POINT)]
u32.MonitorFromWindow.argtypes, u32.MonitorFromWindow.restype = [wt.HWND, wt.DWORD], wt.HMONITOR
u32.GetMonitorInfoW.argtypes = [wt.HMONITOR, ctypes.POINTER(_MONITORINFOEX)]
u32.EnumDisplaySettingsW.argtypes = [wt.LPCWSTR, wt.DWORD, ctypes.POINTER(_DEVMODE)]
u32.SetWindowDisplayAffinity.argtypes = [wt.HWND, wt.DWORD]
k32.OpenProcess.restype = wt.HANDLE
k32.QueryFullProcessImageNameW.argtypes = [wt.HANDLE, wt.DWORD, wt.LPWSTR, ctypes.POINTER(wt.DWORD)]
k32.CloseHandle.argtypes = [wt.HANDLE]
dwm.DwmGetWindowAttribute.argtypes = [wt.HWND, wt.DWORD, ctypes.c_void_p, wt.DWORD]
_ready = True
return u32, k32, dwm
def _exe_of(hwnd: int, cache: dict) -> str:
u32, k32, _ = _api()
pid = wt.DWORD()
u32.GetWindowThreadProcessId(hwnd, ctypes.byref(pid))
if pid.value not in cache:
cache[pid.value] = ""
h = k32.OpenProcess(0x1000, False, pid.value) # PROCESS_QUERY_LIMITED_INFORMATION
if h:
buf, n = ctypes.create_unicode_buffer(1024), wt.DWORD(1024)
if k32.QueryFullProcessImageNameW(h, 0, buf, ctypes.byref(n)):
cache[pid.value] = os.path.basename(buf.value).lower()
k32.CloseHandle(h)
return cache[pid.value]
def client_rect(hwnd: int) -> Rect | None:
"""The window's picture area on screen, in pixels; None if it's gone or minimised."""
u32, _, _ = _api()
if not u32.IsWindow(hwnd) or u32.IsIconic(hwnd):
return None
r, p = _RECT(), wt.POINT(0, 0)
if not u32.GetClientRect(hwnd, ctypes.byref(r)) or not u32.ClientToScreen(hwnd, ctypes.byref(p)):
return None
return Rect(p.x, p.y, r.right - r.left, r.bottom - r.top)
def monitor_of(hwnd: int) -> tuple[Rect, str, int]:
"""The monitor the window is (mostly) on: its rectangle, device name (\\\\.\\DISPLAY1) and refresh rate."""
u32, _, _ = _api()
mon = u32.MonitorFromWindow(hwnd, 2) # MONITOR_DEFAULTTONEAREST
mi = _MONITORINFOEX()
mi.cbSize = ctypes.sizeof(mi)
u32.GetMonitorInfoW(mon, ctypes.byref(mi))
r = mi.rcMonitor
dm = _DEVMODE()
dm.dmSize = ctypes.sizeof(dm)
hz = dm.dmDisplayFrequency if u32.EnumDisplaySettingsW(mi.szDevice, 0xFFFFFFFF, ctypes.byref(dm)) else 60 # current
return Rect(r.left, r.top, r.right - r.left, r.bottom - r.top), mi.szDevice, int(hz) if hz > 1 else 60
def _com(obj, index: int, *argtypes):
vtbl = ctypes.cast(obj, ctypes.POINTER(ctypes.POINTER(ctypes.c_void_p))).contents
return ctypes.WINFUNCTYPE(ctypes.c_long, ctypes.c_void_p, *argtypes)(vtbl[index])
def dda_outputs() -> list[str]:
"""The device names of the outputs (monitors) on DXGI adapter 0, in order: ddagrab's output_idx counts these."""
factory = ctypes.c_void_p()
if ctypes.windll.dxgi.CreateDXGIFactory1(ctypes.byref(_IID_IDXGIFactory1), ctypes.byref(factory)) < 0:
return []
names: list[str] = []
try:
adapter = ctypes.c_void_p()
if _com(factory, 12, wt.UINT, ctypes.POINTER(ctypes.c_void_p))(factory, 0, ctypes.byref(adapter)) < 0:
return [] # IDXGIFactory1::EnumAdapters1
try:
for i in range(16):
out = ctypes.c_void_p()
if _com(adapter, 7, wt.UINT, ctypes.POINTER(ctypes.c_void_p))(adapter, i, ctypes.byref(out)) < 0:
break # IDXGIAdapter::EnumOutputs: DXGI_ERROR_NOT_FOUND, no more
desc = _OUTPUT_DESC()
_com(out, 7, ctypes.POINTER(_OUTPUT_DESC))(out, ctypes.byref(desc)) # IDXGIOutput::GetDesc
_com(out, 2)(out) # Release
names.append(desc.DeviceName)
finally:
_com(adapter, 2)(adapter)
finally:
_com(factory, 2)(factory)
return names
def exclude_from_capture(hwnd: int) -> bool:
"""Leaves a window of ours out of screen captures (and so out of Desktop Duplication): WDA_EXCLUDEFROMCAPTURE,
Windows 10 2004 or newer. False if Windows refused (older Windows, or no desktop composition)."""
u32, _, _ = _api()
return bool(u32.SetWindowDisplayAffinity(hwnd, 0x11))
# ----------------------------------------------------------------------------- finding the window
def find_windows() -> list[AppWindow]:
"""Top-level windows that could be a game stream: visible, not minimised away from view, big enough, not a
tool window or part of Windows' shell, and not this process's own. Known apps first."""
u32, _, dwm = _api()
own, exes, found = os.getpid(), {}, []
@ctypes.WINFUNCTYPE(wt.BOOL, wt.HWND, wt.LPARAM)
def each(hwnd, _):
if not u32.IsWindowVisible(hwnd) or u32.GetWindow(hwnd, 4): # GW_OWNER: dialogs and popups belong to another
return True
if u32.GetWindowLongW(hwnd, -20) & 0x80: # GWL_EXSTYLE & WS_EX_TOOLWINDOW
return True
cloaked = wt.DWORD()
dwm.DwmGetWindowAttribute(hwnd, 14, ctypes.byref(cloaked), ctypes.sizeof(cloaked)) # DWMWA_CLOAKED
if cloaked.value:
return True
pid = wt.DWORD()
u32.GetWindowThreadProcessId(hwnd, ctypes.byref(pid))
if pid.value == own:
return True
exe = _exe_of(hwnd, exes)
if not exe or exe in SKIP_EXE:
return True
n = u32.GetWindowTextLengthW(hwnd)
buf = ctypes.create_unicode_buffer(n + 1)
u32.GetWindowTextW(hwnd, buf, n + 1)
r = client_rect(hwnd)
iconic = bool(u32.IsIconic(hwnd))
if not buf.value or (r is None and not (iconic and exe in KNOWN)): # minimised: only apps it knows
return True
if r is not None and (r.w < MIN_SIZE[0] or r.h < MIN_SIZE[1]):
return True
found.append(AppWindow(int(hwnd), buf.value, exe, r.w if r else 0, r.h if r else 0))
return True
u32.EnumWindows(each, 0)
return sorted(found, key=lambda w: (w.exe not in KNOWN, w.exe not in dict(PRESETS.values()), w.app.lower()))
def pick(query: str, windows: list[AppWindow] | None = None) -> AppWindow | None:
"""The window `query` names: "hwnd:N", "exe:NAME", a preset ("ps-remote-play"), or part of a title. Of several
matches, the biggest. Several queries split by "|" are tried in turn: the launcher passes "hwnd:N|exe:NAME", so
an app reopened since its list was read is still found."""
windows = find_windows() if windows is None else windows
if "|" in query:
return next((w for q in query.split("|") if q.strip() and (w := pick(q, windows))), None)
q = query.strip()
if q.lower().startswith("hwnd:"):
hwnd = int(q[5:], 0)
return next((w for w in windows if w.hwnd == hwnd), None)
if q.lower() in PRESETS:
q = "exe:" + PRESETS[q.lower()][0]
if q.lower().startswith("exe:"):
exe = q[4:].strip().lower()
exe = exe if exe.endswith(".exe") else exe + ".exe"
matches = [w for w in windows if w.exe == exe]
else:
matches = [w for w in windows if q.lower() in w.title.lower()]
return max(matches, key=lambda w: w.w * w.h, default=None)
# ----------------------------------------------------------------------------- capture geometry
@dataclass(frozen=True)
class Grab:
"""What ddagrab is asked for: output_idx, the region (relative to that monitor) and how often to look."""
output: int
region: Rect # relative to the monitor's top-left
hz: int
def plan_grab(client: Rect, monitor: Rect, device: str, outputs: list[str], hz: int) -> Grab | str:
"""Where to grab a window's picture from, or why it can't be. The region is the part of the picture area on the
window's monitor, with even sizes (for the colour conversion)."""
if device not in outputs:
return ("its monitor isn't on the main graphics adapter, which window capture reads from: move the window to "
"the monitor plugged into the graphics card")
part = client.clamp(monitor)
w, h = part.w & ~1, part.h & ~1
if w < MIN_SIZE[0] or h < MIN_SIZE[1]:
return "too little of the window is on screen: move it fully onto one monitor"
return Grab(outputs.index(device), Rect(part.x - monitor.x, part.y - monitor.y, w, h), max(int(hz), 60))
def graph(g: Grab, out_w: int, out_h: int) -> str:
"""The FFmpeg filter graph: Desktop Duplication of the region, only when the screen changes, to the CPU as BGR at
the source's fixed size."""
r = g.region
return (f"ddagrab=output_idx={g.output}:framerate={g.hz}:video_size={r.w}x{r.h}:offset_x={r.x}:offset_y={r.y}"
f":draw_mouse=0:dup_frames=0,hwdownload,format=bgra,scale={out_w}:{out_h}:flags=bilinear,format=bgr24")
# ----------------------------------------------------------------------------- the source
class WindowSource:
"""Ticks from an app's window, as the app draws them (a variable rate: wrap it in sources.Clock60). Iterate it
once. `where()` says where the overlay should go: (the picture area, the monitor), both in screen pixels, or
None while the window is minimised or gone."""
def __init__(self, target: AppWindow, size: tuple[int, int] | None = None, open_fn=None, gpu=None) -> None:
"""open_fn: opens the CPU path (FFmpeg's ddagrab) from a filter graph. gpu: opens the GPU path, (Grab, out_w,
out_h) -> a dda.DdaCapture-like object; None picks dda.DdaCapture when CUDA is there (and no open_fn is
given), False uses the CPU path only."""
from .sources import source_info
self.target = target
self._open = open_fn or _open_lavfi
self._open_gpu = gpu or (_open_dda if gpu is None and open_fn is None and _cuda() else None)
self._said_gpu = False
self._client = client_rect(target.hwnd)
if self._client is None:
raise RuntimeError(f"the {target.app} window is minimised: restore it, then press Play again")
mon, device, hz = monitor_of(target.hwnd)
plan = plan_grab(self._client, mon, device, dda_outputs(), hz)
if isinstance(plan, str):
raise RuntimeError(f"can't capture the {target.app} window: {plan}")
self._grab, self._monitor = plan, mon
self.w, self.h = size or (plan.region.w, plan.region.h)
self.info = source_info("window", name=f"{target.app} window", hz=float(hz))
self.restarts = 0
self._stop = False
self._container = None
self.path = "GPU" if self._open_gpu else "CPU"
print(f"[window] {target.app} ({target.exe}): {plan.region.w}x{plan.region.h} on monitor {plan.output + 1} "
f"at {hz} Hz, captured as {self.w}x{self.h}")
def where(self) -> tuple[Rect, Rect] | None:
return (self._client, self._monitor) if self._client is not None else None
def _moved(self) -> bool:
"""Re-reads the window's place; True if capture has to restart (moved, resized, or to another monitor)."""
client = client_rect(self.target.hwnd)
if client == self._client:
return False
self._client = client
if client is None:
return True
mon, device, hz = monitor_of(self.target.hwnd)
plan = plan_grab(client, mon, device, dda_outputs(), hz)
if isinstance(plan, str):
print(f"[window] {plan}")
self._client = None
return True
self._grab, self._monitor = plan, mon
return True
def __iter__(self):
from .io import Tick
u32, _, _ = _api()
n, check, fails = 0, time.perf_counter() + CHECK_S, 0
while not self._stop:
if not u32.IsWindow(self.target.hwnd):
print(f"[window] the {self.target.app} window closed")
return
if self._client is None: # minimised, or somewhere it can't be captured: the last frame stays up
time.sleep(CHECK_S)
self._moved()
continue
try:
for got in self._frames():
now = time.perf_counter()
if self._stop:
return
if got is not None:
frame, t_arrival, t_source = got
yield Tick(frame, t_arrival, n, t_source=t_source, t_ready=time.perf_counter())
n, fails = n + 1, 0
if now >= check:
check = now + CHECK_S
if self._moved():
self.restarts += 1
break
if not u32.IsWindow(self.target.hwnd):
break
except Exception as e: # noqa: BLE001 - lost the duplication (a mode change, a UAC prompt): retry
from .dda import GpuCaptureUnavailable
if isinstance(e, GpuCaptureUnavailable) and self._open_gpu is not None:
print(f"[window] frames go through the CPU: the GPU path can't run here ({e})")
self._open_gpu, self.path = None, "CPU"
continue
if self._stop:
return
fails += 1
if fails >= 5:
print(f"[window] capture keeps failing ({str(e)[:160]}); stopping")
return
print(f"[window] capture stopped ({str(e)[:160]}); trying again")
time.sleep(CHECK_S)
self._moved()
finally:
self._close_container()
def _frames(self):
"""(frame, t_arrival, t_source) each time the window's picture changes, from one capture (it ends for a
restart); None now and then while nothing changes, so the window can be looked at."""
if self._open_gpu is not None:
r = self._grab.region
self._container = cap = self._open_gpu(self._grab, self.w, self.h)
if not self._said_gpu:
self._said_gpu = True
print(f"[window] capturing on the GPU ({r.w}x{r.h} -> {self.w}x{self.h})")
while not self._stop:
yield cap.grab(100)
else:
self._container = self._open(graph(self._grab, self.w, self.h))
for frame in self._container.decode(video=0):
yield frame.to_ndarray(), time.perf_counter(), frame.time
def _close_container(self) -> None:
c, self._container = self._container, None
if c is not None:
try:
c.close()
except Exception: # noqa: BLE001 - closing
pass
def close(self) -> None:
"""Stops at the next frame. The capture is closed by the thread reading it (closing it from here, mid-read,
isn't safe); Clock60's reader is a daemon thread, so a capture still waiting for the screen to change doesn't
hold up the exit."""
self._stop = True
print(f"[window] capture restarted {self.restarts} time(s) for moves; frames came through the {self.path}")
def _open_lavfi(spec: str):
import av
return av.open(spec, format="lavfi")
def _open_dda(g: Grab, out_w: int, out_h: int):
from .dda import DdaCapture
return DdaCapture(g.output, g.region.x, g.region.y, g.region.w, g.region.h, out_w, out_h)
def _cuda() -> bool:
try:
import torch
return torch.cuda.is_available()
except Exception: # noqa: BLE001 - no torch (DirectML installs have it, CPU-only): the CPU path
return False
def open_window(query: str) -> WindowSource:
"""--window QUERY: the window, or a clear error naming what was looked for."""
target = pick(query)
if target is None:
raise RuntimeError(f"no app window matches {query!r}: open the app and start streaming, then press Play again "
"(python -m framegen.window --list shows what's found)")
return WindowSource(target, size=SIZE)
# ----------------------------------------------------------------------------- command line
def main(argv: list[str] | None = None) -> int:
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--list", action="store_true", help="the app windows that could be captured")
ap.add_argument("--json", action="store_true")
a = ap.parse_args(argv)
if sys.platform != "win32":
print(json.dumps({"windows": []}) if a.json else "window capture needs Windows")
return 0
windows = find_windows()
if a.json:
print(json.dumps({"windows": [{**asdict(w), "app": w.app, "known": w.exe in KNOWN} for w in windows]}))
else:
for w in windows:
print(f"hwnd:{w.hwnd:<10} {w.app:16} {w.w}x{w.h} {w.title}")
if not windows:
print("no app windows found")
return 0
if __name__ == "__main__":
sys.exit(main())
+134
View File
@@ -0,0 +1,134 @@
"""Minimise and restore another program's windows (Windows; does nothing elsewhere).
Used to minimise chiaki-ng while the pipeline's window is in front: chiaki-ng keeps streaming, decoding and
reading the controller, but stops drawing video nobody sees, which otherwise takes GPU time from RIFE.
"""
from __future__ import annotations
import ctypes
import os
import sys
SW_SHOWNOACTIVATE, SW_MINIMIZE, SW_RESTORE = 4, 6, 9
def windows_of(exe: str) -> list[int]:
"""Visible top-level windows whose process image is `exe` (e.g. "chiaki.exe")."""
if sys.platform != "win32":
return []
from ctypes import wintypes as wt
u32, k32 = ctypes.windll.user32, ctypes.windll.kernel32
u32.GetWindowThreadProcessId.argtypes = [wt.HWND, ctypes.POINTER(wt.DWORD)]
u32.IsWindowVisible.argtypes = [wt.HWND]
k32.OpenProcess.restype = wt.HANDLE
k32.QueryFullProcessImageNameW.argtypes = [wt.HANDLE, wt.DWORD, wt.LPWSTR, ctypes.POINTER(wt.DWORD)]
k32.CloseHandle.argtypes = [wt.HANDLE]
names: dict[int, str] = {}
found: list[int] = []
def image(pid: int) -> str:
if pid not in names:
names[pid] = ""
h = k32.OpenProcess(0x1000, False, pid) # PROCESS_QUERY_LIMITED_INFORMATION
if h:
buf, n = ctypes.create_unicode_buffer(1024), wt.DWORD(1024)
if k32.QueryFullProcessImageNameW(h, 0, buf, ctypes.byref(n)):
names[pid] = os.path.basename(buf.value).lower()
k32.CloseHandle(h)
return names[pid]
@ctypes.WINFUNCTYPE(wt.BOOL, wt.HWND, wt.LPARAM)
def visit(hwnd, _):
pid = wt.DWORD()
u32.GetWindowThreadProcessId(hwnd, ctypes.byref(pid))
if u32.IsWindowVisible(hwnd) and image(pid.value) == exe.lower():
found.append(hwnd)
return True
u32.EnumWindows(visit, 0)
return found
def show(hwnds: list[int], cmd: int) -> None:
if sys.platform == "win32":
for h in hwnds:
ctypes.windll.user32.ShowWindow(ctypes.c_void_p(h), cmd)
def bring_to_front(hwnd: int) -> bool:
"""Puts our window in front with the keyboard focus, so its keys work without a click first. Windows only lets
the program that's in front hand the focus on (SetForegroundWindow from anyone else just flashes the taskbar
button), and when the video window opens, the program in front is chiaki-ng, where the player just pressed
connect. So this briefly shares that program's input queue (AttachThreadInput), which lets the focus move.
Call it from the window's own thread. Returns whether our window ended up in front."""
if sys.platform != "win32" or not hwnd:
return False
from ctypes import wintypes as wt
u32, k32 = ctypes.windll.user32, ctypes.windll.kernel32
u32.GetForegroundWindow.restype = wt.HWND
u32.GetWindowThreadProcessId.argtypes = [wt.HWND, ctypes.POINTER(wt.DWORD)]
u32.GetWindowThreadProcessId.restype = wt.DWORD
u32.AttachThreadInput.argtypes = [wt.DWORD, wt.DWORD, wt.BOOL]
for f in (u32.BringWindowToTop, u32.SetForegroundWindow, u32.SetFocus):
f.argtypes = [wt.HWND]
fg = u32.GetForegroundWindow()
if fg == hwnd:
return True
me = k32.GetCurrentThreadId()
other = u32.GetWindowThreadProcessId(fg, None) if fg else 0
joined = bool(other and other != me and u32.AttachThreadInput(me, other, True))
try:
u32.BringWindowToTop(hwnd)
u32.SetForegroundWindow(hwnd)
u32.SetFocus(hwnd)
finally:
if joined:
u32.AttachThreadInput(me, other, False)
return u32.GetForegroundWindow() == hwnd
# ----------------------------------------------------------------------------- scheduling priority
# Keeps frames on time when other programs are busy (a browser, a download, a game launcher updating). Set
# FRAMEGEN_NO_BOOST=1 to turn both off, e.g. to measure the difference.
_AVRT_PRIORITY_HIGH = 1
_D3DKMT_PRIORITY_HIGH = 4 # D3DKMT_SCHEDULINGPRIORITYCLASS: idle 0, below 1, normal 2, above 3, high 4, realtime 5
def _boost_off() -> bool:
return sys.platform != "win32" or os.environ.get("FRAMEGEN_NO_BOOST") == "1"
def boost_thread(task: str = "Games") -> bool:
"""Registers the calling thread with Windows' multimedia class scheduler (MMCSS) under `task`, at high
priority, so it gets the CPU on time. Lasts until the thread ends. Returns whether it worked."""
if _boost_off():
return False
try:
avrt = ctypes.WinDLL("avrt")
avrt.AvSetMmThreadCharacteristicsW.restype = ctypes.c_void_p
avrt.AvSetMmThreadCharacteristicsW.argtypes = [ctypes.c_wchar_p, ctypes.POINTER(ctypes.c_uint32)]
avrt.AvSetMmThreadPriority.argtypes = [ctypes.c_void_p, ctypes.c_int]
index = ctypes.c_uint32(0)
h = avrt.AvSetMmThreadCharacteristicsW(task, ctypes.byref(index))
if not h:
return False
avrt.AvSetMmThreadPriority(h, _AVRT_PRIORITY_HIGH)
return True
except OSError:
return False
def boost_gpu() -> bool:
"""Raises this process's GPU scheduling priority to high (what games and video players use), so other
programs' GPU work doesn't delay ours. Returns whether it worked."""
if _boost_off():
return False
try:
gdi = ctypes.WinDLL("gdi32")
gdi.D3DKMTSetProcessSchedulingPriorityClass.argtypes = [ctypes.c_void_p, ctypes.c_int]
k32 = ctypes.WinDLL("kernel32")
k32.GetCurrentProcess.restype = ctypes.c_void_p
status = gdi.D3DKMTSetProcessSchedulingPriorityClass(k32.GetCurrentProcess(), _D3DKMT_PRIORITY_HIGH)
return status == 0
except (OSError, AttributeError):
return False
+216
View File
@@ -0,0 +1,216 @@
# SmoovPlay launcher and installer
Two Windows programs built from one C# source tree in `launcher\`. They use WPF on .NET Framework 4.8, which every Windows 10 and 11 PC has.
| File | What it is |
|---|---|
| `SmoovPlay-Setup.exe` (~140 MB) | The launcher with the app and chiaki-ng embedded. Walks through **Check your PC → Choose a folder → Install → Ready to play**. Installs per user (no admin rights), downloads the runtime from official sources, prepares the GPU and adds shortcuts. |
| `SmoovPlay.exe` (~0.3 MB) | The launcher, inside every install. Its left rail has five pages: **Play**, **Connect your PS5**, **PC check**, **Settings** and **Help**. Play starts the pipeline *before* chiaki-ng, so the stream's codec header is never missed. **Test with a 60 fps game**, under Play, does the same in test mode (`run.py --test-mode`) and shows a results card when it stops. While a stream plays, the launcher minimises to the taskbar, with a dot on its button (green: playing, amber: starting, red: stopped with an error), and comes back up when the session ends. **Settings** lists the pipeline's own settings (`python -m framegen.settings`): switches for on/off, dropdowns for the rest, each choice with a line on when to pick it. The interpolation model and upscaler dropdowns offer only what SmoovPlay supports today, and end with a note that other models may come later. **Auto-detect**, at the top, runs `python -m framegen.autodetect` (about 10 s; off while playing, and Play waits for it), shows what it found and what it suggests with a reason for each, and **Apply** sets the suggestions. Its output goes to `logs\autodetect.txt`. With nothing playing it edits the settings file; while a stream plays it sends each change to the running pipeline (`run.py --control`, see `framegen/remote.py`), which applies it straight away, and it follows changes made in the video window's menu. |
Source files:
| File | Contents |
|---|---|
| `Core.cs` | Entry point, paths, the install steps, play sessions, chiaki-ng handling, diagnostics, uninstall. |
| `Checks.cs` | The PC check and its fixes. |
| `Ui.xaml` | The window: layout, styles and animations. Embedded and loaded at run time, with no code-behind. |
| `Ui.cs` | The window's logic. |
| `SettingsPage.cs` | The Settings page, built from the pipeline's own list of settings. |
| `AutoDetect.cs` | Auto-detect: times this PC and suggests settings. |
| `Vfg.cs` | NVIDIA VFG setup and removal, with NVIDIA's licence. |
| `Feedback.cs` | The Experimental badge and Send feedback. |
| `Updater.cs` | Updates: finds the newest GitHub release, downloads and checks its setup, hands over to it. |
| `UpdateSignature.cs` | Signs and checks the `.sig` file that comes with each setup (also used by `tools\SignUpdate.cs`). |
## Build
```
.venv\Scripts\python installer\build.py # both exes, into installer\dist
.venv\Scripts\python installer\build.py --version 0.2.0 # a release's version (default: VERSION in build.py)
.venv\Scripts\python installer\build.py --launcher-only # only SmoovPlay.exe
```
A full build also writes `SmoovPlay-Setup.exe.sig`, the update signature (see Updates).
Needs:
* Roslyn `csc.exe` from Visual Studio 2019+ Build Tools.
* WPF's assemblies from `C:\Windows\Microsoft.NET\Framework64\v4.0.30319\WPF`, which are part of Windows.
* The patched chiaki-ng build: `--chiaki-build <folder>`, or set `SMOOVPLAY_CHIAKI_BUILD`.
* Its source checkout, which supplies the licence texts and the patch as a git diff: `--chiaki-src <folder>`, or set `SMOOVPLAY_CHIAKI_SRC`.
* `models\flownet_v4.22.lite.pkl`.
`build.py` pins the embeddable Python's SHA-256, and setup refuses a download that doesn't match it.
## The PC check, and what could stop an install
Setup opens with the PC check, and the launcher's **PC check** page shows the same cards. A **Fail** blocks Continue; **Continue anyway** is there in case a check is wrong. Hovering a card shows more help.
| Card | Checks | If it's a problem |
|---|---|---|
| Graphics card | An NVIDIA card (WMI), with its memory from `nvidia-smi`; otherwise an AMD or Intel card is named. | An AMD Radeon or Intel Arc card: warning, Experimental (RIFE runs through DirectML, slower; expect 60 fps), with **Send feedback**. Built-in graphics: warning, likely too slow. No graphics card found, or an NVIDIA card older than RTX: fail. RTX 20, laptop, or under 6 GB: warning. |
| NVIDIA driver | The version: CUDA 12 needs 528 or newer, and 570+ is recommended (RTX 50 needs it). | **Get the driver** opens NVIDIA's driver page. NVIDIA's installer is theirs to run. Without an NVIDIA card: info, not needed. |
| This PC | 64-bit Windows 10 or 11, and memory. | Under 8 GB: warning. |
| Visual C++ runtime | `msvcp140.dll` 14.40 or newer and `vcruntime140_1.dll`. PyTorch won't load without them, and crashes with older ones. | **Install it for me**: downloads `vc_redist.x64.exe` from Microsoft, checks its Authenticode signature is valid and Microsoft's (WinVerifyTrust), then runs it `/passive` (Windows asks for permission). |
| Disk space | Free space on the install drive (about 12 GB needed). | Warning here. The folder step blocks Install until another drive is chosen. |
| Download servers | python.org, bootstrap.pypa.io, pypi.org, files.pythonhosted.org, download.pytorch.org and pypi.nvidia.com, through Windows' proxy settings. | All unreachable: fail. Some: warning. A system proxy is passed to pip (`--proxy`). |
| Display | The fastest refresh rate a monitor is set to, and the fastest it could be set to. | Set below what it supports: **Open display settings**. A 60 Hz monitor is fine (info). |
| Home network | Wired or Wi-Fi; on Wi-Fi, the band (from `netsh wlan`). | 2.4 GHz: warning, suggesting 5 GHz or a cable. |
The folder step also checks the folder:
* **Admin-only places** (Program Files, Windows) are refused.
* **Network and removable drives** are refused.
* **Long paths:** with Windows' long paths off, a path over 80 characters is refused, because the deepest package file sits about 155 characters below the install folder. The step offers **Use a shorter path** (`<drive>:\SmoovPlay`) and **Turn on long paths** (admin).
* **An existing install** is updated in place.
Not handled in the app:
* **SmartScreen.** "Windows protected your PC" appears before any of our code runs; the way through is More info, then Run anyway. Only code signing (and download history) removes it. The main README explains it to players, with how to check the file's SHA-256.
* **Antivirus.** Some products may quarantine an unsigned exe.
* **.NET Framework 4.8.** It's built into Windows 10 1903 and later.
## Connect your PS5
The launcher opens on this page the first time it runs. It has eight steps the user ticks off, and SmoovPlay remembers them in `%APPDATA%\framegen\smoovplay-launcher.txt`:
1. Turn on Remote Play.
2. Rest-mode settings (optional).
3. Sign in to PSN in chiaki-ng.
4. Register the PS5, automatically or with a PIN.
5. Set the stream to 60 fps with HDR off.
6. Black picture? Turn off HDCP (only if needed). If the picture stays black, or the PS5 says the content can't be shown, turn off Enable HDCP (PS5: Settings → System → HDMI), and turn it back on afterwards for video apps like Netflix.
7. Connect a controller.
8. Press Play.
A capture card's guide has the same HDCP step; there it's always needed on a PS5.
**Open chiaki-ng** starts the bundled chiaki-ng with the frame tap on. A later Play then reuses that same chiaki-ng.
## What setup does
Every step can run again: **Retry** after a failure, or **Repair** in Help later, picks up where it stopped. Closing setup mid-way asks first, then pauses it.
1. Unpacks these:
* `app\`: run.py, framegen and the RIFE weights.
* `chiaki\`: chiaki-ng with the frame tap, its licences and the patch source.
* `SmoovPlay.exe`.
2. Downloads the Python 3.12.10 embeddable package from python.org, verifies its SHA-256, and sets its `._pth` file to see `Lib\site-packages` and `..\..\app`. It then installs pip with `get-pip.py`.
3. Runs `pip install -r app\requirements-runtime.txt` with pinned versions, about 5 GB:
* Sources: pypi.org, plus download.pytorch.org for CUDA PyTorch and pypi.nvidia.com for TensorRT's wheels.
* setuptools and wheel go in first, and pip runs with `--no-build-isolation`, because pip's isolated build doesn't work in the embeddable Python.
* The page shows download speed and time left.
4. `python -m framegen.prepare` builds the TensorRT engine for full motion detail; at half, Auto uses PyTorch, which is faster there. On a new install it then picks settings for the PC (`framegen.autodetect --apply --if-new`, about 10 s). It saves nothing if the graphics card is busy with something else, and never replaces an existing settings file.
5. Adds Start-menu and desktop shortcuts and an Apps & features entry (HKCU), then writes `runtime\ready.txt`.
None of PyTorch, TensorRT, CUDA or PyAV is ever redistributed by us.
## Install layout
```
SmoovPlay\ default: %LOCALAPPDATA%\Programs\SmoovPlay
SmoovPlay.exe
LICENSE.txt, THIRD_PARTY_NOTICES.txt
app\ run.py, framegen\, models\ (weights; TensorRT engines in models\trt)
chiaki\ chiaki-ng + licenses\ + source\
runtime\python\ embeddable Python with the packages
logs\ setup-*.log, session-*.log, results-*.txt (test mode reports, also in Copy diagnostics),
autodetect.txt (the last Auto-detect run)
```
Settings stay in `%APPDATA%\framegen\` and are kept on uninstall.
Uninstall (Help → Uninstall, or Apps & features) removes only what setup created, then the folder if it's empty. Setup never installs into a folder that already holds other files; it makes a `SmoovPlay` subfolder instead.
## Updates
The launcher finds new releases on GitHub and, with a click, installs them itself.
**Finding one.** When the launcher opens, it asks GitHub for the newest release in `RELEASES_REPO` (set in `build.py`; empty turns updates off). Drafts are skipped; pre-releases count, so betas can go out as pre-releases. Tags are versions: `v0.2.0`, `v0.2.0-beta.2`. The answer is cached for 20 hours in `%APPDATA%\framegen\smoovplay-update.txt`, and the request carries only the app's version, in its User-Agent. A newer release shows **Update available: v0.2.0** under the version in the rail, and the Help page mentions it too.
**Installing it.** Clicking that line asks **Update to v0.2.0?** (Update now, What's new, Later). Update now:
1. Downloads `SmoovPlay-Setup.exe` from the release into `%TEMP%\SmoovPlay-update\`, with progress in the rail.
2. Checks it before running anything:
* The SHA-256 must match both GitHub's asset digest and the signed one in `SmoovPlay-Setup.exe.sig`.
* The `.sig` must be signed with SmoovPlay's update key, whose public half is built into every launcher.
* The signed version must be the release's tag, and newer than the running app.
* Nothing runs if any check fails, and the error offers the release page instead.
3. Closes chiaki-ng if it's running from this install, starts `SmoovPlay-Setup.exe --update --dir <install> --wait <launcher pid>`, and closes the launcher.
4. Setup waits for the launcher to exit, then runs its usual steps in place. Python and packages already there are kept, and pip only adds what changed. Engines stay cached, and settings, looks and clips are kept. Then it opens SmoovPlay again.
The next launcher start deletes the downloaded setup. A dev launcher (`SMOOVPLAY_APP`), or a build without the update key, only links to the release page.
**Publishing a release.** Build with `--version`, then upload **both** `installer\dist\SmoovPlay-Setup.exe` and `SmoovPlay-Setup.exe.sig` to a GitHub release tagged `v<version>`. A release without the `.sig` only gets a link to its page.
**The signing key.** The first build makes an RSA-3072 key at `%USERPROFILE%\.smoovplay\update-signing-key.xml` (`SMOOVPLAY_SIGNING_KEY` overrides it), outside the repo. Back it up somewhere safe and never commit it:
* Without it, installed copies can't update themselves. Running a new setup by hand still updates them.
* With it, anyone could sign a setup that installed copies would accept.
`installer\build\SignUpdate.exe sign <key> <file> <version>` signs a file by hand.
**While the repo is private** GitHub's API hides its releases from anyone not signed in, so installed copies find no update. `SMOOVPLAY_GITHUB_TOKEN=<token>` lets a test machine see them; it's sent only to api.github.com, never to the download host it redirects to.
Test switches:
* `SMOOVPLAY_UPDATE_CHECK=0` turns updates off.
* `SMOOVPLAY_RELEASES_REPO=owner/name` points the check at another repo.
* `SMOOVPLAY_RELEASES_API=http://127.0.0.1:<port>` sends it to a stand-in for GitHub's API.
## Command line
```
SmoovPlay-Setup.exe --unattended --dir "C:\Games\SmoovPlay" [--no-shortcuts] [--skip-prepare] # log: <dir>\install.log, exit code 0 = ok
SmoovPlay-Setup.exe --update --dir "<install>" [--wait <pid>] # update in place with the window (what Update now runs)
SmoovPlay.exe --page play|guide|check|settings|help # open on a page
SmoovPlay.exe --diagnostics out.txt # what "Copy diagnostics" copies (user folder replaced by %USERPROFILE%)
SmoovPlay.exe --uninstall [--yes] # --yes: already confirmed (the Help page asks in-app)
SmoovPlay.exe --check-signature file.exe # exit 0 if Microsoft-signed (tests the Visual C++ download check)
```
## Testing
Dev mode runs the launcher against a dev checkout:
* `SMOOVPLAY_PYTHON` and `SMOOVPLAY_APP`: the venv Python and the repo.
* `SMOOVPLAY_CHIAKI` and `SMOOVPLAY_CHIAKI_ARGS`: what "chiaki-ng" is. The fake PS5 stream can stand in for it.
* `SMOOVPLAY_RUN_ARGS`: extra `run.py` arguments.
Other test switches:
* `SMOOVPLAY_SHOTS=<folder>`: saves a PNG of the window on every page or state change. WPF renders it itself, so it's never a screen capture.
* `SMOOVPLAY_RECORD=<folder>`: records the window as video (`frames.mkv`, lossless, encoded on the GPU by ffmpeg on `PATH`) with each frame's time in `frames.txt`. Also rendered by WPF, never a screen capture. `SMOOVPLAY_RECORD_FPS` (default 30) and `SMOOVPLAY_RECORD_SCALE` (default 1.5) tune it. The frames arrive unevenly, so resample a recording to an even frame rate before editing it.
* `SMOOVPLAY_SETTINGS=<file>`: uses this settings file instead of the real one, to show chosen settings without changing yours. Give `run.py` the same file (`--settings` in `SMOOVPLAY_RUN_ARGS`), or the Settings page and the pipeline read different files.
* `SMOOVPLAY_PREFS=<file>`: keeps the guide's ticks out of the real profile.
* `SMOOVPLAY_SOURCES=all`: also offers the video sources that aren't ready yet (`python -m framegen.sources`), with a picker on the Play page (`source-<kind>`), a setup guide for each, and a PC check card for a capture card in place of the home network. `SMOOVPLAY_CAPTURE=<index or video file>` is the capture card (a file stands in for one, played in real time through the capture path), and `SMOOVPLAY_SOURCE_FILE=<video file>` is the "Video file" source.
* `FRAMEGEN_VFX_PATH=<folder>`: where NVIDIA VFG goes (a dev launcher only; an install always uses `runtime\vfx`). On the Settings page, under Interpolation model, **Set up NVIDIA VFG** shows NVIDIA's licence first, then runs `python -m framegen.vfg_setup --install --accept-nvidia-licence` into that folder (NVIDIA's pinned wheel from pypi.nvidia.com, output in `logs\vfg-setup.txt`) and picks it; **Remove** deletes it (only a folder with SmoovPlay's marker file). The NVIDIA VFG choice is greyed out until it's set up. Copy diagnostics leaves out a test report that includes NVIDIA VFG, because NVIDIA's licence forbids publishing its results.
* `SMOOVPLAY_DETECT_ARGS=--timing 9.3,6.8`: Auto-detect uses these times (full, half motion detail, in ms) instead of timing the AI model, so UI tests don't load the graphics card.
* `SMOOVPLAY_FAKE_CHECKS=vc,driver,display,lan,net,longpaths`: shows those checks as problems, to see the fix-it UI on a PC that passes. The fixes still act for real.
* `SMOOVPLAY_TRACE=<file>`: developer tracing.
* `SMOOVPLAY_SHOW_RESULTS=<results .txt>`: opens with that test report on the Play page, to see the results card without playing.
Every named element has a UI Automation id, so tests can drive the window: `Invoke` on buttons, `SelectionItem` on the rail, `Value` on the folder box. On the Settings page, switches are `Set_<key>` (`Toggle`) and dropdowns are `Set_<key>` (`ExpandCollapse`). A row of two to four choices is `Set_<key>`, and each choice `Set_<key>_<value>` (`SelectionItem`, its hint as `HelpText`); the frame-rate pick at the top is `Set_hz`, with `Set_hz_off` for frame generation off. A section's header is `SetFold_<group>` without spaces (`Invoke`; `ItemStatus` says open or closed); a setting that doesn't apply right now (FSR sharpening with RTX VSR picked, say) isn't shown. A dropdown's entries, `Set_<key>_<value>` (`SelectionItem`, e.g. `Set_hz_90`), exist once it has been expanded; look them up under the dropdown, not the window (the popup's own copy has no `SelectionItem`). `Set_<key>_later` is the "may come later" note, which can't be selected. Each entry's hint is its `HelpText`. Auto-detect: `BtnDetect`, `DetectProgress` while it runs, then `Detect_<key>` (a suggestion: "60 fps → 90 fps", or "Auto already set"), `BtnDetectApply` and `BtnDetectDismiss`.
Use a separate tap name so a real chiaki-ng isn't disturbed:
```
set SMOOVPLAY_PYTHON=%CD%\.venv\Scripts\python.exe
set SMOOVPLAY_APP=%CD%
set SMOOVPLAY_CHIAKI=%CD%\.venv\Scripts\python.exe
set SMOOVPLAY_CHIAKI_ARGS=scripts\frametap_fake.py testdata\clip_1080p60.mp4 --seconds 20 --delay 1 --tap Local\sp-test
set SMOOVPLAY_RUN_ARGS=--settings %TEMP%\sp-settings.json --no-minimize-chiaki --chiaki-tap Local\sp-test
set SMOOVPLAY_SETTINGS=%TEMP%\sp-settings.json
installer\dist\SmoovPlay.exe
```
For **Test with a 60 fps game**, add `--native` to the fake's arguments so it sends a 60 fps game.
## Known limits
* **Unsigned:** SmartScreen shows "Windows protected your PC" (More info, then Run anyway) until the exes are code-signed.
* **Size:** the setup is ~140 MB, because chiaki-ng is embedded (its FFmpeg DLL alone is 120 MB). Once the chiaki-ng fork publishes releases, setup can download chiaki-ng too.
* **Updates need a public release:** while the repo is private, installed copies don't see new releases (see Updates).
* **No RTX VSR:** the installed app lacks the RTX Video SDK, so it uses FSR 1.
* **One chiaki-ng at a time:** the launcher only sends video to a chiaki-ng it started itself. If another one is open, it offers to close it.
* **Idle cost:** decorative animations run at 30 fps, and pause while the window is minimised or in the background during a stream.
+54
View File
@@ -0,0 +1,54 @@
SmoovPlay third-party notices
==============================
SmoovPlay's own code is MIT licensed (LICENSE.txt). It contains, bundles or downloads the following.
Included in SmoovPlay (app\ folder)
------------------------------------
* RIFE network definitions, vendored from HolyWu/vs-rife. MIT License, Copyright (c) 2021 HolyWu.
Full text: app\framegen\rife\LICENSE.
* RIFE 4.22 lite model weights (app\models\flownet_v4.22.lite.pkl), trained by hzwer (Practical-RIFE,
MIT License) and published by HolyWu/vs-rife (MIT License).
* AMD FidelityFX Super Resolution 1.0 shaders. MIT License, Copyright (c) 2021 Advanced Micro Devices, Inc.
Full text: app\framegen\shaders\fsr1\LICENSE.txt.
* Sample pictures for the Looks page's preview (app\framegen\samples): screenshots from Grand Theft Auto VI and
Grand Theft Auto V (c) Rockstar Games, Cyberpunk 2077 (c) CD PROJEKT RED, Forza Horizon 5 (c) Microsoft,
Gran Turismo 7 (c) Sony Interactive Entertainment, and skate. (c) Electronic Arts. Included only to show what
a look does; they belong to their publishers and aren't covered by SmoovPlay's MIT licence.
Bundled as a separate program (chiaki\ folder)
----------------------------------------------
* chiaki-ng 1.10.1 with SmoovPlay's frame-tap patch. GNU Affero General Public License 3.0 (with the
OpenSSL exception): chiaki\LICENSE-AGPL-3.0.txt. The source of the patch is in chiaki\source\ (see its
README); the rest is upstream chiaki-ng v1.10.1 at https://github.com/streetpea/chiaki-ng. You can also ask
the SmoovPlay authors for the complete corresponding source.
* chiaki-ng's own dependencies, as built by its Windows CI: Qt 6 (LGPL 3.0), FFmpeg 9.0 "gpl-shared" build from
https://github.com/streetpea/FFmpeg-Builds (GPL 3.0, see chiaki\licenses\FFmpeg-LICENSE.txt), SDL 3 and
sdl2-compat (zlib), OpenSSL 3 (Apache 2.0), libplacebo (LGPL 2.1+), Opus (BSD), HarfBuzz, FreeType, ICU,
libpng, zlib, zstd, GLib, hidapi, fftw (GPL 2+), SpeexDSP and others from MSYS2, each under its own licence.
Downloaded by setup from their official sources (not distributed by SmoovPlay)
---------------------------------------------------------------------------------
* Python 3.12 embeddable package, python.org (PSF License).
* pip, bootstrap.pypa.io (MIT).
* PyTorch with NVIDIA CUDA libraries, download.pytorch.org (BSD-3-Clause; the NVIDIA libraries are under
NVIDIA's licence terms).
* NVIDIA TensorRT (tensorrt-cu12), pypi.org and pypi.nvidia.com (NVIDIA TensorRT licence terms).
* NumPy (BSD), OpenCV (opencv-python, Apache 2.0), glfw / pyGLFW (MIT, GLFW zlib), PyOpenGL (BSD),
PyAV (BSD, with FFmpeg under LGPL/GPL), ONNX (Apache 2.0), onnxscript (MIT), sounddevice (MIT, with
PortAudio under its MIT-style licence; plays a capture card's sound), ONNX Runtime with DirectML
(onnxruntime-directml, MIT, with Microsoft's DirectML library under its own licence; runs RIFE on AMD and Intel
cards), all from pypi.org, plus their dependencies.
Downloaded only if you set it up, from NVIDIA (not distributed by SmoovPlay)
-----------------------------------------------------------------------------
* NVIDIA Video Effects for Python (nvidia-vfx 0.2.0.0, for NVIDIA VFG), pypi.nvidia.com, into runtime\vfx,
after you accept NVIDIA's licence on the Settings page: the NVIDIA Software License Agreement
(https://www.nvidia.com/en-us/agreements/enterprise-software/nvidia-software-license-agreement/), the
Product-Specific Terms for NVIDIA AI Products
(https://www.nvidia.com/en-us/agreements/enterprise-software/product-specific-terms-for-ai-products/) and the
NVIDIA Open Model License
(https://www.nvidia.com/en-us/agreements/enterprise-software/nvidia-open-model-license/).
SmoovPlay isn't affiliated with or endorsed by Sony Interactive Entertainment, NVIDIA, AMD or any game
publisher. PlayStation and PS5 are trademarks of Sony Interactive Entertainment Inc.
+288
View File
@@ -0,0 +1,288 @@
"""Builds SmoovPlay.exe (the launcher) and SmoovPlay-Setup.exe (the launcher with the app and chiaki-ng inside).
.venv\\Scripts\\python installer\\build.py # both, into installer\\dist
.venv\\Scripts\\python installer\\build.py --launcher-only # just SmoovPlay.exe, for trying the launcher
The setup is signed for updates (SmoovPlay-Setup.exe.sig, which goes up to the release with it): the launcher
installs an update only if its signature checks out against the public key built into it. The private key stays on
this PC, outside the repo: %USERPROFILE%\\.smoovplay\\update-signing-key.xml (SMOOVPLAY_SIGNING_KEY overrides
it), made by the first build. Back it up: without it, installed copies can't update themselves (a new setup run by
hand still updates them).
Needs the C# compiler that ships with Visual Studio 2019+ Build Tools (Roslyn csc), the patched chiaki-ng build
(chiaki_tap/build_windows.sh output) and its source checkout (for the licence texts and the patch). The setup
contains only our code, the RIFE weights and chiaki-ng: Python, PyTorch, TensorRT and PyAV are downloaded by
setup from their official sources, so they're never redistributed.
"""
from __future__ import annotations
import argparse
import hashlib
import os
import re
import shutil
import struct
import subprocess
import sys
import urllib.request
import zipfile
from pathlib import Path
import cv2
import numpy as np
VERSION = "0.1.0" # a pre-release sorts before its release: 0.1.0-beta.2 and 0.1.0 both show as updates
# "owner/name" of the GitHub repo whose releases the launcher checks for updates; empty turns the check off
RELEASES_REPO = "smoovplay/smoovplay"
SIGNING_KEY = Path(os.environ.get("SMOOVPLAY_SIGNING_KEY") or Path.home() / ".smoovplay" / "update-signing-key.xml")
PYTHON_VERSION = "3.12.10"
PYTHON_URL = f"https://www.python.org/ftp/python/{PYTHON_VERSION}/python-{PYTHON_VERSION}-embed-amd64.zip"
# python.org lists only an MD5 for this file (fe8ef205f2e9c3ba44d0cf9954e1abd3, which matched); this is its SHA-256.
PYTHON_SHA256 = "4acbed6dd1c744b0376e3b1cf57ce906f9dc9e95e68824584c8099a63025a3c3"
TORCH_INDEX = "https://download.pytorch.org/whl/cu128"
NVIDIA_INDEX = "https://pypi.nvidia.com" # TensorRT's wheels (PyPI only has stubs that can't build here)
MODEL = "flownet_v4.22.lite.pkl"
HERE = Path(__file__).resolve().parent
ROOT = HERE.parent
BUILD = HERE / "build"
DIST = HERE / "dist"
CACHE = HERE / ".cache"
CSC_CANDIDATES = [
Path(r"C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\MSBuild\Current\Bin\Roslyn\csc.exe"),
Path(r"C:\Program Files\Microsoft Visual Studio\2022\BuildTools\MSBuild\Current\Bin\Roslyn\csc.exe"),
Path(r"C:\Program Files\Microsoft Visual Studio\2022\Community\MSBuild\Current\Bin\Roslyn\csc.exe"),
]
WPF = Path(r"C:\Windows\Microsoft.NET\Framework64\v4.0.30319\WPF")
REFS = ["System.dll", "System.Core.dll", "System.Drawing.dll", "System.Management.dll", "System.Xaml.dll",
"System.IO.Compression.dll", "System.IO.Compression.FileSystem.dll", "System.Net.Http.dll",
"System.Web.Extensions.dll", # JavaScriptSerializer, for the Settings page
str(WPF / "PresentationFramework.dll"), str(WPF / "PresentationCore.dll"), str(WPF / "WindowsBase.dll")]
def log(msg: str) -> None:
print(f"[build] {msg}", flush=True)
def python_sha256() -> str:
"""The embeddable Python's SHA-256, checked against the pinned value (setup verifies its download with it)."""
CACHE.mkdir(parents=True, exist_ok=True)
zip_path = CACHE / Path(PYTHON_URL).name
if not zip_path.exists():
log(f"downloading {PYTHON_URL}")
urllib.request.urlretrieve(PYTHON_URL, zip_path)
sha = hashlib.sha256(zip_path.read_bytes()).hexdigest()
if sha != PYTHON_SHA256:
sys.exit(f"[build] {zip_path.name} has SHA-256 {sha}, not the pinned {PYTHON_SHA256}. If python.org's "
"published hash for this file agrees, update PYTHON_SHA256 in installer/build.py.")
return sha
def write_buildinfo(sha: str, update_key: str) -> Path:
path = BUILD / "BuildInfo.cs"
path.write_text(
"// Generated by installer/build.py\n"
"namespace SmoovPlay\n{\n static class BuildInfo\n {\n"
f' public const string Version = "{VERSION}";\n'
f' public const string ReleasesRepo = "{RELEASES_REPO}";\n'
f' public const string UpdateKey = "{update_key}"; // the public key updates are signed with\n'
f' public const string PythonVersion = "{PYTHON_VERSION}";\n'
f' public const string PythonUrl = "{PYTHON_URL}";\n'
f' public const string PythonSha256 = "{sha}";\n'
f' public const string TorchIndex = "{TORCH_INDEX}";\n'
f' public const string NvidiaIndex = "{NVIDIA_INDEX}";\n'
" }\n}\n", encoding="utf-8")
return path
# ---------------------------------------------------------------------------------------------------- icon
def icon_rgba(size: int) -> np.ndarray:
"""The app icon at one size, BGRA: the plain SP up to 32 px, the full logo (a controller in the S, a play button
in the P) from 40 px. Each size is a PNG in installer/icon, rendered from docs/brand/smoovplay-icon*.svg."""
img = cv2.imread(str(HERE / "icon" / f"smoovplay-{size}.png"), cv2.IMREAD_UNCHANGED)
if img is None or img.shape != (size, size, 4):
sys.exit(f"[build] installer/icon/smoovplay-{size}.png is missing or not {size}x{size} RGBA")
return img
def write_ico(path: Path, sizes=(16, 20, 24, 32, 40, 48, 64, 96, 128, 256)) -> None:
"""Multi-size .ico: 32-bit DIBs for the small sizes (every Windows API reads those), PNG for 256."""
blobs = []
for n in sizes:
bgra = icon_rgba(n)
if n >= 256:
ok, png = cv2.imencode(".png", bgra)
assert ok
blobs.append((n, png.tobytes()))
continue
mask_row = ((n + 31) // 32) * 4
header = struct.pack("<IiiHHIIiiII", 40, n, n * 2, 1, 32, 0, n * n * 4 + mask_row * n, 0, 0, 0, 0)
pixels = bgra[::-1].tobytes() # bottom-up rows
blobs.append((n, header + pixels + bytes(mask_row * n)))
out = struct.pack("<HHH", 0, 1, len(blobs))
offset = 6 + 16 * len(blobs)
for n, data in blobs:
out += struct.pack("<BBBBHHII", n % 256, n % 256, 0, 0, 1, 32, len(data), offset)
offset += len(data)
path.write_bytes(out + b"".join(d for _, d in blobs))
# ---------------------------------------------------------------------------------------------------- compile
def csc() -> Path:
for c in CSC_CANDIDATES:
if c.exists():
return c
sys.exit("[build] no Roslyn csc.exe found; install Visual Studio Build Tools (the .NET desktop workload)")
def compile_exe(out: Path, sources: list[Path], icon: Path, resource: Path | None = None) -> None:
args = [str(csc()), "/nologo", "/target:winexe", "/optimize+", "/langversion:7.3", "/platform:anycpu",
f"/out:{out}", f"/win32icon:{icon}", f"/win32manifest:{HERE / 'launcher' / 'app.manifest'}"]
args += [f"/reference:{r}" for r in REFS]
args.append(f"/resource:{HERE / 'launcher' / 'Ui.xaml'},Ui.xaml") # the window, loaded at run time
if resource is not None:
args.append(f"/resource:{resource},payload.zip")
args += [str(s) for s in sources]
res = subprocess.run(args, capture_output=True, text=True)
if res.returncode != 0 or "warning" in res.stdout:
print(res.stdout, res.stderr)
if res.returncode != 0:
sys.exit(f"[build] compiling {out.name} failed")
log(f"{out.name}: {out.stat().st_size / 1e6:.1f} MB")
# ---------------------------------------------------------------------------------------------------- signing
def sign_tool() -> Path:
"""installer/tools/SignUpdate.exe, built with the launcher's own signature code."""
out = BUILD / "SignUpdate.exe"
args = [str(csc()), "/nologo", "/target:exe", "/optimize+", "/langversion:7.3", f"/out:{out}",
str(HERE / "tools" / "SignUpdate.cs"), str(HERE / "launcher" / "UpdateSignature.cs")]
res = subprocess.run(args, capture_output=True, text=True)
if res.returncode != 0:
print(res.stdout, res.stderr)
sys.exit("[build] compiling the signing tool failed")
return out
def update_key(tool: Path) -> str:
"""The public key updates are checked against (made, with its private half, on the first build)."""
res = subprocess.run([str(tool), "key", str(SIGNING_KEY)], capture_output=True, text=True)
if res.returncode != 0:
sys.exit(f"[build] reading the update signing key failed: {res.stderr.strip()}")
if res.stderr.strip():
log(f"{res.stderr.strip()}. Back it up: installed copies only take updates signed with it")
key = res.stdout.strip()
if not key.startswith("<RSAKeyValue>") or '"' in key:
sys.exit("[build] the update signing key doesn't look right")
return key
def sign(tool: Path, setup: Path) -> None:
res = subprocess.run([str(tool), "sign", str(SIGNING_KEY), str(setup), VERSION], capture_output=True, text=True)
if res.returncode != 0:
sys.exit(f"[build] signing {setup.name} failed: {res.stderr.strip()}")
log(f"{setup.name}.sig: signed as {VERSION}; upload it to the release with the setup")
# ---------------------------------------------------------------------------------------------------- payload
def ignore_pycache(_dir: str, names: list[str]) -> list[str]:
return [n for n in names if n == "__pycache__" or n.endswith((".pyc", ".pyo"))]
def stage_payload(stage: Path, launcher: Path, chiaki_build: Path, chiaki_src: Path) -> None:
if stage.exists():
shutil.rmtree(stage)
app = stage / "app"
app.mkdir(parents=True)
shutil.copy2(ROOT / "run.py", app)
shutil.copytree(ROOT / "framegen", app / "framegen", ignore=ignore_pycache)
(app / "models").mkdir()
model = ROOT / "models" / MODEL
if not model.exists():
sys.exit(f"[build] {model} is missing (run the pipeline once to download it)")
shutil.copy2(model, app / "models")
shutil.copy2(HERE / "requirements-runtime.txt", app)
shutil.copy2(ROOT / "LICENSE", stage / "LICENSE.txt")
shutil.copy2(HERE / "THIRD_PARTY_NOTICES.txt", stage)
shutil.copy2(launcher, stage / "SmoovPlay.exe")
# chiaki-ng: the deployed build, its licences and the source of our patch (AGPL: corresponding source).
chiaki = stage / "chiaki"
shutil.copytree(chiaki_build, chiaki)
shutil.copy2(chiaki_src / "COPYING", chiaki / "LICENSE-AGPL-3.0.txt")
lic = chiaki / "licenses"
lic.mkdir()
for f in (chiaki_src / "LICENSES").glob("*"):
shutil.copy2(f, lic)
ffmpeg = next(chiaki_src.glob("ffmpeg-*-win64-gpl-shared-*"), None)
if ffmpeg is not None and (ffmpeg / "LICENSE.txt").exists():
shutil.copy2(ffmpeg / "LICENSE.txt", lic / "FFmpeg-LICENSE.txt")
src = chiaki / "source"
src.mkdir()
for name in ("frametap.c", "frametap.h", "apply_patch.py", "build_windows.sh", "README.md"):
shutil.copy2(ROOT / "chiaki_tap" / name, src)
diff = subprocess.run(["git", "-C", str(chiaki_src), "diff"], capture_output=True, text=True, check=True).stdout
(src / "chiaki-ng-v1.10.1-frametap.patch").write_text(diff, encoding="utf-8")
tag = subprocess.run(["git", "-C", str(chiaki_src), "describe", "--tags"], capture_output=True, text=True).stdout.strip()
(src / "SOURCE.txt").write_text(
f"This chiaki-ng is upstream {tag or 'v1.10.1'} (https://github.com/streetpea/chiaki-ng) with SmoovPlay's frame "
"tap added:\n frametap.c / frametap.h the tap (copied into gui/src and gui/include)\n"
" chiaki-ng-v1.10.1-frametap.patch the changes to chiaki-ng's own files (git diff)\n"
" apply_patch.py, build_windows.sh how it's applied and built (mirrors chiaki-ng's Windows CI)\n"
"With the tap built in, chiaki-ng behaves exactly as before unless CHIAKI_FRAMETAP=1 is set.\n"
"FFmpeg is the gpl-shared build from https://github.com/streetpea/FFmpeg-Builds (its source and build "
"scripts are there).\n", encoding="utf-8")
def zip_dir(src: Path, out: Path) -> None:
with zipfile.ZipFile(out, "w", zipfile.ZIP_DEFLATED, compresslevel=6) as z:
for f in sorted(src.rglob("*")):
if f.is_file():
z.write(f, f.relative_to(src).as_posix())
log(f"payload: {sum(f.stat().st_size for f in src.rglob('*') if f.is_file()) / 1e6:.0f} MB, "
f"zipped {out.stat().st_size / 1e6:.0f} MB")
def main() -> int:
global VERSION
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--launcher-only", action="store_true", help="build only SmoovPlay.exe")
ap.add_argument("--version", default=VERSION, help=f"the version to build (default {VERSION}), e.g. 0.2.0-beta.1")
ap.add_argument("--chiaki-build", type=Path, default=os.environ.get("SMOOVPLAY_CHIAKI_BUILD"),
help="the patched chiaki-ng build folder (chiaki_tap/build_windows.sh output); "
"default: SMOOVPLAY_CHIAKI_BUILD")
ap.add_argument("--chiaki-src", type=Path, default=os.environ.get("SMOOVPLAY_CHIAKI_SRC"),
help="the chiaki-ng source checkout it was built from; default: SMOOVPLAY_CHIAKI_SRC")
a = ap.parse_args()
if not re.fullmatch(r"\d+\.\d+\.\d+(-[0-9A-Za-z.]+)?", a.version):
sys.exit(f"[build] {a.version} isn't a version like 0.2.0 or 0.2.0-beta.1")
VERSION = a.version
BUILD.mkdir(parents=True, exist_ok=True)
DIST.mkdir(parents=True, exist_ok=True)
tool = sign_tool()
sources = sorted((HERE / "launcher").glob("*.cs")) + [write_buildinfo(python_sha256(), update_key(tool))]
icon = BUILD / "smoovplay.ico"
write_ico(icon)
cv2.imwrite(str(BUILD / "icon-256.png"), icon_rgba(256))
launcher = DIST / "SmoovPlay.exe"
compile_exe(launcher, sources, icon)
if a.launcher_only:
return 0
if a.chiaki_build is None or a.chiaki_src is None:
sys.exit("[build] say where chiaki-ng is: --chiaki-build and --chiaki-src, or set SMOOVPLAY_CHIAKI_BUILD "
"and SMOOVPLAY_CHIAKI_SRC")
for p, what in ((a.chiaki_build / "chiaki.exe", "chiaki-ng build"), (a.chiaki_src / "COPYING", "chiaki-ng source")):
if not p.exists():
sys.exit(f"[build] {what} not found ({p})")
stage = BUILD / "stage"
stage_payload(stage, launcher, a.chiaki_build, a.chiaki_src)
payload = BUILD / "payload.zip"
zip_dir(stage, payload)
compile_exe(DIST / "SmoovPlay-Setup.exe", sources, icon, resource=payload)
sign(tool, DIST / "SmoovPlay-Setup.exe")
return 0
if __name__ == "__main__":
sys.exit(main())
Binary file not shown.

After

Width:  |  Height:  |  Size: 5.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 600 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 789 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 919 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.5 KiB

+274
View File
@@ -0,0 +1,274 @@
// Auto-detect, at the top of the Settings page: runs python -m framegen.autodetect (a ~10 s test of the graphics card,
// the display and what's installed; see framegen/autodetect.py) and shows what it found and what it suggests, with the
// reason for each. Apply changes the settings the same way picking them on the page does. The test needs the graphics
// card to itself, so it can't run while playing, and Play waits for it.
// Its output goes to logs\autodetect.txt (not *.log, so a diagnostics report still picks the last session's log).
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Automation;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Animation;
namespace SmoovPlay
{
partial class Ui
{
const string DetectPrefix = "[detect-result] ", DetectLine = "[detect] ";
bool detecting, detectApplied;
readonly HashSet<string> detectChanged = new HashSet<string>(); // what Apply changed, to mark them afterwards
string detectProgress, detectError;
Dictionary<string, object> detectResult;
Button detectApply;
void RunDetect()
{
if (detecting || !paths.RuntimeReady) return;
if (SessionRunning) { Toast("Stop playing first: the test needs the graphics card to itself", true); return; }
detecting = true;
detectResult = null;
detectError = null;
detectApplied = false;
detectProgress = "Starting the test";
RenderDetect();
string log = Path.Combine(paths.Logs, "autodetect.txt");
Task.Run(() =>
{
string json = null, last = null;
int rc = -1;
try
{
Directory.CreateDirectory(paths.Logs);
using (var w = new StreamWriter(log, false))
{
string args = "-m framegen.autodetect --settings \"" + Paths.SettingsFile + "\" "
+ Environment.GetEnvironmentVariable("SMOOVPLAY_DETECT_ARGS"); // testing: --timing FULL,HALF
rc = Proc.Run(Proc.Python(paths.Python, args, paths.App), line =>
{
lock (w) w.WriteLine(line);
if (line.StartsWith(DetectPrefix)) { json = line.Substring(DetectPrefix.Length); return; }
if (line.Trim().Length > 0) last = line;
if (line.StartsWith(DetectLine) && !line.Contains("ERROR"))
{
string step = line.Substring(DetectLine.Length);
OnUi(() => { if (!detecting) return; detectProgress = char.ToUpper(step[0]) + step.Substring(1); RenderDetect(); });
}
}, null);
}
}
catch (Exception e) { last = e.Message; }
OnUi(() =>
{
detecting = false;
try { if (json != null) detectResult = Json.DeserializeObject(json) as Dictionary<string, object>; }
catch (Exception e) { last = e.Message; }
if (detectResult == null)
{
string why = last != null && last.StartsWith(DetectLine) ? last.Substring(DetectLine.Length).Replace("ERROR: ", "") : last;
detectError = rc == 2 ? "PyTorch can't use an NVIDIA graphics card here. Update the NVIDIA driver (see the PC check), then try again."
: "The test didn't finish: " + Shorten(why ?? "exit code " + rc, 180) + ". Its log is " + log + ".";
Program.Trace("auto-detect: " + detectError);
}
RenderDetect();
if (page == "PageSettings") SnapLater("autodetect", 500);
});
});
}
/// <summary>A setting's value as the page shows it now: the running session's, else the file's, else the default.</summary>
object CurrentSetting(SettingSpec spec)
{
var values = liveState != null ? liveState["values"] as Dictionary<string, object> : null;
if (values != null && values.ContainsKey(spec.Key)) return values[spec.Key];
var file = ReadSettingsFile();
if (file.ContainsKey(spec.Key) && spec.Choices.Any(c => Same(c.Key, file[spec.Key]))) return file[spec.Key];
return spec.Default;
}
string ChoiceName(SettingSpec spec, object value)
{
var c = spec.Choices.FirstOrDefault(x => Same(x.Key, value));
return c.Value ?? Json.Serialize(value).Trim('"');
}
/// <summary>The suggestions that differ from the current settings, in the page's order.</summary>
List<KeyValuePair<SettingSpec, object>> DetectChanges()
{
var list = new List<KeyValuePair<SettingSpec, object>>();
var suggested = detectResult != null ? detectResult["settings"] as Dictionary<string, object> : null;
if (suggested == null || settingSpecs == null) return list;
foreach (var spec in settingSpecs)
if (suggested.ContainsKey(spec.Key) && !Same(CurrentSetting(spec), suggested[spec.Key]))
list.Add(new KeyValuePair<SettingSpec, object>(spec, spec.Choices.First(c => Same(c.Key, suggested[spec.Key])).Key));
return list;
}
void ApplyDetect()
{
var changes = DetectChanges();
detectChanged.Clear();
foreach (var c in changes) { ChangeSetting(c.Key, c.Value); detectChanged.Add(c.Key.Key); }
detectApplied = true;
RenderDetect();
if (page == "PageSettings") SnapLater("autodetect-applied", 500);
Toast(changes.Count == 1 ? "1 setting changed" : changes.Count + " settings changed", false);
}
void DismissDetect()
{
detectResult = null;
detectError = null;
detectApplied = false;
RenderDetect();
}
/// <summary>The button: off while playing (the test would slow the video and measure wrong) or testing.</summary>
void UpdateDetect()
{
var b = B("BtnDetect");
bool can = paths.RuntimeReady && settingSpecs != null && !SessionRunning && !detecting;
b.IsEnabled = can;
b.Content = detecting ? "Testing..." : detectResult != null || detectError != null ? "Run again" : "Auto-detect";
b.ToolTip = SessionRunning ? "Stop playing first: the test needs the graphics card to itself."
: !paths.RuntimeReady ? "Finish setting up SmoovPlay first." : null;
if (detectApply != null) detectApply.IsEnabled = !(SessionRunning && liveState == null); // starting: settings are locked
}
void RenderDetect()
{
var body = E<StackPanel>("DetectBody");
body.Children.Clear();
detectApply = null;
if (detecting) body.Children.Add(DetectRunning());
else if (detectError != null)
body.Children.Add(new TextBlock { Style = S("Small"), Foreground = R("Bad"), Text = detectError });
else if (detectResult != null) DetectResults(body);
Show(body, body.Children.Count > 0);
UpdateDetect();
}
FrameworkElement DetectRunning()
{
var sp = new StackPanel();
var track = new Border { Height = 3, Width = 260, CornerRadius = new CornerRadius(1.5), Background = R("Line2"), HorizontalAlignment = HorizontalAlignment.Left, ClipToBounds = true };
var move = new TranslateTransform();
track.Child = new Border { Width = 80, CornerRadius = new CornerRadius(1.5), Background = R("Accent"), HorizontalAlignment = HorizontalAlignment.Left, RenderTransform = move };
move.BeginAnimation(TranslateTransform.XProperty, new DoubleAnimation(-80, 260, TimeSpan.FromSeconds(1.4)) { RepeatBehavior = RepeatBehavior.Forever });
sp.Children.Add(track);
var t = new TextBlock { Style = S("Small"), Text = detectProgress + "...", Margin = new Thickness(0, 9, 0, 0) };
AutomationProperties.SetAutomationId(t, "DetectProgress");
sp.Children.Add(t);
return sp;
}
void DetectResults(StackPanel body)
{
body.Children.Add(Overline("FOUND ON THIS PC", 0));
var found = new Grid();
found.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(118) });
found.ColumnDefinitions.Add(new ColumnDefinition());
foreach (Dictionary<string, object> f in (detectResult["found"] as object[]) ?? new object[0])
{
found.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });
int r = found.RowDefinitions.Count - 1;
var label = new TextBlock { Text = (string)f["label"], FontSize = 12.5, Foreground = R("Muted"), Margin = new Thickness(0, 0, 0, 5) };
var value = new TextBlock { FontSize = 12.5, TextWrapping = TextWrapping.Wrap, Margin = new Thickness(0, 0, 0, 5) };
value.Inlines.Add(new System.Windows.Documents.Run((string)f["value"]));
string detail = f["detail"] as string;
if (!string.IsNullOrEmpty(detail)) value.Inlines.Add(new System.Windows.Documents.Run(" · " + detail) { Foreground = R("Text2") });
Grid.SetRow(label, r); Grid.SetRow(value, r); Grid.SetColumn(value, 1);
found.Children.Add(label);
found.Children.Add(value);
}
body.Children.Add(found);
var suggested = detectResult["settings"] as Dictionary<string, object> ?? new Dictionary<string, object>();
var reasons = detectResult["reasons"] as Dictionary<string, object> ?? new Dictionary<string, object>();
var changes = DetectChanges();
body.Children.Add(Overline(detectApplied ? "APPLIED" : "SUGGESTED", 14));
foreach (var spec in (settingSpecs ?? new List<SettingSpec>()).Where(s => suggested.ContainsKey(s.Key)))
{
var change = changes.FirstOrDefault(c => c.Key == spec);
var row = new Grid { Margin = new Thickness(0, 0, 0, 10) };
row.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(150) });
row.ColumnDefinitions.Add(new ColumnDefinition());
row.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });
row.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });
row.Children.Add(new TextBlock { Text = spec.Label, FontSize = 13, FontWeight = FontWeights.SemiBold });
var value = new TextBlock { FontSize = 13 };
if (change.Key != null)
{
value.Inlines.Add(new System.Windows.Documents.Run(ChoiceName(spec, CurrentSetting(spec))) { Foreground = R("Muted"), TextDecorations = TextDecorations.Strikethrough });
value.Inlines.Add(new System.Windows.Documents.Run(" → ") { Foreground = R("Muted") });
value.Inlines.Add(new System.Windows.Documents.Run(ChoiceName(spec, change.Value)) { Foreground = R("Accent"), FontWeight = FontWeights.SemiBold });
}
else
{
value.Inlines.Add(new System.Windows.Documents.Run(ChoiceName(spec, suggested[spec.Key])));
bool changed = detectApplied && detectChanged.Contains(spec.Key);
value.Inlines.Add(new System.Windows.Documents.Run(changed ? " changed" : " already set") { Foreground = R(changed ? "Good" : "Muted"), FontSize = 12 });
}
AutomationProperties.SetAutomationId(value, "Detect_" + spec.Key);
Grid.SetColumn(value, 1);
row.Children.Add(value);
if (reasons.ContainsKey(spec.Key))
{
var why = new TextBlock { Style = S("Small"), Text = (string)reasons[spec.Key], Margin = new Thickness(0, 3, 0, 0) };
Grid.SetRow(why, 1); Grid.SetColumnSpan(why, 2);
row.Children.Add(why);
}
body.Children.Add(row);
}
foreach (string note in (detectResult["notes"] as object[]) ?? new object[0])
{
var g = new Grid { Margin = new Thickness(0, 2, 0, 8) };
g.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto });
g.ColumnDefinitions.Add(new ColumnDefinition());
g.Children.Add(new TextBlock { Style = S("Icon"), Text = "", FontSize = 13, Foreground = R("Warn"), VerticalAlignment = VerticalAlignment.Top, Margin = new Thickness(0, 2, 9, 0) });
var t = new TextBlock { Style = S("Small"), Foreground = R("Text"), Text = note };
Grid.SetColumn(t, 1);
g.Children.Add(t);
body.Children.Add(g);
}
var buttons = new StackPanel { Orientation = Orientation.Horizontal, Margin = new Thickness(0, 8, 0, 0) };
if (detectApplied)
{
buttons.Children.Add(new TextBlock { Style = S("Icon"), Text = "", FontSize = 13, Foreground = R("Good"), Margin = new Thickness(0, 0, 8, 0) });
buttons.Children.Add(new TextBlock { Style = S("Small"), Foreground = R("Text"), VerticalAlignment = VerticalAlignment.Center, Text = "Done. Fine-tune anything below; Auto-detect won't change it again unless you run it." });
buttons.Children.Add(DetectButton("BtnDetectDismiss", "Ghost", "Hide", DismissDetect, new Thickness(12, 0, 0, 0)));
}
else if (changes.Count == 0)
{
buttons.Children.Add(new TextBlock { Style = S("Small"), Foreground = R("Text"), VerticalAlignment = VerticalAlignment.Center, Text = "Your settings already match this PC." });
buttons.Children.Add(DetectButton("BtnDetectDismiss", "Ghost", "Hide", DismissDetect, new Thickness(12, 0, 0, 0)));
}
else
{
detectApply = DetectButton("BtnDetectApply", "Primary", changes.Count == 1 ? "Apply this change" : "Apply " + changes.Count + " changes", ApplyDetect, new Thickness(0));
buttons.Children.Add(detectApply);
buttons.Children.Add(DetectButton("BtnDetectDismiss", "Ghost", "Not now", DismissDetect, new Thickness(8, 0, 0, 0)));
}
body.Children.Add(buttons);
}
TextBlock Overline(string text, double top)
{
return new TextBlock { Text = text, FontSize = 11, FontWeight = FontWeights.SemiBold, Foreground = R("Muted"), Margin = new Thickness(0, top, 0, 8) };
}
Button DetectButton(string id, string style, string text, Action click, Thickness margin)
{
var b = new Button { Style = S(style), Content = text, Height = 34, Padding = new Thickness(14, 0, 14, 0), Margin = margin };
AutomationProperties.SetAutomationId(b, id);
b.Click += (s, e) => click();
return b;
}
}
}
Loaded 100 of 158 files, more files were not shown because too many files have changed in this diff. Show more