Compare commits

..
1 Commits
Author SHA1 Message Date
Cameron Gutman b23a36908c Add EGLFS GBM and Wayland support to AppImage 2022-04-09 18:23:09 -05:00
275 changed files with 16488 additions and 48382 deletions
+3 -4
View File
@@ -37,13 +37,12 @@ List the games you've tried that exhibit the issue. To see if the issue is game-
- OS: [e.g. Windows 10 1809]
- Moonlight Version: [e.g. v0.9.0]
- GPU: [e.g. Intel HD Graphics 520]
- Linux package type (if applicable): [e.g. Flatpak]
**Server PC details (please complete the following information)**
- OS: [e.g. Windows 10 1809]
- Sunshine or GeForce Experience version: [e.g. Sunshine v0.21.0]
- GPU: [e.g. AMD Radeon RX 7900 XT]
- GPU driver: [e.g. 24.1.1]
- GeForce Experience version: [e.g. 3.16.0.140]
- Nvidia GPU driver: [e.g. 417.35]
- Antivirus and firewall software: [e.g. Windows Defender and Windows Firewall]
**Moonlight Logs (please attach)**
- On Windows, `Moonlight-###.log` files can be found in `%TEMP%`. Simply type that into the File Explorer path field to navigate there.
-9
View File
@@ -1,9 +0,0 @@
# Please see the documentation for all configuration options:
# https://docs.github.com/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file
version: 2
updates:
- package-ecosystem: "gitsubmodule"
directory: "/"
schedule:
interval: "daily"
-165
View File
@@ -1,165 +0,0 @@
---
name: Build - Linux AppImage
permissions:
contents: read
on:
workflow_call:
inputs:
ci_version:
required: true
type: string
jobs:
build:
env:
CI_VERSION: ${{ inputs.ci_version }}
runs-on: ubuntu-22.04
steps:
- name: Checkout Repository
uses: actions/checkout@v5
with:
submodules: 'recursive'
fetch-depth: 1
- name: Setup environment
run: |
wget -qO - https://packages.lunarg.com/lunarg-signing-key-pub.asc | sudo apt-key add -
sudo wget -qO /etc/apt/sources.list.d/lunarg-vulkan-1.4.313-jammy.list https://packages.lunarg.com/vulkan/1.4.313/lunarg-vulkan-1.4.313-jammy.list
sudo apt update
sudo apt install -y qt6-base-dev qt6-declarative-dev libqt6svg6-dev qml6-module-qtquick-controls qml6-module-qtquick-templates qml6-module-qtquick-layouts \
qml6-module-qtqml-workerscript qml6-module-qtquick-window qml6-module-qtquick python3-pip nasm libgbm-dev libdrm-dev libfreetype-dev libasound2-dev \
libdbus-1-dev libegl1-mesa-dev libgl1-mesa-dev libgles2-mesa-dev libglu1-mesa-dev libibus-1.0-dev libpulse-dev libudev-dev libx11-dev libxcursor-dev \
libxext-dev libxi-dev libxinerama-dev libxkbcommon-dev libxrandr-dev libxss-dev libxt-dev libxv-dev libxxf86vm-dev libxcb-dri3-dev libx11-xcb-dev \
libxfixes-dev libxtst-dev wayland-protocols libopus-dev libvdpau-dev libgl-dev libpipewire-0.3-dev liburing-dev vulkan-sdk cmake
sudo pip3 install meson
mkdir -p dep_root/{bin,include,lib}
echo "DEP_ROOT=$PWD/dep_root" >> "${GITHUB_ENV}"
echo "$PWD/dep_root/bin" >> "${GITHUB_PATH}"
- name: Checkout SDL3
uses: actions/checkout@v5
with:
repository: libsdl-org/SDL
ref: a5e02a0927a2dd999718c1903f2d59440319ca99
path: deps/SDL
- name: Build SDL3
working-directory: deps/SDL
run: |
cmake -DSDL_KMSDRM=OFF -DSDL_TEST_LIBRARY=OFF -DSDL_INSTALL_DOCS=OFF -DCMAKE_INTERPROCEDURAL_OPTIMIZATION=ON -S . -B build
cmake --build build -j
sudo cmake --install build
- name: Checkout sdl2-compat
uses: actions/checkout@v5
with:
repository: libsdl-org/sdl2-compat
ref: release-2.32.70
path: deps/sdl2-compat
- name: Build sdl2-compat
working-directory: deps/sdl2-compat
run: |
cmake -DSDL2COMPAT_TESTS=OFF -DCMAKE_INTERPROCEDURAL_OPTIMIZATION=ON -S . -B build
cmake --build build -j
sudo cmake --install build
- name: Checkout SDL_ttf
uses: actions/checkout@v5
with:
repository: libsdl-org/SDL_ttf
ref: a883e490e30fb44a5336ea3dcb990c6982c5216f
path: deps/SDL_ttf
submodules: 'recursive'
- name: Build SDL_ttf
working-directory: deps/SDL_ttf
run: |
./autogen.sh
./configure
make -j$(nproc)
sudo make install
- name: Checkout libva
uses: actions/checkout@v5
with:
repository: intel/libva
ref: 2.23.0
path: deps/libva
- name: Build libva
working-directory: deps/libva
run: |
./autogen.sh
./configure --enable-x11
make -j$(nproc)
sudo make install
- name: Checkout libplacebo
uses: actions/checkout@v5
with:
repository: haasn/libplacebo
ref: 2d0979fb54e025e904c7372666fffbf5dae40f66
path: deps/libplacebo
submodules: 'recursive'
- name: Build libplacebo
working-directory: deps/libplacebo
run: |
meson setup build -Dvulkan=enabled -Dopengl=disabled -Ddemos=false
ninja -C build
sudo ninja install -C build
- name: Build dav1d
working-directory: deps
env:
DAV1D_VER: 1.5.3
run: |
git clone --branch $DAV1D_VER --depth 1 https://code.videolan.org/videolan/dav1d.git
pushd dav1d
meson setup build -Ddefault_library=static -Dbuildtype=release -Denable_tools=false -Denable_tests=false
ninja -C build
sudo ninja install -C build
popd
- name: Checkout FFmpeg
uses: actions/checkout@v5
with:
repository: FFmpeg/FFmpeg
ref: n8.1.1
path: deps/FFmpeg
- name: Build FFmpeg
working-directory: deps/FFmpeg
run: |
./configure --enable-pic --enable-lto --disable-static --enable-shared --disable-all --disable-autodetect \
--enable-avcodec --enable-avformat --enable-swscale \
--enable-decoder=h264 --enable-decoder=hevc --enable-decoder=av1 \
--enable-vaapi --enable-hwaccel=h264_vaapi --enable-hwaccel=hevc_vaapi --enable-hwaccel=av1_vaapi \
--enable-vdpau --enable-hwaccel=h264_vdpau --enable-hwaccel=hevc_vdpau --enable-hwaccel=av1_vdpau \
--enable-libdrm --enable-vulkan --enable-hwaccel=h264_vulkan --enable-hwaccel=hevc_vulkan --enable-hwaccel=av1_vulkan \
--enable-libdav1d --enable-decoder=libdav1d
make -j$(nproc)
sudo make install
- name: Install linuxdeploy
working-directory: dep_root/bin
run: |
wget https://github.com/linuxdeploy/linuxdeploy/releases/download/continuous/linuxdeploy-x86_64.AppImage
wget https://github.com/linuxdeploy/linuxdeploy-plugin-qt/releases/download/continuous/linuxdeploy-plugin-qt-x86_64.AppImage
chmod +x linuxdeploy*.AppImage
- name: Build Binaries
run: |
sudo ldconfig
scripts/build-appimage.sh
- name: Upload Binaries
uses: actions/upload-artifact@v6
with:
name: Moonlight-LinuxAppImage-${{ env.CI_VERSION }}
path: build/installer-release/Moonlight-${{ env.CI_VERSION }}-x86_64.AppImage
compression-level: 0
if-no-files-found: error
-41
View File
@@ -1,41 +0,0 @@
---
name: Build - Steam Link
permissions:
contents: read
on:
workflow_call:
inputs:
ci_version:
required: true
type: string
jobs:
build:
env:
CI_VERSION: ${{ inputs.ci_version }}
runs-on: ubuntu-22.04
steps:
- name: Checkout Repository
uses: actions/checkout@v5
with:
submodules: 'recursive'
fetch-depth: 1
- name: Checkout Steam Link SDK
uses: actions/checkout@v5
with:
repository: ValveSoftware/steamlink-sdk
path: steamlink-sdk
fetch-depth: 1
- name: Build binaries
run: STEAMLINK_SDK_PATH=$PWD/steamlink-sdk scripts/build-steamlink-app.sh
- name: Upload Binaries
uses: actions/upload-artifact@v6
with:
name: Moonlight-SteamLink-${{ env.CI_VERSION }}
path: build/deploy-release/*
if-no-files-found: error
-125
View File
@@ -1,125 +0,0 @@
---
name: Build - Windows and macOS
permissions:
contents: read
on:
workflow_call:
inputs:
ci_version:
required: true
type: string
jobs:
build:
env:
CI_VERSION: ${{ inputs.ci_version }}
strategy:
fail-fast: false
matrix:
include:
# Windows
- os: windows-2025
qt_version: 6.11.1
# macOS
- os: macos-26
qt_version: 6.11.1
runs-on: ${{ matrix.os }}
steps:
- name: Checkout Repository
uses: actions/checkout@v5
with:
submodules: 'recursive'
fetch-depth: 1
- name: Download dependencies (Windows)
if: runner.os == 'Windows'
run: powershell ./setup-deps.ps1
- name: Install create-dmg (macOS)
if: runner.os == 'macOS'
run: |
brew install node
npm install --global create-dmg
- name: Install Qt
uses: jurplel/install-qt-action@v4
with:
cache: true
set-env: ${{ runner.os != 'Windows' }}
add-tools-to-path: ${{ runner.os != 'Windows' }}
version: ${{ matrix.qt_version }}
aqtsource: 'git+https://github.com/miurahr/aqtinstall.git@073e34d7c2ab4ae6961ed7cca690b3abd5ba5a7e'
- name: Install Qt ARM64 (Windows)
if: runner.os == 'Windows'
uses: jurplel/install-qt-action@v4
with:
cache: true
set-env: false
add-tools-to-path: false
arch: win64_msvc2022_arm64_cross_compiled
version: ${{ matrix.qt_version }}
- name: Build x64 binaries (Windows)
if: runner.os == 'Windows'
shell: cmd
run: |
set "PATH=%QT_PATH%;%PATH%"
scripts\build-arch.bat Release x64
env:
QT_PATH: ${{ runner.workspace }}\Qt\${{ matrix.qt_version }}\msvc2022_64\bin
- name: Build ARM64 binaries (Windows)
if: runner.os == 'Windows'
shell: cmd
run: |
set "PATH=%QT_PATH%;%PATH%"
scripts\build-arch.bat Release arm64
env:
QT_PATH: ${{ runner.workspace }}\Qt\${{ matrix.qt_version }}\msvc2022_arm64\bin
- name: Build Package
shell: pwsh
run: |
if ($Env:RUNNER_OS -eq "Windows") {
cmd /c scripts\generate-bundle.bat Release
} else {
bash scripts/generate-dmg.sh Release
}
- name: Upload Binaries (Windows x64)
uses: actions/upload-artifact@v6
if: runner.os == 'Windows'
with:
name: Moonlight-${{ runner.os }}-x64-${{ env.CI_VERSION }}
path: build/deploy-x64-release/*
if-no-files-found: error
- name: Upload Binaries (Windows arm64)
uses: actions/upload-artifact@v6
if: runner.os == 'Windows'
with:
name: Moonlight-${{ runner.os }}-arm64-${{ env.CI_VERSION }}
path: build/deploy-arm64-release/*
if-no-files-found: error
- name: Upload Binaries (macOS)
uses: actions/upload-artifact@v6
if: runner.os == 'macOS'
with:
name: Moonlight-${{ runner.os }}-${{ env.CI_VERSION }}
path: build/installer-Release/*.dmg
compression-level: 0
if-no-files-found: error
- name: Upload Symbols
uses: actions/upload-artifact@v6
with:
name: zDevDbgSyms-${{ runner.os }}-${{ env.CI_VERSION }}
path: |
build/installer-*/*.dsym/*
build/symbols-*/*.pdb
if-no-files-found: error
-45
View File
@@ -1,45 +0,0 @@
---
name: Build
permissions:
contents: read
on:
push:
pull_request:
branches:
- master
concurrency:
group: build-${{ github.ref }}
cancel-in-progress: true
jobs:
setup:
runs-on: ubuntu-latest
outputs:
ci_version: ${{ steps.set-ci-version.outputs.ci_version }}
steps:
- name: Set CI version
id: set-ci-version
shell: bash
run: |
CI_VERSION=`echo ${GITHUB_SHA} | cut -c1-6`
echo "ci_version=${CI_VERSION}" >> "${GITHUB_OUTPUT}"
build-appimage:
needs: setup
uses: ./.github/workflows/build-appimage.yml
with:
ci_version: ${{ needs.setup.outputs.ci_version }}
build-steamlink:
needs: setup
uses: ./.github/workflows/build-steamlink.yml
with:
ci_version: ${{ needs.setup.outputs.ci_version }}
build-windows-macos:
needs: setup
uses: ./.github/workflows/build-win-mac.yml
with:
ci_version: ${{ needs.setup.outputs.ci_version }}
-2
View File
@@ -2,8 +2,6 @@
**/.vs/
.vscode/
build/
libs/
config.tests/*/.qmake.stash
config.tests/*/Makefile
+7
View File
@@ -7,6 +7,13 @@
[submodule "app/SDL_GameControllerDB"]
path = app/SDL_GameControllerDB
url = https://github.com/gabomdq/SDL_GameControllerDB.git
[submodule "soundio/libsoundio"]
path = soundio/libsoundio
url = https://github.com/cgutman/libsoundio.git
[submodule "h264bitstream/h264bitstream"]
path = h264bitstream/h264bitstream
url = https://github.com/aizvorski/h264bitstream.git
[submodule "libs"]
path = libs
url = https://github.com/cgutman/moonlight-qt-prebuilts.git
shallow = true
+11 -22
View File
@@ -158,6 +158,17 @@ private:
L"EZFRD32.dll",
L"EZFRD64.dll",
// These are the newer dList DLLs for Optimus hybrid graphics DDI.
// https://docs.microsoft.com/en-us/windows-hardware/drivers/display/hybrid-system-ddi
//
// We forcefully block them from loading because Optimus has a bug that
// deadlocks DXVA2 when we present with D3DPRESENT_DONOTWAIT. This will prevent
// Optimus from ever using the dGPU even if the user has requested it.
// https://github.com/moonlight-stream/moonlight-qt/issues/240
// https://github.com/moonlight-stream/moonlight-qt/issues/235
L"nvdlist.dll",
L"nvdlistx.dll",
// These are the older dList/AppInit DLLs for Optimus hybrid graphics DDI.
// https://docs.microsoft.com/en-us/windows-hardware/drivers/display/hybrid-system-ddi
//
@@ -207,28 +218,6 @@ private:
// Since the RTSS OSD doesn't even work with DXVA2, we'll just block the hooks entirely.
L"RTSSHooks.dll",
L"RTSSHooks64.dll",
// Bandicam's Vulkan layer DLL crashes during destruction of the Vulkan swapchain
// bdcamvk64+0x10b73:
// 00007ffa`be3b0b73 498b5630 mov rdx,qword ptr [r14+30h] ds:00000000`00000030=????????????????
//
// bdcamvk64+0x10b73
// libplacebo_357!vk_sw_destroy+0x14f [D:\a\moonlight-deps\moonlight-deps\libplacebo\src\vulkan\swapchain.c @ 460]
// libplacebo_357!pl_swapchain_destroy+0x1a [D:\a\moonlight-deps\moonlight-deps\libplacebo\src\swapchain.c @ 30]
// Moonlight!PlVkRenderer::~PlVkRenderer+0x159 [D:\a\moonlight-qt\app\streaming\video\ffmpeg-renderers\plvk.cpp @ 140]
// Moonlight!PlVkRenderer::`scalar deleting destructor'+0x17
// Moonlight!FFmpegVideoDecoder::reset+0x203 [D:\a\moonlight-qt\app\streaming\video\ffmpeg.cpp @ 301]
// Moonlight!FFmpegVideoDecoder::~FFmpegVideoDecoder+0x22 [D:\a\moonlight-qt\app\streaming\video\ffmpeg.cpp @ 257]
// Moonlight!FFmpegVideoDecoder::`scalar deleting destructor'+0x17
// Moonlight!Session::getDecoderInfo+0x19a [D:\a\moonlight-qt\app\streaming\session.cpp @ 415]
// Moonlight!SystemProperties::querySdlVideoInfoInternal+0x134 [D:\a\moonlight-qt\app\backend\systemproperties.cpp @ 161]
// Moonlight!SystemProperties::querySdlVideoInfo+0x97 [D:\a\moonlight-qt\app\backend\systemproperties.cpp @ 123]
// Moonlight!SystemProperties::SystemProperties+0x4bf [D:\a\moonlight-qt\app\backend\systemproperties.cpp @ 75]
//
// https://github.com/moonlight-stream/moonlight-qt/issues/1425
// https://github.com/moonlight-stream/moonlight-qt/issues/1579
L"bdcamvk32.dll",
L"bdcamvk64.dll",
};
};
+27 -54
View File
@@ -1,110 +1,83 @@
# Moonlight PC
[Moonlight PC](https://moonlight-stream.org) is an open source PC client for NVIDIA GameStream and [Sunshine](https://github.com/LizardByte/Sunshine).
[Moonlight PC](https://moonlight-stream.org) is an open source PC client for NVIDIA GameStream, as used by the NVIDIA Shield.
Moonlight also has mobile versions for [Android](https://github.com/moonlight-stream/moonlight-android) and [iOS](https://github.com/moonlight-stream/moonlight-ios).
You can follow development on our [Discord server](https://moonlight-stream.org/discord) and help translate Moonlight into your language on [Weblate](https://hosted.weblate.org/projects/moonlight/moonlight-qt/).
[![Build](https://img.shields.io/github/actions/workflow/status/moonlight-stream/moonlight-qt/build.yml?branch=master)](https://github.com/moonlight-stream/moonlight-qt/actions/workflows/build.yml?query=branch%3Amaster)
[![AppVeyor Build Status](https://ci.appveyor.com/api/projects/status/glj5cxqwy2w3bglv/branch/master?svg=true)](https://ci.appveyor.com/project/cgutman/moonlight-qt/branch/master)
[![Downloads](https://img.shields.io/github/downloads/moonlight-stream/moonlight-qt/total)](https://github.com/moonlight-stream/moonlight-qt/releases)
[![Translation Status](https://hosted.weblate.org/widgets/moonlight/-/moonlight-qt/svg-badge.svg)](https://hosted.weblate.org/projects/moonlight/moonlight-qt/)
## Features
- Hardware accelerated video decoding on Windows, Mac, and Linux
- H.264, HEVC, and AV1 codec support (AV1 requires Sunshine and a supported host GPU)
- YUV 4:4:4 support (Sunshine only)
- Supports streaming at up to 120 FPS (high refresh rate monitor recommended)
- Supports streaming at 720p, 1080p, 1440p, 4K, and the client PC's native screen resolution
- HDR streaming support
- 7.1 surround sound audio support
- 10-point multitouch support (Sunshine only)
- Gamepad support with force feedback and motion controls for up to 16 players
- Support for both pointer capture (for games) and direct mouse control (for remote desktop)
- Support for passing system-wide keyboard shortcuts like Alt+Tab to the host
- Direct touchscreen mouse control
- HEVC support for better image quality at reduced bandwidth
- Gamepad support with force feedback for up to 4 players
## Downloads
- [Windows, macOS, and Steam Link](https://github.com/moonlight-stream/moonlight-qt/releases)
- [Snap (for Ubuntu-based Linux distros)](https://snapcraft.io/moonlight)
- [Flatpak (for other Linux distros)](https://flathub.org/apps/details/com.moonlight_stream.Moonlight)
- [AppImage](https://github.com/moonlight-stream/moonlight-qt/releases)
- [Raspberry Pi 4 and 5](https://github.com/moonlight-stream/moonlight-docs/wiki/Installing-Moonlight-Qt-on-Raspberry-Pi-4)
- [Generic ARM 32-bit and 64-bit Debian packages](https://github.com/moonlight-stream/moonlight-docs/wiki/Installing-Moonlight-Qt-on-ARM%E2%80%90based-Single-Board-Computers) (not for Raspberry Pi)
- [Experimental RISC-V Debian packages](https://github.com/moonlight-stream/moonlight-docs/wiki/Installing-Moonlight-Qt-on-RISC%E2%80%90V-Single-Board-Computers)
- [Raspberry Pi 4](https://github.com/moonlight-stream/moonlight-docs/wiki/Installing-Moonlight-Qt-on-Raspberry-Pi-4)
- [NVIDIA Jetson and Nintendo Switch (Ubuntu L4T)](https://github.com/moonlight-stream/moonlight-docs/wiki/Installing-Moonlight-Qt-on-Linux4Tegra-(L4T)-Ubuntu)
### Nightly Builds
- [Downloads](https://nightly.link/moonlight-stream/moonlight-qt/workflows/build/master)
#### Special Thanks
[![Hosted By: Cloudsmith](https://img.shields.io/badge/OSS%20hosting%20by-cloudsmith-blue?logo=cloudsmith&style=flat-square)](https://cloudsmith.com)
Hosting for Moonlight's Debian and L4T package repositories is graciously provided for free by [Cloudsmith](https://cloudsmith.com).
Hosting for Moonlight's Raspberry Pi and L4T package repositories is graciously provided for free by [Cloudsmith](https://cloudsmith.com).
## Building
### Windows Build Requirements
* Qt 6.7 SDK or later (earlier versions may work but are not officially supported)
* [Visual Studio 2022](https://visualstudio.microsoft.com/downloads/) (Community edition is fine)
* Select **MSVC** option during Qt installation. MinGW is not supported.
* Qt 5.15 SDK or later
* Windows 7 or later
* [Visual Studio 2019](https://visualstudio.microsoft.com/downloads/) (Community edition is fine)
* Select **MSVC 2019** option during Qt installation. MinGW is not supported.
* [7-Zip](https://www.7-zip.org/) (only if building installers for non-development PCs)
* Graphics Tools (only if running debug builds)
* Install "Graphics Tools" in the Optional Features page of the Windows Settings app.
* Alternatively, run `dism /online /add-capability /capabilityname:Tools.Graphics.DirectX~~~~0.0.1.0` and reboot.
* [WiX Toolset](https://wixtoolset.org/releases/v3-14-0-5722/) v3.14.0.5722 or later (only if building installers for non-development PCs)
### macOS Build Requirements
* Qt 6.7 SDK or later (earlier versions may work but are not officially supported)
* Xcode 14 or later (earlier versions may work but are not officially supported)
* Qt 6.2 SDK or later
* macOS Mojave (10.14) or later
* Xcode 13
* [create-dmg](https://github.com/sindresorhus/create-dmg) (only if building DMGs for use on non-development Macs)
### Linux/Unix Build Requirements
* Qt 6 is recommended, but Qt 5.12 or later is also supported (replace `qmake6` with `qmake` when using Qt 5).
* Qt 5.9 SDK or later
* GCC or Clang
* FFmpeg 4.0 or later
* Install the required packages:
* Debian/Ubuntu:
* Base Requirements: `libegl1-mesa-dev libgl1-mesa-dev libopus-dev libsdl2-dev libsdl2-ttf-dev libssl-dev libavcodec-dev libavformat-dev libswscale-dev libva-dev libvdpau-dev libxkbcommon-dev wayland-protocols libdrm-dev`
* Qt 6 (Recommended): `qt6-base-dev qt6-declarative-dev libqt6svg6-dev qt6-wayland qml6-module-qtquick-controls qml6-module-qtquick-templates qml6-module-qtquick-layouts qml6-module-qtqml-workerscript qml6-module-qtquick-window qml6-module-qtquick`
* Qt 5: `qtbase5-dev qt5-qmake qtdeclarative5-dev qtquickcontrols2-5-dev qml-module-qtquick-controls2 qml-module-qtquick-layouts qml-module-qtquick-window2 qml-module-qtquick2 qtwayland5`
* RedHat/Fedora (RPM Fusion repo required):
* Base Requirements: `openssl-devel SDL2-devel SDL2_ttf-devel ffmpeg-devel libva-devel libvdpau-devel opus-devel pulseaudio-libs-devel alsa-lib-devel libdrm-devel`
* Qt 6 (Recommended): `qt6-qtsvg-devel qt6-qtdeclarative-devel`
* Qt 5: `qt5-qtsvg-devel qt5-qtquickcontrols2-devel`
* Building the Vulkan renderer requires a `libplacebo-dev`/`libplacebo-devel` version of at least v7.349.0 and FFmpeg 6.1 or later.
* Debian/Ubuntu: `libegl1-mesa-dev libgl1-mesa-dev libopus-dev libqt5svg5-dev libsdl2-dev libsdl2-ttf-dev libssl-dev libavcodec-dev libva-dev libvdpau-dev libxkbcommon-dev qt5-default qt5-qmake qtbase5-dev qtdeclarative5-dev qtquickcontrols2-5-dev wayland-protocols qml-module-qtquick-controls2 qml-module-qtquick-layouts qml-module-qtquick-window2 qml-module-qtquick2`
* RedHat/Fedora: `openssl-devel SDL2-devel SDL2_ttf-devel ffmpeg-devel qt5-qtsvg-devel qt5-qtquickcontrols2-devel libva-devel libvdpau-devel opus-devel pulseaudio-libs-devel alsa-lib-devel`
* FFmpeg 4.0+ is required to build. If your distro doesn't package FFmpeg 4.0 or later, you can build and install it from source on https://ffmpeg.org/
### Steam Link Build Requirements
* [Steam Link SDK](https://github.com/ValveSoftware/steamlink-sdk) cloned on your build system
* STEAMLINK_SDK_PATH environment variable set to the Steam Link SDK path
**Steam Link Hardware Limitations**
Moonlight builds for Steam Link are subject to hardware limitations of the Steam Link device:
* Maximum resolution: **1080p (1920x1080)**
* Maximum framerate: **60 FPS**
* Maximum video bitrate: **40 Mbps**
* **HDR streaming is not supported** on the original hardware
### Docker containers
If you want to use Docker for building, look at [this repo](https://github.com/cgutman/moonlight-packaging) containing canonical containers
for different architectures, which handle building deps and extra linking for you.
### Build Setup Steps
1. Install the latest Qt SDK (and optionally, the Qt Creator IDE) from https://www.qt.io/download
* You can install Qt via Homebrew on macOS, but you will need to use `brew install qt --with-debug` to be able to create debug builds of Moonlight.
* You may also use your Linux distro's package manager for the Qt SDK as long as the packages are Qt 5.12 or later.
* This step is not required for building on Steam Link, because the Steam Link SDK includes Qt 5.14.
2. Download submodules and dependencies
* Run `git submodule update --init --recursive` from within `moonlight-qt/`.
* On Windows and macOS, you must also run `setup-deps.ps1` (Windows) or `setup-deps.py` (macOS).
* Perform these steps each time you pull new changes from the Git repository.
* You may also use your Linux distro's package manager for the Qt SDK as long as the packages are Qt 5.9 or later.
* This step is not required for building on Steam Link, because the Steam Link SDK includes Qt 5.9.
2. Run `git submodule update --init --recursive` from within `moonlight-qt/`
3. Open the project in Qt Creator or build from qmake on the command line.
* To build a binary for use on non-development machines, use the scripts in the `scripts` folder.
* For Windows builds, use `scripts\build-arch.bat` and `scripts\generate-bundle.bat`. Execute these scripts from the root of the repository within a Qt command prompt. Ensure 7-Zip binary directory is on your `%PATH%`.
* For Windows builds, use `scripts\build-arch.bat` and `scripts\generate-bundle.bat`. Execute these scripts from the root of the repository within a Qt command prompt. Ensure WiX and 7-Zip binary directories are in your `%PATH%`.
* For macOS builds, use `scripts/generate-dmg.sh`. Execute this script from the root of the repository and ensure Qt's `bin` folder is in your `$PATH`.
* For Steam Link builds, run `scripts/build-steamlink-app.sh` from the root of the repository.
* To build from the command line for development use on macOS or Linux, run `qmake6 moonlight-qt.pro` then `make debug` or `make release`.
* The final binary will be placed in `app/moonlight`.
* To create an embedded build for a single-purpose device, use `qmake6 "CONFIG+=embedded" moonlight-qt.pro` and build normally.
* To build from the command line for development use, run `qmake moonlight-qt.pro` then `make debug` or `make release`
* To create an embedded build for a single-purpose device, use `qmake "CONFIG+=embedded" moonlight-qt.pro` and build normally.
* This build will lack windowed mode, Discord/Help links, and other features that don't make sense on an embedded device.
* For platforms with poor GPU performance, add `"CONFIG+=gpuslow"` to prefer direct KMSDRM rendering over GL/Vulkan renderers. Direct KMSDRM rendering can use dedicated YUV/RGB conversion and scaling hardware rather than slower GPU shaders for these operations.
## Contribute
1. Fork us
+2 -24
View File
@@ -2,14 +2,10 @@
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>GCSupportsGameMode</key>
<true/>
<key>CFBundleExecutable</key>
<string>Moonlight</string>
<key>LSSupportsGameMode</key>
<true/>
<key>CFBundleGetInfoString</key>
<string>Stream games and other applications from another PC</string>
<string>Stream games from your NVIDIA GameStream-enabled PC</string>
<key>CFBundleIconFile</key>
<string>moonlight</string>
<key>CFBundleIdentifier</key>
@@ -21,34 +17,16 @@
<key>CFBundleSignature</key>
<string>????</string>
<key>LSMinimumSystemVersion</key>
<string>11.0.0</string>
<string>10.14</string>
<key>NSPrincipalClass</key>
<string>NSApplication</string>
<key>NSSupportsAutomaticGraphicsSwitching</key>
<true/>
<key>GCSupportedGameControllers</key>
<array>
<dict>
<key>ProfileName</key>
<string>ExtendedGamepad</string>
</dict>
</array>
<key>GCSupportsControllerUserInteraction</key>
<true/>
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
<key>NSLocalNetworkUsageDescription</key>
<string>Moonlight uses the local network to connect to your gaming PC for streaming.</string>
<key>CFBundleVersion</key>
<string>VERSION</string>
<key>CFBundleShortVersionString</key>
<string>VERSION</string>
<key>CFBundleDisplayName</key>
<string>Moonlight</string>
<key>LSApplicationCategoryType</key>
<string>public.app-category.games</string>
</dict>
</plist>
+1 -2
View File
@@ -11,8 +11,7 @@
<asmv3:application>
<asmv3:windowsSettings>
<dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true/pm</dpiAware>
<dpiAwareness xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">permonitorv2, permonitor</dpiAwareness>
<heapType xmlns="http://schemas.microsoft.com/SMI/2020/WindowsSettings">SegmentHeap</heapType>
<dpiAwareness xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">permonitor</dpiAwareness>
</asmv3:windowsSettings>
</asmv3:application>
<compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
-67
View File
@@ -1,67 +0,0 @@
//
// Compatibility header for older version of SDL.
// Include this instead of SDL.h directly.
//
#pragma once
#include <SDL.h>
// SDL_FRect wasn't added until 2.0.10
#if !SDL_VERSION_ATLEAST(2, 0, 10)
typedef struct SDL_FRect
{
float x;
float y;
float w;
float h;
} SDL_FRect;
#endif
#ifndef SDL_HINT_VIDEO_X11_FORCE_EGL
#define SDL_HINT_VIDEO_X11_FORCE_EGL "SDL_VIDEO_X11_FORCE_EGL"
#endif
#ifndef SDL_HINT_KMSDRM_REQUIRE_DRM_MASTER
#define SDL_HINT_KMSDRM_REQUIRE_DRM_MASTER "SDL_KMSDRM_REQUIRE_DRM_MASTER"
#endif
#ifndef SDL_HINT_ALLOW_ALT_TAB_WHILE_GRABBED
#define SDL_HINT_ALLOW_ALT_TAB_WHILE_GRABBED "SDL_ALLOW_ALT_TAB_WHILE_GRABBED"
#endif
#ifndef SDL_HINT_JOYSTICK_HIDAPI_PS4_RUMBLE
#define SDL_HINT_JOYSTICK_HIDAPI_PS4_RUMBLE "SDL_JOYSTICK_HIDAPI_PS4_RUMBLE"
#endif
#ifndef SDL_HINT_JOYSTICK_HIDAPI_PS5_RUMBLE
#define SDL_HINT_JOYSTICK_HIDAPI_PS5_RUMBLE "SDL_JOYSTICK_HIDAPI_PS5_RUMBLE"
#endif
#ifndef SDL_HINT_WINDOWS_USE_D3D9EX
#define SDL_HINT_WINDOWS_USE_D3D9EX "SDL_WINDOWS_USE_D3D9EX"
#endif
#ifndef SDL_HINT_GAMECONTROLLER_USE_BUTTON_LABELS
#define SDL_HINT_GAMECONTROLLER_USE_BUTTON_LABELS "SDL_GAMECONTROLLER_USE_BUTTON_LABELS"
#endif
#ifndef SDL_HINT_MOUSE_RELATIVE_SCALING
#define SDL_HINT_MOUSE_RELATIVE_SCALING "SDL_MOUSE_RELATIVE_SCALING"
#endif
#ifndef SDL_HINT_AUDIO_DEVICE_APP_NAME
#define SDL_HINT_AUDIO_DEVICE_APP_NAME "SDL_AUDIO_DEVICE_APP_NAME"
#endif
#ifndef SDL_HINT_APP_NAME
#define SDL_HINT_APP_NAME "SDL_APP_NAME"
#endif
#ifndef SDL_HINT_MOUSE_AUTO_CAPTURE
#define SDL_HINT_MOUSE_AUTO_CAPTURE "SDL_MOUSE_AUTO_CAPTURE"
#endif
#ifndef SDL_HINT_VIDEO_WAYLAND_EMULATE_MOUSE_WARP
#define SDL_HINT_VIDEO_WAYLAND_EMULATE_MOUSE_WARP "SDL_VIDEO_WAYLAND_EMULATE_MOUSE_WARP"
#endif
+103 -216
View File
@@ -1,5 +1,5 @@
QT += core quick network quickcontrols2 svg
CONFIG += c++17
CONFIG += c++11
unix:!macx {
TARGET = moonlight
@@ -12,13 +12,10 @@ include(../globaldefs.pri)
# Precompile QML files to avoid writing qmlcache on portable versions.
# Since this binds the app against the Qt runtime version, we will only
# do this for Windows and Mac (when disable-prebuilts is not defined),
# since they always ship with the matching build of the Qt runtime.
!disable-prebuilts {
win32|macx {
CONFIG(release, debug|release) {
CONFIG += qtquickcompiler
}
# do this for Windows and Mac, since they ship with the Qt runtime.
win32|macx {
CONFIG(release, debug|release) {
CONFIG += qtquickcompiler
}
}
@@ -36,139 +33,100 @@ DEFINES += QT_DEPRECATED_WARNINGS
DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0
win32 {
!exists($$PWD/../libs/windows) {
error("Missing dependencies. Please run 'powershell .\setup-deps.ps1' to fetch prebuilt libraries.")
contains(QT_ARCH, i386) {
LIBS += -L$$PWD/../libs/windows/lib/x86
INCLUDEPATH += $$PWD/../libs/windows/include/x86
}
contains(QT_ARCH, x86_64) {
LIBS += -L$$PWD/../libs/windows/lib/x64
INCLUDEPATH += $$PWD/../libs/windows/include/x64 $$PWD/../libs/windows/include/x64/SDL2
INCLUDEPATH += $$PWD/../libs/windows/include/x64
}
contains(QT_ARCH, arm64) {
LIBS += -L$$PWD/../libs/windows/lib/arm64
INCLUDEPATH += $$PWD/../libs/windows/include/arm64 $$PWD/../libs/windows/include/arm64/SDL2
INCLUDEPATH += $$PWD/../libs/windows/include/arm64
}
INCLUDEPATH += $$PWD/../libs/windows/include
LIBS += ws2_32.lib winmm.lib dxva2.lib ole32.lib gdi32.lib user32.lib d3d9.lib dwmapi.lib dbghelp.lib
}
macx:!disable-prebuilts {
!exists($$PWD/../libs/mac) {
error("Missing dependencies. Please run 'python3 setup-deps.py' to fetch prebuilt libraries.")
}
INCLUDEPATH += $$PWD/../libs/mac/include $$PWD/../libs/mac/include/SDL2
LIBS += -L$$PWD/../libs/mac/lib
macx {
INCLUDEPATH += $$PWD/../libs/mac/include
INCLUDEPATH += $$PWD/../libs/mac/Frameworks/SDL2.framework/Versions/A/Headers
INCLUDEPATH += $$PWD/../libs/mac/Frameworks/SDL2_ttf.framework/Versions/A/Headers
LIBS += -L$$PWD/../libs/mac/lib -F$$PWD/../libs/mac/Frameworks
}
unix:if(!macx|disable-prebuilts) {
unix:!macx {
CONFIG += link_pkgconfig
PKGCONFIG += openssl sdl2 SDL2_ttf
PKGCONFIG += openssl sdl2 SDL2_ttf opus
# We have our own optimized libopus.a for Steam Link
if(!config_SL|disable-prebuilts) {
PKGCONFIG += opus
packagesExist(libavcodec) {
PKGCONFIG += libavcodec libavutil
CONFIG += ffmpeg
packagesExist(libva) {
packagesExist(libva-x11) {
CONFIG += libva-x11
}
packagesExist(libva-wayland) {
CONFIG += libva-wayland
}
packagesExist(libva-drm) {
CONFIG += libva-drm
}
CONFIG += libva
}
packagesExist(vdpau) {
CONFIG += libvdpau
}
packagesExist(mmal) {
PKGCONFIG += mmal
CONFIG += mmal
}
packagesExist(libdrm) {
PKGCONFIG += libdrm
CONFIG += libdrm
}
packagesExist(ffnvcodec) {
PKGCONFIG += ffnvcodec
CONFIG += cuda
}
}
!disable-ffmpeg {
packagesExist(libavcodec) {
PKGCONFIG += libavcodec libavutil libswscale
CONFIG += ffmpeg
packagesExist(wayland-client) {
DEFINES += HAS_WAYLAND
PKGCONFIG += wayland-client
}
!disable-libva {
packagesExist(libva) {
!disable-x11 {
packagesExist(libva-x11) {
CONFIG += libva-x11
}
}
!disable-wayland {
packagesExist(libva-wayland) {
CONFIG += libva-wayland
}
}
!disable-libdrm {
packagesExist(libva-drm) {
CONFIG += libva-drm
}
}
CONFIG += libva
}
}
!disable-libvdpau {
packagesExist(vdpau) {
CONFIG += libvdpau
}
}
!disable-mmal {
packagesExist(mmal) {
PKGCONFIG += mmal
CONFIG += mmal
}
}
!disable-libdrm {
packagesExist(libdrm) {
PKGCONFIG += libdrm
CONFIG += libdrm
}
}
# Disabled by default due to reliability issues. See #1314.
# CUDA interop is superseded by VDPAU and Vulkan Video.
enable-cuda {
packagesExist(ffnvcodec) {
PKGCONFIG += ffnvcodec
CONFIG += cuda
}
}
!disable-libplacebo {
packagesExist(libplacebo) {
PKGCONFIG += libplacebo
CONFIG += libplacebo
}
}
}
!disable-wayland {
packagesExist(wayland-client) {
CONFIG += wayland
PKGCONFIG += wayland-client
}
}
!disable-x11 {
packagesExist(x11) {
DEFINES += HAS_X11
PKGCONFIG += x11
}
}
packagesExist(x11) {
DEFINES += HAS_X11
PKGCONFIG += x11
}
}
win32 {
LIBS += -llibssl -llibcrypto -lSDL2 -lSDL2_ttf -lavcodec -lavutil -lswscale -lopus -ldxgi -ld3d11 -llibplacebo
CONFIG += ffmpeg libplacebo
LIBS += -llibssl -llibcrypto -lSDL2 -lSDL2_ttf -lavcodec -lavutil -lopus -ldxgi -ld3d11
CONFIG += ffmpeg
}
win32:!winrt {
CONFIG += discord-rpc
CONFIG += soundio discord-rpc
}
macx {
!disable-prebuilts {
LIBS += -lssl.3 -lcrypto.3 -lavcodec.62 -lavutil.60 -lswscale.9 -lopus.0 -lSDL2 -lSDL2_ttf -lplacebo
CONFIG += discord-rpc libplacebo
}
LIBS += -lssl -lcrypto -lavcodec.59 -lavutil.57 -lopus -framework SDL2 -framework SDL2_ttf
LIBS += -lobjc -framework VideoToolbox -framework AVFoundation -framework CoreVideo -framework CoreGraphics -framework CoreMedia -framework AppKit -framework Metal
LIBS += -lobjc -framework VideoToolbox -framework AVFoundation -framework CoreVideo -framework CoreGraphics -framework CoreMedia -framework AppKit -framework Metal -framework QuartzCore
CONFIG += ffmpeg
# For libsoundio
LIBS += -framework CoreAudio -framework AudioUnit
CONFIG += ffmpeg soundio discord-rpc
}
SOURCES += \
backend/nvaddress.cpp \
backend/nvapp.cpp \
cli/pair.cpp \
main.cpp \
backend/computerseeker.cpp \
backend/identitymanager.cpp \
@@ -179,7 +137,6 @@ SOURCES += \
backend/boxartmanager.cpp \
backend/richpresencemanager.cpp \
cli/commandlineparser.cpp \
cli/listapps.cpp \
cli/quitstream.cpp \
cli/startstream.cpp \
settings/compatfetcher.cpp \
@@ -196,7 +153,6 @@ SOURCES += \
streaming/audio/renderers/sdlaud.cpp \
gui/computermodel.cpp \
gui/appmodel.cpp \
streaming/bandwidth.cpp \
streaming/streamutils.cpp \
backend/autoupdatechecker.cpp \
path.cpp \
@@ -207,10 +163,8 @@ SOURCES += \
wm.cpp
HEADERS += \
SDL_compat.h \
backend/nvaddress.h \
backend/nvapp.h \
cli/pair.h \
settings/compatfetcher.h \
settings/mappingfetcher.h \
utils.h \
@@ -223,7 +177,6 @@ HEADERS += \
backend/boxartmanager.h \
backend/richpresencemanager.h \
cli/commandlineparser.h \
cli/listapps.h \
cli/quitstream.h \
cli/startstream.h \
settings/streamingpreferences.h \
@@ -234,7 +187,6 @@ HEADERS += \
gui/computermodel.h \
gui/appmodel.h \
streaming/video/decoder.h \
streaming/bandwidth.h \
streaming/streamutils.h \
backend/autoupdatechecker.h \
path.h \
@@ -250,18 +202,16 @@ ffmpeg {
DEFINES += HAVE_FFMPEG
SOURCES += \
streaming/video/ffmpeg.cpp \
streaming/video/ffmpeg-renderers/genhwaccel.cpp \
streaming/video/ffmpeg-renderers/sdlvid.cpp \
streaming/video/ffmpeg-renderers/swframemapper.cpp \
streaming/video/ffmpeg-renderers/pacer/pacer.cpp
streaming/video/ffmpeg-renderers/pacer/pacer.cpp \
streaming/video/ffmpeg-renderers/pacer/nullthreadedvsyncsource.cpp
HEADERS += \
streaming/video/ffmpeg.h \
streaming/video/ffmpeg-renderers/renderer.h \
streaming/video/ffmpeg-renderers/genhwaccel.h \
streaming/video/ffmpeg-renderers/sdlvid.h \
streaming/video/ffmpeg-renderers/swframemapper.h \
streaming/video/ffmpeg-renderers/pacer/pacer.h
streaming/video/ffmpeg-renderers/pacer/pacer.h \
streaming/video/ffmpeg-renderers/pacer/nullthreadedvsyncsource.h
}
libva {
message(VAAPI renderer selected)
@@ -283,7 +233,7 @@ libva-wayland {
PKGCONFIG += libva-wayland
DEFINES += HAVE_LIBVA_WAYLAND
}
libva-drm {
libva-wayland {
message(VAAPI DRM support enabled)
PKGCONFIG += libva-drm
@@ -302,18 +252,6 @@ mmal {
DEFINES += HAVE_MMAL
SOURCES += streaming/video/ffmpeg-renderers/mmal.cpp
HEADERS += streaming/video/ffmpeg-renderers/mmal.h
# We suppress EGL usage when MMAL is available because MMAL has
# significantly better performance than EGL on the Pi. Setting
# this option allows EGL usage even if built with MMAL support.
#
# It is highly recommended to also build with 'gpuslow' to avoid
# EGL being preferred if direct DRM rendering is available.
allow-egl-with-mmal {
message(Allowing EGL usage with MMAL enabled)
DEFINES += ALLOW_EGL_WITH_MMAL
}
}
libdrm {
message(DRM renderer selected)
@@ -323,12 +261,9 @@ libdrm {
HEADERS += streaming/video/ffmpeg-renderers/drm.h
linux {
!disable-masterhooks {
message(Master hooks enabled)
DEFINES += HAVE_DRM_MASTER_HOOKS
SOURCES += masterhook.c masterhook_internal.c
LIBS += -ldl -pthread
}
message(Master hooks enabled)
SOURCES += masterhook.c
LIBS += -ldl
}
}
cuda {
@@ -337,23 +272,6 @@ cuda {
DEFINES += HAVE_CUDA
SOURCES += streaming/video/ffmpeg-renderers/cuda.cpp
HEADERS += streaming/video/ffmpeg-renderers/cuda.h
# ffnvcodec uses libdl in cuda_load_functions()/cuda_free_functions()
LIBS += -ldl
}
libplacebo {
message(Vulkan support enabled via libplacebo)
DEFINES += HAVE_LIBPLACEBO_VULKAN
SOURCES += \
streaming/video/ffmpeg-renderers/plvk.cpp \
streaming/video/ffmpeg-renderers/plvk_c.c
HEADERS += \
streaming/video/ffmpeg-renderers/plvk.h
macx {
SOURCES += streaming/video/ffmpeg-renderers/plvk_objc.mm
}
}
config_EGL {
message(EGL renderer selected)
@@ -362,22 +280,12 @@ config_EGL {
DEFINES += HAVE_EGL
SOURCES += \
streaming/video/ffmpeg-renderers/eglvid.cpp \
streaming/video/ffmpeg-renderers/egl_extensions.cpp \
streaming/video/ffmpeg-renderers/eglimagefactory.cpp
HEADERS += \
streaming/video/ffmpeg-renderers/eglvid.h \
streaming/video/ffmpeg-renderers/eglimagefactory.h
streaming/video/ffmpeg-renderers/egl_extensions.cpp
HEADERS += streaming/video/ffmpeg-renderers/eglvid.h
}
config_SL {
message(Steam Link build configuration selected)
!disable-prebuilts {
# Link against our NEON-optimized libopus build
LIBS += -L$$PWD/../libs/steamlink/lib
INCLUDEPATH += $$PWD/../libs/steamlink/include
LIBS += -lopus -larmasm -lNE10
}
DEFINES += EMBEDDED_BUILD STEAM_LINK HAVE_SLVIDEO HAVE_SLAUDIO
LIBS += -lSLVideo -lSLAudio
@@ -408,13 +316,18 @@ macx {
message(VideoToolbox renderer selected)
SOURCES += \
streaming/video/ffmpeg-renderers/vt_base.mm \
streaming/video/ffmpeg-renderers/vt_avsamplelayer.mm \
streaming/video/ffmpeg-renderers/vt_metal.mm
streaming/video/ffmpeg-renderers/vt.mm
HEADERS += \
streaming/video/ffmpeg-renderers/vt.h
}
soundio {
message(libsoundio audio renderer selected)
DEFINES += HAVE_SOUNDIO SOUNDIO_STATIC_LIBRARY
SOURCES += streaming/audio/renderers/soundioaudiorenderer.cpp
HEADERS += streaming/audio/renderers/soundioaudiorenderer.h
}
discord-rpc {
message(Discord integration enabled)
@@ -426,35 +339,13 @@ embedded {
DEFINES += EMBEDDED_BUILD
}
glslow {
message(GL slow build)
DEFINES += GL_IS_SLOW
}
vkslow {
message(Vulkan slow build)
DEFINES += VULKAN_IS_SLOW
}
gpuslow {
message(GPU slow build)
DEFINES += GL_IS_SLOW VULKAN_IS_SLOW
}
wayland {
message(Wayland extensions enabled)
DEFINES += HAS_WAYLAND
SOURCES += streaming/video/ffmpeg-renderers/pacer/waylandvsyncsource.cpp
HEADERS += streaming/video/ffmpeg-renderers/pacer/waylandvsyncsource.h
}
RESOURCES += \
resources.qrc \
qml.qrc
TRANSLATIONS += \
languages/qml_zh_CN.ts \
languages/qml_zh_cn.ts \
languages/qml_de.ts \
languages/qml_fr.ts \
languages/qml_nb_NO.ts \
@@ -469,21 +360,12 @@ TRANSLATIONS += \
languages/qml_sv.ts \
languages/qml_tr.ts \
languages/qml_uk.ts \
languages/qml_zh_TW.ts \
languages/qml_zh_Hant.ts \
languages/qml_el.ts \
languages/qml_hi.ts \
languages/qml_it.ts \
languages/qml_pt.ts \
languages/qml_pt_BR.ts \
languages/qml_pl.ts \
languages/qml_cs.ts \
languages/qml_he.ts \
languages/qml_ckb.ts \
languages/qml_lt.ts \
languages/qml_et.ts \
languages/qml_bg.ts \
languages/qml_eo.ts \
languages/qml_ta.ts
languages/qml_pt_BR.ts
# Additional import path used to resolve QML modules in Qt Creator's code model
QML_IMPORT_PATH =
@@ -505,6 +387,15 @@ else:unix: LIBS += -L$$OUT_PWD/../qmdnsengine/ -lqmdnsengine
INCLUDEPATH += $$PWD/../qmdnsengine/qmdnsengine/src/include $$PWD/../qmdnsengine
DEPENDPATH += $$PWD/../qmdnsengine/qmdnsengine/src/include $$PWD/../qmdnsengine
soundio {
win32:CONFIG(release, debug|release): LIBS += -L$$OUT_PWD/../soundio/release/ -lsoundio
else:win32:CONFIG(debug, debug|release): LIBS += -L$$OUT_PWD/../soundio/debug/ -lsoundio
else:unix: LIBS += -L$$OUT_PWD/../soundio/ -lsoundio
INCLUDEPATH += $$PWD/../soundio/libsoundio
DEPENDPATH += $$PWD/../soundio/libsoundio
}
win32:CONFIG(release, debug|release): LIBS += -L$$OUT_PWD/../h264bitstream/release/ -lh264bitstream
else:win32:CONFIG(debug, debug|release): LIBS += -L$$OUT_PWD/../h264bitstream/debug/ -lh264bitstream
else:unix: LIBS += -L$$OUT_PWD/../h264bitstream/ -lh264bitstream
@@ -563,19 +454,15 @@ macx {
APP_BUNDLE_RESOURCES.files = moonlight.icns
APP_BUNDLE_RESOURCES.path = Contents/Resources
APP_BUNDLE_FRAMEWORKS.files = $$files(../libs/mac/Frameworks/*.framework, true) $$files(../libs/mac/lib/*.dylib, true)
APP_BUNDLE_FRAMEWORKS.path = Contents/Frameworks
APP_BUNDLE_PLIST.files = $$OUT_PWD/Info.plist
APP_BUNDLE_PLIST.path = Contents
QMAKE_BUNDLE_DATA += APP_BUNDLE_RESOURCES APP_BUNDLE_PLIST
QMAKE_BUNDLE_DATA += APP_BUNDLE_RESOURCES APP_BUNDLE_FRAMEWORKS APP_BUNDLE_PLIST
!disable-prebuilts {
APP_BUNDLE_FRAMEWORKS.files = $$files(../libs/mac/Frameworks/*.framework, true) $$files(../libs/mac/lib/*.dylib, true)
APP_BUNDLE_FRAMEWORKS.path = Contents/Frameworks
QMAKE_BUNDLE_DATA += APP_BUNDLE_FRAMEWORKS
QMAKE_RPATHDIR += @executable_path/../Frameworks
}
QMAKE_RPATHDIR += @executable_path/../Frameworks
}
VERSION = "$$cat(version.txt)"
+10 -21
View File
@@ -6,17 +6,16 @@
#include <QJsonObject>
AutoUpdateChecker::AutoUpdateChecker(QObject *parent) :
QObject(parent)
QObject(parent),
m_Nam(this)
{
m_Nam = new QNetworkAccessManager(this);
// Never communicate over HTTP
m_Nam->setStrictTransportSecurityEnabled(true);
m_Nam.setStrictTransportSecurityEnabled(true);
// Allow HTTP redirects
m_Nam->setRedirectPolicy(QNetworkRequest::NoLessSafeRedirectPolicy);
m_Nam.setRedirectPolicy(QNetworkRequest::NoLessSafeRedirectPolicy);
connect(m_Nam, &QNetworkAccessManager::finished,
connect(&m_Nam, &QNetworkAccessManager::finished,
this, &AutoUpdateChecker::handleUpdateCheckRequestFinished);
QString currentVersion(VERSION_STR);
@@ -29,17 +28,12 @@ AutoUpdateChecker::AutoUpdateChecker(QObject *parent) :
void AutoUpdateChecker::start()
{
if (!m_Nam) {
Q_ASSERT(m_Nam);
return;
}
#if defined(Q_OS_WIN32) || defined(Q_OS_DARWIN) || defined(STEAM_LINK) || defined(APP_IMAGE) // Only run update checker on platforms without auto-update
#if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0) && QT_VERSION < QT_VERSION_CHECK(5, 15, 1) && !defined(QT_NO_BEARERMANAGEMENT)
// HACK: Set network accessibility to work around QTBUG-80947 (introduced in Qt 5.14.0 and fixed in Qt 5.15.1)
QT_WARNING_PUSH
QT_WARNING_DISABLE_DEPRECATED
m_Nam->setNetworkAccessible(QNetworkAccessManager::Accessible);
m_Nam.setNetworkAccessible(QNetworkAccessManager::Accessible);
QT_WARNING_POP
#endif
@@ -51,14 +45,14 @@ void AutoUpdateChecker::start()
#else
request.setAttribute(QNetworkRequest::HTTP2AllowedAttribute, true);
#endif
m_Nam->get(request);
m_Nam.get(request);
#endif
}
void AutoUpdateChecker::parseStringToVersionQuad(QString& string, QVector<int>& version)
{
QStringList list = string.split('.');
for (const QString& component : std::as_const(list)) {
for (const QString& component : list) {
version.append(component.toInt());
}
}
@@ -108,11 +102,6 @@ void AutoUpdateChecker::handleUpdateCheckRequestFinished(QNetworkReply* reply)
{
Q_ASSERT(reply->isFinished());
// Delete the QNetworkAccessManager to free resources and
// prevent the bearer plugin from polling in the background.
m_Nam->deleteLater();
m_Nam = nullptr;
if (reply->error() == QNetworkReply::NoError) {
QTextStream stream(reply);
@@ -139,7 +128,7 @@ void AutoUpdateChecker::handleUpdateCheckRequestFinished(QNetworkReply* reply)
return;
}
for (const auto& updateEntry : std::as_const(array)) {
for (QJsonValueRef updateEntry : array) {
if (updateEntry.isObject()) {
QJsonObject updateObj = updateEntry.toObject();
if (!updateObj.contains("platform") ||
@@ -212,7 +201,7 @@ void AutoUpdateChecker::handleUpdateCheckRequestFinished(QNetworkReply* reply)
<< QSysInfo::buildCpuArchitecture() << getPlatform() << QSysInfo::kernelVersion();
}
else {
qWarning() << "Update checking failed with error:" << reply->error();
qWarning() << "Update checking failed with error: " << reply->error();
reply->deleteLater();
}
}
+1 -1
View File
@@ -25,5 +25,5 @@ private:
QString getPlatform();
QVector<int> m_CurrentVersionQuad;
QNetworkAccessManager* m_Nam;
QNetworkAccessManager m_Nam;
};
+70 -257
View File
@@ -1,7 +1,7 @@
#include "computermanager.h"
#include "boxartmanager.h"
#include "nvhttp.h"
#include "nvpairingmanager.h"
#include "settings/streamingpreferences.h"
#include <Limelight.h>
#include <QtEndian>
@@ -9,10 +9,8 @@
#include <QThread>
#include <QThreadPool>
#include <QCoreApplication>
#include <QRandomGenerator>
#define SER_HOSTS "hosts"
#define SER_HOSTS_BACKUP "hostsbackup"
class PcMonitorThread : public QThread
{
@@ -29,9 +27,9 @@ public:
}
private:
bool tryPollComputer(QNetworkAccessManager* nam, NvAddress address, bool& changed)
bool tryPollComputer(NvAddress address, bool& changed)
{
NvHTTP http(address, 0, m_Computer->serverCert, !m_Computer->isNvidiaServerSoftware, nam);
NvHTTP http(address, 0, m_Computer->serverCert);
QString serverInfo;
try {
@@ -44,7 +42,7 @@ private:
// Ensure the machine that responded is the one we intended to contact
if (m_Computer->uuid != newState.uuid) {
qInfo() << "Found unexpected PC" << newState.name << "looking for" << m_Computer->name;
qInfo() << "Found unexpected PC " << newState.name << " looking for " << m_Computer->name;
return false;
}
@@ -52,9 +50,9 @@ private:
return true;
}
bool updateAppList(QNetworkAccessManager* nam, bool& changed)
bool updateAppList(bool& changed)
{
NvHTTP http(m_Computer, nam);
NvHTTP http(m_Computer);
QVector<NvApp> appList;
@@ -74,21 +72,6 @@ private:
void run() override
{
// Reduce the power and performance impact of our
// computer status polling while it's running.
setPriority(QThread::LowPriority);
#if QT_VERSION >= QT_VERSION_CHECK(6, 9, 0)
setServiceLevel(QThread::QualityOfService::Eco);
#endif
// Share the QNetworkAccessManager to conserve resources when polling.
// Each instance creates a worker thread, so sharing them ensures that
// we are not spamming a new thread for every single polling attempt.
//
// Since QThread inherit the priority of the current thread, this also
// ensures that the NAM's worker thread will inherit our lower priority.
QNetworkAccessManager nam;
// Always fetch the applist the first time
int pollsSinceLastAppListFetch = POLLS_PER_APPLIST_FETCH;
while (!isInterruptionRequested()) {
@@ -101,7 +84,7 @@ private:
return;
}
if (tryPollComputer(&nam, address, stateChanged)) {
if (tryPollComputer(address, stateChanged)) {
if (!wasOnline) {
qInfo() << m_Computer->name << "is now online at" << m_Computer->activeAddress.toString();
}
@@ -132,7 +115,7 @@ private:
stateChanged = false;
}
if (updateAppList(&nam, stateChanged)) {
if (updateAppList(stateChanged)) {
pollsSinceLastAppListFetch = 0;
}
}
@@ -158,43 +141,29 @@ private:
NvComputer* m_Computer;
};
ComputerManager::ComputerManager(StreamingPreferences* prefs)
: m_Prefs(prefs),
ComputerManager::ComputerManager(QObject *parent)
: QObject(parent),
m_PollingRef(0),
m_MdnsBrowser(nullptr),
m_CompatFetcher(nullptr),
m_NeedsDelayedFlush(false)
m_CompatFetcher(nullptr)
{
QSettings settings;
// If there's a hosts backup copy, we must have failed to commit
// a previous update before exiting. Restore the backup now.
int hosts = settings.beginReadArray(SER_HOSTS_BACKUP);
if (hosts == 0) {
// If there's no host backup, read from the primary location.
settings.endArray();
hosts = settings.beginReadArray(SER_HOSTS);
}
// Inflate our hosts from QSettings
int hosts = settings.beginReadArray(SER_HOSTS);
for (int i = 0; i < hosts; i++) {
settings.setArrayIndex(i);
NvComputer* computer = new NvComputer(settings);
m_KnownHosts[computer->uuid] = computer;
m_LastSerializedHosts[computer->uuid] = *computer;
}
settings.endArray();
// Fetch latest compatibility data asynchronously
m_CompatFetcher.start();
// Start the delayed flush thread to handle saveHosts() calls
m_DelayedFlushThread = new DelayedFlushThread(this);
m_DelayedFlushThread->start();
// To quit in a timely manner, we must block additional requests
// after we receive the aboutToQuit() signal. This is necessary
// because NvHTTP uses aboutToQuit() to abort requests in progress
// after we receive the aboutToQuit() signal. This is neccessary
// because NvHTTP uses aboutToQuit() to abort requests in progres
// while quitting, however this is a one time signal - additional
// requests would not be aborted and block termination.
connect(QCoreApplication::instance(), &QCoreApplication::aboutToQuit, this, &ComputerManager::handleAboutToQuit);
@@ -202,21 +171,6 @@ ComputerManager::ComputerManager(StreamingPreferences* prefs)
ComputerManager::~ComputerManager()
{
// Stop the delayed flush thread before acquiring the lock in write mode
// to avoid deadlocking with a flush that needs the lock in read mode.
{
// Wake the delayed flush thread
m_DelayedFlushThread->requestInterruption();
m_DelayedFlushCondition.wakeOne();
// Wait for it to terminate (and finish any pending flush)
m_DelayedFlushThread->wait();
delete m_DelayedFlushThread;
// Delayed flushes should have completed by now
Q_ASSERT(!m_NeedsDelayedFlush);
}
QWriteLocker lock(&m_Lock);
// Delete machines that haven't been resolved yet
@@ -231,95 +185,34 @@ ComputerManager::~ComputerManager()
m_MdnsBrowser = nullptr;
// Interrupt polling
for (ComputerPollingEntry* entry : std::as_const(m_PollEntries)) {
for (ComputerPollingEntry* entry : m_PollEntries) {
entry->interrupt();
}
// Delete all polling entries (and associated threads)
for (ComputerPollingEntry* entry : std::as_const(m_PollEntries)) {
for (ComputerPollingEntry* entry : m_PollEntries) {
delete entry;
}
// Destroy all NvComputer objects now that polling is halted
for (NvComputer* computer : std::as_const(m_KnownHosts)) {
for (NvComputer* computer : m_KnownHosts) {
delete computer;
}
}
void DelayedFlushThread::run() {
for (;;) {
// Wait for a delayed flush request or an interruption
{
QMutexLocker locker(&m_ComputerManager->m_DelayedFlushMutex);
while (!QThread::currentThread()->isInterruptionRequested() && !m_ComputerManager->m_NeedsDelayedFlush) {
m_ComputerManager->m_DelayedFlushCondition.wait(&m_ComputerManager->m_DelayedFlushMutex);
}
// Bail without flushing if we woke up for an interruption alone.
// If we have both an interruption and a flush request, do the flush.
if (!m_ComputerManager->m_NeedsDelayedFlush) {
Q_ASSERT(QThread::currentThread()->isInterruptionRequested());
break;
}
// Reset the delayed flush flag to ensure any racing saveHosts() call will set it again
m_ComputerManager->m_NeedsDelayedFlush = false;
// Update the last serialized hosts map under the delayed flush mutex
m_ComputerManager->m_LastSerializedHosts.clear();
for (const NvComputer* computer : std::as_const(m_ComputerManager->m_KnownHosts)) {
// Copy the current state of the NvComputer to allow us to check later if we need
// to serialize it again when attribute updates occur.
QReadLocker computerLock(&computer->lock);
m_ComputerManager->m_LastSerializedHosts[computer->uuid] = *computer;
}
}
// Perform the flush
{
QSettings settings;
// First, write to the backup location
settings.beginWriteArray(SER_HOSTS_BACKUP);
{
QReadLocker lock(&m_ComputerManager->m_Lock);
int i = 0;
for (const NvComputer* computer : std::as_const(m_ComputerManager->m_KnownHosts)) {
settings.setArrayIndex(i++);
computer->serialize(settings, false);
}
}
settings.endArray();
// Next, write to the primary location
settings.remove(SER_HOSTS);
settings.beginWriteArray(SER_HOSTS);
{
QReadLocker lock(&m_ComputerManager->m_Lock);
int i = 0;
for (const NvComputer* computer : std::as_const(m_ComputerManager->m_KnownHosts)) {
settings.setArrayIndex(i++);
computer->serialize(settings, true);
}
}
settings.endArray();
// Finally, delete the backup copy
settings.remove(SER_HOSTS_BACKUP);
}
}
}
void ComputerManager::saveHosts()
{
Q_ASSERT(m_DelayedFlushThread != nullptr && m_DelayedFlushThread->isRunning());
QSettings settings;
QReadLocker lock(&m_Lock);
// Punt to a worker thread because QSettings on macOS can take ages (> 500 ms)
// to persist our host list to disk (especially when a host has a bunch of apps).
QMutexLocker locker(&m_DelayedFlushMutex);
m_NeedsDelayedFlush = true;
m_DelayedFlushCondition.wakeOne();
settings.remove(SER_HOSTS);
settings.beginWriteArray(SER_HOSTS);
int i = 0;
for (const NvComputer* computer : m_KnownHosts) {
settings.setArrayIndex(i++);
computer->serialize(settings);
}
settings.endArray();
}
QHostAddress ComputerManager::getBestGlobalAddressV6(QVector<QHostAddress> &addresses)
@@ -366,15 +259,16 @@ void ComputerManager::startPolling()
return;
}
if (m_Prefs->enableMdns) {
StreamingPreferences prefs;
if (prefs.enableMdns) {
// Start an MDNS query for GameStream hosts
m_MdnsServer.reset(new QMdnsEngine::Server());
m_MdnsBrowser = new QMdnsEngine::Browser(m_MdnsServer.data(), "_nvstream._tcp.local.");
m_MdnsBrowser = new QMdnsEngine::Browser(&m_MdnsServer, "_nvstream._tcp.local.", &m_MdnsCache);
connect(m_MdnsBrowser, &QMdnsEngine::Browser::serviceAdded,
this, [this](const QMdnsEngine::Service& service) {
qInfo() << "Discovered mDNS host:" << service.hostname();
MdnsPendingComputer* pendingComputer = new MdnsPendingComputer(m_MdnsServer, service);
MdnsPendingComputer* pendingComputer = new MdnsPendingComputer(&m_MdnsServer, service);
connect(pendingComputer, &MdnsPendingComputer::resolvedHost,
this, &ComputerManager::handleMdnsServiceResolved);
m_PendingResolution.append(pendingComputer);
@@ -424,15 +318,13 @@ void ComputerManager::handleMdnsServiceResolved(MdnsPendingComputer* computer,
bool added = false;
// Add the host using the IPv4 address
for (const QHostAddress& address : std::as_const(addresses)) {
for (const QHostAddress& address : addresses) {
if (address.protocol() == QAbstractSocket::IPv4Protocol) {
// NB: We don't just call addNewHost() here with v6Global because the IPv6
// address may not be reachable (if the user hasn't installed the IPv6 helper yet
// or if this host lacks outbound IPv6 capability). We want to add IPv6 even if
// it's not currently reachable.
addNewHost(NvAddress(address, computer->port()),
true, computer->hostname(),
NvAddress(v6Global, computer->port()));
addNewHost(NvAddress(address, computer->port()), true, NvAddress(v6Global, computer->port()));
added = true;
break;
}
@@ -440,15 +332,13 @@ void ComputerManager::handleMdnsServiceResolved(MdnsPendingComputer* computer,
if (!added) {
// If we get here, there wasn't an IPv4 address so we'll do it v6-only
for (const QHostAddress& address : std::as_const(addresses)) {
for (const QHostAddress& address : addresses) {
if (address.protocol() == QAbstractSocket::IPv6Protocol) {
// Use a link-local or site-local address for the "local address"
if (address.isInSubnet(QHostAddress("fe80::"), 10) ||
address.isInSubnet(QHostAddress("fec0::"), 10) ||
address.isInSubnet(QHostAddress("fc00::"), 7)) {
addNewHost(NvAddress(address, computer->port()),
true, computer->hostname(),
NvAddress(v6Global, computer->port()));
addNewHost(NvAddress(address, computer->port()), true, NvAddress(v6Global, computer->port()));
break;
}
}
@@ -459,19 +349,6 @@ void ComputerManager::handleMdnsServiceResolved(MdnsPendingComputer* computer,
computer->deleteLater();
}
void ComputerManager::saveHost(NvComputer *computer)
{
// If no serializable properties changed, don't bother saving hosts
QMutexLocker lock(&m_DelayedFlushMutex);
QReadLocker computerLock(&computer->lock);
if (!m_LastSerializedHosts.value(computer->uuid).isEqualSerialized(*computer)) {
// Queue a request for a delayed flush to QSettings outside of the lock
computerLock.unlock();
lock.unlock();
saveHosts();
}
}
void ComputerManager::handleComputerStateChanged(NvComputer* computer)
{
emit computerStateChanged(computer);
@@ -481,20 +358,15 @@ void ComputerManager::handleComputerStateChanged(NvComputer* computer)
emit quitAppCompleted(QVariant());
}
// Save updates to this host
saveHost(computer);
// Save updated hosts to QSettings
saveHosts();
}
QVector<NvComputer*> ComputerManager::getComputers()
{
QReadLocker lock(&m_Lock);
// Return a sorted host list
auto hosts = QVector<NvComputer*>::fromList(m_KnownHosts.values());
std::stable_sort(hosts.begin(), hosts.end(), [](const NvComputer* host1, const NvComputer* host2) {
return host1->name.toLower() < host2->name.toLower();
});
return hosts;
return QVector<NvComputer*>::fromList(m_KnownHosts.values());
}
class DeferredHostDeletionTask : public QRunnable
@@ -518,7 +390,7 @@ public:
m_ComputerManager->m_KnownHosts.remove(m_Computer->uuid);
}
// Persist the new host list with this computer deleted
// Persist the new host list
m_ComputerManager->saveHosts();
// Delete the polling entry first. This will stop all polling threads too.
@@ -559,17 +431,20 @@ void ComputerManager::renameHost(NvComputer* computer, QString name)
void ComputerManager::clientSideAttributeUpdated(NvComputer* computer)
{
// Persist the change
saveHosts();
// Notify the UI of the state change
handleComputerStateChanged(computer);
}
void ComputerManager::handleAboutToQuit()
{
QReadLocker lock(&m_Lock);
QWriteLocker lock(&m_Lock);
// Interrupt polling threads immediately, so they
// avoid making additional requests while quitting
for (ComputerPollingEntry* entry : std::as_const(m_PollEntries)) {
for (ComputerPollingEntry* entry : m_PollEntries) {
entry->interrupt();
}
}
@@ -580,8 +455,7 @@ class PendingPairingTask : public QObject, public QRunnable
public:
PendingPairingTask(ComputerManager* computerManager, NvComputer* computer, QString pin)
: m_ComputerManager(computerManager),
m_Computer(computer),
: m_Computer(computer),
m_Pin(pin)
{
connect(this, &PendingPairingTask::pairingCompleted,
@@ -601,34 +475,25 @@ private:
switch (result)
{
case NvPairingManager::PairState::PIN_WRONG:
emit pairingCompleted(m_Computer, tr("The PIN from the PC didn't match. Please try again."));
emit pairingCompleted(m_Computer, "The PIN from the PC didn't match. Please try again.");
break;
case NvPairingManager::PairState::FAILED:
if (m_Computer->currentGameId != 0) {
emit pairingCompleted(m_Computer, tr("You cannot pair while a previous session is still running on the host PC. Quit any running games or reboot the host PC, then try pairing again."));
}
else {
emit pairingCompleted(m_Computer, tr("Pairing failed. Please try again."));
}
emit pairingCompleted(m_Computer, "Pairing failed. Please try again.");
break;
case NvPairingManager::PairState::ALREADY_IN_PROGRESS:
emit pairingCompleted(m_Computer, tr("Another pairing attempt is already in progress."));
emit pairingCompleted(m_Computer, "Another pairing attempt is already in progress.");
break;
case NvPairingManager::PairState::PAIRED:
// Persist the newly pinned server certificate for this host
m_ComputerManager->saveHost(m_Computer);
emit pairingCompleted(m_Computer, nullptr);
break;
}
} catch (const GfeHttpResponseException& e) {
emit pairingCompleted(m_Computer, tr("GeForce Experience returned error: %1").arg(e.toQString()));
emit pairingCompleted(m_Computer, "GeForce Experience returned error: " + e.toQString());
} catch (const QtNetworkReplyException& e) {
emit pairingCompleted(m_Computer, e.toQString());
}
}
ComputerManager* m_ComputerManager;
NvComputer* m_Computer;
QString m_Pin;
};
@@ -715,28 +580,23 @@ void ComputerManager::stopPollingAsync()
m_PendingResolution.removeFirst();
}
// Delete the browser and server to stop discovery and refresh polling
// Delete the browser to stop discovery
delete m_MdnsBrowser;
m_MdnsBrowser = nullptr;
m_MdnsServer.reset();
// Interrupt all threads, but don't wait for them to terminate
for (ComputerPollingEntry* entry : std::as_const(m_PollEntries)) {
for (ComputerPollingEntry* entry : m_PollEntries) {
entry->interrupt();
}
}
void ComputerManager::addNewHostManually(QString address)
{
QUrl url = QUrl::fromUserInput("moonlight://" + address);
if (url.isValid() && !url.host().isEmpty() && url.scheme() == "moonlight") {
QUrl url = QUrl::fromUserInput(address);
if (url.isValid() && !url.host().isEmpty()) {
// If there wasn't a port specified, use the default
addNewHost(NvAddress(url.host(), url.port(DEFAULT_HTTP_PORT)), false);
}
else if (QHostAddress(address).protocol() == QAbstractSocket::IPv6Protocol) {
// The user specified an IPv6 literal without URL escaping, so use the default port
addNewHost(NvAddress(address, DEFAULT_HTTP_PORT), false);
}
else {
emit computerAddCompleted(false, false);
}
@@ -747,20 +607,16 @@ class PendingAddTask : public QObject, public QRunnable
Q_OBJECT
public:
PendingAddTask(ComputerManager* computerManager, QString name, NvAddress address, NvAddress mdnsIpv6Address, bool mdns)
PendingAddTask(ComputerManager* computerManager, NvAddress address, NvAddress mdnsIpv6Address, bool mdns)
: m_ComputerManager(computerManager),
m_Name(name),
m_Address(address),
m_MdnsIpv6Address(mdnsIpv6Address),
m_Mdns(mdns),
m_AboutToQuit(false)
m_Mdns(mdns)
{
connect(this, &PendingAddTask::computerAddCompleted,
computerManager, &ComputerManager::computerAddCompleted);
connect(this, &PendingAddTask::computerStateChanged,
computerManager, &ComputerManager::handleComputerStateChanged);
connect(QCoreApplication::instance(), &QCoreApplication::aboutToQuit,
this, &PendingAddTask::handleAboutToQuit);
}
signals:
@@ -769,20 +625,9 @@ signals:
void computerStateChanged(NvComputer* computer);
private:
void handleAboutToQuit()
{
m_AboutToQuit = true;
}
QString fetchServerInfo(NvHTTP& http)
{
QString serverInfo;
// Do nothing if we're quitting
if (m_AboutToQuit) {
return QString();
}
try {
// There's a race condition between GameStream servers reporting presence over
// mDNS and the HTTPS server being ready to respond to our queries. To work
@@ -805,9 +650,10 @@ private:
return serverInfo;
} catch (...) {
if (!m_Mdns) {
unsigned int portTestResult;
StreamingPreferences prefs;
int portTestResult;
if (m_ComputerManager->m_Prefs->detectNetworkBlocking) {
if (prefs.detectNetworkBlocking) {
// We failed to connect to the specified PC. Let's test to make sure this network
// isn't blocking Moonlight, so we can tell the user about it.
portTestResult = LiTestClientConnectivity("qt.conntest.moonlight-stream.org", 443,
@@ -825,21 +671,9 @@ private:
void run()
{
// Use the placeholder UID for the initial poll, then we'll switch to the real one if it's not GFE
NvHTTP http(m_Address, 0, QSslCertificate(), false);
NvHTTP http(m_Address, 0, QSslCertificate());
if (m_Mdns) {
if (m_MdnsIpv6Address.isNull()) {
qInfo() << "Processing new PC" << m_Name << "from mDNS with local address" << m_Address.toString();
}
else {
qInfo() << "Processing new PC" << m_Name << "from mDNS with local address" << m_Address.toString()
<< "and IPv6 address" << m_MdnsIpv6Address.toString();
}
}
else {
qInfo() << "Processing new PC at" << m_Address.toString() << "from user";
}
qInfo() << "Processing new PC at" << m_Address.toString() << "from" << (m_Mdns ? "mDNS" : "user") << "with IPv6 address" << m_MdnsIpv6Address.toString();
// Perform initial serverinfo fetch over HTTP since we don't know which cert to use
QString serverInfo = fetchServerInfo(http);
@@ -854,7 +688,6 @@ private:
// Create initial newComputer using HTTP serverinfo with no pinned cert
NvComputer* newComputer = new NvComputer(http, serverInfo);
http.setTrueUid(!newComputer->isNvidiaServerSoftware);
// Check if we have a record of this host UUID to pull the pinned cert
NvComputer* existingComputer;
@@ -916,31 +749,16 @@ private:
hostAddress.isInSubnet(QHostAddress("192.168.0.0"), 16);
{
// Check if this PC already exists using opportunistic read lock
m_ComputerManager->m_Lock.lockForRead();
// Check if this PC already exists
QWriteLocker lock(&m_ComputerManager->m_Lock);
NvComputer* existingComputer = m_ComputerManager->m_KnownHosts.value(newComputer->uuid);
// If it doesn't already exist, convert to a write lock in preparation for updating.
//
// NB: ComputerManager's lock protects the host map itself, not the elements inside.
// Those are protected by their individual locks. Since we only mutate the map itself
// when the PC doesn't exist, we need the lock in write-mode for that case only.
if (existingComputer == nullptr) {
m_ComputerManager->m_Lock.unlock();
m_ComputerManager->m_Lock.lockForWrite();
// Since we had to unlock to lock for write, someone could have raced and added
// this PC before us. We have to check again whether it already exists.
existingComputer = m_ComputerManager->m_KnownHosts.value(newComputer->uuid);
}
if (existingComputer != nullptr) {
// Fold it into the existing PC
bool changed = existingComputer->update(*newComputer);
delete newComputer;
// Drop the lock before notifying
m_ComputerManager->m_Lock.unlock();
lock.unlock();
// For non-mDNS clients, let them know it succeeded
if (!m_Mdns) {
@@ -961,15 +779,17 @@ private:
m_ComputerManager->startPollingComputer(newComputer);
// Drop the lock before notifying
m_ComputerManager->m_Lock.unlock();
lock.unlock();
// If this wasn't added via mDNS but it is a RFC 1918 IPv4 address and not a VPN,
// go ahead and do the STUN request now to populate an external address.
if (!m_Mdns && addressIsSiteLocalV4 && newComputer->getActiveAddressReachability() != NvComputer::RI_VPN) {
if (!m_Mdns && addressIsSiteLocalV4 && !newComputer->isReachableOverVpn()) {
quint32 addr;
int err = LiFindExternalAddressIP4("stun.moonlight-stream.org", 3478, &addr);
if (err == 0) {
lock.relock();
newComputer->setRemoteAddress(QHostAddress(qFromBigEndian(addr)));
lock.unlock();
}
else {
qWarning() << "STUN failed to get WAN address:" << err;
@@ -988,24 +808,17 @@ private:
}
ComputerManager* m_ComputerManager;
QString m_Name;
NvAddress m_Address;
NvAddress m_MdnsIpv6Address;
bool m_Mdns;
bool m_AboutToQuit;
};
void ComputerManager::addNewHost(NvAddress address, bool mdns, QString name, NvAddress mdnsIpv6Address)
void ComputerManager::addNewHost(NvAddress address, bool mdns, NvAddress mdnsIpv6Address)
{
// Punt to a worker thread to avoid stalling the
// UI while waiting for serverinfo query to complete
PendingAddTask* addTask = new PendingAddTask(this, name, address, mdnsIpv6Address, mdns);
PendingAddTask* addTask = new PendingAddTask(this, address, mdnsIpv6Address, mdns);
QThreadPool::globalInstance()->start(addTask);
}
QString ComputerManager::generatePinString()
{
return QString::asprintf("%04u", QRandomGenerator::system()->bounded(10000));
}
#include "computermanager.moc"
+15 -73
View File
@@ -1,7 +1,7 @@
#pragma once
#include "nvcomputer.h"
#include "settings/streamingpreferences.h"
#include "nvpairingmanager.h"
#include "settings/compatfetcher.h"
#include <qmdnsengine/server.h>
@@ -15,38 +15,17 @@
#include <QSettings>
#include <QRunnable>
#include <QTimer>
#include <QMutex>
#include <QWaitCondition>
class ComputerManager;
class DelayedFlushThread : public QThread
{
Q_OBJECT
public:
DelayedFlushThread(ComputerManager* cm)
: m_ComputerManager(cm)
{
setObjectName("CM Delayed Flush Thread");
}
void run();
private:
ComputerManager* m_ComputerManager;
};
class MdnsPendingComputer : public QObject
{
Q_OBJECT
public:
explicit MdnsPendingComputer(const QSharedPointer<QMdnsEngine::Server> server,
explicit MdnsPendingComputer(QMdnsEngine::Server* server,
const QMdnsEngine::Service& service)
: m_Hostname(service.hostname()),
m_Port(service.port()),
m_ServerWeak(server),
m_Server(server),
m_Resolver(nullptr)
{
// Start resolving
@@ -72,15 +51,9 @@ private slots:
void handleResolvedTimeout()
{
if (m_Addresses.isEmpty()) {
if (m_Retries-- > 0) {
// Try again
qInfo() << "Resolving" << hostname() << "timed out. Retrying...";
resolve();
}
else {
qWarning() << "Giving up on resolving" << hostname() << "after repeated failures";
cleanup();
}
// Try again
qInfo() << "Resolving" << hostname() << "timed out. Retrying...";
resolve();
}
else {
Q_ASSERT(!m_Addresses.isEmpty());
@@ -90,6 +63,7 @@ private slots:
void handleResolvedAddress(const QHostAddress& address)
{
qInfo() << "Resolved" << hostname() << "to" << address;
m_Addresses.push_back(address);
}
@@ -97,29 +71,10 @@ signals:
void resolvedHost(MdnsPendingComputer*,QVector<QHostAddress>&);
private:
void cleanup()
{
// Delete our resolver, so we're guaranteed that nothing is referencing m_Server.
delete m_Resolver;
m_Resolver = nullptr;
// Now delete our strong reference that we held on behalf of m_Resolver.
// The server may be destroyed after we make this call.
m_Server.reset();
}
void resolve()
{
// Clean up any existing resolver object and server references
cleanup();
// Re-acquire a strong reference if the server still exists.
m_Server = m_ServerWeak.toStrongRef();
if (!m_Server) {
return;
}
m_Resolver = new QMdnsEngine::Resolver(m_Server.data(), m_Hostname);
delete m_Resolver;
m_Resolver = new QMdnsEngine::Resolver(m_Server, m_Hostname);
connect(m_Resolver, &QMdnsEngine::Resolver::resolved,
this, &MdnsPendingComputer::handleResolvedAddress);
QTimer::singleShot(2000, this, &MdnsPendingComputer::handleResolvedTimeout);
@@ -127,11 +82,9 @@ private:
QByteArray m_Hostname;
uint16_t m_Port;
QWeakPointer<QMdnsEngine::Server> m_ServerWeak;
QSharedPointer<QMdnsEngine::Server> m_Server;
QMdnsEngine::Server* m_Server;
QMdnsEngine::Resolver* m_Resolver;
QVector<QHostAddress> m_Addresses;
int m_Retries = 10;
};
class ComputerPollingEntry
@@ -150,7 +103,7 @@ public:
// interrupt() should have taken care of this
Q_ASSERT(m_ActiveThread == nullptr);
for (QThread* thread : std::as_const(m_InactiveList)) {
for (QThread* thread : m_InactiveList) {
thread->wait();
delete thread;
}
@@ -213,11 +166,9 @@ class ComputerManager : public QObject
friend class DeferredHostDeletionTask;
friend class PendingAddTask;
friend class PendingPairingTask;
friend class DelayedFlushThread;
public:
explicit ComputerManager(StreamingPreferences* prefs);
explicit ComputerManager(QObject *parent = nullptr);
virtual ~ComputerManager();
@@ -227,9 +178,7 @@ public:
Q_INVOKABLE void addNewHostManually(QString address);
void addNewHost(NvAddress address, bool mdns, QString name = QString(), NvAddress mdnsIpv6Address = NvAddress());
QString generatePinString();
void addNewHost(NvAddress address, bool mdns, NvAddress mdnsIpv6Address = NvAddress());
void pairHost(NvComputer* computer, QString pin);
@@ -263,24 +212,17 @@ private slots:
private:
void saveHosts();
void saveHost(NvComputer* computer);
QHostAddress getBestGlobalAddressV6(QVector<QHostAddress>& addresses);
void startPollingComputer(NvComputer* computer);
StreamingPreferences* m_Prefs;
int m_PollingRef;
QReadWriteLock m_Lock;
QMap<QString, NvComputer*> m_KnownHosts;
QMap<QString, ComputerPollingEntry*> m_PollEntries;
QHash<QString, NvComputer> m_LastSerializedHosts; // Protected by m_DelayedFlushMutex
QSharedPointer<QMdnsEngine::Server> m_MdnsServer;
QMdnsEngine::Server m_MdnsServer;
QMdnsEngine::Browser* m_MdnsBrowser;
QMdnsEngine::Cache m_MdnsCache;
QVector<MdnsPendingComputer*> m_PendingResolution;
CompatFetcher m_CompatFetcher;
DelayedFlushThread* m_DelayedFlushThread;
QMutex m_DelayedFlushMutex; // Lock ordering: Must never be acquired while holding NvComputer lock
QWaitCondition m_DelayedFlushCondition;
bool m_NeedsDelayedFlush;
};
+6 -30
View File
@@ -6,12 +6,6 @@ ComputerSeeker::ComputerSeeker(ComputerManager *manager, QString computerName, Q
: QObject(parent), m_ComputerManager(manager), m_ComputerName(computerName),
m_TimeoutTimer(new QTimer(this))
{
// If we know this computer, send a WOL packet to wake it up in case it is asleep.
NvComputer* matchingComputer = findMatchingComputer();
if (matchingComputer) {
matchingComputer->wake();
}
m_TimeoutTimer->setSingleShot(true);
connect(m_TimeoutTimer, &QTimer::timeout,
this, &ComputerSeeker::onTimeout);
@@ -22,16 +16,11 @@ ComputerSeeker::ComputerSeeker(ComputerManager *manager, QString computerName, Q
void ComputerSeeker::start(int timeout)
{
m_TimeoutTimer->start(timeout);
// If we don't know this computer by name, address, or UUID, try adding it
// manually and see if we can find it by address, hostname, or mDNS.
//
// NB: We don't do this unconditionally because it will wipe out the user's
// manual address if they pass another reachable hostname/address.
if (!findMatchingComputer()) {
m_ComputerManager->addNewHostManually(m_ComputerName);
}
// Seek desired computer by both connecting to it directly (this may fail
// if m_ComputerName is UUID, or the name that doesn't resolve to an IP
// address) and by polling it using mDNS, hopefully one of these methods
// would find the host
m_ComputerManager->addNewHostManually(m_ComputerName);
m_ComputerManager->startPolling();
}
@@ -55,8 +44,7 @@ bool ComputerSeeker::matchComputer(NvComputer *computer) const
return true;
}
const auto uniqueAddresses = computer->uniqueAddresses();
for (const NvAddress& addr : uniqueAddresses) {
for (const NvAddress& addr : computer->uniqueAddresses()) {
if (addr.address().toLower() == value || addr.toString().toLower() == value) {
return true;
}
@@ -65,18 +53,6 @@ bool ComputerSeeker::matchComputer(NvComputer *computer) const
return false;
}
NvComputer* ComputerSeeker::findMatchingComputer() const
{
const auto computers = m_ComputerManager->getComputers();
for (NvComputer* computer : computers) {
if (this->matchComputer(computer)) {
return computer;
}
}
return nullptr;
}
bool ComputerSeeker::isOnline(NvComputer *computer) const
{
return computer->state == NvComputer::CS_ONLINE;
-1
View File
@@ -24,7 +24,6 @@ private slots:
private:
bool matchComputer(NvComputer *computer) const;
NvComputer* findMatchingComputer() const;
bool isOnline(NvComputer *computer) const;
private:
+36 -38
View File
@@ -31,10 +31,6 @@ void IdentityManager::createCredentials(QSettings& settings)
X509* cert = X509_new();
THROW_BAD_ALLOC_IF_NULL(cert);
#if OPENSSL_VERSION_NUMBER >= 0x30000000L
EVP_PKEY* pk = EVP_RSA_gen(2048);
THROW_BAD_ALLOC_IF_NULL(pk);
#else
EVP_PKEY_CTX* ctx = EVP_PKEY_CTX_new_id(EVP_PKEY_RSA, NULL);
THROW_BAD_ALLOC_IF_NULL(ctx);
@@ -47,7 +43,6 @@ void IdentityManager::createCredentials(QSettings& settings)
EVP_PKEY_CTX_free(ctx);
THROW_BAD_ALLOC_IF_NULL(pk);
#endif
X509_set_version(cert, 2);
ASN1_INTEGER_set(X509_get_serialNumber(cert), 0);
@@ -55,20 +50,28 @@ void IdentityManager::createCredentials(QSettings& settings)
X509_gmtime_adj(X509_get_notBefore(cert), 0);
X509_gmtime_adj(X509_get_notAfter(cert), 60 * 60 * 24 * 365 * 20); // 20 yrs
#else
X509_gmtime_adj(X509_getm_notBefore(cert), 0);
X509_gmtime_adj(X509_getm_notAfter(cert), 60 * 60 * 24 * 365 * 20); // 20 yrs
ASN1_TIME* before = ASN1_STRING_dup(X509_get0_notBefore(cert));
THROW_BAD_ALLOC_IF_NULL(before);
ASN1_TIME* after = ASN1_STRING_dup(X509_get0_notAfter(cert));
THROW_BAD_ALLOC_IF_NULL(after);
X509_gmtime_adj(before, 0);
X509_gmtime_adj(after, 60 * 60 * 24 * 365 * 20); // 20 yrs
X509_set1_notBefore(cert, before);
X509_set1_notAfter(cert, after);
ASN1_STRING_free(before);
ASN1_STRING_free(after);
#endif
X509_set_pubkey(cert, pk);
X509_NAME* name = X509_NAME_new();
THROW_BAD_ALLOC_IF_NULL(name);
X509_NAME* name = X509_get_subject_name(cert);
X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC,
reinterpret_cast<unsigned char *>(const_cast<char*>("NVIDIA GameStream Client")),
-1, -1, 0);
X509_set_subject_name(cert, name);
X509_set_issuer_name(cert, name);
X509_NAME_free(name);
X509_sign(cert, pk, EVP_sha256());
@@ -92,14 +95,6 @@ void IdentityManager::createCredentials(QSettings& settings)
BIO_free(biokey);
BIO_free(biocert);
// Check that the new keypair is valid before persisting it
if (getSslCertificate().isNull()) {
qFatal("Newly generated certificate is unreadable");
}
if (getSslKey().isNull()) {
qFatal("Newly generated private key is unreadable");
}
settings.setValue(SER_CERT, m_CachedPemCert);
settings.setValue(SER_KEY, m_CachedPrivateKey);
@@ -128,26 +123,10 @@ IdentityManager::IdentityManager()
// We should have valid credentials now. If not, we're screwed
if (getSslCertificate().isNull()) {
qFatal("Certificate is unreadable");
qFatal("Newly generated certificate is unreadable");
}
if (getSslKey().isNull()) {
qFatal("Private key is unreadable");
}
// Load the unique ID from settings
m_CachedUniqueId = settings.value(SER_UNIQUEID).toString();
if (!m_CachedUniqueId.isEmpty()) {
qInfo() << "Loaded unique ID from settings:" << m_CachedUniqueId;
}
else {
// Generate a new unique ID in base 16
uint64_t uid;
RAND_bytes(reinterpret_cast<unsigned char*>(&uid), sizeof(uid));
m_CachedUniqueId = QString::number(uid, 16);
qInfo() << "Generated new unique ID:" << m_CachedUniqueId;
settings.setValue(SER_UNIQUEID, m_CachedUniqueId);
qFatal("Newly generated private key is unreadable");
}
}
@@ -186,7 +165,7 @@ IdentityManager::getSslKey()
BUF_MEM* mem;
BIO_get_mem_ptr(bio, &mem);
m_CachedSslKey = QSslKey(QByteArray(mem->data, (int)mem->length), QSsl::Rsa);
m_CachedSslKey = QSslKey(QByteArray::fromRawData(mem->data, (int)mem->length), QSsl::Rsa);
BIO_free(bio);
EVP_PKEY_free(pk);
@@ -206,6 +185,25 @@ IdentityManager::getSslConfig()
QString
IdentityManager::getUniqueId()
{
if (m_CachedUniqueId.isEmpty()) {
QSettings settings;
// Load the unique ID from settings
m_CachedUniqueId = settings.value(SER_UNIQUEID).toString();
if (!m_CachedUniqueId.isEmpty()) {
qInfo() << "Loaded unique ID from settings:" << m_CachedUniqueId;
}
else {
// Generate a new unique ID in base 16
uint64_t uid;
RAND_bytes(reinterpret_cast<unsigned char*>(&uid), sizeof(uid));
m_CachedUniqueId = QString::number(uid, 16);
qInfo() << "Generated new unique ID:" << m_CachedUniqueId;
settings.setValue(SER_UNIQUEID, m_CachedUniqueId);
}
}
return m_CachedUniqueId;
}
+1 -3
View File
@@ -25,9 +25,7 @@ public:
bool isInitialized()
{
// We use isNull() instead of isEmpty() here because we want
// to detect cases where the name is unassigned, not empty.
return id != 0 && !name.isNull();
return id != 0 && !name.isEmpty();
}
void
+62 -173
View File
@@ -21,7 +21,6 @@
#define SER_APPLIST "apps"
#define SER_SRVCERT "srvcert"
#define SER_CUSTOMNAME "customname"
#define SER_NVIDIASOFTWARE "nvidiasw"
NvComputer::NvComputer(QSettings& settings)
{
@@ -38,7 +37,6 @@ NvComputer::NvComputer(QSettings& settings)
this->manualAddress = NvAddress(settings.value(SER_MANUALADDR).toString(),
settings.value(SER_MANUALPORT, QVariant(DEFAULT_HTTP_PORT)).toUInt());
this->serverCert = QSslCertificate(settings.value(SER_SRVCERT).toByteArray());
this->isNvidiaServerSoftware = settings.value(SER_NVIDIASOFTWARE).toBool();
int appCount = settings.beginReadArray(SER_APPLIST);
this->appList.reserve(appCount);
@@ -67,14 +65,12 @@ NvComputer::NvComputer(QSettings& settings)
void NvComputer::setRemoteAddress(QHostAddress address)
{
QWriteLocker lock(&this->lock);
Q_ASSERT(this->externalPort != 0);
this->remoteAddress = NvAddress(address, this->externalPort);
}
void NvComputer::serialize(QSettings& settings, bool serializeApps) const
void NvComputer::serialize(QSettings& settings) const
{
QReadLocker lock(&this->lock);
@@ -91,35 +87,19 @@ void NvComputer::serialize(QSettings& settings, bool serializeApps) const
settings.setValue(SER_MANUALADDR, manualAddress.address());
settings.setValue(SER_MANUALPORT, manualAddress.port());
settings.setValue(SER_SRVCERT, serverCert.toPem());
settings.setValue(SER_NVIDIASOFTWARE, isNvidiaServerSoftware);
// Avoid deleting an existing applist if we couldn't get one
if (!appList.isEmpty() && serializeApps) {
if (!appList.isEmpty()) {
settings.remove(SER_APPLIST);
settings.beginWriteArray(SER_APPLIST);
for (int i = 0; i < appList.count(); i++) {
settings.setArrayIndex(i);
appList.at(i).serialize(settings);
appList[i].serialize(settings);
}
settings.endArray();
}
}
bool NvComputer::isEqualSerialized(const NvComputer &that) const
{
return this->name == that.name &&
this->hasCustomName == that.hasCustomName &&
this->uuid == that.uuid &&
this->macAddress == that.macAddress &&
this->localAddress == that.localAddress &&
this->remoteAddress == that.remoteAddress &&
this->ipv6Address == that.ipv6Address &&
this->manualAddress == that.manualAddress &&
this->serverCert == that.serverCert &&
this->isNvidiaServerSoftware == that.isNvidiaServerSoftware &&
this->appList == that.appList;
}
void NvComputer::sortAppList()
{
std::stable_sort(appList.begin(), appList.end(), [](const NvApp& app1, const NvApp& app2) {
@@ -141,7 +121,7 @@ NvComputer::NvComputer(NvHTTP& http, QString serverInfo)
QString newMacString = NvHTTP::getXmlString(serverInfo, "mac");
if (newMacString != "00:00:00:00:00:00") {
QStringList macOctets = newMacString.split(':');
for (const QString& macOctet : std::as_const(macOctets)) {
for (const QString& macOctet : macOctets) {
this->macAddress.append((char) macOctet.toInt(nullptr, 16));
}
}
@@ -151,8 +131,7 @@ NvComputer::NvComputer(NvHTTP& http, QString serverInfo)
this->serverCodecModeSupport = codecSupport.toInt();
}
else {
// Assume H.264 is always supported
this->serverCodecModeSupport = SCM_H264;
this->serverCodecModeSupport = 0;
}
QString maxLumaPixelsHEVC = NvHTTP::getXmlString(serverInfo, "MaxLumaPixelsHEVC");
@@ -166,8 +145,8 @@ NvComputer::NvComputer(NvHTTP& http, QString serverInfo)
this->displayModes = NvHTTP::getDisplayModeList(serverInfo);
std::stable_sort(this->displayModes.begin(), this->displayModes.end(),
[](const NvDisplayMode& mode1, const NvDisplayMode& mode2) {
return (uint64_t)mode1.width * mode1.height * mode1.refreshRate <
(uint64_t)mode2.width * mode2.height * mode2.refreshRate;
return mode1.width * mode1.height * mode1.refreshRate <
mode2.width * mode2.height * mode2.refreshRate;
});
// We can get an IPv4 loopback address if we're using the GS IPv6 Forwarder
@@ -185,7 +164,7 @@ NvComputer::NvComputer(NvHTTP& http, QString serverInfo)
// to support dynamic HTTP WAN ports without requiring the user to manually enter the port.
QString remotePortStr = NvHTTP::getXmlString(serverInfo, "ExternalPort");
if (remotePortStr.isEmpty() || (this->externalPort = remotePortStr.toUShort()) == 0) {
this->externalPort = http.httpPort();
this->externalPort = DEFAULT_HTTP_PORT;
}
QString remoteAddress = NvHTTP::getXmlString(serverInfo, "ExternalIP");
@@ -196,11 +175,6 @@ NvComputer::NvComputer(NvHTTP& http, QString serverInfo)
this->remoteAddress = NvAddress();
}
// Real Nvidia host software (GeForce Experience and RTX Experience) both use the 'Mjolnir'
// codename in the state field and no version of Sunshine does. We can use this to bypass
// some assumptions about Nvidia hardware that don't apply to Sunshine hosts.
this->isNvidiaServerSoftware = NvHTTP::getXmlString(serverInfo, "state").contains("MJOLNIR");
this->pairState = NvHTTP::getXmlString(serverInfo, "PairStatus") == "1" ?
PS_PAIRED : PS_NOT_PAIRED;
this->currentGameId = NvHTTP::getCurrentGame(serverInfo);
@@ -213,57 +187,43 @@ NvComputer::NvComputer(NvHTTP& http, QString serverInfo)
this->isSupportedServerVersion = CompatFetcher::isGfeVersionSupported(this->gfeVersion);
}
bool NvComputer::wake() const
bool NvComputer::wake()
{
QByteArray wolPayload;
{
QReadLocker readLocker(&lock);
if (state == NvComputer::CS_ONLINE) {
qWarning() << name << "is already online";
return true;
}
if (macAddress.isEmpty()) {
qWarning() << name << "has no MAC address stored";
return false;
}
// Create the WoL payload
wolPayload.append(QByteArray::fromHex("FFFFFFFFFFFF"));
for (int i = 0; i < 16; i++) {
wolPayload.append(macAddress);
}
Q_ASSERT(wolPayload.size() == 102);
if (state == NvComputer::CS_ONLINE) {
qWarning() << name << "is already online";
return true;
}
// Ports used as-is
const quint16 STATIC_WOL_PORTS[] = {
if (macAddress.isEmpty()) {
qWarning() << name << "has no MAC address stored";
return false;
}
const quint16 WOL_PORTS[] = {
9, // Standard WOL port (privileged port)
47998, 47999, 48000, 48002, 48010, // Ports opened by GFE
47009, // Port opened by Moonlight Internet Hosting Tool for WoL (non-privileged port)
};
// Ports offset by the HTTP base port for hosts using alternate ports
const quint16 DYNAMIC_WOL_PORTS[] = {
47998, 47999, 48000, 48002, 48010, // Ports opened by GFE
};
// Create the WoL payload
QByteArray wolPayload;
wolPayload.append(QByteArray::fromHex("FFFFFFFFFFFF"));
for (int i = 0; i < 16; i++) {
wolPayload.append(macAddress);
}
Q_ASSERT(wolPayload.count() == 102);
// Add the addresses that we know this host to be
// and broadcast addresses for this link just in
// case the host has timed out in ARP entries.
QMap<QString, quint16> addressMap;
QSet<quint16> basePortSet;
const auto uniqueHostAddresses = uniqueAddresses();
for (const NvAddress& addr : uniqueHostAddresses) {
addressMap.insert(addr.address(), addr.port());
basePortSet.insert(addr.port());
QVector<QString> addressList;
for (const NvAddress& addr : uniqueAddresses()) {
addressList.append(addr.address());
}
addressMap.insert("255.255.255.255", 0);
addressList.append("255.255.255.255");
// Try to broadcast on all available NICs
const auto allInterfaces = QNetworkInterface::allInterfaces();
for (const QNetworkInterface& nic : allInterfaces) {
for (const QNetworkInterface& nic : QNetworkInterface::allInterfaces()) {
// Ensure the interface is up and skip the loopback adapter
if ((nic.flags() & QNetworkInterface::IsUp) == 0 ||
(nic.flags() & QNetworkInterface::IsLoopBack) != 0) {
@@ -271,8 +231,7 @@ bool NvComputer::wake() const
}
QHostAddress allNodesMulticast("FF02::1");
const auto allInterfaceAddresses = nic.addressEntries();
for (const QNetworkAddressEntry& addr : allInterfaceAddresses) {
for (const QNetworkAddressEntry& addr : nic.addressEntries()) {
// Store the scope ID for this NIC if IPv6 is enabled
if (!addr.ip().scopeId().isEmpty()) {
allNodesMulticast.setScopeId(addr.ip().scopeId());
@@ -280,42 +239,31 @@ bool NvComputer::wake() const
// Skip IPv6 which doesn't support broadcast
if (!addr.broadcast().isNull()) {
addressMap.insert(addr.broadcast().toString(), 0);
addressList.append(addr.broadcast().toString());
}
}
if (!allNodesMulticast.scopeId().isEmpty()) {
addressMap.insert(allNodesMulticast.toString(), 0);
addressList.append(allNodesMulticast.toString());
}
}
// Try all unique address strings or host names
bool success = false;
for (auto i = addressMap.constBegin(); i != addressMap.constEnd(); i++) {
QHostAddress literalAddress;
QList<QHostAddress> addressList;
for (QString& addressString : addressList) {
QHostInfo hostInfo = QHostInfo::fromName(addressString);
// If this is an IPv4/IPv6 literal, don't use QHostInfo::fromName() because that will
// try to perform a reverse DNS lookup that leads to delays sending WoL packets.
if (literalAddress.setAddress(i.key())) {
addressList.append(literalAddress);
}
else {
QHostInfo hostInfo = QHostInfo::fromName(i.key());
if (hostInfo.error() != QHostInfo::NoError) {
qWarning() << "Error resolving" << i.key() << ":" << hostInfo.errorString();
continue;
}
addressList.append(hostInfo.addresses());
if (hostInfo.error() != QHostInfo::NoError) {
qWarning() << "Error resolving" << addressString << ":" << hostInfo.errorString();
continue;
}
// Try all IP addresses that this string resolves to
for (QHostAddress& address : addressList) {
for (QHostAddress& address : hostInfo.addresses()) {
QUdpSocket sock;
// Send to all static ports
for (quint16 port : STATIC_WOL_PORTS) {
// Send to all ports
for (quint16 port : WOL_PORTS) {
if (sock.writeDatagram(wolPayload, address, port)) {
qInfo().nospace().noquote() << "Sent WoL packet to " << name << " via " << address.toString() << ":" << port;
success = true;
@@ -324,69 +272,32 @@ bool NvComputer::wake() const
qWarning() << "Send failed:" << sock.error();
}
}
QList<quint16> basePorts;
if (i.value() != 0) {
// If we have a known base port for this address, use only that port
basePorts.append(i.value());
}
else {
// If this is a broadcast address without a known HTTP port, try all of them
basePorts.append(basePortSet.values());
}
// Send to all dynamic ports using the HTTP port offset(s) for this address
for (quint16 basePort : basePorts) {
for (quint16 port : DYNAMIC_WOL_PORTS) {
port = (port - 47989) + basePort;
if (sock.writeDatagram(wolPayload, address, port)) {
qInfo().nospace().noquote() << "Sent WoL packet to " << name << " via " << address.toString() << ":" << port;
success = true;
}
else {
qWarning() << "Send failed:" << sock.error();
}
}
}
}
}
return success;
}
NvComputer::ReachabilityType NvComputer::getActiveAddressReachability() const
bool NvComputer::isReachableOverVpn()
{
NvAddress copyOfActiveAddress;
{
QReadLocker readLocker(&lock);
if (activeAddress.isNull()) {
return ReachabilityType::RI_UNKNOWN;
}
// Grab a copy of the active address to avoid having to hold
// the computer lock while doing socket operations
copyOfActiveAddress = activeAddress;
if (activeAddress.isNull()) {
return false;
}
QTcpSocket s;
s.setProxy(QNetworkProxy::NoProxy);
s.connectToHost(copyOfActiveAddress.address(), copyOfActiveAddress.port());
s.connectToHost(activeAddress.address(), activeAddress.port());
if (s.waitForConnected(3000)) {
Q_ASSERT(!s.localAddress().isNull());
Q_ASSERT(!s.peerAddress().isNull());
const auto allInterfaces = QNetworkInterface::allInterfaces();
for (const QNetworkInterface& nic : allInterfaces) {
for (const QNetworkInterface& nic : QNetworkInterface::allInterfaces()) {
// Ensure the interface is up
if ((nic.flags() & QNetworkInterface::IsUp) == 0) {
continue;
}
const auto allInterfaceAddresses = nic.addressEntries();
for (const QNetworkAddressEntry& addr : allInterfaceAddresses) {
for (const QNetworkAddressEntry& addr : nic.addressEntries()) {
if (addr.ip() == s.localAddress()) {
qInfo() << "Found matching interface:" << nic.humanReadableName() << nic.hardwareAddress() << nic.flags();
@@ -397,68 +308,48 @@ NvComputer::ReachabilityType NvComputer::getActiveAddressReachability() const
if (nic.type() == QNetworkInterface::Virtual ||
nic.type() == QNetworkInterface::Ppp) {
// Treat PPP and virtual interfaces as likely VPNs
return ReachabilityType::RI_VPN;
return true;
}
if (nic.maximumTransmissionUnit() != 0 && nic.maximumTransmissionUnit() < 1500) {
// Treat MTUs under 1500 as likely VPNs
return ReachabilityType::RI_VPN;
return true;
}
#endif
if (nic.flags() & QNetworkInterface::IsPointToPoint) {
// Treat point-to-point links as likely VPNs.
// This check detects OpenVPN on Unix-like OSes.
return ReachabilityType::RI_VPN;
return true;
}
#ifdef Q_OS_WINDOWS
if (nic.name().startsWith("iftype53_") || nic.name().startsWith("iftype131_")) {
// Match by NDIS interface type. These values are Microsoft's recommended values for VPN connections:
// https://learn.microsoft.com/en-US/troubleshoot/windows-client/networking/windows-connection-manager-disconnects-wlan#more-information
//
// The following VPNs use IF_TYPE_PROP_VIRTUAL under Windows:
// - WireguardNT VPNs
// - All WinTun-based VPNs (such as Slack Nebula)
// - OpenVPN with tap-windows6
return ReachabilityType::RI_VPN;
}
#endif
if (nic.hardwareAddress().startsWith("00:FF", Qt::CaseInsensitive)) {
// OpenVPN TAP interfaces have a MAC address starting with 00:FF on Windows
return ReachabilityType::RI_VPN;
return true;
}
if (nic.humanReadableName().startsWith("ZeroTier")) {
// ZeroTier interfaces always start with "ZeroTier"
return ReachabilityType::RI_VPN;
return true;
}
if (nic.humanReadableName().contains("VPN")) {
// This one is just a final VPN heuristic if all else fails
return ReachabilityType::RI_VPN;
// This one is just a final heuristic if all else fails
return true;
}
// Didn't meet any of our VPN heuristics. Let's see if the peer address is on-link.
Q_ASSERT(addr.prefixLength() >= 0);
if (addr.prefixLength() >= 0 && s.localAddress().isInSubnet(s.peerAddress(), addr.prefixLength())) {
return ReachabilityType::RI_LAN;
}
// Default to unknown if nothing else matched
return ReachabilityType::RI_UNKNOWN;
// Didn't meet any of our VPN heuristics
return false;
}
}
}
qWarning() << "No match found for address:" << s.localAddress();
return ReachabilityType::RI_UNKNOWN;
return false;
}
else {
// If we fail to connect, just pretend that it's not a VPN
qWarning() << "Unable to check for reachability within 3 seconds";
return ReachabilityType::RI_UNKNOWN;
return false;
}
}
@@ -468,7 +359,7 @@ bool NvComputer::updateAppList(QVector<NvApp> newAppList) {
}
// Propagate client-side attributes to the new app list
for (const NvApp& existingApp : std::as_const(appList)) {
for (const NvApp& existingApp : appList) {
for (NvApp& newApp : newAppList) {
if (existingApp.id == newApp.id) {
newApp.hidden = existingApp.hidden;
@@ -484,7 +375,6 @@ bool NvComputer::updateAppList(QVector<NvApp> newAppList) {
QVector<NvAddress> NvComputer::uniqueAddresses() const
{
QReadLocker readLocker(&lock);
QVector<NvAddress> uniqueAddressList;
// Start with addresses correctly ordered
@@ -516,7 +406,7 @@ QVector<NvAddress> NvComputer::uniqueAddresses() const
return uniqueAddressList;
}
bool NvComputer::update(const NvComputer& that)
bool NvComputer::update(NvComputer& that)
{
bool changed = false;
@@ -566,7 +456,6 @@ bool NvComputer::update(const NvComputer& that)
ASSIGN_IF_CHANGED(gfeVersion);
ASSIGN_IF_CHANGED(appVersion);
ASSIGN_IF_CHANGED(isSupportedServerVersion);
ASSIGN_IF_CHANGED(isNvidiaServerSoftware);
ASSIGN_IF_CHANGED(maxLumaPixelsHEVC);
ASSIGN_IF_CHANGED(gpuModel);
ASSIGN_IF_CHANGED_AND_NONNULL(serverCert);
+6 -37
View File
@@ -8,16 +8,6 @@
#include <QSettings>
#include <QRunnable>
class CopySafeReadWriteLock : public QReadWriteLock
{
public:
CopySafeReadWriteLock() = default;
// Don't actually copy the QReadWriteLock
CopySafeReadWriteLock(const CopySafeReadWriteLock&) : QReadWriteLock() {}
CopySafeReadWriteLock& operator=(const CopySafeReadWriteLock &) { return *this; }
};
class NvComputer
{
friend class PcMonitorThread;
@@ -32,14 +22,6 @@ private:
bool pendingQuit;
public:
NvComputer() = default;
// Caller is responsible for synchronizing read access to the other host
NvComputer(const NvComputer&) = default;
// Caller is responsible for synchronizing read access to the other host
NvComputer& operator=(const NvComputer &) = default;
explicit NvComputer(NvHTTP& http, QString serverInfo);
explicit NvComputer(QSettings& settings);
@@ -48,30 +30,19 @@ public:
setRemoteAddress(QHostAddress);
bool
update(const NvComputer& that);
update(NvComputer& that);
bool
wake() const;
wake();
enum ReachabilityType
{
RI_UNKNOWN,
RI_LAN,
RI_VPN,
};
ReachabilityType
getActiveAddressReachability() const;
bool
isReachableOverVpn();
QVector<NvAddress>
uniqueAddresses() const;
void
serialize(QSettings& settings, bool serializeApps) const;
// Caller is responsible for synchronizing read access to both hosts
bool
isEqualSerialized(const NvComputer& that) const;
serialize(QSettings& settings) const;
enum PairState
{
@@ -112,11 +83,9 @@ public:
QString uuid;
QSslCertificate serverCert;
QVector<NvApp> appList;
bool isNvidiaServerSoftware;
// Remember to update isEqualSerialized() when adding fields here!
// Synchronization
mutable CopySafeReadWriteLock lock;
mutable QReadWriteLock lock;
private:
uint16_t externalPort;
+94 -91
View File
@@ -18,16 +18,8 @@
#define RESUME_TIMEOUT_MS 30000
#define QUIT_TIMEOUT_MS 30000
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
#define XML_NAME_EQUALS(x, y) ((x) == (y))
#else
#define XML_NAME_EQUALS(x, y) ((x) == (u##y))
#endif
NvHTTP::NvHTTP(NvAddress address, uint16_t httpsPort, QSslCertificate serverCert, bool useTrueUid, QNetworkAccessManager* nam) :
m_Nam(nam ? nam : new QNetworkAccessManager(this)),
m_ServerCert(serverCert),
m_UseTrueUid(useTrueUid)
NvHTTP::NvHTTP(NvAddress address, uint16_t httpsPort, QSslCertificate serverCert) :
m_ServerCert(serverCert)
{
m_BaseUrlHttp.setScheme("http");
m_BaseUrlHttps.setScheme("https");
@@ -37,12 +29,15 @@ NvHTTP::NvHTTP(NvAddress address, uint16_t httpsPort, QSslCertificate serverCert
// Never use a proxy server
QNetworkProxy noProxy(QNetworkProxy::NoProxy);
m_Nam->setProxy(noProxy);
m_Nam.setProxy(noProxy);
connect(&m_Nam, &QNetworkAccessManager::sslErrors, this, &NvHTTP::handleSslErrors);
}
NvHTTP::NvHTTP(NvComputer* computer, QNetworkAccessManager* nam) :
NvHTTP(computer->activeAddress, computer->activeHttpsPort, computer->serverCert, !computer->isNvidiaServerSoftware, nam)
NvHTTP::NvHTTP(NvComputer* computer) :
NvHTTP(computer->activeAddress, computer->activeHttpsPort, computer->serverCert)
{
}
void NvHTTP::setServerCert(QSslCertificate serverCert)
@@ -67,11 +62,6 @@ void NvHTTP::setHttpsPort(uint16_t port)
m_BaseUrlHttps.setPort(port);
}
void NvHTTP::setTrueUid(bool useTrueUid)
{
m_UseTrueUid = useTrueUid;
}
NvAddress NvHTTP::address()
{
return m_Address;
@@ -120,7 +110,7 @@ NvHTTP::getCurrentGame(QString serverInfo)
// has the semantics that its name would indicate. To contain the effects of this change as much
// as possible, we'll force the current game to zero if the server isn't in a streaming session.
QString serverState = getXmlString(serverInfo, "state");
if (serverState.endsWith("_SERVER_BUSY"))
if (serverState != nullptr && serverState.endsWith("_SERVER_BUSY"))
{
return getXmlString(serverInfo, "currentgame").toInt();
}
@@ -197,15 +187,12 @@ NvHTTP::getServerInfo(NvLogLevel logLevel, bool fastFail)
}
void
NvHTTP::startApp(QString verb,
bool isGfe,
int appId,
PSTREAM_CONFIGURATION streamConfig,
bool sops,
bool localAudio,
int gamepadMask,
bool persistGameControllersOnDisconnect,
QString& rtspSessionUrl)
NvHTTP::launchApp(int appId,
PSTREAM_CONFIGURATION streamConfig,
bool sops,
bool localAudio,
int gamepadMask,
QString& rtspSessionUrl)
{
int riKeyId;
@@ -214,27 +201,25 @@ NvHTTP::startApp(QString verb,
QString response =
openConnectionToString(m_BaseUrlHttps,
verb,
"launch",
"appid="+QString::number(appId)+
"&mode="+QString::number(streamConfig->width)+"x"+
QString::number(streamConfig->height)+"x"+
// Using an FPS value over 60 causes SOPS to default to 720p60,
// so force it to 0 to ensure the correct resolution is set. We
// used to use 60 here but that locked the frame rate to 60 FPS
// on GFE 3.20.3. We don't need this hack for Sunshine.
QString::number((streamConfig->fps > 60 && isGfe) ? 0 : streamConfig->fps)+
// on GFE 3.20.3.
QString::number(streamConfig->fps > 60 ? 0 : streamConfig->fps)+
"&additionalStates=1&sops="+QString::number(sops ? 1 : 0)+
"&rikey="+QByteArray(streamConfig->remoteInputAesKey, sizeof(streamConfig->remoteInputAesKey)).toHex()+
"&rikeyid="+QString::number(riKeyId)+
((streamConfig->supportedVideoFormats & VIDEO_FORMAT_MASK_10BIT) ?
(streamConfig->enableHdr ?
"&hdrMode=1&clientHdrCapVersion=0&clientHdrCapSupportedFlagsInUint32=0&clientHdrCapMetaDataId=NV_STATIC_METADATA_TYPE_1&clientHdrCapDisplayData=0x0x0x0x0x0x0x0x0x0x0" :
"")+
"&localAudioPlayMode="+QString::number(localAudio ? 1 : 0)+
"&surroundAudioInfo="+QString::number(SURROUNDAUDIOINFO_FROM_AUDIO_CONFIGURATION(streamConfig->audioConfiguration))+
"&remoteControllersBitmap="+QString::number(gamepadMask)+
"&gcmap="+QString::number(gamepadMask)+
"&gcpersist="+QString::number(persistGameControllersOnDisconnect ? 1 : 0)+
LiGetLaunchUrlQueryParameters(),
"&gcmap="+QString::number(gamepadMask),
LAUNCH_TIMEOUT_MS);
qInfo() << "Launch response:" << response;
@@ -245,6 +230,30 @@ NvHTTP::startApp(QString verb,
rtspSessionUrl = getXmlString(response, "sessionUrl0");
}
void
NvHTTP::resumeApp(PSTREAM_CONFIGURATION streamConfig, QString& rtspSessionUrl)
{
int riKeyId;
memcpy(&riKeyId, streamConfig->remoteInputAesIv, sizeof(riKeyId));
riKeyId = qFromBigEndian(riKeyId);
QString response =
openConnectionToString(m_BaseUrlHttps,
"resume",
"rikey="+QString(QByteArray(streamConfig->remoteInputAesKey, sizeof(streamConfig->remoteInputAesKey)).toHex())+
"&rikeyid="+QString::number(riKeyId)+
"&surroundAudioInfo="+QString::number(SURROUNDAUDIOINFO_FROM_AUDIO_CONFIGURATION(streamConfig->audioConfiguration)),
RESUME_TIMEOUT_MS);
qInfo() << "Resume response:" << response;
// Throws if the request failed
verifyResponseStatus(response);
rtspSessionUrl = getXmlString(response, "sessionUrl0");
}
void
NvHTTP::quitApp()
{
@@ -260,7 +269,7 @@ NvHTTP::quitApp()
verifyResponseStatus(response);
// Newer GFE versions will just return success even if quitting fails
// if we're not the original requester.
// if we're not the original requestor.
if (getCurrentGame(getServerInfo(NvHTTP::NVLL_ERROR)) != 0) {
// Generate a synthetic GfeResponseException letting the caller know
// that they can't kill someone else's stream.
@@ -277,19 +286,17 @@ NvHTTP::getDisplayModeList(QString serverInfo)
while (!xmlReader.atEnd()) {
while (xmlReader.readNextStartElement()) {
auto name = xmlReader.name();
if (XML_NAME_EQUALS(name, "DisplayMode")) {
if (name == QString("DisplayMode")) {
modes.append(NvDisplayMode());
}
else if (!modes.isEmpty()) {
if (XML_NAME_EQUALS(name, "Width")) {
modes.last().width = xmlReader.readElementText().toInt();
}
else if (XML_NAME_EQUALS(name, "Height")) {
modes.last().height = xmlReader.readElementText().toInt();
}
else if (XML_NAME_EQUALS(name, "RefreshRate")) {
modes.last().refreshRate = xmlReader.readElementText().toInt();
}
else if (name == QString("Width")) {
modes.last().width = xmlReader.readElementText().toInt();
}
else if (name == QString("Height")) {
modes.last().height = xmlReader.readElementText().toInt();
}
else if (name == QString("RefreshRate")) {
modes.last().refreshRate = xmlReader.readElementText().toInt();
}
}
}
@@ -312,36 +319,26 @@ NvHTTP::getAppList()
while (!xmlReader.atEnd()) {
while (xmlReader.readNextStartElement()) {
auto name = xmlReader.name();
if (XML_NAME_EQUALS(name, "App")) {
if (name == QString("App")) {
// We must have a valid app before advancing to the next one
if (!apps.isEmpty() && !apps.last().isInitialized()) {
qWarning() << "Invalid applist XML";
throw std::runtime_error("Invalid applist XML");
Q_ASSERT(false);
return QVector<NvApp>();
}
apps.append(NvApp());
}
else if (!apps.isEmpty()) {
if (XML_NAME_EQUALS(name, "AppTitle")) {
// If an app has no name, Sunshine may send us <AppTitle/>,
// which readElementText() returns as a null QString.
// We want to treat this as an empty QString instead, so we
// will explicitly convert it. An empty string will satisfy
// NvApp's isInitialized() check.
QString name = xmlReader.readElementText();
if (name.isNull()) {
name = "";
}
apps.last().name = name;
}
else if (XML_NAME_EQUALS(name, "ID")) {
apps.last().id = xmlReader.readElementText().toInt();
}
else if (XML_NAME_EQUALS(name, "IsHdrSupported")) {
apps.last().hdrSupported = xmlReader.readElementText() == "1";
}
else if (XML_NAME_EQUALS(name, "IsAppCollectorGame")) {
apps.last().isAppCollectorGame = xmlReader.readElementText() == "1";
}
else if (name == QString("AppTitle")) {
apps.last().name = xmlReader.readElementText();
}
else if (name == QString("ID")) {
apps.last().id = xmlReader.readElementText().toInt();
}
else if (name == QString("IsHdrSupported")) {
apps.last().hdrSupported = xmlReader.readElementText() == "1";
}
else if (name == QString("IsAppCollectorGame")) {
apps.last().isAppCollectorGame = xmlReader.readElementText() == "1";
}
}
}
@@ -356,7 +353,7 @@ NvHTTP::verifyResponseStatus(QString xml)
while (xmlReader.readNextStartElement())
{
if (XML_NAME_EQUALS(xmlReader.name(), "root"))
if (xmlReader.name() == QString("root"))
{
// Status code can be 0xFFFFFFFF in some rare cases on GFE 3.20.3, and
// QString::toInt() will fail in that case, so use QString::toUInt()
@@ -385,7 +382,7 @@ NvHTTP::verifyResponseStatus(QString xml)
}
}
throw GfeHttpResponseException(-1, "Malformed XML (missing root element)");
throw GfeHttpResponseException(-1, "Malformed GFE XML (missing root element)");
}
QImage
@@ -407,7 +404,13 @@ QByteArray
NvHTTP::getXmlStringFromHex(QString xml,
QString tagName)
{
return QByteArray::fromHex(getXmlString(xml, tagName).toUtf8());
QString str = getXmlString(xml, tagName);
if (str == nullptr)
{
return nullptr;
}
return QByteArray::fromHex(str.toLatin1());
}
QString
@@ -429,7 +432,7 @@ NvHTTP::getXmlString(QString xml,
}
}
return QString();
return nullptr;
}
void NvHTTP::handleSslErrors(QNetworkReply* reply, const QList<QSslError>& errors)
@@ -492,9 +495,11 @@ NvHTTP::openConnection(QUrl baseUrl,
QUrl url(baseUrl);
url.setPath("/" + command);
// Use a placeholder UID for GFE allow them to quit games for each other.
url.setQuery("uniqueid=" + (m_UseTrueUid ? IdentityManager::get()->getUniqueId() : "0123456789ABCDEF") +
"&uuid=" + QUuid::createUuid().toRfc4122().toHex() +
// Use a common UID for Moonlight clients to allow them to quit
// games for each other (otherwise GFE gets screwed up and it requires
// manual intervention to solve).
url.setQuery("uniqueid=0123456789ABCDEF&uuid=" +
QUuid::createUuid().toRfc4122().toHex() +
((arguments != nullptr) ? ("&" + arguments) : ""));
QNetworkRequest request(url);
@@ -507,15 +512,15 @@ NvHTTP::openConnection(QUrl baseUrl,
request.setAttribute(QNetworkRequest::Http2AllowedAttribute, false);
#endif
#if QT_VERSION >= QT_VERSION_CHECK(6, 3, 0)
// Use fine-grained idle timeouts to avoid calling QNetworkAccessManager::clearAccessCache(),
// which tears down the NAM's global thread each time. We must not keep persistent connections
// or GFE will puke.
request.setAttribute(QNetworkRequest::ConnectionCacheExpiryTimeoutSecondsAttribute, 0);
#if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0) && QT_VERSION < QT_VERSION_CHECK(5, 15, 1) && !defined(QT_NO_BEARERMANAGEMENT)
// HACK: Set network accessibility to work around QTBUG-80947 (introduced in Qt 5.14.0 and fixed in Qt 5.15.1)
QT_WARNING_PUSH
QT_WARNING_DISABLE_DEPRECATED
m_Nam.setNetworkAccessible(QNetworkAccessManager::Accessible);
QT_WARNING_POP
#endif
auto sslErrorsConnection = connect(m_Nam, &QNetworkAccessManager::sslErrors, this, &NvHTTP::handleSslErrors);
QNetworkReply* reply = m_Nam->get(request);
QNetworkReply* reply = m_Nam.get(request);
// Run the request with a timeout if requested
QEventLoop loop;
@@ -538,17 +543,15 @@ NvHTTP::openConnection(QUrl baseUrl,
reply->abort();
}
#if QT_VERSION < QT_VERSION_CHECK(6, 3, 0)
// If we couldn't use fine-grained connection idle timeouts, kill them all now
m_Nam->clearAccessCache();
#endif
disconnect(sslErrorsConnection);
// We must clear out cached authentication and connections or
// GFE will puke next time
m_Nam.clearAccessCache();
// Handle error
if (reply->error() != QNetworkReply::NoError)
{
if (logLevel >= NvLogLevel::NVLL_ERROR) {
qWarning() << command << "request failed with error:" << reply->error();
qWarning() << command << " request failed with error " << reply->error();
}
if (reply->error() == QNetworkReply::SslHandshakeFailedError) {
+24 -24
View File
@@ -33,19 +33,19 @@ class GfeHttpResponseException : public std::exception
public:
GfeHttpResponseException(int statusCode, QString message) :
m_StatusCode(statusCode),
m_StatusMessage(message.toUtf8())
m_StatusMessage(message)
{
}
const char* what() const throw()
{
return m_StatusMessage.constData();
return m_StatusMessage.toLatin1();
}
const char* getStatusMessage() const
{
return m_StatusMessage.constData();
return m_StatusMessage.toLatin1();
}
int getStatusCode() const
@@ -55,12 +55,12 @@ public:
QString toQString() const
{
return QString::fromUtf8(m_StatusMessage) + " (Error " + QString::number(m_StatusCode) + ")";
return m_StatusMessage + " (Error " + QString::number(m_StatusCode) + ")";
}
private:
int m_StatusCode;
QByteArray m_StatusMessage;
QString m_StatusMessage;
};
class QtNetworkReplyException : public std::exception
@@ -68,19 +68,19 @@ class QtNetworkReplyException : public std::exception
public:
QtNetworkReplyException(QNetworkReply::NetworkError error, QString errorText) :
m_Error(error),
m_ErrorText(errorText.toUtf8())
m_ErrorText(errorText)
{
}
const char* what() const throw()
{
return m_ErrorText.constData();
return m_ErrorText.toLatin1();
}
const char* getErrorText() const
{
return m_ErrorText.constData();
return m_ErrorText.toLatin1();
}
QNetworkReply::NetworkError getError() const
@@ -90,12 +90,12 @@ public:
QString toQString() const
{
return QString::fromUtf8(m_ErrorText) + " (Error " + QString::number(m_Error) + ")";
return m_ErrorText + " (Error " + QString::number(m_Error) + ")";
}
private:
QNetworkReply::NetworkError m_Error;
QByteArray m_ErrorText;
QString m_ErrorText;
};
class NvHTTP : public QObject
@@ -109,9 +109,9 @@ public:
NVLL_VERBOSE
};
explicit NvHTTP(NvAddress address, uint16_t httpsPort, QSslCertificate serverCert, bool useTrueUid, QNetworkAccessManager* nam = nullptr);
explicit NvHTTP(NvAddress address, uint16_t httpsPort, QSslCertificate serverCert);
explicit NvHTTP(NvComputer* computer, QNetworkAccessManager* nam = nullptr);
explicit NvHTTP(NvComputer* computer);
static
int
@@ -142,9 +142,9 @@ public:
NvLogLevel logLevel = NvLogLevel::NVLL_VERBOSE);
void setServerCert(QSslCertificate serverCert);
void setAddress(NvAddress address);
void setHttpsPort(uint16_t port);
void setTrueUid(bool useTrueUid);
NvAddress address();
@@ -162,15 +162,16 @@ public:
quitApp();
void
startApp(QString verb,
bool isGfe,
int appId,
PSTREAM_CONFIGURATION streamConfig,
bool sops,
bool localAudio,
int gamepadMask,
bool persistGameControllersOnDisconnect,
QString& rtspSessionUrl);
resumeApp(PSTREAM_CONFIGURATION streamConfig,
QString& rtspSessionUrl);
void
launchApp(int appId,
PSTREAM_CONFIGURATION streamConfig,
bool sops,
bool localAudio,
int gamepadMask,
QString& rtspSessionUrl);
QVector<NvApp>
getAppList();
@@ -196,7 +197,6 @@ private:
NvLogLevel logLevel);
NvAddress m_Address;
QNetworkAccessManager* m_Nam;
QNetworkAccessManager m_Nam;
QSslCertificate m_ServerCert;
bool m_UseTrueUid;
};
+36 -53
View File
@@ -54,18 +54,16 @@ NvPairingManager::generateRandomBytes(int length)
QByteArray
NvPairingManager::encrypt(const QByteArray& plaintext, const QByteArray& key)
{
if (plaintext.isEmpty()) {
return QByteArray();
}
QByteArray ciphertext(plaintext.size(), 0);
EVP_CIPHER_CTX* cipher;
int ciphertextLen;
EVP_CIPHER_CTX* cipher = EVP_CIPHER_CTX_new();
cipher = EVP_CIPHER_CTX_new();
THROW_BAD_ALLOC_IF_NULL(cipher);
EVP_EncryptInit(cipher, EVP_aes_128_ecb(), reinterpret_cast<const unsigned char*>(key.data()), NULL);
EVP_CIPHER_CTX_set_padding(cipher, 0);
QByteArray ciphertext(plaintext.size(), 0);
int ciphertextLen;
EVP_EncryptUpdate(cipher,
reinterpret_cast<unsigned char*>(ciphertext.data()),
&ciphertextLen,
@@ -81,18 +79,16 @@ NvPairingManager::encrypt(const QByteArray& plaintext, const QByteArray& key)
QByteArray
NvPairingManager::decrypt(const QByteArray& ciphertext, const QByteArray& key)
{
if (ciphertext.isEmpty()) {
return QByteArray();
}
QByteArray plaintext(ciphertext.size(), 0);
EVP_CIPHER_CTX* cipher;
int plaintextLen;
EVP_CIPHER_CTX* cipher = EVP_CIPHER_CTX_new();
cipher = EVP_CIPHER_CTX_new();
THROW_BAD_ALLOC_IF_NULL(cipher);
EVP_DecryptInit(cipher, EVP_aes_128_ecb(), reinterpret_cast<const unsigned char*>(key.data()), NULL);
EVP_CIPHER_CTX_set_padding(cipher, 0);
QByteArray plaintext(ciphertext.size(), 0);
int plaintextLen;
EVP_DecryptUpdate(cipher,
reinterpret_cast<unsigned char*>(plaintext.data()),
&plaintextLen,
@@ -105,29 +101,6 @@ NvPairingManager::decrypt(const QByteArray& ciphertext, const QByteArray& key)
return plaintext;
}
QByteArray
NvPairingManager::getSignatureFromCert(X509* cert)
{
#if (OPENSSL_VERSION_NUMBER < 0x10002000L)
ASN1_BIT_STRING *asnSignature = cert->signature;
#elif (OPENSSL_VERSION_NUMBER < 0x10100000L)
ASN1_BIT_STRING *asnSignature;
X509_get0_signature(&asnSignature, NULL, cert);
#else
const ASN1_BIT_STRING *asnSignature;
X509_get0_signature(&asnSignature, NULL, cert);
#endif
return QByteArray(
#if (OPENSSL_VERSION_NUMBER < 0x10100000L)
reinterpret_cast<const char*>(ASN1_STRING_data(asnSignature)),
#else
reinterpret_cast<const char*>(ASN1_STRING_get0_data(asnSignature)),
#endif
ASN1_STRING_length(asnSignature)
);
}
QByteArray
NvPairingManager::getSignatureFromPemCert(const QByteArray& certificate)
{
@@ -141,7 +114,18 @@ NvPairingManager::getSignatureFromPemCert(const QByteArray& certificate)
X509* cert = PEM_read_bio_X509(bio, nullptr, nullptr, nullptr);
BIO_free_all(bio);
QByteArray signature = getSignatureFromCert(cert);
#if (OPENSSL_VERSION_NUMBER < 0x10002000L)
ASN1_BIT_STRING *asnSignature = cert->signature;
#elif (OPENSSL_VERSION_NUMBER < 0x10100000L)
ASN1_BIT_STRING *asnSignature;
X509_get0_signature(&asnSignature, NULL, cert);
#else
const ASN1_BIT_STRING *asnSignature;
X509_get0_signature(&asnSignature, NULL, cert);
#endif
QByteArray signature(reinterpret_cast<char*>(asnSignature->data), asnSignature->length);
X509_free(cert);
return signature;
@@ -200,7 +184,7 @@ NvPairingManager::signMessage(const QByteArray& message)
QByteArray
NvPairingManager::saltPin(const QByteArray& salt, QString pin)
{
return QByteArray().append(salt).append(pin.toUtf8());
return QByteArray().append(salt).append(pin.toLatin1());
}
NvPairingManager::PairState
@@ -243,7 +227,8 @@ NvPairingManager::pair(QString appVersion, QString pin, QSslCertificate& serverC
}
QByteArray serverCertStr = NvHTTP::getXmlStringFromHex(getCert, "plaincert");
if (serverCertStr.isEmpty()) {
if (serverCertStr == nullptr)
{
qCritical() << "Server likely already pairing";
m_Http.openConnectionToString(m_Http.m_BaseUrlHttp, "unpair", nullptr, REQUEST_TIMEOUT_MS);
return PairState::ALREADY_IN_PROGRESS;
@@ -278,18 +263,22 @@ NvPairingManager::pair(QString appVersion, QString pin, QSslCertificate& serverC
}
QByteArray challengeResponseData = decrypt(m_Http.getXmlStringFromHex(challengeXml, "challengeresponse"), aesKey);
if (challengeResponseData.size() < hashLength) {
qCritical() << "Invalid challengeresponse at stage #2";
m_Http.openConnectionToString(m_Http.m_BaseUrlHttp, "unpair", nullptr, REQUEST_TIMEOUT_MS);
return PairState::FAILED;
}
QByteArray clientSecretData = generateRandomBytes(16);
QByteArray challengeResponse;
QByteArray serverResponse(challengeResponseData.data(), hashLength);
#if (OPENSSL_VERSION_NUMBER < 0x10002000L)
ASN1_BIT_STRING *asnSignature = m_Cert->signature;
#elif (OPENSSL_VERSION_NUMBER < 0x10100000L)
ASN1_BIT_STRING *asnSignature;
X509_get0_signature(&asnSignature, NULL, m_Cert);
#else
const ASN1_BIT_STRING *asnSignature;
X509_get0_signature(&asnSignature, NULL, m_Cert);
#endif
challengeResponse.append(challengeResponseData.data() + hashLength, 16);
challengeResponse.append(getSignatureFromCert(m_Cert));
challengeResponse.append(reinterpret_cast<char*>(asnSignature->data), asnSignature->length);
challengeResponse.append(clientSecretData);
QByteArray paddedHash = QCryptographicHash::hash(challengeResponse, hashAlgo);
@@ -309,14 +298,8 @@ NvPairingManager::pair(QString appVersion, QString pin, QSslCertificate& serverC
}
QByteArray pairingSecret = NvHTTP::getXmlStringFromHex(respXml, "pairingsecret");
if (pairingSecret.size() <= 16) {
qCritical() << "Invalid pairingsecret at stage #3";
m_Http.openConnectionToString(m_Http.m_BaseUrlHttp, "unpair", nullptr, REQUEST_TIMEOUT_MS);
return PairState::FAILED;
}
QByteArray serverSecret = pairingSecret.left(16);
QByteArray serverSignature = pairingSecret.mid(16);
QByteArray serverSecret = QByteArray(pairingSecret.data(), 16);
QByteArray serverSignature = QByteArray(&pairingSecret.data()[16], 256);
if (!verifySignature(serverSecret,
serverSignature,
-3
View File
@@ -37,9 +37,6 @@ private:
QByteArray
decrypt(const QByteArray& ciphertext, const QByteArray& key);
QByteArray
getSignatureFromCert(X509* cert);
QByteArray
getSignatureFromPemCert(const QByteArray& certificate);
+117 -135
View File
@@ -2,7 +2,6 @@
#include "utils.h"
#include <QGuiApplication>
#include <QLibraryInfo>
#include "streaming/session.h"
#include "streaming/streamutils.h"
@@ -12,53 +11,21 @@
#include <Windows.h>
#endif
class SystemPropertyQueryThread : public QThread
{
public:
SystemPropertyQueryThread(SystemProperties* properties)
: QThread(properties), m_Properties(properties)
{
setObjectName("System Properties Async Query Thread");
}
private:
void run() override
{
bool hasHardwareAcceleration;
bool rendererAlwaysFullScreen;
bool supportsHdr;
QSize maximumResolution;
Session::getDecoderInfo(m_Properties->testWindow, hasHardwareAcceleration, rendererAlwaysFullScreen, supportsHdr, maximumResolution);
// Propagate the decoder properties to the SystemProperties singleton and emit any change signals on the main thread
QMetaObject::invokeMethod(m_Properties, "updateDecoderProperties",
Qt::QueuedConnection,
Q_ARG(bool, hasHardwareAcceleration),
Q_ARG(bool, rendererAlwaysFullScreen),
Q_ARG(QSize, maximumResolution),
Q_ARG(bool, supportsHdr));
}
private:
SystemProperties* m_Properties;
};
SystemProperties::SystemProperties()
{
versionString = QString(VERSION_STR);
hasDesktopEnvironment = WMUtils::isRunningDesktopEnvironment();
isRunningWayland = WMUtils::isRunningWayland();
isRunningXWayland = isRunningWayland && QGuiApplication::platformName() == "xcb";
usesMaterial3Theme = QLibraryInfo::version() >= QVersionNumber(6, 5, 0);
QString nativeArch = QSysInfo::currentCpuArchitecture();
#ifdef Q_OS_WIN32
{
USHORT processArch, machineArch;
// Use IsWow64Process2() because it doesn't lie on ARM64
if (IsWow64Process2(GetCurrentProcess(), &processArch, &machineArch)) {
// Use IsWow64Process2 on TH2 and later, because it supports ARM64
auto fnIsWow64Process2 = (decltype(IsWow64Process2)*)GetProcAddress(GetModuleHandleA("kernel32.dll"), "IsWow64Process2");
if (fnIsWow64Process2 != nullptr && fnIsWow64Process2(GetCurrentProcess(), &processArch, &machineArch)) {
switch (machineArch) {
case IMAGE_FILE_MACHINE_I386:
nativeArch = "i386";
@@ -97,86 +64,62 @@ SystemProperties::SystemProperties()
hasDiscordIntegration = false;
#endif
// These will be queried asynchronously to avoid blocking the UI
hasHardwareAcceleration = true;
rendererAlwaysFullScreen = false;
supportsHdr = true;
maximumResolution = QSize(0, 0);
unmappedGamepads = SdlInputHandler::getUnmappedGamepads();
// Populate data that requires talking to SDL. We do it all in one shot
// and cache the results to speed up future queries on this data.
querySdlVideoInfo();
Q_ASSERT(maximumStreamingFrameRate >= 60);
Q_ASSERT(!monitorDesktopResolutions.isEmpty());
Q_ASSERT(!monitorNativeResolutions.isEmpty());
}
SystemProperties::~SystemProperties()
QRect SystemProperties::getDesktopResolution(int displayIndex)
{
waitForAsyncLoad();
}
void SystemProperties::updateDecoderProperties(bool hasHardwareAcceleration, bool rendererAlwaysFullScreen, QSize maximumResolution, bool supportsHdr)
{
SDL_assert(testWindow);
if (hasHardwareAcceleration != this->hasHardwareAcceleration) {
this->hasHardwareAcceleration = hasHardwareAcceleration;
emit hasHardwareAccelerationChanged();
}
if (rendererAlwaysFullScreen != this->rendererAlwaysFullScreen) {
this->rendererAlwaysFullScreen = rendererAlwaysFullScreen;
emit rendererAlwaysFullScreenChanged();
}
if (maximumResolution != this->maximumResolution) {
this->maximumResolution = maximumResolution;
emit maximumResolutionChanged();
}
if (supportsHdr != this->supportsHdr) {
this->supportsHdr = supportsHdr;
emit supportsHdrChanged();
}
SDL_DestroyWindow(testWindow);
testWindow = nullptr;
SDL_QuitSubSystem(SDL_INIT_VIDEO);
// Returns default constructed QRect if out of bounds
return monitorDesktopResolutions.value(displayIndex);
}
QRect SystemProperties::getNativeResolution(int displayIndex)
{
// Returns default constructed QRect if out of bounds
Q_ASSERT(!monitorNativeResolutions.isEmpty());
return monitorNativeResolutions.value(displayIndex);
}
QRect SystemProperties::getSafeAreaResolution(int displayIndex)
class QuerySdlVideoThread : public QThread
{
// Returns default constructed QRect if out of bounds
Q_ASSERT(!monitorSafeAreaResolutions.isEmpty());
return monitorSafeAreaResolutions.value(displayIndex);
}
public:
QuerySdlVideoThread(SystemProperties* me) :
QThread(nullptr),
m_Me(me) {}
int SystemProperties::getRefreshRate(int displayIndex)
{
// Returns 0 if out of bounds
Q_ASSERT(!monitorRefreshRates.isEmpty());
return monitorRefreshRates.value(displayIndex);
}
void SystemProperties::startAsyncLoad()
{
if (systemPropertyQueryThread) {
// Already started/completed
return;
void run() override
{
m_Me->querySdlVideoInfoInternal();
}
// This isn't actually asynchronous (due to the need to synchronize with
// SdlGamepadKeyNavigation), but we don't query it in the constructor
// because it's expensive.
unmappedGamepads = SdlInputHandler::getUnmappedGamepads();
if (!unmappedGamepads.isEmpty()) {
emit unmappedGamepadsChanged();
SystemProperties* m_Me;
};
void SystemProperties::querySdlVideoInfo()
{
if (WMUtils::isRunningX11() || WMUtils::isRunningWayland()) {
// Use a separate thread to temporarily initialize SDL
// video to avoid stomping on Qt's X11 and OGL state.
QuerySdlVideoThread thread(this);
thread.start();
thread.wait();
}
else {
querySdlVideoInfoInternal();
}
}
void SystemProperties::querySdlVideoInfoInternal()
{
hasHardwareAcceleration = false;
// We initialize the video subsystem and test window on the main thread
// because some platforms (macOS) do not support window creation on
// non-main threads.
if (SDL_InitSubSystem(SDL_INIT_VIDEO) != 0) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
"SDL_InitSubSystem(SDL_INIT_VIDEO) failed: %s",
@@ -184,34 +127,64 @@ void SystemProperties::startAsyncLoad()
return;
}
testWindow = StreamUtils::createTestWindow();
if (!testWindow) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
"Failed to create window for hardware decode test: %s",
SDL_GetError());
SDL_QuitSubSystem(SDL_INIT_VIDEO);
return;
}
// Update display related attributes (max FPS, native resolution, etc).
//
// NB: SDL3 will forcefully refresh displays when a window is created,
// so we place this after the window creation to ensure we don't pay
// the penalty for mode enumeration twice.
refreshDisplays();
// We call the internal variant because we're already in a safe thread context.
refreshDisplaysInternal();
systemPropertyQueryThread = new SystemPropertyQueryThread(this);
systemPropertyQueryThread->start();
SDL_Window* testWindow = SDL_CreateWindow("", 0, 0, 1280, 720,
SDL_WINDOW_HIDDEN | StreamUtils::getPlatformWindowFlags());
if (!testWindow) {
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION,
"Failed to create test window with platform flags: %s",
SDL_GetError());
testWindow = SDL_CreateWindow("", 0, 0, 1280, 720, SDL_WINDOW_HIDDEN);
if (!testWindow) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
"Failed to create window for hardware decode test: %s",
SDL_GetError());
SDL_QuitSubSystem(SDL_INIT_VIDEO);
return;
}
}
Session::getDecoderInfo(testWindow, hasHardwareAcceleration, rendererAlwaysFullScreen, supportsHdr, maximumResolution);
SDL_DestroyWindow(testWindow);
SDL_QuitSubSystem(SDL_INIT_VIDEO);
}
void SystemProperties::waitForAsyncLoad()
class RefreshDisplaysThread : public QThread
{
if (systemPropertyQueryThread) {
systemPropertyQueryThread->wait();
public:
RefreshDisplaysThread(SystemProperties* me) :
QThread(nullptr),
m_Me(me) {}
void run() override
{
m_Me->refreshDisplaysInternal();
}
SystemProperties* m_Me;
};
void SystemProperties::refreshDisplays()
{
if (WMUtils::isRunningX11() || WMUtils::isRunningWayland()) {
// Use a separate thread to temporarily initialize SDL
// video to avoid stomping on Qt's X11 and OGL state.
RefreshDisplaysThread thread(this);
thread.start();
thread.wait();
}
else {
refreshDisplaysInternal();
}
}
void SystemProperties::refreshDisplays()
void SystemProperties::refreshDisplaysInternal()
{
if (SDL_InitSubSystem(SDL_INIT_VIDEO) != 0) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
@@ -220,17 +193,37 @@ void SystemProperties::refreshDisplays()
return;
}
monitorDesktopResolutions.clear();
monitorNativeResolutions.clear();
// Never let the maximum drop below 60 FPS
maximumStreamingFrameRate = 60;
SDL_DisplayMode bestMode;
for (int displayIndex = 0; displayIndex < SDL_GetNumVideoDisplays(); displayIndex++) {
SDL_DisplayMode desktopMode;
SDL_Rect safeArea;
int err;
if (StreamUtils::getNativeDesktopMode(displayIndex, &desktopMode, &safeArea)) {
err = SDL_GetDesktopDisplayMode(displayIndex, &desktopMode);
if (err == 0) {
if (desktopMode.w <= 8192 && desktopMode.h <= 8192) {
monitorDesktopResolutions.insert(displayIndex, QRect(0, 0, desktopMode.w, desktopMode.h));
}
else {
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION,
"Skipping resolution over 8K: %dx%d",
desktopMode.w, desktopMode.h);
}
}
else {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
"SDL_GetDesktopDisplayMode() failed: %s",
SDL_GetError());
}
if (StreamUtils::getRealDesktopMode(displayIndex, &desktopMode)) {
if (desktopMode.w <= 8192 && desktopMode.h <= 8192) {
monitorNativeResolutions.insert(displayIndex, QRect(0, 0, desktopMode.w, desktopMode.h));
monitorSafeAreaResolutions.insert(displayIndex, QRect(0, 0, safeArea.w, safeArea.h));
}
else {
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION,
@@ -240,8 +233,7 @@ void SystemProperties::refreshDisplays()
// Start at desktop mode and work our way up
bestMode = desktopMode;
int numDisplayModes = SDL_GetNumDisplayModes(displayIndex);
for (int i = 0; i < numDisplayModes; i++) {
for (int i = 0; i < SDL_GetNumDisplayModes(displayIndex); i++) {
SDL_DisplayMode mode;
if (SDL_GetDisplayMode(displayIndex, i, &mode) == 0) {
if (mode.w == desktopMode.w && mode.h == desktopMode.h) {
@@ -252,17 +244,7 @@ void SystemProperties::refreshDisplays()
}
}
// Try to normalize values around our our standard refresh rates.
// Some displays/OSes report values that are slightly off.
if (bestMode.refresh_rate >= 58 && bestMode.refresh_rate <= 62) {
monitorRefreshRates.append(60);
}
else if (bestMode.refresh_rate >= 28 && bestMode.refresh_rate <= 32) {
monitorRefreshRates.append(30);
}
else {
monitorRefreshRates.append(bestMode.refresh_rate);
}
maximumStreamingFrameRate = qMax(maximumStreamingFrameRate, bestMode.refresh_rate);
}
}
+20 -42
View File
@@ -3,19 +3,18 @@
#include <QObject>
#include <QRect>
#include "SDL_compat.h"
class SystemProperties : public QObject
{
Q_OBJECT
friend class SystemPropertyQueryThread;
friend class QuerySdlVideoThread;
friend class RefreshDisplaysThread;
public:
SystemProperties();
~SystemProperties();
// Static properties queried synchronously during the constructor
Q_PROPERTY(bool hasHardwareAcceleration MEMBER hasHardwareAcceleration CONSTANT)
Q_PROPERTY(bool rendererAlwaysFullScreen MEMBER rendererAlwaysFullScreen CONSTANT)
Q_PROPERTY(bool isRunningWayland MEMBER isRunningWayland CONSTANT)
Q_PROPERTY(bool isRunningXWayland MEMBER isRunningXWayland CONSTANT)
Q_PROPERTY(bool isWow64 MEMBER isWow64 CONSTANT)
@@ -23,40 +22,26 @@ public:
Q_PROPERTY(bool hasDesktopEnvironment MEMBER hasDesktopEnvironment CONSTANT)
Q_PROPERTY(bool hasBrowser MEMBER hasBrowser CONSTANT)
Q_PROPERTY(bool hasDiscordIntegration MEMBER hasDiscordIntegration CONSTANT)
Q_PROPERTY(bool usesMaterial3Theme MEMBER usesMaterial3Theme CONSTANT)
Q_PROPERTY(QString versionString MEMBER versionString CONSTANT)
// Properties queried asynchronously (startAsyncLoad() must be called!)
Q_PROPERTY(bool hasHardwareAcceleration MEMBER hasHardwareAcceleration NOTIFY hasHardwareAccelerationChanged)
Q_PROPERTY(bool rendererAlwaysFullScreen MEMBER rendererAlwaysFullScreen NOTIFY rendererAlwaysFullScreenChanged)
Q_PROPERTY(QString unmappedGamepads MEMBER unmappedGamepads NOTIFY unmappedGamepadsChanged)
Q_PROPERTY(QSize maximumResolution MEMBER maximumResolution NOTIFY maximumResolutionChanged)
Q_PROPERTY(bool supportsHdr MEMBER supportsHdr NOTIFY supportsHdrChanged)
Q_PROPERTY(int maximumStreamingFrameRate MEMBER maximumStreamingFrameRate CONSTANT)
Q_PROPERTY(QSize maximumResolution MEMBER maximumResolution CONSTANT)
Q_PROPERTY(QString versionString MEMBER versionString CONSTANT)
Q_PROPERTY(bool supportsHdr MEMBER supportsHdr CONSTANT)
// Either startAsyncLoad()+waitForAsyncLoad() or refreshDisplays() must be invoked first
Q_INVOKABLE QRect getNativeResolution(int displayIndex);
Q_INVOKABLE QRect getSafeAreaResolution(int displayIndex);
Q_INVOKABLE int getRefreshRate(int displayIndex);
Q_INVOKABLE void startAsyncLoad();
Q_INVOKABLE void waitForAsyncLoad();
Q_INVOKABLE void refreshDisplays();
Q_INVOKABLE QRect getDesktopResolution(int displayIndex);
Q_INVOKABLE QRect getNativeResolution(int displayIndex);
signals:
void unmappedGamepadsChanged();
void hasHardwareAccelerationChanged();
void rendererAlwaysFullScreenChanged();
void maximumResolutionChanged();
void supportsHdrChanged();
private slots:
void updateDecoderProperties(bool hasHardwareAcceleration, bool rendererAlwaysFullScreen, QSize maximumResolution, bool supportsHdr);
private:
QThread* systemPropertyQueryThread = nullptr;
SDL_Window* testWindow = nullptr;
void querySdlVideoInfo();
void querySdlVideoInfoInternal();
void refreshDisplaysInternal();
// Properties set by the constructor
bool hasHardwareAcceleration;
bool rendererAlwaysFullScreen;
bool isRunningWayland;
bool isRunningXWayland;
bool isWow64;
@@ -64,19 +49,12 @@ private:
bool hasDesktopEnvironment;
bool hasBrowser;
bool hasDiscordIntegration;
QString versionString;
bool usesMaterial3Theme;
// Properties only set if startAsyncLoad() is called
bool hasHardwareAcceleration;
bool rendererAlwaysFullScreen;
QSize maximumResolution;
bool supportsHdr;
QString unmappedGamepads;
// Properties set by refreshDisplays()
int maximumStreamingFrameRate;
QSize maximumResolution;
QList<QRect> monitorDesktopResolutions;
QList<QRect> monitorNativeResolutions;
QList<QRect> monitorSafeAreaResolutions;
QList<int> monitorRefreshRates;
QString versionString;
bool supportsHdr;
};
+15 -138
View File
@@ -59,6 +59,13 @@ public:
void showMessage(QString message, MessageType type) const
{
#if defined(Q_OS_WIN32)
UINT flags = MB_OK | MB_TOPMOST | MB_SETFOREGROUND;
flags |= (type == Info ? MB_ICONINFORMATION : MB_ICONERROR);
QString title = "Moonlight";
MessageBoxW(nullptr, reinterpret_cast<const wchar_t *>(message.utf16()),
reinterpret_cast<const wchar_t *>(title.utf16()), flags);
#endif
message = message.endsWith('\n') ? message : message + '\n';
fputs(qPrintable(message), type == Info ? stdout : stderr);
}
@@ -106,7 +113,7 @@ public:
QPair<int,int> getResolutionOptionValue(QString name) const
{
static QRegularExpression re("^(\\d+)x(\\d+)$", QRegularExpression::CaseInsensitiveOption);
QRegularExpression re("^(\\d+)x(\\d+)$", QRegularExpression::CaseInsensitiveOption);
auto match = re.match(value(name));
if (!match.hasMatch()) {
showError(QString("Invalid %1 format: %2").arg(name, value(name)));
@@ -157,10 +164,8 @@ GlobalCommandLineParser::ParseResult GlobalCommandLineParser::parse(const QStrin
"Starts Moonlight normally if no arguments are given.\n"
"\n"
"Available actions:\n"
" list List the available apps on a host\n"
" quit Quit the currently running app\n"
" stream Start streaming an app\n"
" pair Pair a new host\n"
"\n"
"See 'moonlight <action> --help' for help of specific action."
);
@@ -188,14 +193,10 @@ GlobalCommandLineParser::ParseResult GlobalCommandLineParser::parse(const QStrin
return QuitRequested;
} else if (action == "stream") {
return StreamRequested;
} else if (action == "pair") {
return PairRequested;
} else if (action == "list") {
return ListRequested;
}
}
parser.showError("Invalid action");
parser.showError(QString("Invalid action"));
}
}
@@ -241,58 +242,6 @@ QString QuitCommandLineParser::getHost() const
return m_Host;
}
PairCommandLineParser::PairCommandLineParser()
{
}
PairCommandLineParser::~PairCommandLineParser()
{
}
void PairCommandLineParser::parse(const QStringList &args)
{
CommandLineParser parser;
parser.setupCommonOptions();
parser.setApplicationDescription(
"\n"
"Pair with the specified host."
);
parser.addPositionalArgument("pair", "pair host");
parser.addPositionalArgument("host", "Host computer name, UUID, or IP address", "<host>");
parser.addValueOption("pin", "4 digit pairing PIN");
if (!parser.parse(args)) {
parser.showError(parser.errorText());
}
parser.handleUnknownOptions();
// This method will not return and terminates the process if --version or
// --help is specified
parser.handleHelpAndVersionOptions();
// Verify that host has been provided
auto posArgs = parser.positionalArguments();
if (posArgs.length() < 2) {
parser.showError("Host not provided");
}
m_Host = parser.positionalArguments().at(1);
m_PredefinedPin = parser.value("pin");
if (!m_PredefinedPin.isEmpty() && m_PredefinedPin.length() != 4) {
parser.showError("PIN must be 4 digits");
}
}
QString PairCommandLineParser::getHost() const
{
return m_Host;
}
QString PairCommandLineParser::getPredefinedPin() const
{
return m_PredefinedPin;
}
StreamCommandLineParser::StreamCommandLineParser()
{
m_WindowModeMap = {
@@ -309,7 +258,6 @@ StreamCommandLineParser::StreamCommandLineParser()
{"auto", StreamingPreferences::VCC_AUTO},
{"H.264", StreamingPreferences::VCC_FORCE_H264},
{"HEVC", StreamingPreferences::VCC_FORCE_HEVC},
{"AV1", StreamingPreferences::VCC_FORCE_AV1},
};
m_VideoDecoderMap = {
{"auto", StreamingPreferences::VDS_AUTO},
@@ -365,9 +313,6 @@ void StreamCommandLineParser::parse(const QStringList &args, StreamingPreference
parser.addToggleOption("reverse-scroll-direction", "inverted scroll direction");
parser.addToggleOption("swap-gamepad-buttons", "swap A/B and X/Y gamepad buttons (Nintendo-style)");
parser.addToggleOption("keep-awake", "prevent display sleep while streaming");
parser.addToggleOption("performance-overlay", "show performance overlay");
parser.addToggleOption("hdr", "HDR streaming");
parser.addToggleOption("yuv444", "YUV 4:4:4 sampling, if supported");
parser.addChoiceOption("capture-system-keys", "capture system key combos", m_CaptureSysKeysModeMap.keys());
parser.addChoiceOption("video-codec", "video codec", m_VideoCodecMap.keys());
parser.addChoiceOption("video-decoder", "video decoder", m_VideoDecoderMap.keys());
@@ -379,7 +324,7 @@ void StreamCommandLineParser::parse(const QStringList &args, StreamingPreference
parser.handleUnknownOptions();
// Resolve display's width and height
static QRegularExpression resolutionRexExp("^(720|1080|1440|4K|resolution)$");
QRegularExpression resolutionRexExp("^(720|1080|1440|4K|resolution)$");
QStringList resoOptions = parser.optionNames().filter(resolutionRexExp);
bool displaySet = !resoOptions.isEmpty();
if (displaySet) {
@@ -406,20 +351,20 @@ void StreamCommandLineParser::parse(const QStringList &args, StreamingPreference
// Resolve --fps option
if (parser.isSet("fps")) {
preferences->fps = parser.getIntOption("fps");
if (!inRange(preferences->fps, 10, 480)) {
fprintf(stderr, "Warning: FPS is out of the supported range (10 - 480 FPS). Performance may suffer!\n");
if (!inRange(preferences->fps, 30, 240)) {
parser.showError("FPS must be in range: 30 - 240");
}
}
// Resolve --bitrate option
if (parser.isSet("bitrate")) {
preferences->bitrateKbps = parser.getIntOption("bitrate");
if (!inRange(preferences->bitrateKbps, 500, 500000)) {
fprintf(stderr, "Warning: Bitrate is out of the supported range (500 - 500000 Kbps). Performance may suffer!\n");
if (!inRange(preferences->bitrateKbps, 500, 150000)) {
parser.showError("Bitrate must be in range: 500 - 150000");
}
} else if (displaySet || parser.isSet("fps")) {
preferences->bitrateKbps = preferences->getDefaultBitrate(
preferences->width, preferences->height, preferences->fps, preferences->enableYUV444);
preferences->width, preferences->height, preferences->fps);
}
// Resolve --packet-size option
@@ -482,15 +427,6 @@ void StreamCommandLineParser::parse(const QStringList &args, StreamingPreference
// Resolve --keep-awake and --no-keep-awake options
preferences->keepAwake = parser.getToggleOptionValue("keep-awake", preferences->keepAwake);
// Resolve --performance-overlay and --no-performance-overlay options
preferences->showPerformanceOverlay = parser.getToggleOptionValue("performance-overlay", preferences->showPerformanceOverlay);
// Resolve --hdr and --no-hdr options
preferences->enableHdr = parser.getToggleOptionValue("hdr", preferences->enableHdr);
// Resolve --yuv444 and --no-yuv444 options
preferences->enableYUV444 = parser.getToggleOptionValue("yuv444", preferences->enableYUV444);
// Resolve --capture-system-keys option
if (parser.isSet("capture-system-keys")) {
preferences->captureSysKeysMode = mapValue(m_CaptureSysKeysModeMap, parser.getChoiceOptionValue("capture-system-keys"));
@@ -532,62 +468,3 @@ QString StreamCommandLineParser::getAppName() const
{
return m_AppName;
}
ListCommandLineParser::ListCommandLineParser()
{
}
ListCommandLineParser::~ListCommandLineParser()
{
}
void ListCommandLineParser::parse(const QStringList &args)
{
CommandLineParser parser;
parser.setupCommonOptions();
parser.setApplicationDescription(
"\n"
"List the available apps on the given host."
);
parser.addPositionalArgument("list", "list available apps");
parser.addPositionalArgument("host", "Host computer name, UUID, or IP address", "<host>");
parser.addFlagOption("csv", "Print as CSV with additional information");
parser.addFlagOption("verbose", "Displays additional information");
if (!parser.parse(args)) {
parser.showError(parser.errorText());
}
parser.handleUnknownOptions();
m_PrintCSV = parser.isSet("csv");
m_Verbose = parser.isSet("verbose");
// This method will not return and terminates the process if --version or
// --help is specified
parser.handleHelpAndVersionOptions();
// Verify that host has been provided
auto posArgs = parser.positionalArguments();
if (posArgs.length() < 2) {
parser.showError("Host not provided");
}
m_Host = parser.positionalArguments().at(1);
}
QString ListCommandLineParser::getHost() const
{
return m_Host;
}
bool ListCommandLineParser::isPrintCSV() const
{
return m_PrintCSV;
}
bool ListCommandLineParser::isVerbose() const
{
return m_Verbose;
}
-36
View File
@@ -12,8 +12,6 @@ public:
NormalStartRequested,
StreamRequested,
QuitRequested,
PairRequested,
ListRequested,
};
GlobalCommandLineParser();
@@ -37,22 +35,6 @@ private:
QString m_Host;
};
class PairCommandLineParser
{
public:
PairCommandLineParser();
virtual ~PairCommandLineParser();
void parse(const QStringList &args);
QString getHost() const;
QString getPredefinedPin() const;
private:
QString m_Host;
QString m_PredefinedPin;
};
class StreamCommandLineParser
{
public:
@@ -73,21 +55,3 @@ private:
QMap<QString, StreamingPreferences::VideoDecoderSelection> m_VideoDecoderMap;
QMap<QString, StreamingPreferences::CaptureSysKeysMode> m_CaptureSysKeysModeMap;
};
class ListCommandLineParser
{
public:
ListCommandLineParser();
virtual ~ListCommandLineParser();
void parse(const QStringList &args);
QString getHost() const;
bool isPrintCSV() const;
bool isVerbose() const;
private:
QString m_Host;
bool m_PrintCSV;
bool m_Verbose;
};
-196
View File
@@ -1,196 +0,0 @@
#include "listapps.h"
#include "backend/boxartmanager.h"
#include "backend/computermanager.h"
#include "backend/computerseeker.h"
#include <QCoreApplication>
#define COMPUTER_SEEK_TIMEOUT 30000
namespace CliListApps
{
enum State {
StateInit,
StateSeekComputer,
StateListApps,
StateFailure,
};
class Event
{
public:
enum Type {
ComputerFound,
ComputerSeekTimedout,
Executed,
};
Event(Type type)
: type(type), computerManager(nullptr), computer(nullptr) {}
Type type;
ComputerManager *computerManager;
NvComputer *computer;
QString errorMessage;
};
class LauncherPrivate
{
Q_DECLARE_PUBLIC(Launcher)
public:
LauncherPrivate(Launcher *q) : q_ptr(q) {}
void handleEvent(Event event)
{
Q_Q(Launcher);
NvApp app;
switch (event.type) {
// Occurs when CLI main calls execute
case Event::Executed:
if (m_State == StateInit) {
m_State = StateSeekComputer;
m_ComputerManager = event.computerManager;
m_ComputerSeeker = new ComputerSeeker(m_ComputerManager, m_ComputerName, q);
q->connect(m_ComputerSeeker, &ComputerSeeker::computerFound,
q, &Launcher::onComputerFound);
q->connect(m_ComputerSeeker, &ComputerSeeker::errorTimeout,
q, &Launcher::onComputerSeekTimeout);
m_ComputerSeeker->start(COMPUTER_SEEK_TIMEOUT);
m_BoxArtManager = new BoxArtManager(q);
if (m_Arguments.isVerbose()) {
fprintf(stdout, "Establishing connection to PC...\n");
}
}
break;
// Occurs when computer search timed out
case Event::ComputerSeekTimedout:
if (m_State == StateSeekComputer) {
fprintf(stderr, "%s\n", qPrintable(QString("Failed to connect to %1").arg(m_ComputerName)));
QCoreApplication::exit(-1);
}
break;
// Occurs when searched computer is found
case Event::ComputerFound:
if (m_State == StateSeekComputer) {
if (event.computer->pairState == NvComputer::PS_PAIRED) {
m_State = StateListApps;
m_Computer = event.computer;
if (m_Arguments.isVerbose()) {
fprintf(stdout, "Loading app list...\n");
}
// To avoid race conditions where ComputerSeeker stops async polling, but
// ComputerManager is yet to update the app list, we will explicitly fetch the latest app list.
// Otherwise, it becomes complicated as we would have to guess whether ComputerManager
// would emit 1 signal (the list did not change) or 2 signals (indicating that the list has changed)
try {
NvHTTP http{m_Computer};
const auto appList = http.getAppList();
m_Arguments.isPrintCSV() ? printAppsCSV(appList) : printApps(appList);
QCoreApplication::exit(0);
} catch (std::exception& exception) {
fprintf(stderr, "%s\n", exception.what());
QCoreApplication::exit(1);
}
} else {
m_State = StateFailure;
fprintf(stderr, "%s\n", qPrintable(QObject::tr("Computer %1 has not been paired. "
"Please open Moonlight to pair before retrieving games list.")
.arg(event.computer->name)));
QCoreApplication::exit(-1);
}
}
break;
}
}
void printApps(QVector<NvApp> apps) {
for (int i = 0; i < apps.length(); i++) {
fprintf(stdout, "%s\n", qPrintable(apps[i].name));
}
}
void printAppsCSV(QVector<NvApp> apps) {
fprintf(stdout, "Name, ID, HDR Support, App Collection Game, Hidden, Direct Launch, Boxart URL\n");
for (int i = 0; i < apps.length(); i++) {
printAppCSV(apps[i]);
}
}
void printAppCSV(NvApp app) const
{
fprintf(stdout, "\"%s\",%d,%s,%s,%s,%s,\"%s\"\n", qPrintable(app.name),
app.id,
app.hdrSupported ? "true" : "false",
app.isAppCollectorGame ? "true" : "false",
app.hidden ? "true" : "false",
app.directLaunch ? "true" : "false",
qPrintable(m_BoxArtManager->loadBoxArt(m_Computer, app).toDisplayString()));
}
Launcher *q_ptr;
ComputerManager *m_ComputerManager;
QString m_ComputerName;
ComputerSeeker *m_ComputerSeeker;
BoxArtManager *m_BoxArtManager;
NvComputer *m_Computer;
State m_State;
ListCommandLineParser m_Arguments;
};
Launcher::Launcher(QString computer, ListCommandLineParser arguments, QObject *parent)
: QObject(parent),
m_DPtr(new LauncherPrivate(this))
{
Q_D(Launcher);
d->m_ComputerName = computer;
d->m_State = StateInit;
d->m_Arguments = arguments;
}
Launcher::~Launcher()
{
}
void Launcher::execute(ComputerManager *manager)
{
Q_D(Launcher);
Event event(Event::Executed);
event.computerManager = manager;
d->handleEvent(event);
}
bool Launcher::isExecuted() const
{
Q_D(const Launcher);
return d->m_State != StateInit;
}
void Launcher::onComputerFound(NvComputer *computer)
{
Q_D(Launcher);
Event event(Event::ComputerFound);
event.computer = computer;
d->handleEvent(event);
}
void Launcher::onComputerSeekTimeout()
{
Q_D(Launcher);
Event event(Event::ComputerSeekTimedout);
d->handleEvent(event);
}
}
-37
View File
@@ -1,37 +0,0 @@
#pragma once
#include "commandlineparser.h"
#include <QObject>
#include <QVariant>
class ComputerManager;
class NvComputer;
namespace CliListApps
{
class LauncherPrivate;
class Launcher : public QObject
{
Q_OBJECT
Q_DECLARE_PRIVATE_D(m_DPtr, Launcher)
public:
explicit Launcher(QString computer, ListCommandLineParser arguments, QObject *parent = nullptr);
~Launcher();
Q_INVOKABLE void execute(ComputerManager *manager);
Q_INVOKABLE bool isExecuted() const;
private slots:
void onComputerFound(NvComputer *computer);
void onComputerSeekTimeout();
private:
QScopedPointer<LauncherPrivate> m_DPtr;
ListCommandLineParser m_Arguments;
};
}
-181
View File
@@ -1,181 +0,0 @@
#include "pair.h"
#include "backend/computermanager.h"
#include "backend/computerseeker.h"
#include <QCoreApplication>
#include <QTimer>
#define COMPUTER_SEEK_TIMEOUT 10000
namespace CliPair
{
enum State {
StateInit,
StateSeekComputer,
StatePairing,
StateFailure,
StateComplete,
};
class Event
{
public:
enum Type {
ComputerFound,
Executed,
PairingCompleted,
Timedout,
};
Event(Type type)
: type(type), computerManager(nullptr), computer(nullptr) {}
Type type;
ComputerManager *computerManager;
NvComputer *computer;
QString errorMessage;
};
class LauncherPrivate
{
Q_DECLARE_PUBLIC(Launcher)
public:
LauncherPrivate(Launcher *q) : q_ptr(q) {}
void handleEvent(Event event)
{
Q_Q(Launcher);
switch (event.type) {
// Occurs when CliPair becomes visible and the UI calls launcher's execute()
case Event::Executed:
if (m_State == StateInit) {
m_State = StateSeekComputer;
m_ComputerManager = event.computerManager;
q->connect(m_ComputerManager, &ComputerManager::pairingCompleted,
q, &Launcher::onPairingCompleted);
// If we weren't provided a predefined PIN, generate one now
if (m_PredefinedPin.isEmpty()) {
m_PredefinedPin = m_ComputerManager->generatePinString();
}
m_ComputerSeeker = new ComputerSeeker(m_ComputerManager, m_ComputerName, q);
q->connect(m_ComputerSeeker, &ComputerSeeker::computerFound,
q, &Launcher::onComputerFound);
q->connect(m_ComputerSeeker, &ComputerSeeker::errorTimeout,
q, &Launcher::onTimeout);
m_ComputerSeeker->start(COMPUTER_SEEK_TIMEOUT);
emit q->searchingComputer();
}
break;
// Occurs when searched computer is found
case Event::ComputerFound:
if (m_State == StateSeekComputer) {
if (event.computer->pairState == NvComputer::PS_PAIRED) {
m_State = StateFailure;
QString msg = QObject::tr("%1 is already paired").arg(event.computer->name);
emit q->failed(msg);
}
else {
Q_ASSERT(!m_PredefinedPin.isEmpty());
m_State = StatePairing;
m_ComputerManager->pairHost(event.computer, m_PredefinedPin);
emit q->pairing(event.computer->name, m_PredefinedPin);
}
}
break;
// Occurs when pairing operation completes
case Event::PairingCompleted:
if (m_State == StatePairing) {
if (event.errorMessage.isEmpty()) {
m_State = StateComplete;
emit q->success();
}
else {
m_State = StateFailure;
emit q->failed(event.errorMessage);
}
}
break;
// Occurs when computer search timed out
case Event::Timedout:
if (m_State == StateSeekComputer) {
m_State = StateFailure;
emit q->failed(QObject::tr("Failed to connect to %1").arg(m_ComputerName));
}
break;
}
}
Launcher *q_ptr;
QString m_ComputerName;
QString m_PredefinedPin;
ComputerManager *m_ComputerManager;
ComputerSeeker *m_ComputerSeeker;
NvComputer *m_Computer;
State m_State;
QTimer *m_TimeoutTimer;
};
Launcher::Launcher(QString computer, QString predefinedPin, QObject *parent)
: QObject(parent),
m_DPtr(new LauncherPrivate(this))
{
Q_D(Launcher);
d->m_ComputerName = computer;
d->m_PredefinedPin = predefinedPin;
d->m_State = StateInit;
d->m_TimeoutTimer = new QTimer(this);
d->m_TimeoutTimer->setSingleShot(true);
connect(d->m_TimeoutTimer, &QTimer::timeout,
this, &Launcher::onTimeout);
}
Launcher::~Launcher()
{
}
void Launcher::execute(ComputerManager *manager)
{
Q_D(Launcher);
Event event(Event::Executed);
event.computerManager = manager;
d->handleEvent(event);
}
bool Launcher::isExecuted() const
{
Q_D(const Launcher);
return d->m_State != StateInit;
}
void Launcher::onComputerFound(NvComputer *computer)
{
Q_D(Launcher);
Event event(Event::ComputerFound);
event.computer = computer;
d->handleEvent(event);
}
void Launcher::onTimeout()
{
Q_D(Launcher);
Event event(Event::Timedout);
d->handleEvent(event);
}
void Launcher::onPairingCompleted(NvComputer* computer, QString error)
{
Q_D(Launcher);
Event event(Event::PairingCompleted);
event.computer = computer;
event.errorMessage = error;
d->handleEvent(event);
}
}
-44
View File
@@ -1,44 +0,0 @@
#pragma once
#include <QObject>
#include <QVariant>
class ComputerManager;
class NvComputer;
class Session;
class StreamingPreferences;
namespace CliPair
{
class Event;
class LauncherPrivate;
class Launcher : public QObject
{
Q_OBJECT
Q_DECLARE_PRIVATE_D(m_DPtr, Launcher)
public:
explicit Launcher(QString computer, QString predefinedPin,
QObject *parent = nullptr);
~Launcher();
Q_INVOKABLE void execute(ComputerManager *manager);
Q_INVOKABLE bool isExecuted() const;
signals:
void searchingComputer();
void pairing(QString pcName, QString pin);
void failed(QString text);
void success();
private slots:
void onComputerFound(NvComputer *computer);
void onPairingCompleted(NvComputer *computer, QString error);
void onTimeout();
private:
QScopedPointer<LauncherPrivate> m_DPtr;
};
}
+3 -3
View File
@@ -6,7 +6,7 @@
#include <QCoreApplication>
#include <QTimer>
#define COMPUTER_SEEK_TIMEOUT 30000
#define COMPUTER_SEEK_TIMEOUT 10000
#define APP_SEEK_TIMEOUT 10000
namespace CliStartStream
@@ -118,7 +118,7 @@ public:
}
break;
// Occurs when the previous app quit has been completed, handles quitting errors if any
// happened. ComputerUpdated event's handler handles session start when previous app has
// happended. ComputerUpdated event's handler handles session start when previous app has
// quit.
case Event::AppQuitCompleted:
if (m_State == StateSeekApp && !event.errorMessage.isEmpty()) {
@@ -162,7 +162,7 @@ public:
QString getCurrentAppName() const
{
for (const NvApp& app : std::as_const(m_Computer->appList)) {
for (NvApp app : m_Computer->appList) {
if (m_Computer->currentGameId == app.id) {
return app.name;
}
@@ -1,272 +1,41 @@
<?xml version="1.0" encoding="UTF-8"?>
<component type="desktop-application">
<component type="desktop">
<id>com.moonlight_stream.Moonlight</id>
<metadata_license>CC0-1.0</metadata_license>
<project_license>GPL-3.0+</project_license>
<name>Moonlight</name>
<summary>Stream games and other applications from another PC running Sunshine or GeForce Experience</summary>
<summary>Play games remotely from your NVIDIA GameStream-enabled PC</summary>
<description>
<p>Moonlight can stream games and other applications from another PC with Sunshine or GeForce Experience software installed.</p>
<p>Moonlight can stream games and other applications from a PC with an NVIDIA GeForce GTX/RTX or NVIDIA Quadro GPU and GeForce/Quadro Experience installed.</p>
<p>Features include:</p>
<ul>
<li>Hardware accelerated video decoding with VAAPI, VDPAU, and Vulkan Video support</li>
<li>H.264, HEVC, and AV1 codec support</li>
<li>Streaming at up to 4K resolution</li>
<li>Support for up to 120 FPS streaming (high refresh rate monitor recommended)</li>
<li>Hardware accelerated video decoding with VAAPI, VDPAU, and NVDEC support</li>
<li>7.1 surround sound audio support</li>
<li>10-point multitouch support</li>
<li>Gamepad support with force feedback for up to 16 players</li>
<li>Support for both pointer capture (for games) and direct mouse control (for remote desktop)</li>
<li>Support for passing system-wide keyboard shortcuts like Alt+Tab to the host</li>
<li>Direct touchscreen mouse control</li>
<li>HEVC support for better video compression efficiency</li>
<li>Gamepad support with force feedback for up to 4 players</li>
</ul>
</description>
<url type="homepage">https://moonlight-stream.org</url>
<url type="bugtracker">https://github.com/moonlight-stream/moonlight-qt/issues</url>
<url type="help">https://github.com/moonlight-stream/moonlight-docs/wiki/Setup-Guide</url>
<url type="vcs-browser">https://github.com/moonlight-stream/moonlight-qt</url>
<developer id="org.moonlight-stream">
<name>Moonlight Game Streaming Team</name>
</developer>
<update_contact>cameron@moonlight-stream.org</update_contact>
<launchable type="desktop-id">com.moonlight_stream.Moonlight.desktop</launchable>
<provides>
<binary>moonlight</binary>
</provides>
<content_rating type="oars-1.1" />
<branding>
<color type="primary" scheme_preference="light">#710085</color>
<color type="primary" scheme_preference="dark">#55285d</color>
</branding>
<screenshots>
<screenshot type="default">
<image>https://moonlight-stream.org/appstream_resources/moonlight_screenshot_1.png</image>
<caption>Host selection page showing local PCs</caption>
</screenshot>
<screenshot>
<image>https://moonlight-stream.org/appstream_resources/moonlight_screenshot_2.png</image>
<caption>Settings page displaying streaming options</caption>
</screenshot>
</screenshots>
<releases>
<release version="6.1.0" date="2024-09-16">
<description>
<p>New features:</p>
<ul>
<li>Experimental YUV 4:4:4 support for improved text clarity during remote desktop usage</li>
<li>HDR is now supported with software decoding (requires GPU with Vulkan support)</li>
<li>Bitrate limit can now be increased to 500 Mbps</li>
<li>Audio decoding now uses 32-bit floating point format</li>
</ul>
<p>Bugfixes:</p>
<ul>
<li>Fixed incorrect color range when streaming with AV1 from a host with an AMD GPU</li>
<li>Updated community-contributed translations from Weblate</li>
</ul>
</description>
</release>
<release version="6.0.1" date="2024-06-30">
<description>
<p>New features:</p>
<ul>
<li>HDR to SDR tonemapping is now supported by the Vulkan renderer on Linux</li>
</ul>
<p>Behavior Changes:</p>
<ul>
<li>More time is now provided for PCs to wake up before displaying an error when starting a stream from the CLI</li>
<li>Moonlight will no longer try to guess VA driver names when running libva 2.20 or later</li>
</ul>
<p>Bugfixes:</p>
<ul>
<li>Fixed crash when the Vulkan renderer executed on a system with no Vulkan devices</li>
<li>Updated community-contributed translations from Weblate</li>
</ul>
</description>
</release>
<release version="6.0.0" date="2024-06-06">
<description>
<p>New features:</p>
<ul>
<li>HDR is now supported on Steam Deck and other HDR-capable Linux systems using a new Vulkan-based renderer</li>
<li>Vulkan Video decoding of H.264, HEVC, and AV1 is now supported using the new Vulkan renderer</li>
<li>Full E2E stream encryption is now supported when streaming from Sunshine v0.22 or later</li>
<li>Initiating a stream via the command-line will now automatically wake the target machine if it is sleeping</li>
<li>Error codes are now displayed in the connection termination dialog</li>
<li>Detailed PC state information is now available via the new "View Details" context menu option (similar to the Android client)</li>
<li>The performance overlay can now be configured to be shown by default when starting a stream</li>
</ul>
<p>Behavior Changes:</p>
<ul>
<li>The selected bitrate is no longer silently adjusted by Moonlight based upon the video codec or HDR mode</li>
<li>The selected mouse mode when starting a stream no longer influences the acceleration curve when the mouse mode is toggled using the Ctrl+Alt+Shift+M key combo while streaming</li>
<li>Hardcoded fallback paths for VAAPI and VDPAU drivers are no longer used</li>
<li>Per-session keys (rikey and rikeyid values) are now automatically stripped from logs</li>
<li>Log messages will now be logged to stderr rather than stdout</li>
<li>EGL is now always used instead of GLX for loading OpenGL in X11 environments on non-x86 platforms</li>
</ul>
<p>Bugfixes:</p>
<ul>
<li>Improved reliability of streaming during momentary drops of WiFi connections</li>
<li>Improved performance with high polling rate mice</li>
<li>Improved input latency when a gamepad is connected</li>
<li>Added missing command-line options to control HDR and AV1 codec usage</li>
<li>Fixed instant connection termination error when streaming over the Internet behind certain Carrier-Grade NAT devices</li>
<li>Fixed incorrect MTU detection when streaming over the Internet without a VPN</li>
<li>Fixed recovery of audio when no audio output device is present when the stream starts</li>
<li>Fixed merging of gamepad state when multi-controller mode is disabled</li>
<li>Fixed indefinitely resending mDNS queries when a host could not be resolved</li>
<li>Fixed inability to pair when the host is not using a RSA-2048 key</li>
<li>Updated included gamepad mappings</li>
<li>Updated community-contributed translations from Weblate</li>
</ul>
</description>
</release>
<release version="5.0.1" date="2023-11-02">
<description>
<p>Bugfixes:</p>
<ul>
<li>Fixed connection issue streaming from some hosts running GeForce Experience or Sunshine v0.20 and earlier</li>
<li>Updated community-contributed translations from Weblate</li>
</ul>
</description>
</release>
<release version="5.0.0" date="2023-10-18">
<description>
<p>New features:</p>
<ul>
<li>Custom FPS values</li>
<li>Streaming using the AV1 codec from Sunshine hosts</li>
<li>Horizontal scrolling with Sunshine hosts</li>
<li>Native multi-touch input with Sunshine hosts</li>
<li>Controller type information is passed to Sunshine for controller type autoselection</li>
<li>Extended features of PS4/PS5 controllers (touchpad, battery state, gyro/accelerometer motion, and RGB LED) are natively passed to Sunshine hosts</li>
<li>Support for up to 16 gamepads with Sunshine hosts</li>
<li>Frame pacing support on Wayland</li>
<li>Host-side processing latency is now displayed in the performance overlay with Sunshine hosts</li>
<li>Window title now includes the PC name when streaming</li>
<li>Alphabetical sorting of the PC list</li>
<li>Updated Play and Stop button design to improve contrast with app box art</li>
<li>The settings page automatically scrolls to the selected element when using keyboard or gamepad navigation</li>
<li>Pressing Share+PS buttons on PS4/PS5 controllers can be used to emulate a clickpad press</li>
<li>Improved audio quality when streaming with a high bitrate from remote hosts</li>
<li>Increased mouse polling rate</li>
</ul>
<p>Behavior Changes:</p>
<ul>
<li>IPv6 addresses must be provided in URL-escaped form. Example: [2001:db8::1234:5678] or [2001:db8::1234:5678]:47989</li>
<li>Default bitrate logic has been adjusted to behave better with custom resolutions and frame rates</li>
</ul>
<p>Bugfixes:</p>
<ul>
<li>Reduced the frequency of audio underruns (clicks and pops) by increasing audio buffer size</li>
<li>Fixed "Quitting App" message never dismissing in some cases</li>
<li>Fixed parsing IPv6 literals with port numbers</li>
<li>Fixed unnecessary WiFi activity causing stream disruptions</li>
<li>Fixed paired hosts being forgotten if Moonlight terminates while writing hosts to disk</li>
<li>Fixed freeze when closing the stream on Windows with some software that uses DX11 hooks</li>
<li>Fixed delayed PC wake when activating Wake-On-LAN feature</li>
<li>Fixed Wake-on-LAN when Sunshine is running on alternate ports</li>
<li>Fixed leak of /dev/dri fds when trying to initialize VAAPI decoder</li>
<li>Fixed support for the Applications/Menu key</li>
<li>Fixed automatic language detection for Simplified Chinese and Traditional Chinese</li>
<li>Fixed streaming from Sunshine when the client PC has multiple network interfaces or IPv6 privacy extensions enabled</li>
<li>Fixed small receive buffer causing video packet loss on some systems</li>
<li>Fixed theme overrides causing the UI to be unusable on some systems</li>
<li>Fixed tearing with V-Sync enabled on macOS and Linux when using the SDL renderer (software decoding and some hardware decoders)</li>
<li>Fixed stateful V4L2 hardware decoding using h264_v4l2m2m and hevc_v4l2m2m decoders</li>
<li>Fixed CVE-2023-42801</li>
<li>Updated included gamepad mappings</li>
<li>Updated community-contributed translations from Weblate</li>
</ul>
</description>
</release>
<release version="4.3.1" date="2022-11-03">
<description>
<p>Changes:</p>
<ul>
<li>Fixed crash during specific patterns of audio packet loss</li>
<li>Fixed detection of local streaming when using IPv6 addresses</li>
<li>Windowed mode streaming now starts maximized if the GUI window was maximized</li>
<li>Updated community-contributed translations from Weblate</li>
</ul>
</description>
</release>
<release version="4.3.0" date="2022-10-28">
<description>
<p>New features:</p>
<ul>
<li>Improved support for GeForce Experience 3.26</li>
<li>Improved image quality and performance when recovering from video packet loss using HEVC</li>
<li>Improved error concealment after audio packet loss</li>
<li>Improved UI performance when paired with many hosts or hosts with large numbers of apps</li>
<li>Pairing with Sunshine hosts is now supported even if the host is in a streaming session</li>
</ul>
<p>Bugfixes:</p>
<ul>
<li>Fixed streaming at resolutions below 720x480 with GeForce Experience 3.26</li>
<li>Fixed window position and size being lost when toggling between full-screen and windowed mode</li>
<li>Fixed initial window size not always respecting the stream aspect ratio</li>
<li>Fixed unexpected error when streaming at resolutions above 4096x4096 using Sunshine</li>
<li>Updated included gamepad mappings</li>
<li>Updated community-contributed translations from Weblate</li>
</ul>
</description>
</release>
<release version="4.2.1" date="2022-09-12">
<description>
<p>Bugfixes:</p>
<ul>
<li>Fixed streaming from hosts running Sunshine</li>
<li>Updated community-contributed translations from Weblate</li>
</ul>
</description>
</release>
<release version="4.2.0" date="2022-09-10">
<description>
<p>New features:</p>
<ul>
<li>Added support for pairing via the terminal</li>
<li>Added support for listing installed apps on a host via the terminal</li>
<li>Improved handling of V-Sync on Wayland systems to reduce latency</li>
<li>Improved performance using the legacy non-EGL VAAPI rendering code</li>
</ul>
<p>Bugfixes:</p>
<ul>
<li>Fixed native resolution detection on high DPI Wayland systems</li>
<li>Fixed audio crackling with SDL 2.24.0 on systems using PulseAudio</li>
<li>Updated included gamepad mappings</li>
<li>Updated community-contributed translations from Weblate</li>
</ul>
</description>
</release>
<release version="4.1.0" date="2022-05-23">
<description>
<p>New features:</p>
<ul>
<li>Overlays are now supported on the non-EGL X11 VAAPI renderer (requires RGBA subpicture support in the VAAPI driver)</li>
<li>Cursor lock can now be disabled when in full-screen mode</li>
</ul>
<p>Behavior Changes:</p>
<ul>
<li>Moonlight can now reduce the client display resolution in full-screen mode if the current display mode doesn't have a high enough refresh rate for the selected stream frame rate</li>
<li>When choosing a new client display resolution in full-screen mode, Moonlight will pick a display mode with the closest aspect ratio to the selected stream resolution</li>
<li>Moonlight now defaults to borderless windowed mode on Wayland systems</li>
</ul>
<p>Bugfixes:</p>
<ul>
<li>Fixed missing toolbar buttons in certain languages</li>
<li>Fixed some text on the settings page not updating when the language is changed</li>
<li>Fixed a frame pacing bug that could cause excessive frame drops</li>
<li>Fixed the "keep display awake" setting not being saved when Moonlight restarts</li>
<li>Fixed black screen after unmaximizing the Moonlight window on some Linux systems</li>
<li>Updated included gamepad mappings</li>
<li>Updated community-contributed translations from Weblate</li>
</ul>
</description>
</release>
<release version="4.0.0" date="2022-04-02">
<description>
<p>New features:</p>
@@ -833,4 +602,19 @@
</release>
</releases>
<categories>
<category>Game</category>
<category>Qt</category>
</categories>
<developer_name>Moonlight Game Streaming Team</developer_name>
<update_contact>cameron@moonlight-stream.org</update_contact>
<launchable type="desktop-id">com.moonlight_stream.Moonlight.desktop</launchable>
<provides>
<binary>moonlight</binary>
</provides>
<content_rating type="oars-1.0" />
</component>
@@ -1,9 +1,9 @@
[Desktop Entry]
Name=Moonlight
Comment=Stream games and other applications from another PC running Sunshine or GeForce Experience
Comment=Stream games from your NVIDIA GameStream-enabled PC
Exec=moonlight
Icon=moonlight
Terminal=false
Type=Application
Categories=Qt;Game;Network;RemoteAccess;
Keywords=nvidia;gamestream;stream;sunshine;remote play;
Categories=Qt;Game;
Keywords=nvidia;gamestream;stream;
+1 -5
View File
@@ -5,13 +5,9 @@
# pairing data will be lost each reboot.
HOME=/usr/local/moonlight
# Enable Steam Controller detection in SDL
# https://github.com/moonlight-stream/moonlight-qt/issues/697
export SDL_ENABLE_STEAM_CONTROLLERS=1
# Renice PE_Single_CPU which seems to host A/V stuff
renice -10 -p $(pidof PE_Single_CPU)
# Renice Moonlight itself to avoid preemption by background tasks
# Write output to a logfile in /tmp
exec nice -n -10 ./bin/moonlight > /tmp/moonlight.log 2>&1
exec nice -n -10 ./bin/moonlight > /tmp/moonlight.log
+36 -44
View File
@@ -1,6 +1,5 @@
import QtQuick 2.9
import QtQuick.Controls 2.2
import QtQuick.Controls.Material 2.2
import AppModel 1.0
import ComputerManager 1.0
@@ -38,7 +37,7 @@ CenteredGridView {
activated = true
// Highlight the first item if a gamepad is connected
if (currentIndex === -1 && SdlGamepadKeyNavigation.getConnectedGamepads() > 0) {
if (currentIndex == -1 && SdlGamepadKeyNavigation.getConnectedGamepads() > 0) {
currentIndex = 0
}
@@ -90,13 +89,13 @@ CenteredGridView {
onSourceSizeChanged: {
// Nearly all of Nvidia's official box art does not match the dimensions of placeholder
// images, however the one known exception is Overcooked. Therefore, we only execute
// images, however the one known exeception is Overcooked. Therefore, we only execute
// the image size checks if this is not an app collector game. We know the officially
// supported games all have box art, so this check is not required.
if (!model.isAppCollectorGame &&
((sourceSize.width === 130 && sourceSize.height === 180) || // GFE 2.0 placeholder image
(sourceSize.width === 628 && sourceSize.height === 888) || // GFE 3.0 placeholder image
(sourceSize.width === 200 && sourceSize.height === 266))) // Our no_app_image.png
((sourceSize.width == 130 && sourceSize.height == 180) || // GFE 2.0 placeholder image
(sourceSize.width == 628 && sourceSize.height == 888) || // GFE 3.0 placeholder image
(sourceSize.width == 200 && sourceSize.height == 266))) // Our no_app_image.png
{
isPlaceholder = true
}
@@ -122,19 +121,21 @@ CenteredGridView {
anchors.fill: appIcon
sourceComponent: Item {
RoundButton {
// Don't steal focus from the toolbar buttons
focusPolicy: Qt.NoFocus
ToolButton {
anchors.horizontalCenterOffset: appIcon.isPlaceholder ? -47 : 0
anchors.verticalCenterOffset: appIcon.isPlaceholder ? -75 : -60
anchors.centerIn: parent
implicitWidth: 85
implicitHeight: 85
implicitWidth: 125
implicitHeight: 125
icon.source: "qrc:/res/play_arrow_FILL1_wght700_GRAD200_opsz48.svg"
icon.width: 75
icon.height: 75
Image {
source: "qrc:/res/baseline-play_circle_filled_white-48px.svg"
anchors.centerIn: parent
sourceSize {
width: 75
height: 75
}
}
onClicked: {
launchOrResumeSelectedApp(true)
@@ -144,23 +145,23 @@ CenteredGridView {
ToolTip.delay: 1000
ToolTip.timeout: 3000
ToolTip.visible: hovered
Material.background: "#D0808080"
}
RoundButton {
// Don't steal focus from the toolbar buttons
focusPolicy: Qt.NoFocus
ToolButton {
anchors.horizontalCenterOffset: appIcon.isPlaceholder ? 47 : 0
anchors.verticalCenterOffset: appIcon.isPlaceholder ? -75 : 60
anchors.centerIn: parent
implicitWidth: 85
implicitHeight: 85
implicitWidth: 125
implicitHeight: 125
icon.source: "qrc:/res/stop_FILL1_wght700_GRAD200_opsz48.svg"
icon.width: 75
icon.height: 75
Image {
source: "qrc:/res/baseline-cancel-24px.svg"
anchors.centerIn: parent
sourceSize {
width: 75
height: 75
}
}
onClicked: {
doQuitGame()
@@ -170,8 +171,6 @@ CenteredGridView {
ToolTip.delay: 1000
ToolTip.timeout: 3000
ToolTip.visible: hovered
Material.background: "#D0808080"
}
}
}
@@ -252,7 +251,7 @@ CenteredGridView {
anchors.fill: parent
acceptedButtons: Qt.RightButton;
onClicked: {
parent.pressAndHold()
parent.onPressAndHold()
}
}
@@ -294,17 +293,19 @@ CenteredGridView {
asynchronous: true
sourceComponent: NavigableMenu {
id: appContextMenu
initiator: appContextMenuLoader.parent
NavigableMenuItem {
parentMenu: appContextMenu
text: model.running ? qsTr("Resume Game") : qsTr("Launch Game")
onTriggered: launchOrResumeSelectedApp(true)
}
NavigableMenuItem {
parentMenu: appContextMenu
text: qsTr("Quit Game")
onTriggered: doQuitGame()
visible: model.running
}
NavigableMenuItem {
parentMenu: appContextMenu
checkable: true
checked: model.directLaunch
text: qsTr("Direct Launch")
@@ -317,6 +318,7 @@ CenteredGridView {
ToolTip.visible: hovered
}
NavigableMenuItem {
parentMenu: appContextMenu
checkable: true
checked: model.hidden
text: qsTr("Hide Game")
@@ -332,19 +334,6 @@ CenteredGridView {
}
}
Row {
anchors.centerIn: parent
spacing: 5
visible: appGrid.count === 0
Label {
text: qsTr("This computer doesn't seem to have any applications or some applications are hidden")
font.pointSize: 20
verticalAlignment: Text.AlignVCenter
wrapMode: Text.Wrap
}
}
NavigableMessageDialog {
id: quitAppDialog
property string appName : ""
@@ -356,7 +345,7 @@ CenteredGridView {
function quitApp() {
var component = Qt.createComponent("QuitSegue.qml")
var params = {"appName": appName, "quitRunningAppFn": function() { appModel.quitRunningApp() }}
var params = {"appName": appName}
if (segueToStream) {
// Store the session and app name if we're going to stream after
// successfully quitting the old app.
@@ -369,6 +358,9 @@ CenteredGridView {
}
stackView.push(component.createObject(stackView, params))
// Trigger the quit after pushing the quit segue on screen
appModel.quitRunningApp()
}
onAccepted: quitApp()
-15
View File
@@ -2,7 +2,6 @@ import QtQuick 2.9
import QtQuick.Controls 2.2
import SdlGamepadKeyNavigation 1.0
import SystemProperties 1.0
// https://stackoverflow.com/questions/45029968/how-do-i-set-the-combobox-width-to-fit-the-largest-item
ComboBox {
@@ -39,23 +38,9 @@ ComboBox {
popup.onAboutToShow: {
// Switch to normal navigation for combo boxes
SdlGamepadKeyNavigation.setUiNavMode(false)
// Override the popup color to improve contrast with the overridden
// Material 2 background color set in main.qml.
if (SystemProperties.usesMaterial3Theme) {
popup.background.color = "#424242"
}
}
popup.onAboutToHide: {
SdlGamepadKeyNavigation.setUiNavMode(true)
}
Keys.onLeftPressed: {
decrementCurrentIndex()
}
Keys.onRightPressed: {
incrementCurrentIndex()
}
}
+18
View File
@@ -2,6 +2,10 @@ import QtQuick 2.9
import QtQuick.Controls 2.2
GridView {
// Detect Qt 5.11 or earlier using presence of synchronousDrag.
// Prior to 5.12, the leftMargin and rightMargin values did not work.
property bool hasBrokenMargins: this.synchronousDrag === undefined
property int minMargin: 10
property real availableWidth: (parent.width - 2 * minMargin)
property int itemsPerRow: availableWidth / cellWidth
@@ -11,6 +15,11 @@ GridView {
function updateMargins() {
leftMargin = horizontalMargin
rightMargin = horizontalMargin
if (hasBrokenMargins) {
anchors.leftMargin = leftMargin
anchors.rightMargin = rightMargin
}
}
onHorizontalMarginChanged: {
@@ -18,6 +27,15 @@ GridView {
}
Component.onCompleted: {
if (hasBrokenMargins) {
// This will cause an anchor conflict with the parent StackView
// which breaks animation, but otherwise the grid will not be
// centered in the window.
anchors.fill = parent
anchors.topMargin = topMargin
anchors.bottomMargin = bottomMargin
}
updateMargins()
}
-87
View File
@@ -1,87 +0,0 @@
import QtQuick 2.0
import QtQuick.Controls 2.2
import ComputerManager 1.0
Item {
function onSearchingComputer() {
stageLabel.text = qsTr("Establishing connection to PC...")
}
function onPairing(pcName, pin) {
stageLabel.text = qsTr("Pairing... Please enter '%1' on %2.").arg(pin).arg(pcName)
}
function onFailed(message) {
stageIndicator.visible = false
errorDialog.text = message
errorDialog.open()
}
function onSuccess(appName) {
stageIndicator.visible = false
pairCompleteDialog.open()
}
// Allow user to back out of pairing
Keys.onEscapePressed: {
Qt.quit()
}
Keys.onBackPressed: {
Qt.quit()
}
Keys.onCancelPressed: {
Qt.quit()
}
StackView.onActivated: {
if (!launcher.isExecuted()) {
toolBar.visible = false
launcher.searchingComputer.connect(onSearchingComputer)
launcher.pairing.connect(onPairing)
launcher.failed.connect(onFailed)
launcher.success.connect(onSuccess)
launcher.execute(ComputerManager)
}
}
Row {
anchors.centerIn: parent
spacing: 5
id: stageIndicator
BusyIndicator {
id: stageSpinner
running: visible
}
Label {
id: stageLabel
height: stageSpinner.height
font.pointSize: 20
verticalAlignment: Text.AlignVCenter
wrapMode: Text.Wrap
}
}
ErrorMessageDialog {
id: errorDialog
onClosed: {
Qt.quit();
}
}
NavigableMessageDialog {
id: pairCompleteDialog
closePolicy: Popup.CloseOnEscape
text:qsTr("Pairing completed successfully")
standardButtons: Dialog.Ok
onClosed: {
Qt.quit()
}
}
}
-1
View File
@@ -34,7 +34,6 @@ Item {
BusyIndicator {
id: stageSpinner
running: visible
}
Label {
+8 -3
View File
@@ -2,6 +2,7 @@ import QtQuick 2.0
import QtQuick.Controls 2.2
import ComputerManager 1.0
import SdlGamepadKeyNavigation 1.0
Item {
function onSearchingComputer() {
@@ -25,7 +26,6 @@ Item {
function onLaunchFailed(message) {
errorDialog.text = message
errorDialog.open()
console.error(message)
}
function onAppQuitRequired(appName) {
@@ -37,6 +37,10 @@ Item {
if (!launcher.isExecuted()) {
toolBar.visible = false
// Normally this is enabled by PcView, but we will won't
// load PcView when streaming from the command-line.
SdlGamepadKeyNavigation.enable()
launcher.searchingComputer.connect(onSearchingComputer)
launcher.searchingApp.connect(onSearchingApp)
launcher.sessionCreated.connect(onSessionCreated)
@@ -52,7 +56,6 @@ Item {
BusyIndicator {
id: stageSpinner
running: visible
}
Label {
@@ -81,8 +84,10 @@ Item {
function quitApp() {
var component = Qt.createComponent("QuitSegue.qml")
var params = {"appName": appName, "quitRunningAppFn": function() { launcher.quitRunningApp() }}
var params = {"appName": appName}
stackView.push(component.createObject(stackView, params))
// Trigger the quit after pushing the quit segue on screen
launcher.quitRunningApp()
}
onAccepted: quitApp()
+10 -6
View File
@@ -1,13 +1,17 @@
import QtQuick 2.0
import QtQuick.Controls 2.5
import QtQuick.Controls 2.2
Dialog {
modal: true
anchors.centerIn: Overlay.overlay
// We should use Overlay.overlay here but that's not available in Qt 5.9 :(
parent: ApplicationWindow.contentItem
onClosed: {
// We must force focus back to the last item. If we don't,
// gamepad and keyboard navigation will break after a
x: Math.round((parent.width - width) / 2)
y: Math.round((parent.height - height) / 2)
onAboutToHide: {
// We must force focus back to the last item for platforms without
// support for more than one active window like Steam Link. If
// we don't, gamepad and keyboard navigation will break after a
// dialog appears.
stackView.forceActiveFocus()
}
-5
View File
@@ -17,11 +17,6 @@ ItemDelegate {
}
Keys.onUpPressed: {
grid.moveCurrentIndexUp()
// If we've reached the top of the grid, move focus to the toolbar
if (grid.currentItem === this) {
nextItemInFocusChain(false).forceActiveFocus(Qt.TabFocus)
}
}
Keys.onReturnPressed: {
clicked()
+6 -11
View File
@@ -2,18 +2,13 @@ import QtQuick 2.0
import QtQuick.Controls 2.2
Menu {
property var initiator
onOpened: {
// If the initiating object currently has keyboard focus,
// give focus to the first visible and enabled menu item
if (initiator.focus) {
for (var i = 0; i < count; i++) {
var item = itemAt(i)
if (item.visible && item.enabled) {
item.forceActiveFocus(Qt.TabFocusReason)
break
}
// Give focus to the first visible and enabled menu item
for (var i = 0; i < count; i++) {
var item = itemAt(i)
if (item.visible && item.enabled) {
item.forceActiveFocus(Qt.TabFocusReason)
break
}
}
}
+6 -2
View File
@@ -2,6 +2,10 @@ import QtQuick 2.0
import QtQuick.Controls 2.2
MenuItem {
// Qt 5.10 has a menu property, but we need to support 5.9
// so we must make our own.
property Menu parentMenu
// Ensure focus can't be given to an invisible item
enabled: visible
height: visible ? implicitHeight : 0
@@ -11,7 +15,7 @@ MenuItem {
// We must close the context menu first or
// it can steal focus from any dialogs that
// onTriggered may spawn.
menu.close()
parentMenu.close()
}
Keys.onReturnPressed: {
@@ -23,6 +27,6 @@ MenuItem {
}
Keys.onEscapePressed: {
menu.close()
parentMenu.close()
}
}
+13 -13
View File
@@ -15,9 +15,7 @@ NavigableDialog {
onOpened: {
// Force keyboard focus on the label so keyboard navigation works
if (dialogButtonBox.count > 0) {
dialogButtonBox.itemAt(dialogButtonBox.count - 1).forceActiveFocus(Qt.TabFocus)
}
dialogLabel.forceActiveFocus()
}
RowLayout {
@@ -26,7 +24,6 @@ NavigableDialog {
BusyIndicator {
id: dialogSpinner
visible: false
running: visible
}
Image {
@@ -54,6 +51,18 @@ NavigableDialog {
// will cause word wrap to kick in.
Layout.maximumWidth: 400
Layout.maximumHeight: 400
Keys.onReturnPressed: {
accept()
}
Keys.onEnterPressed: {
accept()
}
Keys.onEscapePressed: {
reject()
}
}
}
@@ -61,15 +70,6 @@ NavigableDialog {
id: dialogButtonBox
standardButtons: dialog.standardButtons
delegate: Button {
flat: true
Keys.onReturnPressed: clicked()
Keys.onEnterPressed: clicked()
Keys.onRightPressed: nextItemInFocusChain(true).forceActiveFocus(Qt.TabFocus)
Keys.onLeftPressed: nextItemInFocusChain(false).forceActiveFocus(Qt.TabFocus)
}
onHelpRequested: {
Qt.openUrlExternally(helpUrl)
close()
+11 -3
View File
@@ -7,9 +7,17 @@ ToolButton {
activeFocusOnTab: true
icon.source: iconSource
icon.width: background.width
icon.height: background.height
// FIXME: We're using an Image here rather than icon.source because
// icons don't work on Qt 5.9 LTS.
Image {
id: image
source: iconSource
anchors.centerIn: parent.background
sourceSize {
width: parent.background.width * 1.10
height: parent.background.height * 1.10
}
}
// This determines the size of the Material highlight. We increase it
// from the default because we use larger than normal icons for TV readability.
+45 -47
View File
@@ -6,7 +6,6 @@ import ComputerModel 1.0
import ComputerManager 1.0
import StreamingPreferences 1.0
import SystemProperties 1.0
import SdlGamepadKeyNavigation 1.0
CenteredGridView {
@@ -34,8 +33,13 @@ CenteredGridView {
// Setup signals on CM
ComputerManager.computerAddCompleted.connect(addComplete)
// This is a bit of a hack to do this here as opposed to main.qml, but
// we need it enabled before calling getConnectedGamepads() and PcView
// is never destroyed, so it should be okay.
SdlGamepadKeyNavigation.enable()
// Highlight the first item if a gamepad is connected
if (currentIndex === -1 && SdlGamepadKeyNavigation.getConnectedGamepads() > 0) {
if (currentIndex == -1 && SdlGamepadKeyNavigation.getConnectedGamepads() > 0) {
currentIndex = 0
}
}
@@ -90,13 +94,12 @@ CenteredGridView {
BusyIndicator {
id: searchSpinner
visible: StreamingPreferences.enableMdns
running: visible
}
Label {
height: searchSpinner.height
elide: Label.ElideRight
text: StreamingPreferences.enableMdns ? qsTr("Searching for compatible hosts on your local network...")
text: StreamingPreferences.enableMdns ? qsTr("Searching for PCs on your local network with NVIDIA GameStream enabled...")
: qsTr("Automatic PC discovery is disabled. Add your PC manually.")
font.pointSize: 20
verticalAlignment: Text.AlignVCenter
@@ -127,12 +130,12 @@ CenteredGridView {
id: stateIcon
anchors.horizontalCenter: pcIcon.horizontalCenter
anchors.verticalCenter: pcIcon.verticalCenter
anchors.verticalCenterOffset: !model.online ? -18 : -16
anchors.verticalCenterOffset: -15
visible: !model.statusUnknown && (!model.online || !model.paired)
source: !model.online ? "qrc:/res/warning_FILL1_wght300_GRAD200_opsz24.svg" : "qrc:/res/baseline-lock-24px.svg"
source: !model.online ? "qrc:/res/baseline-warning-24px.svg" : "qrc:/res/baseline-lock-24px.svg"
sourceSize {
width: !model.online ? 75 : 70
height: !model.online ? 75 : 70
width: 75
height: 75
}
}
@@ -144,7 +147,6 @@ CenteredGridView {
width: 75
height: 75
visible: model.statusUnknown
running: visible
}
Label {
@@ -165,13 +167,13 @@ CenteredGridView {
asynchronous: true
sourceComponent: NavigableMenu {
id: pcContextMenu
initiator: pcContextMenuLoader.parent
MenuItem {
text: qsTr("PC Status: %1").arg(model.online ? qsTr("Online") : qsTr("Offline"))
font.bold: true
enabled: false
}
NavigableMenuItem {
parentMenu: pcContextMenu
text: qsTr("View All Apps")
onTriggered: {
var component = Qt.createComponent("AppView.qml")
@@ -181,11 +183,13 @@ CenteredGridView {
visible: model.online && model.paired
}
NavigableMenuItem {
parentMenu: pcContextMenu
text: qsTr("Wake PC")
onTriggered: computerModel.wakeComputer(index)
visible: !model.online && model.wakeable
}
NavigableMenuItem {
parentMenu: pcContextMenu
text: qsTr("Test Network")
onTriggered: {
computerModel.testConnectionForComputer(index)
@@ -194,6 +198,7 @@ CenteredGridView {
}
NavigableMenuItem {
parentMenu: pcContextMenu
text: qsTr("Rename PC")
onTriggered: {
renamePcDialog.pcIndex = index
@@ -202,20 +207,14 @@ CenteredGridView {
}
}
NavigableMenuItem {
parentMenu: pcContextMenu
text: qsTr("Delete PC")
onTriggered: {
deletePcDialog.pcIndex = index
deletePcDialog.pcName = model.name
// get confirmation first, actual closing is called from the dialog
deletePcDialog.open()
}
}
NavigableMenuItem {
text: qsTr("View Details")
onTriggered: {
showPcDetailsDialog.pcDetails = model.details
showPcDetailsDialog.open()
}
}
}
}
@@ -233,14 +232,22 @@ CenteredGridView {
stackView.push(appView)
}
else {
var pin = computerModel.generatePinString()
if (!model.busy) {
var pin = computerModel.generatePinString()
// Kick off pairing in the background
computerModel.pairComputer(index, pin)
// Kick off pairing in the background
computerModel.pairComputer(index, pin)
// Display the pairing dialog
pairDialog.pin = pin
pairDialog.open()
// Display the pairing dialog
pairDialog.pin = pin
pairDialog.open()
}
else {
// cannot pair while something is streaming or attempting to pair
errorDialog.text = qsTr("You cannot pair while a previous session is still running on the host PC. Quit any running games or reboot the host PC, then try pairing again.")
errorDialog.helpText = ""
errorDialog.open()
}
}
} else if (!model.online) {
// Using open() here because it may be activated by keyboard
@@ -263,7 +270,7 @@ CenteredGridView {
anchors.fill: parent
acceptedButtons: Qt.RightButton;
onClicked: {
parent.pressAndHold()
parent.onPressAndHold()
}
}
@@ -272,12 +279,6 @@ CenteredGridView {
// the ItemDelegate and not where the mouse cursor is
pcContextMenu.open()
}
Keys.onDeletePressed: {
deletePcDialog.pcIndex = index
deletePcDialog.pcName = model.name
deletePcDialog.open()
}
}
ErrorMessageDialog {
@@ -290,12 +291,15 @@ CenteredGridView {
NavigableMessageDialog {
id: pairDialog
// Pairing dialog must be modal to prevent double-clicks from triggering
// pairing twice
modal: true
closePolicy: Popup.CloseOnEscape
// don't allow edits to the rest of the window while open
property string pin : "0000"
text:qsTr("Please enter %1 on your host PC. This dialog will close when pairing is completed.").arg(pin)+"\n\n"+
qsTr("If your host PC is running Sunshine, navigate to the Sunshine web UI to enter the PIN.")
text:qsTr("Please enter %1 on your GameStream PC. This dialog will close when pairing is completed.").arg(pin)
standardButtons: Dialog.Cancel
onRejected: {
// FIXME: We should interrupt pairing here
@@ -305,14 +309,16 @@ CenteredGridView {
NavigableMessageDialog {
id: deletePcDialog
// don't allow edits to the rest of the window while open
property int pcIndex : -1
property string pcName : ""
text: qsTr("Are you sure you want to remove '%1'?").arg(pcName)
property int pcIndex : -1;
text:qsTr("Are you sure you want to remove this PC?")
standardButtons: Dialog.Yes | Dialog.No
onAccepted: {
computerModel.deleteComputer(pcIndex)
function deletePc() {
console.log("deleting PC pairing for PC at index: " + pcIndex)
computerModel.deleteComputer(pcIndex);
}
onAccepted: deletePc()
}
NavigableMessageDialog {
@@ -321,7 +327,7 @@ CenteredGridView {
standardButtons: Dialog.Ok
onAboutToShow: {
testConnectionDialog.text = qsTr("Moonlight is testing your network connection to determine if any required ports are blocked.") + "\n\n" + qsTr("This may take a few seconds…")
testConnectionDialog.text = qsTr("Moonlight is testing your network connection to determine if NVIDIA GameStream is blocked.") + "\n\n" + qsTr("This may take a few seconds…")
showSpinner = true
}
@@ -392,13 +398,5 @@ CenteredGridView {
}
}
NavigableMessageDialog {
id: showPcDetailsDialog
property string pcDetails : "";
text: showPcDetailsDialog.pcDetails
imageSrc: "qrc:/res/baseline-help_outline-24px.svg"
standardButtons: Dialog.Ok
}
ScrollBar.vertical: ScrollBar {}
}
-8
View File
@@ -6,7 +6,6 @@ import Session 1.0
Item {
property string appName
property var quitRunningAppFn
property Session nextSession : null
property string nextAppName : ""
@@ -18,7 +17,6 @@ Item {
if (error !== undefined) {
errorDialog.text = error
errorDialog.open()
console.error(error)
}
// If we're supposed to launch another game after this, do so now
@@ -39,11 +37,6 @@ Item {
// Connect the quit completion signal
ComputerManager.quitAppCompleted.connect(quitAppCompleted)
// Start the quit operation if requested
if (quitRunningAppFn) {
quitRunningAppFn()
}
}
StackView.onDeactivating: {
@@ -60,7 +53,6 @@ Item {
BusyIndicator {
id: stageSpinner
running: visible
}
Label {
+252 -526
View File
File diff suppressed because it is too large Load Diff
+34 -63
View File
@@ -4,7 +4,6 @@ import QtQuick.Window 2.2
import SdlGamepadKeyNavigation 1.0
import Session 1.0
import SystemProperties 1.0
Item {
property Session session
@@ -46,7 +45,17 @@ Item {
{
// Display the error dialog after Session::exec() returns
streamSegueErrorDialog.text = text
console.error(text)
}
function displayLaunchWarning(text)
{
// This toast appears for 3 seconds, just shorter than how long
// Session will wait for it to be displayed. This gives it time
// to transition to invisible before continuing.
var toast = Qt.createQmlObject('import QtQuick.Controls 2.2; ToolTip {}', parent, '')
toast.text = text
toast.timeout = 3000
toast.visible = true
}
function quitStarting()
@@ -65,19 +74,23 @@ Item {
streamSegueErrorDialog.text += "\n\n" + qsTr("This PC's Internet connection is blocking Moonlight. Streaming over the Internet may not work while connected to this network.")
}
// Re-enable GUI gamepad usage now
// Enable GUI gamepad usage now
SdlGamepadKeyNavigation.enable()
// Pop the StreamSegue off the stack if this is a GUI-based app launch
if (!quitAfter) {
if (quitAfter) {
if (streamSegueErrorDialog.text) {
// Quit when the error dialog is acknowledged
streamSegueErrorDialog.quitAfter = quitAfter
streamSegueErrorDialog.open()
}
else {
// Quit immediately
Qt.quit()
}
} else {
// Exit this view
stackView.pop()
}
if (quitAfter && !streamSegueErrorDialog.text) {
// If this was a CLI launch without errors, exit now
Qt.quit()
}
else {
// Show the Qt window again after streaming
window.visible = true
@@ -104,7 +117,7 @@ Item {
// Show the toolbar again when popped off the stack
toolBar.visible = true
// Re-enable GUI gamepad usage now
// Enable GUI gamepad usage now
SdlGamepadKeyNavigation.enable()
}
@@ -117,14 +130,11 @@ Item {
session.stageFailed.connect(stageFailed)
session.connectionStarted.connect(connectionStarted)
session.displayLaunchError.connect(displayLaunchError)
session.displayLaunchWarning.connect(displayLaunchWarning)
session.quitStarting.connect(quitStarting)
session.sessionFinished.connect(sessionFinished)
session.readyForDeletion.connect(sessionReadyForDeletion)
// Ensure the SystemProperties async thread is finished,
// since it may currently be using the SDL video subsystem
SystemProperties.waitForAsyncLoad()
// Kick off the stream
spinnerTimer.start()
streamLoader.active = true
@@ -139,20 +149,7 @@ Item {
// middle of the animation on Windows, which looks very
// obviously broken.
interval: 100
onTriggered: stageSpinner.visible = true
}
Timer {
id: startSessionTimer
onTriggered: {
// Garbage collect QML stuff before we start streaming,
// since we'll probably be streaming for a while and we
// won't be able to GC during the stream.
gc()
// Run the streaming session to completion
session.start()
}
onTriggered: stageSpinner.running = true
}
Loader {
@@ -171,38 +168,13 @@ Item {
// Stop GUI gamepad usage now
SdlGamepadKeyNavigation.disable()
// Initialize the session and probe for host/client capabilities
if (!session.initialize(window)) {
sessionFinished(0);
sessionReadyForDeletion();
return;
}
// Garbage collect QML stuff before we start streaming,
// since we'll probably be streaming for a while and we
// won't be able to GC during the stream.
gc()
// Don't wait unless we have toasts to display
startSessionTimer.interval = 0
// Display the toasts together in a vertical centered arrangement
var yOffset = 0
for (var i = 0; i < session.launchWarnings.length; i++) {
var text = session.launchWarnings[i]
console.warn(text)
// Show the tooltip for 3 seconds
var toast = Qt.createQmlObject('import QtQuick.Controls 2.2; ToolTip {}', parent, '')
toast.timeout = 3000
toast.text = text
toast.y += yOffset
toast.visible = true
// Offset the next toast below the previous one
yOffset = toast.y + toast.padding + toast.height
// Allow an extra 500 ms for the tooltip's fade-out animation to finish
startSessionTimer.interval = toast.timeout + 500;
}
// Start the timer to wait for toasts (or start the session immediately)
startSessionTimer.start()
// Run the streaming session to completion
session.exec(Screen.virtualX, Screen.virtualY)
}
sourceComponent: Item {}
@@ -214,8 +186,7 @@ Item {
BusyIndicator {
id: stageSpinner
running: visible
visible: false
running: false
}
Label {
+3 -3
View File
@@ -120,7 +120,7 @@ void AppModel::quitRunningApp()
bool AppModel::isAppCurrentlyVisible(const NvApp& app)
{
for (const NvApp& visibleApp : std::as_const(m_VisibleApps)) {
for (const NvApp& visibleApp : m_VisibleApps) {
if (app.id == visibleApp.id) {
return true;
}
@@ -156,7 +156,7 @@ void AppModel::updateAppList(QVector<NvApp> newList)
const NvApp& existingApp = m_VisibleApps.at(i);
bool found = false;
for (const NvApp& newApp : std::as_const(newVisibleList)) {
for (const NvApp& newApp : newVisibleList) {
if (existingApp.id == newApp.id) {
// If the data changed, update it in our list
if (existingApp != newApp) {
@@ -178,7 +178,7 @@ void AppModel::updateAppList(QVector<NvApp> newList)
}
// Process additions now
for (const NvApp& newApp : std::as_const(newVisibleList)) {
for (const NvApp& newApp : newVisibleList) {
int insertionIndex = m_VisibleApps.size();
bool found = false;
+19 -52
View File
@@ -2,6 +2,8 @@
#include <QThreadPool>
#include <random>
ComputerModel::ComputerModel(QObject* object)
: QAbstractListModel(object) {}
@@ -42,46 +44,6 @@ QVariant ComputerModel::data(const QModelIndex& index, int role) const
return computer->state == NvComputer::CS_UNKNOWN;
case ServerSupportedRole:
return computer->isSupportedServerVersion;
case DetailsRole: {
QString state, pairState;
switch (computer->state) {
case NvComputer::CS_ONLINE:
state = tr("Online");
break;
case NvComputer::CS_OFFLINE:
state = tr("Offline");
break;
default:
state = tr("Unknown");
break;
}
switch (computer->pairState) {
case NvComputer::PS_PAIRED:
pairState = tr("Paired");
break;
case NvComputer::PS_NOT_PAIRED:
pairState = tr("Unpaired");
break;
default:
pairState = tr("Unknown");
break;
}
return tr("Name: %1").arg(computer->name) + '\n' +
tr("Status: %1").arg(state) + '\n' +
tr("Active Address: %1").arg(computer->activeAddress.toString()) + '\n' +
tr("UUID: %1").arg(computer->uuid) + '\n' +
tr("Local Address: %1").arg(computer->localAddress.toString()) + '\n' +
tr("Remote Address: %1").arg(computer->remoteAddress.toString()) + '\n' +
tr("IPv6 Address: %1").arg(computer->ipv6Address.toString()) + '\n' +
tr("Manual Address: %1").arg(computer->manualAddress.toString()) + '\n' +
tr("MAC Address: %1").arg(computer->macAddress.isEmpty() ? tr("Unknown") : QString(computer->macAddress.toHex(':'))) + '\n' +
tr("Pair State: %1").arg(pairState) + '\n' +
tr("Running Game ID: %1").arg(computer->state == NvComputer::CS_ONLINE ? QString::number(computer->currentGameId) : tr("Unknown")) + '\n' +
tr("HTTPS Port: %1").arg(computer->state == NvComputer::CS_ONLINE ? QString::number(computer->activeHttpsPort) : tr("Unknown"));
}
default:
return QVariant();
}
@@ -109,7 +71,6 @@ QHash<int, QByteArray> ComputerModel::roleNames() const
names[WakeableRole] = "wakeable";
names[StatusUnknownRole] = "statusUnknown";
names[ServerSupportedRole] = "serverSupported";
names[DetailsRole] = "details";
return names;
}
@@ -179,9 +140,14 @@ void ComputerModel::renameComputer(int computerIndex, QString name)
m_ComputerManager->renameHost(m_Computers[computerIndex], name);
}
// TODO: Use QRandomGenerator when we drop Qt 5.9 support
QString ComputerModel::generatePinString()
{
return m_ComputerManager->generatePinString();
std::uniform_int_distribution<int> dist(0, 9999);
std::random_device rd;
std::mt19937 engine(rd());
return QString::asprintf("%04u", dist(engine));
}
class DeferredTestConnectionTask : public QObject, public QRunnable
@@ -227,18 +193,19 @@ void ComputerModel::handlePairingCompleted(NvComputer*, QString error)
void ComputerModel::handleComputerStateChanged(NvComputer* computer)
{
QVector<NvComputer*> newComputerList = m_ComputerManager->getComputers();
// Reset the model if the structural layout of the list has changed
if (m_Computers != newComputerList) {
beginResetModel();
m_Computers = newComputerList;
endResetModel();
// If this is an existing computer, we can report the data changed
int index = m_Computers.indexOf(computer);
if (index >= 0) {
// Let the view know that this specific computer changed
emit dataChanged(createIndex(index, 0), createIndex(index, 0));
}
else {
// Let the view know that this specific computer changed
int index = m_Computers.indexOf(computer);
emit dataChanged(createIndex(index, 0), createIndex(index, 0));
// This is a new PC which may be inserted at an arbitrary point
// in our computer list (since it comes from CM's QMap). Reload
// the whole model state to ensure it stays consistent.
beginResetModel();
m_Computers = m_ComputerManager->getComputers();
endResetModel();
}
}
+1 -2
View File
@@ -15,8 +15,7 @@ class ComputerModel : public QAbstractListModel
BusyRole,
WakeableRole,
StatusUnknownRole,
ServerSupportedRole,
DetailsRole
ServerSupportedRole
};
public:
+53 -89
View File
@@ -2,7 +2,6 @@ import QtQuick 2.9
import QtQuick.Controls 2.2
import QtQuick.Layouts 1.3
import QtQuick.Window 2.2
import QtQuick.Controls.Material 2.2
import ComputerManager 1.0
import AutoUpdateChecker 1.0
@@ -19,81 +18,23 @@ ApplicationWindow {
property bool clearOnBack: false
id: window
visible: true
width: 1280
height: 600
// This function runs prior to creation of the initial StackView item
function doEarlyInit() {
// Override the background color to Material 2 colors for Qt 6.5+
// in order to improve contrast between GFE's placeholder box art
// and the background of the app grid.
if (SystemProperties.usesMaterial3Theme) {
Material.background = "#303030"
}
SdlGamepadKeyNavigation.enable()
}
Component.onCompleted: {
// Show the window according to the user's preferences
visibility: {
if (SystemProperties.hasDesktopEnvironment) {
if (StreamingPreferences.uiDisplayMode == StreamingPreferences.UI_MAXIMIZED) {
window.showMaximized()
}
else if (StreamingPreferences.uiDisplayMode == StreamingPreferences.UI_FULLSCREEN) {
window.showFullScreen()
}
else {
window.show()
}
if (StreamingPreferences.uiDisplayMode == StreamingPreferences.UI_WINDOWED) return "Windowed"
else if (StreamingPreferences.uiDisplayMode == StreamingPreferences.UI_MAXIMIZED) return "Maximized"
else if (StreamingPreferences.uiDisplayMode == StreamingPreferences.UI_FULLSCREEN) return "FullScreen"
} else {
window.showFullScreen()
}
// Display any modal dialogs for configuration warnings
if (runConfigChecks) {
if (SystemProperties.isWow64) {
wow64Dialog.open()
}
// Hardware acceleration and unmapped gamepads are checked asynchronously
SystemProperties.hasHardwareAccelerationChanged.connect(hasHardwareAccelerationChanged)
SystemProperties.unmappedGamepadsChanged.connect(hasUnmappedGamepadsChanged)
SystemProperties.startAsyncLoad()
return "FullScreen"
}
}
function hasHardwareAccelerationChanged() {
if (!SystemProperties.hasHardwareAcceleration && StreamingPreferences.videoDecoderSelection !== StreamingPreferences.VDS_FORCE_SOFTWARE) {
if (SystemProperties.isRunningXWayland) {
xWaylandDialog.open()
}
else {
noHwDecoderDialog.open()
}
}
}
function hasUnmappedGamepadsChanged() {
if (SystemProperties.unmappedGamepads) {
unmappedGamepadDialog.unmappedGamepads = SystemProperties.unmappedGamepads
unmappedGamepadDialog.open()
}
}
// It would be better to use TextMetrics here, but it always lays out
// the text slightly more compactly than real Text does in ToolTip,
// causing unexpected line breaks to be inserted
Text {
id: tooltipTextLayoutHelper
visible: false
font: ToolTip.toolTip.font
text: ToolTip.toolTip.text
}
// This configures the maximum width of the singleton attached QML ToolTip. If left unconstrained,
// it will never insert a line break and just extend on forever.
ToolTip.toolTip.contentWidth: Math.min(tooltipTextLayoutHelper.width, 400)
ToolTip.toolTip.contentWidth: ToolTip.toolTip.implicitContentWidth < 400 ? ToolTip.toolTip.implicitContentWidth : 400
function goBack() {
if (clearOnBack) {
@@ -108,16 +49,10 @@ ApplicationWindow {
StackView {
id: stackView
initialItem: initialView
anchors.fill: parent
focus: true
Component.onCompleted: {
// Perform our early initialization before constructing
// the initial view and pushing it to the StackView
doEarlyInit()
push(initialView)
}
onCurrentItemChanged: {
// Ensure focus travels to the next view when going back
if (currentItem) {
@@ -191,9 +126,6 @@ ApplicationWindow {
pollingActive = true
}
}
// Poll for gamepad input only when the window is in focus
SdlGamepadKeyNavigation.notifyWindowFocus(visible && active)
}
onActiveChanged: {
@@ -212,15 +144,47 @@ ApplicationWindow {
// if focus does not return within a few minutes.
inactivityTimer.restart()
}
// Poll for gamepad input only when the window is in focus
SdlGamepadKeyNavigation.notifyWindowFocus(visible && active)
}
function navigateTo(url, objectType)
property bool initialized: false
// BUG: Using onAfterSynchronizing: here causes very strange
// failures on Linux. Many shaders fail to compile and we
// eventually segfault deep inside the Qt OpenGL code.
onAfterRendering: {
// We use this callback to trigger dialog display because
// it only happens once the window is fully constructed.
// Doing it earlier can lead to the dialog appearing behind
// the window or otherwise without input focus.
if (!initialized) {
// Set initialized before calling anything else, because
// pumping the event loop can cause us to get another
// onAfterRendering call and potentially reenter this code.
initialized = true;
if (SystemProperties.isWow64) {
wow64Dialog.open()
}
else if (!SystemProperties.hasHardwareAcceleration) {
if (SystemProperties.isRunningXWayland) {
xWaylandDialog.open()
}
else {
noHwDecoderDialog.open()
}
}
if (SystemProperties.unmappedGamepads) {
unmappedGamepadDialog.unmappedGamepads = SystemProperties.unmappedGamepads
unmappedGamepadDialog.open()
}
}
}
function navigateTo(url, objectName)
{
var existingItem = stackView.find(function(item, index) {
return item instanceof objectType
return item.objectName === objectName
})
if (existingItem !== null) {
@@ -287,7 +251,7 @@ ApplicationWindow {
Label {
id: versionLabel
visible: stackView.currentItem instanceof SettingsView
visible: stackView.currentItem.objectName === qsTr("Settings")
text: qsTr("Version %1").arg(SystemProperties.versionString)
font.pointSize: 12
horizontalAlignment: Qt.AlignRight
@@ -297,9 +261,9 @@ ApplicationWindow {
NavigableToolButton {
id: discordButton
visible: SystemProperties.hasBrowser &&
stackView.currentItem instanceof SettingsView
stackView.currentItem.objectName === qsTr("Settings")
iconSource: "qrc:/res/discord.svg"
iconSource: "qrc:/res/Discord-Logo-White.svg"
ToolTip.delay: 1000
ToolTip.timeout: 3000
@@ -316,7 +280,7 @@ ApplicationWindow {
NavigableToolButton {
id: addPcButton
visible: stackView.currentItem instanceof PcView
visible: stackView.currentItem.objectName === qsTr("Computers")
iconSource: "qrc:/res/ic_add_to_queue_white_48px.svg"
@@ -414,7 +378,7 @@ ApplicationWindow {
iconSource: "qrc:/res/ic_videogame_asset_white_48px.svg"
onClicked: navigateTo("qrc:/gui/GamepadMapper.qml", GamepadMapper)
onClicked: navigateTo("qrc:/gui/GamepadMapper.qml", qsTr("Gamepad Mapping"))
Keys.onDownPressed: {
stackView.currentItem.forceActiveFocus(Qt.TabFocus)
@@ -426,7 +390,7 @@ ApplicationWindow {
iconSource: "qrc:/res/settings.svg"
onClicked: navigateTo("qrc:/gui/SettingsView.qml", SettingsView)
onClicked: navigateTo("qrc:/gui/SettingsView.qml", qsTr("Settings"))
Keys.onDownPressed: {
stackView.currentItem.forceActiveFocus(Qt.TabFocus)
@@ -514,7 +478,7 @@ ApplicationWindow {
NavigableDialog {
id: addPcDialog
property string label: qsTr("Enter the IP address of your host PC:")
property string label: qsTr("Enter the IP address of your GameStream PC:")
standardButtons: Dialog.Ok | Dialog.Cancel
+58 -52
View File
@@ -4,16 +4,15 @@
#include <QGuiApplication>
#include <QWindow>
#include "settings/streamingpreferences.h"
#include "settings/mappingmanager.h"
#define AXIS_NAVIGATION_REPEAT_DELAY 150
SdlGamepadKeyNavigation::SdlGamepadKeyNavigation(StreamingPreferences* prefs)
: m_Prefs(prefs),
m_Enabled(false),
SdlGamepadKeyNavigation::SdlGamepadKeyNavigation()
: m_Enabled(false),
m_UiNavMode(false),
m_FirstPoll(false),
m_HasFocus(false),
m_LastAxisNavigationEventTime(0)
{
m_PollingTimer = new QTimer(this);
@@ -51,16 +50,11 @@ void SdlGamepadKeyNavigation::enable()
// on first init of the GC subsystem. We can't depend on them due to
// overlapping lifetimes of SdlGamepadKeyNavigation instances, so we
// will attach ourselves.
//
// NB: We use SDL_JoystickUpdate() instead of SDL_PumpEvents() because
// the latter can do a bit more work that we want (like handling video
// events that we intentionally do not want to process yet).
SDL_JoystickUpdate();
SDL_PumpEvents();
SDL_FlushEvent(SDL_CONTROLLERDEVICEADDED);
// Open all currently attached game controllers
int numJoysticks = SDL_NumJoysticks();
for (int i = 0; i < numJoysticks; i++) {
for (int i = 0; i < SDL_NumJoysticks(); i++) {
if (SDL_IsGameController(i)) {
SDL_GameController* gc = SDL_GameControllerOpen(i);
if (gc != nullptr) {
@@ -69,10 +63,13 @@ void SdlGamepadKeyNavigation::enable()
}
}
m_Enabled = true;
// Flush events on the first poll
m_FirstPoll = true;
// Start the polling timer if the window is focused
updateTimerState();
// Poll every 50 ms for a new joystick event
m_PollingTimer->start(50);
m_Enabled = true;
}
void SdlGamepadKeyNavigation::disable()
@@ -81,9 +78,7 @@ void SdlGamepadKeyNavigation::disable()
return;
}
m_Enabled = false;
updateTimerState();
Q_ASSERT(!m_PollingTimer->isActive());
m_PollingTimer->stop();
while (!m_Gamepads.isEmpty()) {
SDL_GameControllerClose(m_Gamepads[0]);
@@ -91,31 +86,26 @@ void SdlGamepadKeyNavigation::disable()
}
SDL_QuitSubSystem(SDL_INIT_GAMECONTROLLER);
}
void SdlGamepadKeyNavigation::notifyWindowFocus(bool hasFocus)
{
m_HasFocus = hasFocus;
updateTimerState();
m_Enabled = false;
}
void SdlGamepadKeyNavigation::onPollingTimerFired()
{
SDL_Event event;
// Update joystick state without pumping other events (see enable() comment)
SDL_JoystickUpdate();
StreamingPreferences prefs;
// Discard any pending button events on the first poll to avoid picking up
// stale input data from the stream session (like the quit combo).
if (m_FirstPoll) {
SDL_PumpEvents();
SDL_FlushEvent(SDL_CONTROLLERBUTTONDOWN);
SDL_FlushEvent(SDL_CONTROLLERBUTTONUP);
m_FirstPoll = false;
}
// Peep events rather than polling to avoid calling SDL_PumpEvents()
while (SDL_PeepEvents(&event, 1, SDL_GETEVENT, SDL_FIRSTEVENT, SDL_LASTEVENT) == 1) {
while (SDL_PollEvent(&event)) {
switch (event.type) {
case SDL_QUIT:
// SDL may send us a quit event since we initialize
@@ -131,7 +121,7 @@ void SdlGamepadKeyNavigation::onPollingTimerFired()
QEvent::Type::KeyPress : QEvent::Type::KeyRelease;
// Swap face buttons if needed
if (m_Prefs->swapFaceButtons) {
if (prefs.swapFaceButtons) {
switch (event.cbutton.button) {
case SDL_CONTROLLER_BUTTON_A:
event.cbutton.button = SDL_CONTROLLER_BUTTON_B;
@@ -201,24 +191,14 @@ void SdlGamepadKeyNavigation::onPollingTimerFired()
case SDL_CONTROLLERDEVICEADDED:
SDL_GameController* gc = SDL_GameControllerOpen(event.cdevice.which);
if (gc != nullptr) {
// SDL_CONTROLLERDEVICEADDED can be reported multiple times for the same
// gamepad in rare cases, because SDL doesn't fixup the device index in
// the SDL_CONTROLLERDEVICEADDED event if an unopened gamepad disappears
// before we've processed the add event.
if (!m_Gamepads.contains(gc)) {
m_Gamepads.append(gc);
}
else {
// We already have this game controller open
SDL_GameControllerClose(gc);
}
m_Gamepads.append(gc);
}
break;
}
}
// Handle analog sticks by polling
for (auto gc : std::as_const(m_Gamepads)) {
for (auto gc : m_Gamepads) {
short leftX = SDL_GameControllerGetAxis(gc, SDL_CONTROLLER_AXIS_LEFTX);
short leftY = SDL_GameControllerGetAxis(gc, SDL_CONTROLLER_AXIS_LEFTY);
if (SDL_GetTicks() - m_LastAxisNavigationEventTime < AXIS_NAVIGATION_REPEAT_DELAY) {
@@ -259,6 +239,31 @@ void SdlGamepadKeyNavigation::onPollingTimerFired()
sendKey(QEvent::Type::KeyRelease, Qt::Key_Right);
m_LastAxisNavigationEventTime = SDL_GetTicks();
}
// In UI navigation mode (settings page), use the right stick to scroll
if (m_UiNavMode) {
short rightX = SDL_GameControllerGetAxis(gc, SDL_CONTROLLER_AXIS_RIGHTX);
short rightY = SDL_GameControllerGetAxis(gc, SDL_CONTROLLER_AXIS_RIGHTY);
QPoint wheelDelta;
if (rightX > 30000) {
wheelDelta.setX(30);
}
else if (rightX < -30000) {
wheelDelta.setX(-30);
}
if (rightY > 30000) {
wheelDelta.setY(-30);
}
else if (rightY < -30000) {
wheelDelta.setY(30);
}
if (!wheelDelta.isNull()) {
sendWheel(wheelDelta);
}
}
}
}
@@ -272,17 +277,19 @@ void SdlGamepadKeyNavigation::sendKey(QEvent::Type type, Qt::Key key, Qt::Keyboa
}
}
void SdlGamepadKeyNavigation::updateTimerState()
void SdlGamepadKeyNavigation::sendWheel(QPoint& angleDelta)
{
if (m_PollingTimer->isActive() && (!m_HasFocus || !m_Enabled)) {
m_PollingTimer->stop();
}
else if (!m_PollingTimer->isActive() && m_HasFocus && m_Enabled) {
// Flush events on the first poll
m_FirstPoll = true;
// Poll every 50 ms for a new joystick event
m_PollingTimer->start(50);
QGuiApplication* app = static_cast<QGuiApplication*>(QGuiApplication::instance());
QWindow* focusWindow = app->focusWindow();
if (focusWindow != nullptr) {
QPoint mousePos(focusWindow->width() / 2, focusWindow->height() / 2);
QPoint globalPos(focusWindow->mapToGlobal(mousePos));
#if QT_VERSION >= QT_VERSION_CHECK(5, 12, 0)
QWheelEvent wheelEvent(mousePos, globalPos, QPoint(), angleDelta, Qt::NoButton, Qt::NoModifier, Qt::NoScrollPhase, false, Qt::MouseEventSynthesizedByApplication);
#else
QWheelEvent wheelEvent(mousePos, globalPos, QPoint(), angleDelta, angleDelta.y(), Qt::Vertical, Qt::NoButton, Qt::NoModifier, Qt::NoScrollPhase, Qt::MouseEventSynthesizedByApplication, false);
#endif
app->sendEvent(focusWindow, &wheelEvent);
}
}
@@ -296,8 +303,7 @@ int SdlGamepadKeyNavigation::getConnectedGamepads()
Q_ASSERT(m_Enabled);
int count = 0;
int numJoysticks = SDL_NumJoysticks();
for (int i = 0; i < numJoysticks; i++) {
for (int i = 0; i < SDL_NumJoysticks(); i++) {
if (SDL_IsGameController(i)) {
count++;
}
+3 -10
View File
@@ -3,16 +3,14 @@
#include <QTimer>
#include <QEvent>
#include "SDL_compat.h"
#include "settings/streamingpreferences.h"
#include <SDL.h>
class SdlGamepadKeyNavigation : public QObject
{
Q_OBJECT
public:
SdlGamepadKeyNavigation(StreamingPreferences* prefs);
SdlGamepadKeyNavigation();
~SdlGamepadKeyNavigation();
@@ -20,27 +18,22 @@ public:
Q_INVOKABLE void disable();
Q_INVOKABLE void notifyWindowFocus(bool hasFocus);
Q_INVOKABLE void setUiNavMode(bool settingsMode);
Q_INVOKABLE int getConnectedGamepads();
private:
void sendKey(QEvent::Type type, Qt::Key key, Qt::KeyboardModifiers modifiers = Qt::NoModifier);
void updateTimerState();
void sendWheel(QPoint& angleDelta);
private slots:
void onPollingTimerFired();
private:
StreamingPreferences* m_Prefs;
QTimer* m_PollingTimer;
QList<SDL_GameController*> m_Gamepads;
bool m_Enabled;
bool m_UiNavMode;
bool m_FirstPoll;
bool m_HasFocus;
Uint32 m_LastAxisNavigationEventTime;
};
Binary file not shown.
File diff suppressed because it is too large Load Diff
Binary file not shown.
File diff suppressed because it is too large Load Diff
Binary file not shown.
File diff suppressed because it is too large Load Diff
Binary file not shown.
+393 -653
View File
File diff suppressed because it is too large Load Diff
Binary file not shown.
+298 -554
View File
File diff suppressed because it is too large Load Diff
Binary file not shown.
File diff suppressed because it is too large Load Diff
Binary file not shown.
+304 -560
View File
File diff suppressed because it is too large Load Diff
Binary file not shown.
File diff suppressed because it is too large Load Diff
Binary file not shown.
+398 -619
View File
File diff suppressed because it is too large Load Diff
Binary file not shown.
File diff suppressed because it is too large Load Diff
Binary file not shown.
+292 -556
View File
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
Binary file not shown.
+665 -937
View File
File diff suppressed because it is too large Load Diff
Binary file not shown.
+305 -561
View File
File diff suppressed because it is too large Load Diff
Binary file not shown.
+306 -566
View File
File diff suppressed because it is too large Load Diff
Binary file not shown.
+304 -564
View File
File diff suppressed because it is too large Load Diff
Binary file not shown.
File diff suppressed because it is too large Load Diff
Binary file not shown.
+406 -662
View File
File diff suppressed because it is too large Load Diff
Binary file not shown.
+374 -630
View File
File diff suppressed because it is too large Load Diff

Some files were not shown because too many files have changed in this diff Show More