Compare commits

..
678 Commits
Author SHA1 Message Date
Cameron Gutman 81943b12c0 Version 2.2.0 2020-09-09 22:26:12 -07:00
Cameron Gutman 18fa7c2832 Add Discord button in Settings 2020-09-09 21:49:45 -07:00
Cameron Gutman dd02bf809e Don't require linking to wlanapi.dll
This is not always available on Windows Server
2020-09-08 18:27:01 -07:00
Cameron Gutman 2f3a1a5d79 Work around bug where GLES surface creation repeatedly fails on X11 2020-09-07 23:53:29 -07:00
Cameron Gutman 18654cb011 Work around QSGRenderThread crash on Wayland 2020-09-07 23:07:31 -07:00
Cameron Gutman 5954f80645 Update common-c to avoid TCP tests for single addresses 2020-09-07 10:57:23 -07:00
Cameron Gutman 3e36357315 Remove HDR option because it doesn't currently work 2020-09-06 17:33:40 -07:00
Cameron Gutman a06a454ade Ignore ICMP Port Unreachable messages on our UDP sockets 2020-09-06 15:02:11 -07:00
Cameron Gutman c0fab4b41f Try TCP 47989 and TCP 48010 as fallbacks if 47984 doesn't work 2020-09-06 11:56:12 -07:00
Cameron Gutman 80b79f3636 Rebuild SDL for macOS
changeset 8f1abe5e7d8f

Patches:
https://bugzilla.libsdl.org/show_bug.cgi?id=5276
https://bugzilla.libsdl.org/show_bug.cgi?id=5282
2020-09-05 15:16:19 -07:00
Cameron Gutman b97ae25f93 Flush mouse position before sending a mouse button event 2020-09-05 14:50:38 -07:00
Cameron Gutman 4722ea6096 Update SDL_GameControllerDB 2020-09-05 14:08:13 -07:00
Cameron Gutman 3e9781033a Create windows with SDL_WINDOW_METAL on macOS
This prevents the window from being recreated when initializing a Metal renderer.
2020-09-05 14:06:58 -07:00
Cameron Gutman 62b296cf85 Rebuild SDL for macOS
changeset 8f1abe5e7d8f

Patches:
https://bugzilla.libsdl.org/show_bug.cgi?id=5276
2020-09-05 14:06:58 -07:00
Cameron Gutman dcbaa52683 Rebuild SDL2 for Windows
changeset 8f1abe5e7d8f

Patches:
https://bugzilla.libsdl.org/show_bug.cgi?id=5272
https://bugzilla.libsdl.org/show_bug.cgi?id=5274
https://bugzilla.libsdl.org/show_bug.cgi?id=5276

Defines:
#undef SDL_JOYSTICK_RAWINPUT
#undef SDL_JOYSTICK_WGI
#define USE_D3D9EX 1
2020-09-05 11:28:47 -07:00
Cameron Gutman 1e29f61656 Merge pull request #433 from annk15/master
Added option to switch primary and secondary mouse buttons
2020-09-05 10:40:00 -07:00
Anton 89319dc7aa Added option to swap left and right mouse buttons
Changed the use of SDL buttons to Moonlight buttons definitions
2020-09-05 08:32:00 +02:00
Cameron Gutman 5755afc4ea Fix app window not hiding when streaming starts 2020-09-04 22:38:54 -07:00
Cameron Gutman d00c434ccc Don't try STUN for manually added PCs over VPNs 2020-09-02 22:56:59 -07:00
Cameron Gutman 4ada59ba48 Populate the external IP address when a PC is added manually using an RFC 1918 IPv4 address 2020-08-30 19:03:55 -07:00
Cameron Gutman 14ccc38f4c Fix certain CLI options not overriding GUI preferences. Fixes #435 2020-08-30 01:38:26 -07:00
Cameron Gutman a8be299bbd Fix compile warnings in moonlight-common-c 2020-08-29 21:37:34 -07:00
Cameron Gutman 2e87f5ff85 Add warning if no key frames can be received in 10 seconds 2020-08-29 21:02:22 -07:00
Cameron Gutman 829ebba622 Fix STUN socket errors being clobbered by closeSocket() 2020-08-29 13:45:20 -07:00
Cameron Gutman 81019fa2a8 Initialize gamepad navigation when streaming from the terminal 2020-08-29 12:59:27 -07:00
Cameron Gutman 1bc3675548 Update AppImage to libva 2.8.0 2020-08-23 16:08:43 -07:00
Cameron Gutman 678ec979c9 Update ASan flags for x64 support in MSVC 16.7
https://devblogs.microsoft.com/cppblog/asan-for-windows-x64-and-debug-build-support/
2020-08-22 17:36:16 -07:00
Cameron Gutman d1a48ae641 Update SDL_GameControllerDB 2020-08-22 14:39:05 -07:00
Cameron Gutman eded86bc10 Allow game controllers to be ignored during streaming only
STREAM_GAMECONTROLLER_IGNORE_DEVICES and STREAM_GAMECONTROLLER_IGNORE_DEVICES_EXCEPT environment variables provide the same functionality as SDL_GAMECONTROLLER_IGNORE_DEVICES and SDL_GAMECONTROLLER_IGNORE_DEVICES_EXCEPT, with the difference being SDL_* variables take effect at all times (UI and streaming) while STREAM_* variables take place only while streaming.

Fixes #425
2020-08-22 12:02:26 -07:00
Cameron Gutman 5a7a49d1d5 Display resolution and codec in OSD 2020-08-20 20:52:05 -07:00
Cameron Gutman d3de8049bf QTBUG-80947 is fixed for real in Qt 5.15.1 2020-08-19 21:47:45 -07:00
Cameron Gutman d09dd90a73 Fix hardcoded tick unit duration which is incorrect on Apple silicon 2020-08-12 18:07:10 -07:00
Cameron Gutman 78203eb9be Enable media streaming mode for 802.11 WLAN interfaces on Windows 2020-08-11 22:14:26 -07:00
Cameron Gutman 31c7d4e36f Don't hide the games immediately 2020-08-11 18:46:06 -07:00
Cameron Gutman d3949806f5 Move connection establishment to a separate thread to keep the UI responsive 2020-08-10 22:21:54 -07:00
Cameron Gutman 28ff15c99e Update common-c to prevent server-side log spam 2020-08-09 17:57:12 -07:00
Cameron Gutman bd2c74fe90 Remove UDP 7 and add UDP 47009 for WoL 2020-08-09 14:49:33 -07:00
Cameron Gutman fb6995db94 Add network test option to PC context menu 2020-08-08 20:25:26 -07:00
Cameron Gutman 8c2c4d3282 Reorder PC context menu to place destructive actions at the bottom 2020-08-08 18:32:36 -07:00
Cameron Gutman b81392b818 Add an option to disable the automatic connection testing 2020-08-08 18:29:36 -07:00
Cameron Gutman ad08440023 Test for blocked ports when adding a PC fails 2020-08-08 18:11:25 -07:00
Cameron Gutman ec17623400 Test for blocked ports when a stream fails 2020-08-08 17:59:26 -07:00
Cameron Gutman 288eca7849 Display a friendly error when the Windows Firewall service is disabled 2020-08-08 17:18:25 -07:00
Cameron Gutman b5f202150e Update Windows AppVeyor builds to Qt 5.15 2020-08-02 23:08:12 -07:00
Cameron Gutman 539bf0cb30 Add support for hiding games
Fixes #255
2020-08-01 21:06:01 -07:00
Cameron Gutman 9385d62c89 Enable poll() in ENet for Linux/BSD 2020-07-27 00:04:25 -07:00
Cameron Gutman 897f916552 Update common-c with client connectivity test and select() replacement 2020-07-26 21:05:11 -07:00
Cameron Gutman 914cf6753e Update AppImage to FFmpeg 4.3.1 2020-07-14 20:53:52 -07:00
Cameron Gutman 392208057e Update moonlight-common-c to fix FEC validation assert on GFE 3.20.4 2020-07-14 20:52:49 -07:00
Cameron Gutman 8d2cbf806d Improve message for broken Intel drivers to indicate that users should update their driver 2020-07-12 15:26:38 -07:00
Cameron Gutman ab5025efbf Ignore mouse events outside the video region 2020-07-12 15:06:36 -07:00
Cameron Gutman 912e51d863 Synchronize the client and host cursor when starting absolute mode capture 2020-07-12 15:03:08 -07:00
Cameron Gutman d1c4ca5eae Use uniform_int_distribution for generating PINs 2020-07-12 13:19:26 -07:00
Cameron Gutman 16bb4a148e Only use libsoundio on Windows or macOS 2020-07-08 18:57:27 -05:00
Cameron Gutman d7071cb67f Improve verbiage around quit app and optimize game settings options 2020-06-23 22:17:40 -07:00
Cameron Gutman a13fb3d7c5 Update AppImage to FFmpeg 4.3 2020-06-20 17:03:52 -07:00
Cameron Gutman 85558904a4 Update SDL_GameControllerDB 2020-06-20 17:02:30 -07:00
Cameron Gutman 88ed72fdc1 Use regular VSync when enabled because adaptive VSync still tears 2020-06-20 14:44:21 -07:00
Cameron Gutman 586a93d7aa Use the new EGL renderer for VAAPI by default 2020-06-13 20:21:54 -07:00
Cameron Gutman a446699c6c Update moonlight-common-c to fix QoS-related connection issues 2020-06-12 22:00:24 -07:00
Cameron Gutman f1c459fd6c Fix leak of renderer when we fail to create a GL context 2020-06-08 20:39:12 -07:00
Cameron Gutman 752f0a988b Fix crash during key generation introduced by dcba5762c7 2020-06-08 20:16:42 -07:00
Cameron Gutman 719b266691 Fix build with OpenSSL versions prior to 1.1.0 2020-06-07 16:58:47 -07:00
Cameron Gutman dcba5762c7 Avoid using functions deprecated in OpenSSL 3.0 2020-06-07 16:26:19 -07:00
Cameron Gutman 0757717bea Address const-correctness issues in NvPairingManager 2020-06-07 15:15:33 -07:00
Cameron Gutman a9f762aa96 Fix macOS AppVeyor build 2020-06-07 14:14:06 -07:00
Cameron Gutman db45f46d9e Update AppImage to FFmpeg 4.2.3 2020-06-07 12:17:43 -07:00
Cameron Gutman f00653964e Batch absolute mouse motion like we do for relative motion 2020-05-31 13:34:50 -07:00
Cameron Gutman e0154f9314 Rebuild SDL for macOS
changeset a564e72e3b2d

Patches:
https://bugzilla-attachments.libsdl.org/attachment.cgi?id=4322 for bug #5111
https://bugzilla-attachments.libsdl.org/attachment.cgi?id=4356 for bug #5158
2020-05-31 12:01:50 -07:00
Cameron Gutman 4408a3a354 Delete cached box art when the host is deleted 2020-05-29 21:44:38 -07:00
Cameron Gutman 5abf5a157d Update metadata for Quadro streaming 2020-05-27 20:05:24 -07:00
Cameron Gutman d55d5f60a5 Update common-c 2020-05-26 18:22:39 -07:00
Cameron Gutman feacf2c359 Include stdexcept for std::runtime_error 2020-05-26 17:44:18 -07:00
Cameron Gutman 72ea1601e9 Use a better workaround for the GFE 3.20.3 high FPS bug 2020-05-25 18:57:42 -07:00
Cameron Gutman 02cfd8d978 Revert "Disable SOPS for streams over 60 FPS for GFE 3.20.3"
This reverts commit d6b5c5f63e.
2020-05-25 18:46:34 -07:00
Cameron Gutman 728377cba3 Set AV_PKT_FLAG_KEY for key frames 2020-05-25 18:31:19 -07:00
Cameron Gutman f2283b56b9 Version 2.1.0 2020-05-16 23:45:09 -07:00
Cameron Gutman b515f2a599 Update SDL_GameControllerDB 2020-05-16 22:45:29 -07:00
Cameron Gutman 4354b49496 Fix CLI video decoder options being reversed 2020-05-16 17:44:04 -07:00
Cameron Gutman 994312c212 Force GL to block after the current frame instead during the next frame 2020-05-16 16:25:13 -07:00
Cameron Gutman 5f25e0d4e2 Add limited support for frame pacing to EGLRenderer 2020-05-16 15:59:10 -07:00
Cameron Gutman 4bbe571f5f Fix build without FFmpeg and with older EGL 1.5 headers 2020-05-16 13:25:10 -07:00
Cameron Gutman c58d21375c EGL 1.4 doesn't have EGLAttrib either 2020-05-16 12:20:52 -07:00
Cameron Gutman ed128c558f Add support for EGLRenderer on EGL 1.4 2020-05-16 12:13:00 -07:00
Cameron Gutman 828932d95c Fix EGL detection on RPi 2020-05-16 11:10:45 -07:00
Cameron Gutman 42ced309d3 Restore the original GL attributes after EGLRenderer is destroyed 2020-05-15 20:22:11 -07:00
Cameron Gutman 1fcd306879 Fix EGLRenderer when SDL isn't built with X11 or Wayland backends 2020-05-15 20:01:22 -07:00
Cameron Gutman 26c9ad7f06 Use eglGetProcAddress() for all GLES 2.0 extensions 2020-05-15 19:39:41 -07:00
Cameron Gutman 4b7b01ce0a Fix EGL build 2020-05-15 17:54:45 -07:00
Cameron Gutman 6632154906 Remove some unnecessary headers and definitions 2020-05-15 16:59:29 -07:00
Cameron Gutman ca67c7ef43 Provide a main function for the compile test 2020-05-15 16:57:09 -07:00
Cameron Gutman c4039a929c Use a compile test for EGL support 2020-05-15 16:46:03 -07:00
Cameron Gutman a1b74e1220 Fix vaExportSurfaceHandle() detection with i965 VAAPI driver 2020-05-14 20:56:24 -07:00
Cameron Gutman 01f6188824 Add VAAPI_FORCE_DIRECT and VAAPI_FORCE_INDIRECT env vars to control rendering technique 2020-05-13 19:45:30 -07:00
Cameron Gutman 283f31a734 Test if vaExportSurfaceHandle() works before claiming EGL export is supported 2020-05-13 19:39:45 -07:00
Cameron Gutman b800ce9ebe Allow use of VA drivers without VAEntrypointVideoProc 2020-05-13 19:31:25 -07:00
Cameron Gutman eb9d54465c Don't use EGLRenderer if not built with SDL 2.0.10+ 2020-05-13 19:19:11 -07:00
Cameron Gutman eb9e1f81d4 Enable the EGLRenderer to use the render thread 2020-05-13 19:09:20 -07:00
Cameron Gutman ddfbd70b55 Remove Wayland performance warning message 2020-05-13 18:56:18 -07:00
Cameron Gutman 51e9ab83ad Send a null AVFrame to indicate end of stream to allow renderers to do render thread cleanup 2020-05-13 18:55:21 -07:00
Cameron Gutman 5ed7e03b2e Merge pull request #365 from xdbob/wayland_for_upstream
Introduce a new FFMPEG frontend renderer: EGLRenderer
2020-05-13 18:39:18 -07:00
Cameron Gutman 0cb8d5b12f Add the older dList DLLs for the 390 drivers to the blacklist
Fixes #386
2020-05-13 04:25:53 -07:00
Cameron Gutman b4548c1af2 Flush all window events after SDL_CreateRenderer() 2020-05-12 18:41:36 -07:00
Antoine Damhet 0a396f3112 Introduce a new FFMPEG frontend renderer: EGLRenderer
Right now this renderer works on X11 & Wayland with VAAPI as a backend.

Some rendering latency benchmarks on my `i7-10510U` (with
`intel-media-driver` 20.1.1 which cause a *huge* regression with the
SDL_Renderer):
|             | X11    | Wayland |
| Before      | 6.78ms | 22.50ms |
| EGLRenderer | 0.76ms | 00.77ms |

Signed-off-by: Antoine Damhet <antoine.damhet@lse.epita.fr>
2020-05-12 11:11:35 +02:00
Cameron Gutman 2aa18dc88f Add a bit of extra padding on the right for the scrollbar 2020-05-10 13:02:10 -07:00
Cameron Gutman 8d89983eeb Parent ScrollBars to their Flingables, not the StackView
This ensures they disappear when navigating to a new page
2020-05-10 12:53:27 -07:00
Cameron Gutman 573c470965 Ensure the title label doesn't get drawn over when the window is small 2020-05-10 12:38:56 -07:00
Cameron Gutman daa0c751e2 Fix settings layout spacing and centering 2020-05-10 12:30:15 -07:00
Cameron Gutman e1babefc80 Center toolbar text 2020-05-10 11:48:24 -07:00
Cameron Gutman ce99b0e162 Improve settings page behavior when the window is too small 2020-05-10 11:12:37 -07:00
Cameron Gutman 4c3a23b1bd Resize toolbar text 2020-05-09 23:02:09 -07:00
Cameron Gutman 12016af326 Display version number in toolbar on the settings page
Fixes #341
2020-05-09 22:20:39 -07:00
Cameron Gutman fc9871b075 Delay mouse capture until after SDL_RecreateWindow() has been called 2020-05-09 19:48:13 -07:00
Cameron Gutman 3cb3c1c6d8 Revert "Use the physical desktop size in pixels rather than the native resolution on macOS"
Let's wait until functionality is confirmed on a 5K iMac before doing this.

This reverts commit 8fe3474589.
2020-05-09 16:52:18 -07:00
Cameron Gutman 8fe3474589 Use the physical desktop size in pixels rather than the native resolution on macOS
It seems like some Macs (5K iMacs at least) don't have kDisplayModeNativeFlag set
2020-05-09 16:34:48 -07:00
Cameron Gutman dc3c565ec0 Move serialization and deserialization into NvApp class 2020-05-07 19:54:36 -07:00
Cameron Gutman 350c7d7081 Persist the IsAppCollectorGame attribute 2020-05-07 19:37:10 -07:00
Cameron Gutman 0428bc8fe3 Generate synthetic mouse button up if the mouse has left the window and the button is raised 2020-05-07 19:26:02 -07:00
Cameron Gutman 514a8575a2 Use the viewport size for computing the overlay position 2020-05-07 18:56:53 -07:00
Cameron Gutman fc11377552 Fix build on Qt 5.11 and earlier 2020-05-07 17:13:16 -07:00
Cameron Gutman fbaa70a2ae Enable the right stick to scroll the settings page. Fixes #220 2020-05-06 22:38:52 -07:00
Cameron Gutman f30c11ddf4 Properly fix SDL_HINT_MOUSE_FOCUS_CLICKTHROUGH on macOS VTRenderer 2020-05-06 22:20:21 -07:00
Cameron Gutman 51c4ecc879 Revert "Partially unrevert 05e82c24 for macOS which still needs it"
This reverts commit 080421f2fb.
2020-05-06 21:41:57 -07:00
Cameron Gutman 080421f2fb Partially unrevert 05e82c24 for macOS which still needs it 2020-05-06 21:18:23 -07:00
Cameron Gutman 8cc61ca8b8 Use SDL_HINT_MOUSE_FOCUS_CLICKTHROUGH to get click events on focus gain 2020-05-06 20:43:41 -07:00
Cameron Gutman 400754c5b3 Revert "Pass through focus-gain clicks to the host in absolute mouse mode"
This reverts commit 05e82c24f8.
2020-05-06 20:04:07 -07:00
Cameron Gutman 05e82c24f8 Pass through focus-gain clicks to the host in absolute mouse mode 2020-05-06 18:58:43 -07:00
Cameron Gutman 97c15c7876 Ensure the Info.plist is included for builds in the IDE
It is required for SDL_WINDOW_ALLOW_HIGHDPI to work
2020-05-04 20:25:19 -07:00
Cameron Gutman 36e7cc8e89 Use a smaller MaximumUncompressedMediaSize for unofficial builds to speed up compression a bit 2020-05-04 18:32:38 -07:00
Cameron Gutman ad2ce4de53 Update moonlight-common-c 2020-05-04 18:29:55 -07:00
Cameron Gutman 2a28f7c4d2 Use jom to parallelize command-line builds on Windows 2020-05-04 18:06:32 -07:00
Cameron Gutman 0cdbe080a6 Don't archive installers on Windows AppVeyor build
They interact poorly with installed official versions.
2020-05-04 17:51:57 -07:00
Cameron Gutman 96fe1a7da1 Revert "Allow side-by-side installation of nightly and release builds"
This reverts commit 33e814122e.
2020-05-04 17:51:57 -07:00
Cameron Gutman 4f73af2920 Revert "Fix AppVeyor build archiving"
This reverts commit 402e8c1897.
2020-05-04 17:51:57 -07:00
Cameron Gutman 7ca4e49bf5 Compile in parallel on macOS 2020-05-04 17:49:24 -07:00
Cameron Gutman dfa63297fc Fix incorrectly scaled output from the SDL renderer on macOS 2020-05-04 17:48:32 -07:00
Cameron Gutman 402e8c1897 Fix AppVeyor build archiving 2020-05-02 20:59:22 -07:00
Cameron Gutman 33e814122e Allow side-by-side installation of nightly and release builds 2020-05-02 17:56:55 -07:00
Cameron Gutman f28a4df5ee Restore the full QTBUG-80947 hack as it appears to still be required sometimes 2020-05-02 10:14:54 -07:00
Cameron Gutman 417aa2815c Add a friendly error message when no video traffic is received 2020-05-01 21:28:48 -07:00
Cameron Gutman 2fdabe37aa Raise the window before capturing in relative mode 2020-05-01 18:44:22 -07:00
Cameron Gutman d8270dfb6a Capture mouse by default on debug builds too 2020-05-01 18:43:54 -07:00
Cameron Gutman b75f662c41 Add the ability to rename PCs 2020-05-01 18:34:15 -07:00
Cameron Gutman 0d9d0845f5 Add --touchscreen-trackpad options 2020-04-30 21:10:53 -07:00
Cameron Gutman 5d66a1f298 Fix absolute mouse mode help text 2020-04-30 21:05:53 -07:00
Cameron Gutman 9bf52eb63a Improve relative touch deadzone behavior 2020-04-30 21:04:51 -07:00
Cameron Gutman 0c9d72a9a1 Restore the option for relative touch mode 2020-04-30 20:55:15 -07:00
Cameron Gutman c2c2bd2df6 Split input.cpp into smaller files 2020-04-30 20:22:43 -07:00
Cameron Gutman 78fc594d84 Move input code into a subfolder 2020-04-30 20:09:36 -07:00
Cameron Gutman 53b1e7c573 Update moonlight-common-c 2020-04-29 20:22:02 -07:00
Cameron Gutman c14404a7c1 Restore the QTBUG-80947 hack for support for direct connections without a router 2020-04-29 20:20:17 -07:00
Cameron Gutman 96e6750f9c Don't confine the cursor to the full-screen window when not capturing input 2020-04-28 20:37:00 -07:00
Cameron Gutman dbafd05a4e Store a pointer to the window inside the input handler 2020-04-28 20:24:27 -07:00
Cameron Gutman d7fd578cc3 Don't set MODIFIER_META when meta key is disabled 2020-04-28 20:06:30 -07:00
Cameron Gutman 0e8572e1db Version 2.0.0 2020-04-28 02:08:10 -07:00
Cameron Gutman 98a997bd8e Update AppImage to Qt 5.14.2 2020-04-27 17:09:52 -07:00
Cameron Gutman 6fbc95cc41 Update readme with links for new platforms 2020-04-26 21:31:29 -07:00
Cameron Gutman 1852f74e8b Add missing return statement 2020-04-26 20:42:01 -07:00
Cameron Gutman 55e3e16860 Try radeonsi if other VAAPI drivers fail 2020-04-26 20:18:46 -07:00
Cameron Gutman 7cf2a55b43 Allow radeonsi to direct render on XWayland 2020-04-26 20:13:00 -07:00
Cameron Gutman c41cbbd2da Allow the radeonsi VAAPI driver on XWayland 2020-04-26 20:06:53 -07:00
Cameron Gutman 7283bb046b Disable initial mouse capture on XWayland 2020-04-26 19:33:25 -07:00
Cameron Gutman dd2df6cbcf Default to starting in a non-maximized window 2020-04-26 17:57:28 -07:00
Cameron Gutman 01f1cac811 Update readme and metadata 2020-04-26 16:12:10 -07:00
Cameron Gutman aaa112c3f3 Don't use VAAPI drivers that lack VPP support
intel-media-va-driver (free) is one example of such a driver which
is apparently missing the shaders to perform colorspace conversion.
2020-04-26 15:38:05 -07:00
Cameron Gutman dc0fa9c64d Update AppImage's libva to 2.7.1 for compatibility with VA-API 1.7 drivers 2020-04-26 11:38:31 -07:00
Cameron Gutman f749b38aa2 Warn when starting a game with remote desktop mouse mode enabled 2020-04-25 23:50:12 -07:00
Cameron Gutman 43d79673e1 Rebuild SDL2 for Windows
changeset:   13787:a564e72e3b2d
2020-04-25 21:04:44 -07:00
Cameron Gutman fc841f572c Rebuild SDL2 for macOS
changeset: 13787:a564e72e3b2d

with https://bugzilla-attachments.libsdl.org/attachment.cgi?id=4322 for bug #5111
2020-04-25 19:53:00 -07:00
Cameron Gutman df9f117a08 Update SDL_GameControllerDB 2020-04-25 19:02:24 -07:00
Cameron Gutman bedc46a1be Rebuild SDL2 for macOS
changeset:   13787:a564e72e3b2d
2020-04-25 16:56:25 -07:00
Cameron Gutman a7c6095be5 Add special error text for the -1 launch error code 2020-04-25 16:05:39 -07:00
Cameron Gutman f2d5cf785e Don't cancel mouse capture on focus loss in absolute mode 2020-04-25 15:42:13 -07:00
Cameron Gutman f926ad9b5e Fix inverted capture-by-default setting 2020-04-25 15:41:45 -07:00
Cameron Gutman 68acf969f2 Move focus handling into the input code 2020-04-25 15:37:33 -07:00
Cameron Gutman 65d53e800b Confine the cursor to the window in full-screen exclusive mode 2020-04-25 13:15:14 -07:00
Cameron Gutman e44d8ac7e9 Only enable the absolute mouse checkbox if the platform has a window manager 2020-04-25 13:04:22 -07:00
Cameron Gutman d1823dd6e1 Capture the mouse by default always on release builds and in absolute mode for debug builds 2020-04-25 13:01:15 -07:00
Cameron Gutman 80bfd3b8e9 Change raw input checkbox to adjust absolute vs relative mouse mode 2020-04-25 13:00:39 -07:00
Cameron Gutman 07128cc7fe Allow keyboard input when the mouse is not captured 2020-04-24 21:35:38 -07:00
Cameron Gutman 0892f0b0bb Don't capture the cursor on a touch event 2020-04-24 21:26:59 -07:00
Cameron Gutman 8cf7f3ac08 Fix absolute mouse positioning on SDL renderer 2020-04-24 19:37:15 -07:00
Cameron Gutman ab2bb51879 Clamp mouse motion to the video region rather than dropping it 2020-04-24 17:35:35 -07:00
Cameron Gutman 8cb98b5365 Rewrite touchscreen support for direct input 2020-04-23 21:34:03 -07:00
Cameron Gutman 782c5f8a34 Fix parsing rare GFE status code of 0xFFFFFFFF 2020-04-23 18:34:14 -07:00
Cameron Gutman d6b5c5f63e Disable SOPS for streams over 60 FPS for GFE 3.20.3 2020-04-12 11:39:25 -07:00
Cameron Gutman ef6dfa6d91 Add basic support for absolute mouse input 2020-04-11 21:28:11 -07:00
Cameron Gutman 3840ee8ee7 Add MSVC ASan support 2020-04-10 17:21:17 -07:00
Cameron Gutman f47e40fa2a Blacklist more broken A-Volute DLLs 2020-04-10 17:20:21 -07:00
Cameron Gutman 49a4a61876 Enable QoS for ENet on Windows and fix disconnect delay on GFE 3.20.3 2020-04-09 18:02:49 -07:00
Khalid Jebbari 669c1a6f0d Add comment that describe kb shortcut of overlay (#358) 2020-04-06 18:31:02 -07:00
Cameron Gutman 15342190fa Make audio debug logs more readable 2020-04-04 12:53:03 -07:00
Cameron Gutman c98ef6e8a9 Display a friendly error when trying to stream over 4K with H.264 2020-04-04 12:47:44 -07:00
Cameron Gutman d36d5936da Don't include resolutions over 8K in settings list 2020-04-04 12:46:42 -07:00
Cameron Gutman 70de75ae3d Use EF instead of CS7 for DSCP on ENet traffic 2020-04-04 10:59:03 -07:00
Cameron Gutman ea62e33e51 Add 7.1 surround sound support to libsoundio audio renderer 2020-04-04 09:49:10 -07:00
Cameron Gutman 524e92c81a Add 7.1 surround sound support to SLAudio 2020-04-03 19:04:11 -07:00
Cameron Gutman d5a26b1d70 Enable auto-update for AppImages 2020-04-03 17:03:12 -07:00
Cameron Gutman cd7649a666 Add 7.1 surround sound support for SDL audio output 2020-04-03 00:12:52 -07:00
Cameron Gutman 847cc0a38a Migrate to the new audio configuration macros 2020-03-31 21:36:16 -07:00
Cameron Gutman 3588eb9bf8 Reduce retransmission delay on packet loss and enable QoS marking on ENet traffic 2020-03-29 15:49:52 -07:00
Cameron Gutman 296e22d3ca Remove the Wayland post-cleanup hack
It seems to do more harm than good on Fedora 32, causing deadlocks
when the stream is closed. The original bug it was trying to avoid
seems to have already been fixed.
2020-03-28 00:46:04 -07:00
Cameron Gutman 923e590da1 Delay the spinner on the stream segue to prevent animation glitching on Windows 2020-03-27 23:32:46 -07:00
Cameron Gutman e56329d05a Don't render with vaPutSurface() on XWayland 2020-03-27 19:11:03 -07:00
Cameron Gutman 2452e80e57 Add VDPAU driver path fallbacks for AppImage 2020-03-26 19:06:24 -07:00
Cameron Gutman b9019831a9 Fix failure to try the default VAAPI driver with the modified LIBVA_DRIVERS_PATH 2020-03-26 18:25:52 -07:00
Cameron Gutman b3b49b440e Add VAAPI driver path fallbacks for AppImage 2020-03-24 00:09:03 -07:00
Cameron Gutman cbedf0f74f Bundle a newer libva, FFmpeg, and Qt Wayland plugin into the AppImage 2020-03-23 23:57:38 -07:00
Cameron Gutman 6c980eba68 Fix build on Qt 5.15 Beta 2
Reverts most of 10dae7482c
2020-03-23 18:30:56 -07:00
Cameron Gutman e9f766904e Build AppImages on AppVeyor 2020-03-23 01:04:08 -07:00
Cameron Gutman 62d76c006d Move all builds to AppVeyor 2020-03-22 21:26:07 -07:00
Cameron Gutman 615b78a612 Update SDL_GameControllerDB to d222918bd6f786a35f9c42fd87921ca29493b785 2020-03-22 18:41:21 -07:00
Cameron Gutman aaf0340d6c Use 10 ms audio samples on low bandwidth connections 2020-03-21 01:04:41 -07:00
Cameron Gutman 93ea437760 Key repeat is handled server-side, so don't send repeat events 2020-03-20 23:56:44 -07:00
Cameron Gutman fe6a1244ed Fix a couple compiler warnings 2020-03-18 22:46:32 -07:00
Cameron Gutman 953858b0e7 Add workaround for Steam Link graphics bug. Fixes #254 2020-03-18 22:26:15 -07:00
Cameron Gutman f3da46833f Revert "Temporarily switch to gamecontrollerdb to fix build after DMCA takedown of SDL_GameControllerDB"
The DMCA takedown has been disputed and the repo is back up.

This reverts commit 6314676b9c.
2020-03-18 19:48:26 -07:00
Cameron Gutman ba2488b6e2 Try the iHD VA driver as a fallback to fix Comet Lake and later 2020-03-18 18:39:43 -07:00
Cameron Gutman 4e7e0d67e5 Add a workaround for Mesa Iris returning the wrong VA driver 2020-03-17 17:34:35 -07:00
Cameron Gutman faa16b207c Implement a more reliable mouse capture workaround for GNOME+Wayland 2020-03-14 00:33:53 -07:00
Cameron Gutman 2d9f62761c Don't pass through the super key to the host 2020-03-13 18:11:31 -07:00
Cameron Gutman 60689f531d Update to SDL 2.0.12 with USE_D3D9EX 2020-03-11 21:27:45 -07:00
Cameron Gutman 3f97692311 Update macOS to SDL 2.0.12 2020-03-11 17:51:46 -07:00
Cameron Gutman 81221336f4 Rec 601 seems to be a bit more accurate on macOS 2020-03-10 23:21:00 -07:00
Cameron Gutman ecfc758ce4 Attach colorspace data to CVPixelBuffer. Fixes #323 2020-03-10 22:21:09 -07:00
Cameron Gutman 2cb3a132c6 Fix false positives in SDL_GameControllerRumble() support detection 2020-03-07 17:00:38 -08:00
Cameron Gutman 519473e498 Enable rumble on Bluetooth PS4 controllers 2020-03-07 16:46:41 -08:00
Cameron Gutman 9b271d918a Use SDL_GameControllerSetPlayerIndex() to indicate player index 2020-03-03 20:15:35 -08:00
Cameron Gutman 5b4d874851 Avoid sending excessively large mDNS queries on networks with lots of mDNS traffic 2020-03-02 02:52:02 -08:00
Cameron Gutman 9dc1dbc002 Update qmdnsengine to address mDNS traffic amplification 2020-03-02 02:33:50 -08:00
Cameron Gutman 7ee323f0d5 Fix deprecation warning on macOS 2020-02-29 15:54:10 -08:00
Cameron Gutman 4bb6f711b9 Avoid using the QTBUG-80947 workaround on Qt 5.14.2 and later 2020-02-27 18:03:28 -08:00
Cameron Gutman 816cec8f5c Remove deprecated listener callbacks 2020-02-25 00:31:05 -08:00
Cameron Gutman 2394dfe88a Change errorCode to an int type 2020-02-24 23:03:34 -08:00
Cameron Gutman dfc0d2303b Fix incorrect #endif location 2020-02-24 20:55:07 -08:00
Cameron Gutman 598a48ec50 Remove the Wayland mouse capture hack that is not necessary on SDL 2.0.11 2020-02-24 20:33:33 -08:00
Cameron Gutman 9f41e98e3f Remove RPi hacks that are not necessary on SDL 2.0.11 2020-02-24 19:55:22 -08:00
Cameron Gutman 489891ff3c Fix build on Windows and macOS with Qt 5.13 and earlier 2020-02-24 18:17:23 -08:00
Cameron Gutman a44ed0b047 Allow initial destination position to be used as an offset with scaleSourceToDestinationSurface() 2020-02-24 18:01:30 -08:00
Cameron Gutman 1aaa97b91d Override SDL 2.0.12 default of mapping buttons to labels rather than position 2020-02-24 17:44:56 -08:00
Cameron Gutman 13d68e789f Fix Clazy warnings 2020-02-24 17:44:21 -08:00
Cameron Gutman 10dae7482c Fix build with Qt 5.15 2020-02-24 17:39:24 -08:00
Cameron Gutman 979de190dc Cap resolution options at 1080p on Steam Link and Raspberry Pi due to hardware limitations 2020-02-23 00:43:43 -08:00
Cameron Gutman 46bcbda972 MMAL is always full-screen 2020-02-23 00:25:01 -08:00
Cameron Gutman 43bdc353fb Fix 720p streaming on MMAL 2020-02-23 00:22:44 -08:00
Cameron Gutman 6314676b9c Temporarily switch to gamecontrollerdb to fix build after DMCA takedown of SDL_GameControllerDB 2020-02-22 19:20:52 -08:00
Cameron Gutman 9f77f3d968 Don't leave 0 byte files if saving the box art image failed and deal with those that may already exist. Fixes #346 2020-02-20 19:06:19 -08:00
Cameron Gutman f4733dbbe8 Fix unused parameter warning on Linux 2020-02-20 14:13:03 -08:00
Cameron Gutman 61fc0e4893 Don't allow Flickables to be dragged beyond bounds 2020-02-20 13:38:01 -08:00
Cameron Gutman 652ad86cad Update SDL_GameControllerDB to cc4b7f603698914fad9a172a5e47bfece93a45f6 2020-02-20 13:29:36 -08:00
Cameron Gutman 60f308bd76 Build dual binary bundles for Steam Link 2020-02-12 18:20:15 -08:00
Cameron Gutman b2113ff95b Raspberry Pi's full KMS driver is broken with MMAL, so just advise fake KMS 2020-02-09 12:52:11 -08:00
Cameron Gutman b8188a46a9 Display a friendly warning when running without a KMS driver 2020-02-09 12:40:07 -08:00
Cameron Gutman e790b0761e Add another RPi hack to fix mouse capture in full-screen in LXDE 2020-02-09 12:00:30 -08:00
Cameron Gutman fa3317f6cd Enable double buffering on SDL backends that support it 2020-02-09 11:54:09 -08:00
Cameron Gutman b080f7a81c Don't display browser links in non-GUI environment 2020-02-09 11:41:44 -08:00
Cameron Gutman 57a1c5eb76 Disable the window mode options for always full-screen renderers 2020-02-09 11:35:05 -08:00
Cameron Gutman 5b7e2521cc Ignore unbind and full-screen key combos on EGLFS 2020-02-09 10:20:41 -08:00
Cameron Gutman fced653c1c Add a hack to avoid PulseAudio on RPi 2020-02-08 23:35:42 -08:00
Cameron Gutman 9253e6ac5e Fix GLES library not being found on RPi when running from console 2020-02-08 22:34:07 -08:00
Cameron Gutman aff2ed22b9 Use EGLFS platform plugin if X and Wayland aren't detected 2020-02-08 21:37:17 -08:00
Cameron Gutman 5520a52379 Force full-screen mode on EGLFS 2020-02-08 21:31:04 -08:00
Cameron Gutman 505050e936 Fix high DPI check in 0437835b 2020-02-08 18:47:59 -08:00
Cameron Gutman 0437835bde Avoid enabling High DPI mode on EGLFS to fix font rendering 2020-02-08 18:11:33 -08:00
Cameron Gutman 77386f8dfc Reduce buffering for MMAL to avoid requiring 128 MB VRAM split 2020-02-08 17:56:30 -08:00
Cameron Gutman 529fdf0341 Add decoder options dictionary to prepareDecoderContext() 2020-02-08 17:47:26 -08:00
Cameron Gutman fa74700ad9 Fix build with new Steam Link SDK 2020-02-05 17:24:05 -08:00
Cameron Gutman caca491943 Add build script to generate AppImage 2020-02-01 15:46:53 -08:00
Cameron Gutman 4794f44a6d Charge decoders for time spent holding on to frames 2020-01-26 20:15:11 -08:00
Cameron Gutman f0119b1231 Add support for the out-of-tree Jetson FFmpeg NVMPI decoders
https://github.com/jocover/jetson-ffmpeg
2020-01-26 19:16:03 -08:00
Cameron Gutman 4c579aa826 Provide another frame if avcodec_receive_frame() returns EAGAIN 2020-01-26 15:36:22 -08:00
Cameron Gutman b9463b3c0e Allow NV12 and NV21 to be selected for non-hwaccel decoders using the SDL renderer 2020-01-26 15:02:29 -08:00
Cameron Gutman cede6ce8a9 Add H264_DECODER_HINT and HEVC_DECODER_HINT envvars to specify a decoder manually 2020-01-26 14:40:48 -08:00
Cameron Gutman 956e6e3638 Avoid slicing for hardware decoders that use SDL as the renderer 2020-01-26 14:13:42 -08:00
Cameron Gutman b282c7d815 Fix parsing CLI flags that accept values when passed before 'action' argument 2020-01-26 13:32:24 -08:00
Cameron Gutman 5b6142e2d9 Always create IdentityManager on the main thread 2020-01-25 19:34:37 -08:00
Cameron Gutman 58313ad8fc Allow default mouse polling interval to be overridden by setting MOUSE_POLLING_INTERVAL 2020-01-21 19:15:17 -08:00
Cameron Gutman 7aff148e9f Add --packet-size command-line option 2020-01-21 19:10:10 -08:00
Cameron Gutman ee5c61fb74 Centralize Discord invite links 2020-01-18 10:53:05 -08:00
Cameron Gutman 91be6c8028 Only hide Qt's mouse cursor on EGLFS 2020-01-15 18:23:02 -08:00
Cameron Gutman 2e0bd2ec28 Invoke avcodec_receive_frame() during decoder testing 2020-01-15 18:09:59 -08:00
Cameron Gutman a0151fbc04 Fix memory leak if 10-bit color is not supported 2020-01-15 17:56:11 -08:00
Cameron Gutman d853782fea Add support for the Meta/Super/Windows key on macOS and Linux 2020-01-15 17:54:57 -08:00
Cameron Gutman c6638a7154 Add support for 10-bit output in full-screen with DXVA2 2020-01-14 17:12:55 -08:00
Cameron Gutman 4abebe3aec Hide the Qt cursor when streaming 2020-01-11 02:06:08 -08:00
Cameron Gutman 5aed8f928a Add V4L2M2M support using SDL renderer
Note: This requires FFmpeg master to work, since it depends on:
https://github.com/FFmpeg/FFmpeg/commit/d61cf1b1ebc2477749d7d7825a072400ed24af9
2020-01-10 20:52:16 -08:00
Cameron Gutman afe6cfc383 Update build dependencies in README 2020-01-05 23:32:48 -08:00
Cameron Gutman 174983ce1e Update Windows builds to FFmpeg 4.2.1 with D3D11VA+DXVA2 enabled 2020-01-01 01:09:33 -06:00
Cameron Gutman 1313c7b3bf Enable HDR as an experimental option 2019-12-30 18:05:43 -06:00
Cameron Gutman bee622bcad Improve speed of initial PC status poll 2019-12-30 17:51:23 -06:00
Cameron Gutman 8cefdeae49 Update macOS builds to FFmpeg 4.2.1 2019-12-30 02:10:26 -06:00
Cameron Gutman 7cf70b9607 Clear Add PC textbox when closing the dialog 2019-12-29 20:13:45 -06:00
Cameron Gutman add4b582b5 Update issue template configuration 2019-12-28 21:02:14 -06:00
Cameron Gutman b419d21940 Only use the QTBUG-80947 hack on Qt 5.14 2019-12-21 13:54:09 -08:00
Cameron Gutman 227ff4e13a Version 1.2.1 (hotfix for Windows and macOS) 2019-12-21 13:01:44 -08:00
Cameron Gutman 8e6e70683e Add workaround for QTBUG-80947 2019-12-21 12:58:45 -08:00
Cameron Gutman 626f0aec6a Rebuild SDL 2.0.10 for macOS with https://bugzilla.libsdl.org/show_bug.cgi?id=4888 patch 2019-12-21 12:49:40 -08:00
Cameron Gutman 973d174a30 Version 1.2.0 (take 2) 2019-12-17 18:25:37 -08:00
Cameron Gutman 9f35690b95 Update DMG signing to support disambiguating identity shortnames 2019-12-17 18:10:39 -08:00
Cameron Gutman d961f2bc13 Switch to QElapsedTimer since QTime is deprecated for our usecase in Qt 5.14 2019-12-16 23:16:31 -08:00
Cameron Gutman 10e8277044 Version 1.2.0 2019-12-16 22:51:11 -08:00
Cameron Gutman b4c40d9b18 Update SDL_GameControllerDB submodule 2019-12-16 22:38:58 -08:00
Cameron Gutman e1603f0808 Explicitly use Rec 601 for VDPAU 2019-12-16 18:02:28 -08:00
Cameron Gutman d4c2350d63 Fix DXVA2 rendering with the wrong colorspace on AMD GPUs 2019-12-15 13:29:19 -08:00
Cameron Gutman 5e5470ae12 Specify video transfer matrix for SLVideo 2019-12-15 11:27:47 -08:00
Cameron Gutman 6230a99360 Fix colorspace conversion with SDL as frontend renderer 2019-12-14 17:17:29 -08:00
Cameron Gutman 801adb6af7 Add colorspace support to VAAPI renderer 2019-12-14 16:58:04 -08:00
Cameron Gutman 8b9b96f422 Only enable slicing when CPU decoding 2019-12-14 15:34:48 -08:00
Cameron Gutman 160684f23e Allow decoders to choose a desired colorspace 2019-12-14 15:25:56 -08:00
Cameron Gutman 88930a9de4 Optimize decoder capability checking 2019-12-14 15:20:44 -08:00
Cameron Gutman af6b8c9b88 Update common-c with colorspace configuration support 2019-12-14 14:40:02 -08:00
Cameron Gutman bf52d3189d Switch to Bionic build image on Travis CI 2019-12-14 13:25:57 -08:00
Cameron Gutman 5d872e8b5b Add auto update check to Steam Link 2019-12-13 20:21:35 -08:00
Cameron Gutman 4832d8007b Print joystick haptic capabilities to log 2019-12-13 18:43:35 -08:00
Cameron Gutman 879e084383 Enable Qt 5.14's new fractional DPI scaling 2019-12-12 20:36:23 -08:00
Cameron Gutman 1ae16bb657 Add source archival script 2019-12-09 18:27:51 -08:00
Cameron Gutman 2177bc68db Add git-archive-all.sh script from https://github.com/meitar/git-archive-all.sh 2019-12-09 18:27:51 -08:00
Cameron Gutman c8b887fe32 Use the new SDL_GameControllerRumble() API on SDL 2.0.9 to fix rumble on HIDAPI gamepads 2019-12-07 16:17:01 -08:00
Cameron Gutman 7205242f38 Improve VPN detection on Windows 2019-12-07 16:00:03 -08:00
Cameron Gutman be33b5b387 Update default window mode on macOS after upgrading 2019-12-07 13:27:47 -08:00
Cameron Gutman 66a123f4b9 Store binaries on the symbol server too 2019-12-03 19:14:19 -08:00
Cameron Gutman 76a4ee22b3 Update SDL_GameControllerDB submodule 2019-12-03 19:02:29 -08:00
Cameron Gutman 3a6bf4d20b Disable arbitrary audio duration for libsoundio until further testing is done 2019-12-03 19:00:43 -08:00
Cameron Gutman 09cf105cdc Block RTSS hooks due to user reported crashes 2019-12-03 18:31:18 -08:00
Cameron Gutman ce02e086a3 Add missing return when no interface address matches 2019-12-02 17:27:57 -08:00
Cameron Gutman e8d4313454 Fix build on Qt 5.10 and earlier 2019-12-02 17:18:29 -08:00
Cameron Gutman 49046f88cf Ignore unknown MTUs 2019-12-01 22:10:07 -08:00
Cameron Gutman 5e2f32e3eb Force remote streaming mode if connecting through a VPN 2019-12-01 21:50:36 -08:00
Cameron Gutman b4a1393bf6 Update common-c with PMTUD and low bitrate audio fixes 2019-12-01 19:45:15 -08:00
Cameron Gutman 0ccee9d806 Support arbitrary audio duration in libsoundio renderer 2019-12-01 19:43:22 -08:00
Cameron Gutman 5700272dc4 Improve low bandwidth audio performance for SDL and SLAudio and fix RTSP issues with broken PMTUD 2019-11-30 22:24:28 -06:00
Cameron Gutman 7e5a3925b3 Fix typo in channel mapping 2019-11-17 14:35:37 -08:00
Cameron Gutman 1febe32e73 Fix 5.1 channel mapping on Steam Link 2019-11-17 12:22:57 -08:00
Cameron Gutman 6059c982cf Fix auto-comment line breaks 2019-11-16 11:58:07 -08:00
Cameron Gutman de7b973239 Plumb presentation time from server into AVFrame.pts field 2019-11-11 18:03:47 -08:00
Cameron Gutman 741113a607 Add configuration for auto-comment bot 2019-11-09 15:04:28 -08:00
Cameron Gutman c20daa8867 Add compatibility checks for HEVC Main10 in VT backend 2019-11-05 18:36:43 -08:00
Cameron Gutman 5e57a7d5c0 Prevent SDL renderer from trying to render 10-bit output 2019-11-05 17:29:21 -08:00
Cameron Gutman 7c8d27700e Add 10-bit output support to VDPAU renderer 2019-11-05 17:09:44 -08:00
Cameron Gutman f8621be5ee Add an HEVC Main10 test frame 2019-11-05 17:08:25 -08:00
Cameron Gutman 8ed87e10b4 Change PC icon to be consistent with iOS and Android 2019-11-05 17:06:57 -08:00
Cameron Gutman ca26fa2dd0 Add basic HEVC Main10 support in DXVA2 renderer 2019-11-04 22:57:12 -08:00
Cameron Gutman 1669095fb1 Prevent double-clicks from triggering pairing twice. Fixes #286 2019-11-04 19:30:38 -08:00
Cameron Gutman 13eed48877 Update moonlight-common-c submodule 2019-11-02 21:49:00 -07:00
Cameron Gutman 07494e6eff Fix Linux build 2019-10-12 19:44:59 -07:00
Cameron Gutman 41b1d72825 Update moonlight-common-c submodule 2019-10-12 19:22:19 -07:00
Cameron Gutman 4d2965e74f Always install the VC redistributable 2019-09-30 00:11:37 -07:00
Cameron Gutman 12526bfca4 Version 1.1.1 2019-09-29 22:11:39 -07:00
Cameron Gutman 3e2c344140 Display the Moonlight icon in Discord Rich Presence info 2019-09-29 22:06:12 -07:00
Cameron Gutman 33730dd584 Display the update tooltip on launch if an update is available 2019-09-29 21:32:24 -07:00
Cameron Gutman 1cb03b1882 Add padding to app labels 2019-09-29 21:26:07 -07:00
Cameron Gutman 2f0a6db414 Add hacks for SDL+Mutter interaction bugs 2019-09-29 21:05:31 -07:00
Cameron Gutman a42328d971 Use VSWhere to locate Visual Studio and redistributables 2019-09-29 15:01:53 -07:00
Cameron Gutman 96ff51d598 Use SDL audio for platforms that libsoundio doesn't support 2019-09-22 12:03:53 -07:00
Cameron Gutman 7c3d3af681 Fix control stream connection error on multi-homed hosts 2019-09-14 14:08:38 -07:00
Cameron Gutman 6942bca5a7 Link to download page from download badge 2019-08-25 23:24:34 -07:00
Cameron Gutman 9eac9a190e Add Downloads badge 2019-08-25 23:20:55 -07:00
Cameron Gutman 40e4fbd9a6 Update common-c for parallel STUN requests 2019-08-20 19:05:54 -07:00
Cameron Gutman 7b6996ed80 Add a little help to the build scripts 2019-08-13 18:07:42 -07:00
Cameron Gutman ef2827a9d8 Update common-c for STUN fallback 2019-08-07 23:14:07 -07:00
Cameron Gutman dbf98ce3a6 Require keyframes even for software H.264 decoding 2019-08-07 22:38:31 -07:00
Cameron Gutman ee7cb5123d Add NVDEC to list of supported video acceleration APIs 2019-08-05 18:31:38 -07:00
Cameron Gutman 77e1d6ab8a Version 1.1 2019-08-05 18:28:26 -07:00
Cameron Gutman 1640bed7a5 Improve reliability of mDNS discovery 2019-08-04 18:04:33 -07:00
Cameron Gutman c6fd5cbbce Update common-c to fix high quality surround sound over the Internet 2019-08-04 15:15:51 -07:00
Cameron Gutman 5288041da5 Prevent us from consuming more than 4 samples per write callback to bound latency 2019-08-03 12:47:44 -07:00
Cameron Gutman a848fb1dd1 Add Steam Link to Travis CI 2019-08-02 21:31:07 -07:00
Cameron Gutman 172945434c Build the full DMG on Travis CI 2019-08-02 20:52:23 -07:00
Cameron Gutman a0967e0281 Fix building a dmg with no code signing identities 2019-08-02 20:40:20 -07:00
Cameron Gutman deab717c73 Remove AppVeyor OpenSSL hack 2019-08-02 20:21:10 -07:00
Cameron Gutman 5db5a088ea Fix NVDEC artifacts if the renderer is delayed for a bit 2019-08-01 20:25:58 -07:00
Cameron Gutman 5e106d2f19 Only store the local address from mDNS if it actually worked 2019-07-31 22:16:11 -07:00
Cameron Gutman 940da6bc73 Fix discovery of IPv6-only hosts 2019-07-31 22:07:20 -07:00
Cameron Gutman d110bff253 Update qmdnsengine to improve reliability of mDNS on multi-homed systems 2019-07-31 22:03:27 -07:00
Cameron Gutman 4caa329c36 Update Windows to SDL 2.0.10 with USE_D3D9EX 2019-07-28 12:01:12 -07:00
Cameron Gutman 7c7d279337 Update SDL_GameControllerDB to dca1a629d9e094baa17fff8ba1642cabc6125eed 2019-07-26 16:43:20 -04:00
Cameron Gutman 831e6ee76d Update moonlight-common-c to fix termination error code on GFE 3.19.0.107 2019-07-26 16:43:20 -04:00
Cameron Gutman b01842ad02 Update macOS to SDL 2.0.10 2019-07-26 16:43:20 -04:00
Cameron Gutman 7acf91883a Rework audio renderer selection to fall back and treat ML_AUDIO as a hard selection 2019-07-26 12:50:45 -04:00
Cameron Gutman 897f6fdd3e Improve handling of IPv6-only cases 2019-07-15 01:07:31 -07:00
Cameron Gutman 6f9c3fbc38 Add support for zero configuration IPv6 streaming 2019-07-14 17:56:57 -07:00
Cameron Gutman bcbd1a5b4b Fix subsystem print in VAAPI 2019-07-07 15:41:26 -07:00
Cameron Gutman 6468efd7e4 Add VAAPI DRM support 2019-07-07 15:32:38 -07:00
Cameron Gutman 66863789c7 Update common-c for compatibility with legacy servers 2019-07-05 22:52:42 -07:00
Cameron Gutman b30058fc29 Fix pairing to Gen 3-5 servers 2019-07-05 21:04:04 -07:00
Cameron Gutman a41cd0b070 Generate SHA-256 client certificates instead of SHA-1 2019-07-05 20:57:21 -07:00
Cameron Gutman ea8b905f02 Missed a call to SDL_SetRelativeMouseMode 2019-07-02 22:39:09 -07:00
Cameron Gutman 16b301236b Add a mouse capture fallback if SDL_SetRelativeMouseMode() fails 2019-07-02 22:17:38 -07:00
Cameron Gutman 22162dda83 Fix runtime SDL version report 2019-06-30 18:48:11 -07:00
Cameron Gutman 024af89be3 Add an option to disable the gamepad mouse button toggle 2019-06-29 18:24:59 -07:00
Cameron Gutman e1a697658e Add Discord Rich Presence for macOS 2019-06-29 17:55:21 -07:00
Cameron Gutman 0a5051f959 Add Discord Rich Presence integration for Windows 2019-06-29 17:40:30 -07:00
Cameron Gutman 82b6b60b31 Take advantage of SDL 2.0.10 bugfixes and new APIs. Fixes #133 2019-06-29 16:08:04 -07:00
Cameron Gutman 06b3c3636a Print compile-time and run-time SDL versions 2019-06-29 15:43:45 -07:00
Cameron Gutman e5712a9474 Move dylibs into the Frameworks folder in the app bundle 2019-06-29 15:39:20 -07:00
Cameron Gutman 6ff845c53b Use borderless windowed mode as the default on macOS. Fixes #246 2019-06-29 14:58:27 -07:00
Cameron Gutman 1c225ed04d Use CUDA acceleration if other hwaccels are unavailable 2019-06-26 21:54:29 -07:00
Cameron Gutman 612b738968 Use the preferred sw_format when reading frames back 2019-06-26 21:25:41 -07:00
Cameron Gutman 87356ef594 Add CUDA acceleration support 2019-06-26 21:02:33 -07:00
Cameron Gutman 20a4dfa6d6 Update bug report template 2019-06-25 21:41:02 -07:00
Cameron Gutman 524cc97f51 Use borderless windowed mode when toggling to full-screen from an initially windowed stream. Fixes #248 2019-06-23 13:29:57 -07:00
Cameron Gutman fc849fb51a Switch back to SDL for audio on Linux. Fixes #245 2019-06-23 13:16:00 -07:00
Cameron Gutman c88651939a Re-add latency bounding on the SDL audio renderer 2019-06-23 13:14:55 -07:00
Cameron Gutman 01254f67f0 Allow audio renderers to specify capabilities 2019-06-23 12:49:37 -07:00
Cameron Gutman 212ed33b21 Block Optimus from using the dGPU due to driver bugs. Fixes #240. Fixes #235 2019-06-22 19:49:05 -07:00
Cameron Gutman bd3f8aef21 Remove OpenSSL 1.0.2 for Qt 5.12.4/5.13 2019-06-18 19:54:35 -07:00
Cameron Gutman 3785acea29 Update to OpenSSL 1.1.1c in preparation for Qt 5.12.4/5.13 2019-06-16 15:20:04 -07:00
Cameron Gutman 866e2f1762 Version 1.0.1 2019-05-27 09:31:01 -07:00
Cameron Gutman 0a705d6752 Fix video on GFE 3.19 2019-05-27 02:24:55 -07:00
Cameron Gutman 4f74fd5354 Fix uninitialized variables and a race condition with CVDisplayLinkStart() 2019-05-21 09:09:16 -07:00
Cameron Gutman 3df9a5d01c Version 1.0.0 2019-05-21 00:14:12 -07:00
Cameron Gutman 2682829bd3 Fix Steam Link audio latency cap 2019-05-20 23:57:27 -07:00
Cameron Gutman 30cfa2607d Hide mouse cursor after streaming on Steam Link 2019-05-19 17:43:46 -07:00
Cameron Gutman 4467c2e6ad Update SDL_GameControllerDB 2019-05-19 13:46:05 -07:00
Cameron Gutman 2c0e8a0ddf Send WoL packet to 48002 and 48010 to workaround ISP blocking of 7 and 9 2019-05-19 13:36:05 -07:00
Cameron Gutman 4c17f32a2e Fix extra non-working gamepad appearing to the host 2019-05-19 13:24:06 -07:00
Cameron Gutman 674220087f Finish mouse emulation support with overlay and bugfixes 2019-05-19 13:10:42 -07:00
Cameron Gutman fc8d5d5799 Add gamepad mouse emulation support 2019-05-19 12:17:23 -07:00
Cameron Gutman 4e4f04c174 Focus on first item when a gamepad is connected 2019-05-19 11:08:23 -07:00
Cameron Gutman 65c21f3392 Improve gamepad navigation on settings page 2019-05-19 10:16:54 -07:00
Cameron Gutman 97fb30cdf1 Fix a few bugs in CVDisplayLink integration in VTRenderer 2019-05-19 09:52:59 -07:00
Cameron Gutman c975279589 Only enable exception-based thread naming on debug builds 2019-05-13 17:54:03 -07:00
Cameron Gutman b3ee7a635f Cap queued audio at 40 ms on Steam Link 2019-05-11 19:09:59 -07:00
Cameron Gutman c2b12868bb Move DisplayLinkVsyncSource back into VTRenderer to reduce latency 2019-05-11 18:33:12 -07:00
Cameron Gutman bdbb03e16f Request 20 ms audio frames on Steam Link to reduce CPU overhead 2019-05-04 15:46:11 -07:00
Cameron Gutman 53138d7c16 Name threads for easier debugging 2019-05-03 21:18:58 -07:00
Cameron Gutman 18d1d35104 Use QByteArray::reserve() rather than reallocating each time we must resize 2019-05-02 22:54:18 -07:00
Cameron Gutman 99d9de35de Add NV21 pixel format support to SDL renderer 2019-05-02 22:51:28 -07:00
Cameron Gutman e6a48481a5 Restore the bulk submission optimization for Steam Link 2019-05-01 22:31:52 -07:00
Cameron Gutman 21f2b1224a Decode directly into the audio renderer's buffer to avoid a copy 2019-05-01 21:27:41 -07:00
Cameron Gutman 187f47a353 Update common-c to fix receive time corruption 2019-04-30 23:23:02 -07:00
Cameron Gutman cb75b3d6d2 Version 0.10.1 2019-04-28 19:27:30 -07:00
Cameron Gutman 27708b9ecb Disable HIDAPI for Xbox gamepads on macOS 2019-04-28 18:45:56 -07:00
Cameron Gutman 5443165fce Update macOS to SDL 2.0.9 with https://bugzilla.libsdl.org/show_bug.cgi?id=4614 patch 2019-04-28 18:28:06 -07:00
Cameron Gutman dfb006d264 More Steam Link performance optimizations 2019-04-28 15:57:57 -07:00
Cameron Gutman 4f00f62674 Batch controller axis events for reduced CPU usage on Steam Link 2019-04-28 15:16:04 -07:00
Cameron Gutman cec527ffd5 Update common-c with performance optimizations and audio bandwidth reduction 2019-04-28 13:17:22 -07:00
Cameron Gutman 4f2fe5c988 Reduce polling rate on SL due to CPU performance limitations 2019-04-28 13:04:58 -07:00
Cameron Gutman 2bf552f801 Batch audio frames on Steam Link to save CPU cycles 2019-04-28 12:55:04 -07:00
Cameron Gutman 477fa8fedf Add logging callbacks for SLAudio and SLVideo 2019-04-28 11:01:54 -07:00
Cameron Gutman f1c7c5f02c Don't emit boxArtLoadComplete on box art load failure to prevent an infinite loop 2019-04-27 18:48:06 -07:00
Cameron Gutman 4e936193c7 Request a test frame for MMAL decoder 2019-04-24 21:31:52 -07:00
Cameron Gutman f9895c22b6 Update SDL_GameControllerDB to cbebd79740bc1360978bdf6d9d4d13d189e420a3 2019-04-24 20:27:23 -07:00
Cameron Gutman 6e46537112 Fix highlights for toolbar buttons to be more visible 2019-04-24 20:22:39 -07:00
Cameron Gutman 92b3918b26 Correct the path used by forfiles commands 2019-04-23 23:25:10 -07:00
Cameron Gutman 34c615a5fd Only include pre-compiled QML files in the installer and portable zips 2019-04-23 22:28:28 -07:00
Cameron Gutman fa29260e09 Work around Qt 5.12 dialog crash on disconnect 2019-04-23 19:40:21 -07:00
cgutman1 a05816b495 Pre-generate QML cache for our QtQuick dependences. Fixes #217 2019-04-22 21:04:21 -07:00
Cameron Gutman 9c5d847dae Autodetect a Wayland environment and configure SDL correctly. Fixes #211 2019-04-21 18:31:11 -07:00
Cameron Gutman 082e330f9d Partially revert fa4c0e82bd because we'll need Qt initialized first to detect Wayland 2019-04-21 17:43:38 -07:00
Cameron Gutman 8878c4a136 Use VAAPI decoder for AMD on Wayland 2019-04-21 15:33:21 -07:00
Cameron Gutman 00926bac81 Fix build warning in SDL renderer 2019-04-21 11:09:11 -07:00
Cameron Gutman 67b0907e52 Add globaldefs.pri for setting qmake values in each project 2019-04-21 11:08:33 -07:00
Cameron Gutman dba479774b Add DRM renderer for Rockchip devices 2019-04-21 05:22:37 +00:00
Cameron Gutman 5c8a1e632b Add support for rendering NV12 hwframes with SDL 2019-04-19 22:16:06 -07:00
Cameron Gutman d65e29111f Fix some codec selection bugs 2019-04-19 20:57:21 -07:00
Cameron Gutman ed170b8092 Prevent the computer name from overflowing the PC grid item 2019-04-18 21:03:37 -07:00
Cameron Gutman ac36fef968 Fix incorrect placeholder status after loading box art causing app label to be absent 2019-04-18 20:58:40 -07:00
Cameron Gutman 10f6b73cad Revert "Avoid using ANGLE on debug builds due to assert issues on Qt 5.12.2"
Qt 5.12.3 fixes the bug. https://bugreports.qt.io/browse/QTBUG-74467

This reverts commit 26bdc3e1d5.
2019-04-18 20:57:39 -07:00
Cameron Gutman 13d933fc07 Until Qt 5.13, VS 2019 is not supported 2019-04-18 20:08:27 -07:00
Cameron Gutman 3ba98e86f2 Remove QC1 style variable since QC1 dialogs are no longer used 2019-04-18 20:04:24 -07:00
Cameron Gutman 1dfca525cf Refactor renderer initialization to reduce duplication and inconsistency 2019-04-18 20:02:14 -07:00
Cameron Gutman e51ad1a68a Fix use-after-free due to stale m_FrontendRenderer pointer. Fixes #214 2019-04-18 19:26:13 -07:00
Cameron Gutman 9c76700f74 Add MMAL renderer for Raspberry Pi 2019-04-16 01:20:21 -07:00
Cameron Gutman 773b1af6f1 Minor refactoring in preparation for non-hwaccel decoder support 2019-04-15 21:56:01 -07:00
Cameron Gutman b8b633a6cc Use SDL to render on Wayland for VAAPI 2019-04-12 22:54:21 -07:00
Cameron Gutman ada2270bd1 Reduce code duplication in renderers 2019-04-12 22:12:53 -07:00
Cameron Gutman 25e5175c54 Refactor parameter passing to decoders and split backend/decode-only and frontend renderers 2019-04-11 22:27:20 -07:00
Cameron Gutman 9dcd770df2 Fix alloc-dealloc mismatch 2019-04-09 21:51:39 -07:00
Cameron Gutman 00a1948b73 Treat AV_CODEC_CAP_HARDWARE codecs as hardware accelerated too 2019-04-09 21:50:22 -07:00
Cameron Gutman 859a5a5e0c Allow a renderer to opt-out of the render thread and use that for SDL on OGL 2019-04-09 21:46:14 -07:00
Cameron Gutman 6783cf57da TTF_OpenFontRW retains the SDL_RWops on success, so we must keep the font data around to back it 2019-04-09 21:26:47 -07:00
Cameron Gutman a8dc5ac14a Add App Notarization and Hardened Runtime for macOS builds 2019-04-09 18:30:25 -07:00
Cameron Gutman 6182553d79 Version 0.10.0 2019-04-07 13:21:02 -07:00
Cameron Gutman 905a0cdac1 Make GFE-reported errors more clear 2019-04-07 12:21:05 -07:00
Cameron Gutman f20ddcf26d Fix long delay in LiStopConnection() that can cause a hang on quit 2019-04-06 15:28:48 -07:00
Cameron Gutman fe26098c2b Fix quitting via Command-Q on macOS 2019-04-06 15:22:14 -07:00
Cameron Gutman 2354a0a640 Fix unresponsive GUI on quit if a polling operation is in progress 2019-04-06 13:11:36 -07:00
Cameron Gutman 7c3f09c70c Update poor connection behavior 2019-04-06 12:25:35 -07:00
Cameron Gutman caf5350fe6 Update SDL_GameControllerDB to e411d95fcda34c19270c2d12335fc47512a87dec 2019-04-06 12:06:52 -07:00
Cameron Gutman 84084835ce Refactor and fix the GridView centering code to avoid flipping between states 2019-04-06 11:48:58 -07:00
Cameron Gutman 7f38a67ede Fix brown-paper-bag bug in 948910bfa2 2019-04-03 21:13:12 -07:00
Cameron Gutman 54383b84ec Fix random deadlocks on window resize with the software decoder due to processing window messages off the render thread 2019-04-03 20:44:50 -07:00
Cameron Gutman 948910bfa2 Don't open the app context menu for mouse clicks 2019-04-03 20:27:00 -07:00
Cameron Gutman ce5dac07d3 Ensure the anchor hack stays in sync with changing margins prior to Qt 5.12 2019-04-01 22:12:49 -07:00
Cameron Gutman d4b0057423 Minor tweak to the label layout of running apps 2019-04-01 20:55:11 -07:00
Cameron Gutman de8b12f594 Fix grid view margins and scroll bar positioning on Qt 5.9 2019-04-01 20:40:52 -07:00
Cameron Gutman 69e31a0a37 Redesign the app view UI to feature larger game artwork and less text 2019-04-01 19:49:33 -07:00
Cameron Gutman c383cd39f4 Fix text wrapping with giant error messages 2019-04-01 18:31:13 -07:00
Cameron Gutman e88d2f0ab2 Add files and scripts to build for Steam Link 2019-03-31 23:26:17 -07:00
Cameron Gutman 32535578a0 Use newlines for the help text separator on the unmapped gamepad dialog 2019-03-31 20:10:56 -07:00
Cameron Gutman 2e9af8fef0 Fix focus and rejection of Yes/No dialogs on SL 2019-03-31 19:40:30 -07:00
Cameron Gutman 0aa87aacc6 Fix focus issues after dismissal of consecutive dialogs (like Add PC -> Add PC error) 2019-03-31 19:32:17 -07:00
Cameron Gutman bc38c302ed Cap the maximum width of the error dialogs 2019-03-31 19:05:38 -07:00
Cameron Gutman c724902508 Clean up code for new QC2 dialogs and remove some unused imports 2019-03-31 17:44:19 -07:00
Cameron Gutman 73604020d7 Rewrite dialog code to use Quick Controls 2 2019-03-31 17:24:25 -07:00
Cameron Gutman 060a00b9c7 Consolidate help handling into ErrorMessageDialog 2019-03-31 15:16:48 -07:00
Cameron Gutman 2cd32bf25a Move the cursor into the lower right corner on SL 2019-03-31 13:58:27 -07:00
Cameron Gutman 81ad1a18fa Fix error dialog focus issues after dismissal on Steam Link 2019-03-31 13:57:57 -07:00
Cameron Gutman 1d94903eef Add a hack to ensure the layout anchors work properly on Qt 5.11 and earlier 2019-03-30 12:28:18 -07:00
Cameron Gutman 2d7dcb495c Remove CAPABILITY_DIRECT_SUBMIT for the video decoder because it can block for significant time periods when D3D9 is reconfiguring display settings (and holding the D3D global lock)
This can cause false reports of packet loss.
2019-03-29 23:38:23 -07:00
Cameron Gutman bc580c9aaa Ensure SdlGamepadKeyNavigation is only re-enabled after the sessionFinished() callback to avoid conflicts with SdlInputHandler 2019-03-29 23:20:43 -07:00
Cameron Gutman f8e2740532 Add placeholder text when no PCs are present 2019-03-27 18:13:20 -07:00
Cameron Gutman a079ecd20b Improve transitions and eliminate conflicting anchor warnings 2019-03-27 01:28:46 -07:00
Cameron Gutman 89c8725766 Improve Add PC dialog readability on Windows 2019-03-27 00:39:25 -07:00
Cameron Gutman da7d532564 Move Add PC button to toolbar 2019-03-26 21:31:51 -07:00
Cameron Gutman 4752d4966d Improve Add PC dialog to have a proper text field 2019-03-26 21:12:53 -07:00
Cameron Gutman 50f47f1ed5 Fix handling of screen saver after fa4c0e82bd and reset background events hint for UI after streaming 2019-03-26 21:11:24 -07:00
Cameron Gutman 26bdc3e1d5 Avoid using ANGLE on debug builds due to assert issues on Qt 5.12.2 2019-03-24 19:23:02 -07:00
Cameron Gutman 764360c0f3 Avoid doing non-trivial work in onCheckedChanged on settings page load 2019-03-24 19:15:35 -07:00
Cameron Gutman 08482577eb Fix connection termination dialog regression from 03c0be0720 2019-03-24 15:19:38 -07:00
Cameron Gutman cabbba2448 Move status update overlay to bottom left for SDL 2019-03-23 21:14:21 -07:00
Cameron Gutman c48ed7bb0d Fix undefined variable usage after 2703efedef 2019-03-23 20:25:19 -07:00
Cameron Gutman fa4c0e82bd Only initialize the video subsystem once per launch 2019-03-23 17:46:42 -07:00
Cameron Gutman c0bf8b9c25 Remove redundant initializtion of SDL video 2019-03-23 14:26:08 -07:00
Cameron Gutman d2cff86c97 Refactor SdlGamepadKeyNavigation to avoid multiple reinitializations of SDL 2019-03-23 14:15:55 -07:00
Cameron Gutman 03c0be0720 Only display help options on platforms with web browsers 2019-03-23 13:51:34 -07:00
Cameron Gutman a3361363e4 Remove duplicate data files on Linux 2019-03-23 12:20:01 -07:00
Cameron Gutman 40e142c5c7 Add force feedback to feature list 2019-03-23 12:14:43 -07:00
Cameron Gutman 2703efedef Improve performance of looking up static system properties 2019-03-23 12:05:08 -07:00
Cameron Gutman c313f1a20b Embed our data files inside the binary with QRC 2019-03-23 10:45:44 -07:00
Cameron Gutman b7116657d9 Add SLAudio renderer for Steam Link 2019-03-22 23:08:10 -07:00
Cameron Gutman 2bf3f1b94b Refactor Steam Link support files 2019-03-22 22:51:08 -07:00
Cameron Gutman b78a7971d9 Fix the launch warning toasts on Qt 5.9 2019-03-22 21:30:06 -07:00
Cameron Gutman 5079bc4976 Fix SDL video initialization on Steam Link 2019-03-22 21:11:17 -07:00
Cameron Gutman 555032c15c Add fallback font hack for Steam Link 2019-03-22 20:53:02 -07:00
Cameron Gutman bcff327565 Use QRC URLs for the initialView value to fix loading from the QRC blob 2019-03-22 19:21:04 -07:00
Cameron Gutman e95ff989b1 Allow DXVA2 renderer blacklists to be bypassed 2019-03-21 20:44:30 -07:00
Cameron Gutman 018e8999e2 Add connection status overlay for the VT renderer 2019-03-18 20:56:53 -07:00
Cameron Gutman f624a1817e Add preference and tweak connection warning 2019-03-18 20:21:52 -07:00
Cameron Gutman 202a643e5a Fix size of the status update overlay on DXVA2 2019-03-17 15:12:25 -07:00
Cameron Gutman c75b9c9221 Add connection status overlay for DXVA2 and SDL 2019-03-17 15:08:21 -07:00
Cameron Gutman 9a6f5ba1a8 Improve speed of process termination on exit 2019-03-17 12:23:13 -07:00
Cameron Gutman 052194714a Adjust thread priorities based on recent refactoring 2019-03-17 00:45:31 -07:00
Cameron Gutman 5ccb4a8b7f Improve busy PC error text 2019-03-17 00:33:52 -07:00
Cameron Gutman 7c3cec0451 Add EZFRD32.dll and EZFRD64.dll to blacklist based on crash reports 2019-03-17 00:23:32 -07:00
Cameron Gutman b79d3b31b3 Disable minimize on focus loss by default 2019-03-17 00:20:47 -07:00
Cameron Gutman bf5d43d0cf Use SDL_HINT_OVERRIDE for critical hints 2019-03-17 00:18:15 -07:00
Cameron Gutman f2ac570949 Rebuild SDL2 (5dc13016cf) with USE_D3D9EX 2019-03-16 23:52:40 -07:00
Cameron Gutman 37636ef1eb Allow other SSL errors as long as the cert is correct 2019-03-16 19:01:55 -07:00
Cameron Gutman c540bec824 Remove logging hack now that Qt 5.12.2 fixes the bug 2019-03-16 16:59:49 -07:00
Cameron Gutman 9288cfa684 Basic support for building as UWP app 2019-03-13 01:02:04 -07:00
Cameron Gutman b1de8b703b Update bug report template for Snap package 2019-03-06 21:32:51 -08:00
Cameron Gutman ccd0777ce9 Use a Loader to be able to use StackView.onActivated to trigger stream start 2019-03-02 20:55:50 -08:00
Cameron Gutman 49b67b3e18 Adjust QGnomePlatform hack to avoid disabling desktop settings awareness. Fixes #185 2019-03-02 19:50:05 -08:00
Cameron Gutman bc97168dc7 Update moonlight-common-c 2019-03-02 14:14:54 -08:00
Cameron Gutman 0ec04df334 Hide hint text when the connection completes 2019-03-02 14:13:32 -08:00
Cameron Gutman 26d7946b4a Fix toolbar hiding in quit segue 2019-03-02 14:13:14 -08:00
Cameron Gutman 292cc579cf Partially revert 8037fb76fc to fix mouse polling issues on Windows 2019-03-02 14:11:30 -08:00
Cameron Gutman 8492482e55 Add a script to create a zip of Qt PDBs 2019-02-26 19:10:17 -08:00
Cameron Gutman ac8183feee Fix selection loss when going back caused by previous commit 2019-02-22 22:44:09 -08:00
Cameron Gutman 8037fb76fc Use StackView activation callbacks to perform init and cleanup since visibility callbacks aren't guaranteed to run in any order 2019-02-22 22:14:06 -08:00
Cameron Gutman 754a14941b Update Windows build to OpenSSL 1.1.0k to fix App Verifier TLS warning 2019-02-22 21:14:40 -08:00
Konstantin Budnikov e32bc1a0a3 SDL_HapticRumblePlay rumble for gamepad without SDL_HAPTIC_LEFTRIGHT support (#181) 2019-02-20 19:22:38 -08:00
Cameron Gutman e5a8b49c93 Limit the number of queued frames in Pacer to prevent excessive memory consumption if the renderer gets blocked for a while 2019-02-18 12:13:45 -08:00
Cameron Gutman b6872456cd Version 0.9.1 2019-02-17 13:13:57 -08:00
Cameron Gutman 2a12b018da Fix special key combos on non-QWERTY latin keyboards 2019-02-17 13:07:54 -08:00
Cameron Gutman f64486c88f Version 0.9.0 2019-02-17 00:18:42 -08:00
Cameron Gutman 80a40ac5f9 Increase frame drop threshold 2019-02-16 23:13:35 -08:00
Cameron Gutman a1956350b1 Rename pacing drop to jitter drop to be less confusing for users 2019-02-16 23:04:25 -08:00
Cameron Gutman 2c09875556 Fix input handler cleanup on startup failure 2019-02-16 01:39:31 -08:00
Cameron Gutman 561eed4cbd Use 2 concurrent jobs on Travis CI 2019-02-16 00:59:00 -08:00
Cameron Gutman a8f72df7f8 Fix in-tree builds 2019-02-16 00:42:09 -08:00
Cameron Gutman ab4127f940 Use presence of a frame after rendering rather than render time for frame dropping 2019-02-15 22:44:52 -08:00
Cameron Gutman f03d12b677 Use a separate render thread even with a V-Sync source 2019-02-15 22:09:50 -08:00
Cameron Gutman 81c6202582 Rename renderFrameAtVsync() to renderFrame() in preparation for further refactoring 2019-02-15 21:07:02 -08:00
Cameron Gutman 6cab2bec61 Don't trust VT to tell us whether decode is supported 2019-02-15 19:10:21 -08:00
Cameron Gutman 94ffda653c Update SDL_GameControllerDB to add new mappings 2019-02-15 19:00:30 -08:00
Cameron Gutman c2268b45f6 Merge pull request #177 from konst2/master
Fix hotkeys for non-latin keyboard layouts
2019-02-15 18:57:24 -08:00
Cameron Gutman 38b8a59fe5 Adjust overlay color for more contrast 2019-02-15 18:53:40 -08:00
Cameron Gutman 640e3213ee Copy the required data files into place for building in the IDE 2019-02-15 18:47:42 -08:00
Cameron Gutman b1799009b3 Use the Path class to lookup ModeSeven.ttf 2019-02-15 18:13:36 -08:00
Cameron Gutman f8e693a060 Drop samples to account for lost time reinitializing audio. Fixes #176 2019-02-14 22:32:54 -08:00
Cameron Gutman aba806bc32 Implement debug overlay for VideoToolbox renderer 2019-02-13 20:55:52 -08:00
Cameron Gutman b1fb3f2391 Set FFmpeg log level at debug until first frame is rendered 2019-02-13 18:34:59 -08:00
konst2 041e901c61 Fix hotkeys for non-latin keyboard layouts 2019-02-13 19:56:44 +03:00
Cameron Gutman bb72134992 Attempt to fix Travis CI Linux build 2019-02-12 23:25:23 -08:00
Cameron Gutman f83853c2fb OverlayManager now manages font size for the overlays 2019-02-12 22:36:56 -08:00
Cameron Gutman d5f7b20be3 Update common-c with sign extension fix 2019-02-12 22:24:47 -08:00
Cameron Gutman b878d64460 Check rumble controller number is within the supported range 2019-02-12 22:05:55 -08:00
Cameron Gutman 5397e8ae1a Don't use SDL_GameControllerGetPlayerIndex() because the indexes may be non-contiguous (and wrong) on XInput 2019-02-12 22:04:05 -08:00
Cameron Gutman 46bd8ad83d Add debug overlay for SDL renderer 2019-02-12 21:55:15 -08:00
Cameron Gutman 4dac57cf8c Add SDL2_ttf dependency for Linux 2019-02-12 21:38:51 -08:00
Cameron Gutman 95cb026446 Add SDL2_ttf for macOS 2019-02-12 21:32:11 -08:00
Cameron Gutman 76ea714257 Add SDL2_ttf for Windows 2019-02-12 21:18:55 -08:00
Cameron Gutman 5788fa7204 Make OverlayManager own the overlay color setting 2019-02-12 20:39:10 -08:00
Cameron Gutman d077c6450f Split SdlRenderer from renderer.h 2019-02-12 19:58:36 -08:00
Cameron Gutman 4499ed3878 Work around dialog rendering issue with QGnomePlatform. Fixes #161 2019-02-12 19:45:14 -08:00
Cameron Gutman feb5e3bc78 Fix SDL_WasInit asserts firing due to lifetime management issues with SdlInputHandler 2019-02-12 19:30:02 -08:00
Cameron Gutman 23f1060756 Polish the resume/quit buttons 2019-02-12 19:07:48 -08:00
Cameron Gutman 6ed512e762 Provide a renderer callback when the overlay data changes 2019-02-12 18:43:38 -08:00
Cameron Gutman 947970e07b Shortcut decoder initialization when only using it for capability testing 2019-02-12 18:42:53 -08:00
Cameron Gutman df567b405a Minor bugfixes to haptics 2019-02-11 21:55:56 -08:00
MINICOM\mrb11 7b0596d9df Add controller rumble support. 2019-02-11 21:39:55 -08:00
Cameron Gutman 4b7200ae69 Don't display the connection terminated dialog for intended disconnects 2019-02-10 02:19:37 -08:00
Cameron Gutman 710648f3f4 Fix QuitSegue -> StreamSegue transition to be direct via replacement and disallow toolbar interactions 2019-02-09 21:15:17 -08:00
Cameron Gutman d2002b6a62 Fix SOPS issues causing 720p60 settings on non-standard resolutions and FPS values 2019-02-09 20:37:11 -08:00
Cameron Gutman 8de42b3199 Fix gamepad menu focus and dismissal issues 2019-02-09 19:59:01 -08:00
Cameron Gutman 48e78d2cd3 Don't allow focus on invisible menu items 2019-02-09 19:21:43 -08:00
Cameron Gutman 1fd099db70 Log when StretchRect() fails 2019-02-09 18:47:57 -08:00
Cameron Gutman 2986a40c5a Fix some gamepads working for UI navigation but not in game 2019-01-29 22:01:05 -08:00
Cameron Gutman 8bb6d4d0d9 Fix VDPAU scaling on AMD cards. Fixes #171 2019-01-29 20:52:41 -08:00
Cameron Gutman 00f08578ee Update common-c to fix IDR issue on GFE 3.17 2019-01-29 20:18:03 -08:00
Cameron Gutman 6a514c7f51 Update readme to point to Snap package 2019-01-29 18:30:56 -08:00
Cameron Gutman 21aad643f3 Use 32 pixel alignment for HEVC to fix Intel green line issue 2019-01-28 21:26:27 -08:00
Cameron Gutman 8687448966 Use StretchRect() on Intel GPUs or if VideoProcessBlt() fails 2019-01-28 19:18:43 -08:00
Cameron Gutman 6fcc8b721b Add a button for quitting the running app 2019-01-26 23:57:02 -08:00
Cameron Gutman b4bbd58c77 Add long press action on PC view for touchscreens 2019-01-26 23:11:09 -08:00
Cameron Gutman 1a45b8f07a Fix dialog box styles 2019-01-26 21:45:32 -08:00
Cameron Gutman 4471a858db Fix miscounted pacer dropped frames in non-pacing mode 2019-01-22 21:21:29 -08:00
Cameron Gutman 22e712af5a Add v-sync text to stats overlay 2019-01-22 20:55:58 -08:00
Cameron Gutman 9799b82d53 Improve long render time logic 2019-01-22 20:55:35 -08:00
Cameron Gutman 78915e0b99 Use a separate render thread when not using frame pacing 2019-01-22 20:31:31 -08:00
Cameron Gutman c9cc65aae7 Fix appstream metadata release date for v0.8.1 2019-01-22 19:07:14 -08:00
Cameron Gutman a4edd9d202 Submit frame directly from the decoder thread to avoid interference from the main thread 2019-01-21 20:27:37 -08:00
Cameron Gutman 7747624c80 Revert "Wake up main thread immediately after new frame is pushed"
This reverts commit aab7191a44.
2019-01-21 20:10:13 -08:00
Cameron Gutman aab7191a44 Wake up main thread immediately after new frame is pushed 2019-01-21 18:57:14 -08:00
Cameron Gutman 1f972b1828 Require several consecutive long render times to drop a frame 2019-01-21 17:58:42 -08:00
Cameron Gutman 58b77cf589 Fix inaccurate pacer drop and network drop percentages and add total FPS stat 2019-01-21 17:43:15 -08:00
Cameron Gutman c064f87889 Drop a frame if the rendering time exceeds the v-sync period 2019-01-20 19:59:29 -08:00
Cameron Gutman d6b4c8e7da Avoid blocking decoding operations during Present calls 2019-01-20 14:08:53 -08:00
Cameron Gutman 49f0b45fa8 Update build requirements for Windows 2019-01-20 11:58:30 -08:00
Cameron Gutman b19c4bfc5d Add performance overlay for DXVA2 renderer 2019-01-19 23:05:56 -08:00
Cameron Gutman e944c819d9 Add prefix for NvLogLevel enum values 2019-01-19 21:32:35 -08:00
Cameron Gutman 75f631599c Ensure all polling threads are dead before destroying hosts, even ones that have been detached by stopPollingAsync() 2019-01-19 19:18:50 -08:00
Cameron Gutman e0bebeae25 Allow theme overrides via environment variables 2019-01-19 17:06:35 -08:00
Cameron Gutman 32e7ddf272 Version 0.8.1 2019-01-08 00:48:49 -08:00
Cameron Gutman 7091e0324e Update macOS builds to FFmpeg 4.1 2019-01-07 21:43:18 -08:00
Cameron Gutman 8f8532921c Update FFmpeg build script for Mac to avoid manual steps 2019-01-07 21:39:59 -08:00
Cameron Gutman e9936992ec Update Windows builds to FFmpeg 4.1 2019-01-07 21:08:08 -08:00
Cameron Gutman 6375055b3e Set scripts executable 2019-01-07 20:34:56 -08:00
Cameron Gutman 88b1ea296c Remove video bitrate tooltip since audio is accounted for during remote streaming 2019-01-06 15:41:00 -08:00
Cameron Gutman 2a13a869f3 Don't allow the scroll wheel to move the bitrate slider 2019-01-06 15:39:54 -08:00
Cameron Gutman 89c342bb6f Introduce more granular HTTP timeouts 2019-01-06 14:35:33 -08:00
Cameron Gutman 067f5e33aa Increase audio buffer on Linux to 25 ms. Fixes #147. Fixes #157. 2019-01-06 13:49:20 -08:00
Cameron Gutman 33695f1c6b Update common-c to reduce audio latency 2019-01-06 13:29:06 -08:00
Cameron Gutman 52ef84873e Remove excess latency control logic from SDL renderer, since it doesn't appear to work very well anyway 2019-01-06 13:28:43 -08:00
Cameron Gutman c21ba5c808 Allow the audio renderer to be overriden by the ML_AUDIO environment variable 2019-01-06 13:28:05 -08:00
Cameron Gutman 6cf408f12b Update macOS build steps 2019-01-05 19:23:01 -08:00
Cameron Gutman 8bdc2d285d Rename macOS build output to match final release name 2019-01-05 19:06:00 -08:00
Cameron Gutman a66fbcd6be Use version.txt for Info.plist too 2019-01-05 18:53:17 -08:00
Cameron Gutman 93402a62fc Archive symbol ZIP to ML_SYMBOL_ARCHIVE folder 2019-01-05 18:20:53 -08:00
Cameron Gutman 2a56fb6c70 Add config.test generated files to gitignore 2019-01-05 18:10:20 -08:00
Cameron Gutman 8276c031e9 Name the Windows output binaries to match their final names on GitHub 2019-01-05 18:09:52 -08:00
Cameron Gutman 102e5f6de9 Move the version string into version.txt 2019-01-05 18:08:34 -08:00
Cameron Gutman 1f7bdbfbcb Fail signed release builds if unstaged changes exist 2019-01-05 17:25:40 -08:00
Cameron Gutman f2fdd048c7 Use stun.moonlight-stream.org for STUN 2019-01-04 20:16:27 -08:00
Cameron Gutman 5a2cfc15a6 Ensure WoL works properly on multi-homed hosts. Fixes #135 2019-01-04 20:05:31 -08:00
Cameron Gutman 11c7131875 Replace forgotten clamp to frameCountMax removed by e75dce2543 2019-01-03 18:49:18 -08:00
Cameron Gutman 34aacc90d7 Include version string in update tooltip 2019-01-03 18:00:54 -08:00
Cameron Gutman e75dce2543 Remove one-sample-per-callback write logic to fix crackling at 44.1 KHz. Fixes #152 2019-01-03 17:23:29 -08:00
Cameron Gutman e2774309fb Fix context menus on Qt 5.9 2019-01-02 19:49:06 -08:00
Cameron Gutman dfefdc93c5 Update macOS icns 2019-01-01 19:33:08 -08:00
Cameron Gutman d46ea28bba Merge pull request #151 from Jorys-Paulin/feature/icon-tweaks
Updated Moonlight icon
2019-01-01 19:32:21 -08:00
Cameron Gutman d35c5bcaba Print socket errors when sending WoL packets 2019-01-01 19:20:09 -08:00
Cameron Gutman 2b14856d7f Update common-c for strict remote bitrate logic 2019-01-01 19:03:52 -08:00
Jorys Paulin 3316fdb80e Updated Moonlight icon 2018-12-26 13:29:49 +01:00
Cameron Gutman c5d70c48c9 Fix QMap usage where insertion on read of missing value was not intended 2018-12-26 00:59:30 -08:00
Cameron Gutman 82230ef2f5 Version 0.8.0 2018-12-25 22:29:27 -08:00
Cameron Gutman dcfd3d3e48 Add a debug print for V-sync 2018-12-25 22:19:23 -08:00
Cameron Gutman cb1e2ac32e Avoid filling our client logs with QNetworkReplyHttpImplPrivate warnings 2018-12-25 21:54:20 -08:00
Cameron Gutman ec2c15946a Update audio buffering parameters based on local testing 2018-12-25 21:45:15 -08:00
Cameron Gutman 8be73142f8 Fix cert pinning on macOS 2018-12-25 21:15:59 -08:00
Cameron Gutman d1640e3bb8 Audio latency tweaks and fix for PulseAudio with A2DP 2018-12-25 17:54:18 -08:00
Cameron Gutman 8612e6726d Remove accidentally enabled debug prints 2018-12-25 14:05:55 -08:00
Cameron Gutman 3b4694e9f8 Add libraries required by libsoundio 2018-12-25 14:05:35 -08:00
Cameron Gutman 14cb2e1999 Remove latency drop logic and replace by single frame writes 2018-12-25 14:05:17 -08:00
Cameron Gutman cfabaf334e Add frame pacing toggle 2018-12-25 12:57:00 -08:00
Cameron Gutman c054536fab Count Pacer delay in frame stats 2018-12-25 12:09:45 -08:00
Cameron Gutman 35aac18b4e Improve bitrate slider label and add tooltip 2018-12-25 11:48:34 -08:00
Cameron Gutman de3928cb4d Reduce FPs on the unmapped gamepad dialog 2018-12-25 11:41:48 -08:00
Cameron Gutman 9bf612b800 Update common-c with bitrate fix 2018-12-24 20:10:37 -08:00
Cameron Gutman d9a8d67e3d Use a shared UID for all Moonlight clients 2018-12-22 21:04:44 -08:00
Cameron Gutman 99b0a56a6a Add additional cert pinning assert 2018-12-22 20:05:45 -08:00
Cameron Gutman 61d7aa0400 Require cert pinning for HTTPS 2018-12-22 19:55:28 -08:00
Cameron Gutman 1e98594972 Handle server cert change by pairing again 2018-12-21 19:17:32 -08:00
Cameron Gutman c6383f042c Pin server cert to host during pairing 2018-12-21 18:08:07 -08:00
Cameron Gutman b4d8e0e551 Update bug_report.md 2018-12-19 23:11:15 +04:00
555 changed files with 51108 additions and 9744 deletions
+20 -6
View File
@@ -1,8 +1,10 @@
---
name: Bug report
about: Create a report to help us address broken functionality
about: Ask for help on Discord before reporting a bug
---
**READ ME FIRST!**
This issue tracker is not the right place to ask for troubleshooting help if you're not able to connect or stream at all. For those requests, please use the #pc-help channel on our Discord server where there are many more people who can help (or direct you back here if it looks like a Moonlight bug after all). https://moonlight-stream.org/discord
**Describe the bug**
A clear and concise description of what the bug is.
@@ -13,19 +15,31 @@ Any special steps that are required for the bug to appear.
**Screenshots**
If applicable, add screenshots to help explain your problem. If the issue is related to video glitching or poor quality, please include screenshots.
**Affected games**
List the games you've tried that exhibit the issue. To see if the issue is game-specific, try streaming Steam Big Picture with Moonlight and see if the issue persists there.
**Other Moonlight clients**
- Does the issue occur when using Moonlight on iOS or Android?
**Moonlight settings (please complete the following information)**
- Have any settings been adjusted from defaults?
- If so, which settings have been changed?
- Does the problem still occur after reverting settings back to default?
**Client PC details (please complete the following information)**
- OS: [e.g. Windows 10 1803]
- Moonlight Version: [e.g. v0.2.0]
- OS: [e.g. Windows 10 1809]
- Moonlight Version: [e.g. v0.9.0]
**Logs (please attach)**
**Server PC details (please complete the following information)**
- OS: [e.g. Windows 10 1809]
- GeForce Experience version: [e.g. 3.16.0.140]
- Nvidia GPU driver: [e.g. 417.35]
**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.
- On macOS, `Moonlight-###.log` files can be found in `/tmp`. In Finder, press Cmd+Shift+G, then type `/tmp` to navigate there.
- On Linux, logs print to the terminal when running via `flatpak run com.moonlight_stream.Moonlight`
- On Linux with the Flatpak, logs print to the terminal when running with the command: `flatpak run com.moonlight_stream.Moonlight`
- On Linux with the Snap, logs print to the terminal when running with the command: `moonlight`
**Additional context**
Add any other context about the problem here.
Anything else you think may be relevant to the issue
+1
View File
@@ -0,0 +1 @@
blank_issues_enabled: false
+4
View File
@@ -0,0 +1,4 @@
issuesOpened: >
If this is a question about Moonlight or you need help troubleshooting a streaming problem, please use the help channels on our [Discord server](https://moonlight-stream.org/discord) instead of GitHub issues. There are many more people available on Discord to help you and answer your questions.<br /><br />
This issue tracker should only be used for specific bugs or feature requests.<br /><br />
Thank you, and happy streaming!
+3 -1
View File
@@ -2,4 +2,6 @@
**/.vs/
build/
build/
config.tests/*/.qmake.stash
config.tests/*/Makefile
-50
View File
@@ -1,50 +0,0 @@
language: cpp
git:
depth: 1
matrix:
include:
- os: osx
compiler: clang
- os: linux
sudo: required
dist: xenial
compiler: gcc
addons:
apt:
sources:
- sourceline: 'ppa:beineri/opt-qt596-xenial'
- sourceline: 'ppa:jonathonf/ffmpeg-4'
packages:
- qt59base
- qt59quickcontrols2
- qt59svg
- qt59multimedia
- libesd0-dev
- libgl-dev
- libegl1-mesa-dev
- libxkbcommon-dev
- wayland-protocols
- libopus-dev
- libavcodec-dev
- libavutil-dev
- libva-dev
- libvdpau-dev
install:
- '[ "$TRAVIS_OS_NAME" != osx ] || brew install qt5'
- '[ "$TRAVIS_OS_NAME" != osx ] || brew link --force qt5'
- if [[ "$TRAVIS_OS_NAME" = "linux" ]]; then export SDL2_VER=2.0.8 && wget https://www.libsdl.org/release/SDL2-$SDL2_VER.tar.gz && tar -xvf SDL2-$SDL2_VER.tar.gz && cd SDL2-$SDL2_VER && ./configure && make && sudo make install && cd ..; fi
before_script:
- '[ "$TRAVIS_OS_NAME" != "linux" ] || source /opt/qt59/bin/qt59-env.sh'
- qmake -v
- '[[ "$TRAVIS_OS_NAME" != linux || "$CXX" != clang++ ]] || export QMAKESPEC=linux-clang'
- '[[ "$TRAVIS_OS_NAME" != linux || "$CXX" != g++ ]] || export QMAKESPEC=linux-g++'
- '[ "$TRAVIS_OS_NAME" != osx ] || export QMAKESPEC=macx-clang'
script:
- qmake moonlight-qt.pro -spec $QMAKESPEC
- make debug
- make release
+1 -5
View File
@@ -3,11 +3,7 @@ QT -= core gui
TARGET = AntiHooking
TEMPLATE = lib
# Support debug and release builds from command line for CI
CONFIG += debug_and_release
# Ensure symbols are always generated
CONFIG += force_debug_info
include(../globaldefs.pri)
INCLUDEPATH += $$PWD/../libs/windows/include
contains(QT_ARCH, i386) {
+75 -4
View File
@@ -131,10 +131,81 @@ private:
static LoadLibraryExWFunc s_RealLoadLibraryExW;
static constexpr LPCWSTR k_BlacklistedDlls[] = {
// This DLL shipped with ASUS Sonic Radar 3 improperly handles
// D3D9 exclusive fullscreen in a way that causes CreateDeviceEx()
// to deadlock. https://github.com/moonlight-stream/moonlight-qt/issues/102
L"NahimicOSD.dll"
// These A-Volute DLLs shipped with various audio driver packages improperly handle
// D3D9 exclusive fullscreen in a way that causes CreateDeviceEx() to deadlock.
// https://github.com/moonlight-stream/moonlight-qt/issues/102
L"NahimicOSD.dll", // ASUS Sonic Radar 3
L"SSAudioOSD.dll", // SteelSeries headsets
L"SS2OSD.dll", // ASUS Sonic Studio 2
L"Nahimic2OSD.dll",
L"NahimicMSIOSD.dll",
L"nhAsusPhoebusOSD.dll" // ASUS Phoebus
// This DLL has been seen in several crash reports. Some Googling
// suggests it's highly unstable and causes issues in many games.
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
//
// These seem to cause a crash in PresentEx() in full-screen exclusive mode.
// This block will prevent Optimus from ever using the dGPU even if the user has requested it.
// https://github.com/moonlight-stream/moonlight-qt/issues/386
//
// d3d9!CSwapChain::BltToHybridPrimary+0x200:
// 00007ffa`23f37e58 488b01 mov rax,qword ptr [rcx] ds:00000000`00000038=????????????????
// 00 0000004e`496ff4e0 00007ffa`23f39e2c d3d9!CSwapChain::BltToHybridPrimary+0x200
// 01 0000004e`496ff880 00007ffa`23ee39ce d3d9!CSwapChain::FlipToSurface+0x15c
// 02 0000004e`496ff900 00007ffa`23f4dd75 d3d9!CSwapChain::PresentMain+0x3e13e
// 03 0000004e`496ffab0 00007ffa`23f4dccd d3d9!CBaseDevice::PresentMain+0x9d
// 04 0000004e`496ffb00 00007ff7`8e31016f d3d9!CBaseDevice::PresentEx+0xbd
// 05 0000004e`496ffb50 00007ff7`8e30df1e Moonlight!DXVA2Renderer::renderFrame+0x61f [C:\moonlight-qt\app\streaming\video\ffmpeg-renderers\dxva2.cpp @ 1035]
// 06 0000004e`496ffd50 00007ff7`8e30e46a Moonlight!Pacer::renderFrame+0x3e [C:\moonlight-qt\app\streaming\video\ffmpeg-renderers\pacer\pacer.cpp @ 265]
// 07 (Inline Function) --------`-------- Moonlight!Pacer::renderLastFrameAndUnlock+0x197 [C:\moonlight-qt\app\streaming\video\ffmpeg-renderers\pacer\pacer.cpp @ 156]
// 08 0000004e`496ffda0 00007ffa`14476978 Moonlight!Pacer::renderThread+0x1ca [C:\moonlight-qt\app\streaming\video\ffmpeg-renderers\pacer\pacer.cpp @ 88]
// 09 0000004e`496ffde0 00007ffa`14476ee2 SDL2!SDL_RunThread+0x38 [C:\Users\camer\SDL\src\thread\SDL_thread.c @ 276]
// 0a 0000004e`496ffe10 00007ffa`2aae0e82 SDL2!RunThread+0x12 [C:\Users\camer\SDL\src\thread\windows\SDL_systhread.c @ 83]
// 0b 0000004e`496ffe40 00007ffa`2d627bd4 ucrtbase!thread_start<unsigned int (__cdecl*)(void *),1>+0x42
// 0c 0000004e`496ffe70 00007ffa`2da4ce51 kernel32!BaseThreadInitThunk+0x14
// 0d 0000004e`496ffea0 00000000`00000000 ntdll!RtlUserThreadStart+0x21
//
L"nvinit.dll",
L"nvinitx.dll",
// In some unknown circumstances, RTSS tries to hook in the middle of an instruction, leaving garbage
// code inside d3d9.dll that causes a crash when executed:
//
// 0:000> u
// d3d9!D3D9GetCurrentOwnershipMode+0x5d:
// 00007ff8`95b95861 9b wait
// 00007ff8`95b95862 a7 cmps dword ptr [rsi],dword ptr [rdi] <--- crash happens here
// 00007ff8`95b95863 ff ???
// 00007ff8`95b95864 bfe8ca8a00 mov edi,8ACAE8h
// 00007ff8`95b95869 00eb add bl,ch
// 00007ff8`95b9586b f1 ???
// 00007ff8`95b9586c b808000000 mov eax,8
// 00007ff8`95b95871 ebe6 jmp d3d9!D3D9GetCurrentOwnershipMode+0x55 (00007ff8`95b95859)
//
// Disassembling starting at the exact address of the attempted hook yields the intended jmp instruction
//
// 0:000> u d3d9!D3D9GetCurrentOwnershipMode+0x5c:
// 00007ff8`95b95860 e99ba7ffbf jmp 00007ff8`55b90000
//
// Since the RTSS OSD doesn't even work with DXVA2, we'll just block the hooks entirely.
L"RTSSHooks.dll",
L"RTSSHooks64.dll",
};
};
+35 -20
View File
@@ -4,53 +4,68 @@
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://discord.gg/6ERtzFY).
You can follow development on our [Discord server](https://moonlight-stream.org/discord).
[![Windows AppVeyor Status](https://ci.appveyor.com/api/projects/status/glj5cxqwy2w3bglv/branch/master?svg=true)](https://ci.appveyor.com/project/cgutman/moonlight-qt/branch/master)
[![Mac and Linux Travis CI Status](https://travis-ci.org/moonlight-stream/moonlight-qt.svg?branch=master)](https://travis-ci.org/moonlight-stream/moonlight-qt)
[![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)
## Features
- Hardware accelerated video decoding on Windows, Mac, and Linux
- 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
- 5.1 surround sound audio
- 7.1 surround sound audio support
- Support for both pointer capture (for games) and direct mouse control (for remote desktop)
- Direct touchscreen mouse control
- HEVC support for better image quality at reduced bandwidth
- Keyboard and mouse support
- Gamepad support with SDL gamepad mappings
- Gamepad support with force feedback for up to 4 players
## Downloads
- [Windows and macOS](https://github.com/moonlight-stream/moonlight-qt/releases)
- [Linux](https://flathub.org/apps/details/com.moonlight_stream.Moonlight)
- [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](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)
## Building
### General Build Requirements
* Qt 5.9 SDK or later
### Windows-specific Requirements
### Windows Build Requirements
* Qt 5.12.4 SDK or later
* Windows 7 or later
* Visual Studio 2015 or later
* [Visual Studio](https://visualstudio.microsoft.com/downloads/) 2017 (Community edition is fine)
* Select MSVC Desktop toolchain during Qt installation
* 7-Zip (only if building installers for non-development PCs)
* WiX Toolset v3.11 or later (only if building installers for non-development PCs)
* [DirectX SDK](https://www.microsoft.com/en-us/download/details.aspx?id=6812)
* [7-Zip](https://www.7-zip.org/) (only if building installers for non-development PCs)
* [WiX Toolset](http://wixtoolset.org/releases/) v3.11 or later (only if building installers for non-development PCs)
### Mac-specific Requirements
* macOS El Capitan (10.11) or later
* Xcode with High Sierra (10.13) SDK (Mojave SDK not yet supported until Qt 5.12 later this year)
### macOS Build Requirements
* Qt 5.14 SDK or later
* macOS High Sierra (10.13) or later
* Xcode 11
* [create-dmg](https://github.com/sindresorhus/create-dmg) (only if building DMGs for use on non-development Macs)
### Linux-specific Requirements
### Linux/Unix Build Requirements
* Qt 5.9 SDK or later
* GCC or Clang
* Install your distro equivalents of: `openssl-devel qt5-devel SDL2-devel ffmpeg-devel qt5-qtquickcontrols2-devel libva-devel libvdpau-devel opus-devel`
* Install your distro equivalents of: `openssl-devel qt5-devel SDL2-devel ffmpeg-devel qt5-qtquickcontrols2-devel libva-devel libvdpau-devel opus-devel pulseaudio-libs-devel alsa-lib-devel SDL2_ttf-devel`
* FFmpeg 4.0 is required to build. If your distro doesn't package FFmpeg 4.0, you can build and install it from source on http://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
### Build Setup Steps
1. Install the latest Qt SDK (and optionally, the Qt Creator IDE) from https://www.qt.io/download
* You may also use Homebrew on macOS or your Linux distro's package manager for the Qt SDK as long as the packages are Qt 5.9 or later.
* 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.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\generate-installers.bat`. Execute this script 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, run `qmake moonlight-qt.pro` then `make debug` or `make release`
## Contribute
1. Fork us
+2 -2
View File
@@ -23,9 +23,9 @@
<key>NSSupportsAutomaticGraphicsSwitching</key>
<true/>
<key>CFBundleVersion</key>
<string>0.7.0</string>
<string>VERSION</string>
<key>CFBundleShortVersionString</key>
<string>0.7.0</string>
<string>VERSION</string>
<key>CFBundleDisplayName</key>
<string>Moonlight</string>
</dict>
BIN
View File
Binary file not shown.
+141 -59
View File
@@ -8,11 +8,7 @@ unix:!macx {
TARGET = Moonlight
}
# Support debug and release builds from command line for CI
CONFIG += debug_and_release
# Ensure symbols are always generated
CONFIG += force_debug_info
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
@@ -37,33 +33,31 @@ DEFINES += QT_DEPRECATED_WARNINGS
DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0
win32 {
INCLUDEPATH += $$PWD/../libs/windows/include
INCLUDEPATH += \
$$PWD/../libs/windows/include \
$$(DXSDK_DIR)/Include
contains(QT_ARCH, i386) {
LIBS += -L$$PWD/../libs/windows/lib/x86
LIBS += -L$$(DXSDK_DIR)/Lib/x86
}
contains(QT_ARCH, x86_64) {
LIBS += -L$$PWD/../libs/windows/lib/x64
LIBS += -L$$(DXSDK_DIR)/Lib/x64
}
LIBS += ws2_32.lib winmm.lib dxva2.lib ole32.lib gdi32.lib user32.lib d3d9.lib dwmapi.lib dbghelp.lib
LIBS += ws2_32.lib winmm.lib dxva2.lib ole32.lib gdi32.lib user32.lib d3d9.lib dwmapi.lib dbghelp.lib qwave.lib
}
macx {
INCLUDEPATH += $$PWD/../libs/mac/include $$PWD/../libs/mac/Frameworks/SDL2.framework/Versions/A/Headers
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:!macx {
CONFIG += link_pkgconfig soundio
PKGCONFIG += openssl sdl2 opus
# For libsoundio
packagesExist(libpulse) {
PKGCONFIG += libpulse
}
packagesExist(alsa) {
PKGCONFIG += alsa
}
CONFIG += link_pkgconfig
PKGCONFIG += openssl sdl2 SDL2_ttf opus
packagesExist(libavcodec) {
PKGCONFIG += libavcodec libavutil
@@ -76,29 +70,56 @@ unix:!macx {
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(wayland-client) {
DEFINES += HAS_WAYLAND
PKGCONFIG += wayland-client
}
packagesExist(x11) {
DEFINES += HAS_X11
PKGCONFIG += x11
}
}
win32 {
LIBS += -llibssl -llibcrypto -lSDL2 -lavcodec -lavutil -lopus
CONFIG += ffmpeg soundio
LIBS += -llibssl -llibcrypto -lSDL2 -lSDL2_ttf -lavcodec -lavutil -lopus -ld3dx9
CONFIG += ffmpeg
}
win32:!winrt {
CONFIG += soundio discord-rpc
}
macx {
LIBS += -lssl -lcrypto -lavcodec.58 -lavutil.56 -lopus -framework SDL2
LIBS += -lobjc -framework VideoToolbox -framework AVFoundation -framework CoreVideo -framework CoreGraphics -framework CoreMedia -framework AppKit
LIBS += -lssl -lcrypto -lavcodec.58 -lavutil.56 -lopus -framework SDL2 -framework SDL2_ttf
LIBS += -lobjc -framework VideoToolbox -framework AVFoundation -framework CoreVideo -framework CoreGraphics -framework CoreMedia -framework AppKit -framework Metal
# For libsoundio
LIBS += -framework CoreAudio -framework AudioUnit
CONFIG += ffmpeg soundio
CONFIG += ffmpeg soundio discord-rpc
}
SOURCES += \
backend/nvapp.cpp \
main.cpp \
backend/computerseeker.cpp \
backend/identitymanager.cpp \
@@ -107,11 +128,17 @@ SOURCES += \
backend/nvpairingmanager.cpp \
backend/computermanager.cpp \
backend/boxartmanager.cpp \
backend/richpresencemanager.cpp \
cli/commandlineparser.cpp \
cli/quitstream.cpp \
cli/startstream.cpp \
settings/streamingpreferences.cpp \
streaming/input.cpp \
streaming/input/abstouch.cpp \
streaming/input/gamepad.cpp \
streaming/input/input.cpp \
streaming/input/keyboard.cpp \
streaming/input/mouse.cpp \
streaming/input/reltouch.cpp \
streaming/session.cpp \
streaming/audio/audio.cpp \
streaming/audio/renderers/sdlaud.cpp \
@@ -121,9 +148,13 @@ SOURCES += \
backend/autoupdatechecker.cpp \
path.cpp \
settings/mappingmanager.cpp \
gui/sdlgamepadkeynavigation.cpp
gui/sdlgamepadkeynavigation.cpp \
streaming/video/overlaymanager.cpp \
backend/systemproperties.cpp \
wm.cpp
HEADERS += \
backend/nvapp.h \
utils.h \
backend/computerseeker.h \
backend/identitymanager.h \
@@ -132,11 +163,12 @@ HEADERS += \
backend/nvpairingmanager.h \
backend/computermanager.h \
backend/boxartmanager.h \
backend/richpresencemanager.h \
cli/commandlineparser.h \
cli/quitstream.h \
cli/startstream.h \
settings/streamingpreferences.h \
streaming/input.h \
streaming/input/input.h \
streaming/session.h \
streaming/audio/renderers/renderer.h \
streaming/audio/renderers/sdl.h \
@@ -147,7 +179,9 @@ HEADERS += \
backend/autoupdatechecker.h \
path.h \
settings/mappingmanager.h \
gui/sdlgamepadkeynavigation.h
gui/sdlgamepadkeynavigation.h \
streaming/video/overlaymanager.h \
backend/systemproperties.h
# Platform-specific renderers and decoders
ffmpeg {
@@ -157,13 +191,15 @@ ffmpeg {
SOURCES += \
streaming/video/ffmpeg.cpp \
streaming/video/ffmpeg-renderers/sdlvid.cpp \
streaming/video/ffmpeg-renderers/cuda.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/sdlvid.h \
streaming/video/ffmpeg-renderers/cuda.h \
streaming/video/ffmpeg-renderers/pacer/pacer.h \
streaming/video/ffmpeg-renderers/pacer/nullthreadedvsyncsource.h
}
@@ -187,6 +223,12 @@ libva-wayland {
PKGCONFIG += libva-wayland
DEFINES += HAVE_LIBVA_WAYLAND
}
libva-wayland {
message(VAAPI DRM support enabled)
PKGCONFIG += libva-drm
DEFINES += HAVE_LIBVA_DRM
}
libvdpau {
message(VDPAU renderer selected)
@@ -194,16 +236,44 @@ libvdpau {
SOURCES += streaming/video/ffmpeg-renderers/vdpau.cpp
HEADERS += streaming/video/ffmpeg-renderers/vdpau.h
}
config_SLVideo {
message(SLVideo decoder/renderer selected)
mmal {
message(MMAL renderer selected)
DEFINES += HAVE_SLVIDEO
LIBS += -lSLVideo
SOURCES += streaming/video/sl.cpp
HEADERS += streaming/video/sl.h
DEFINES += HAVE_MMAL
SOURCES += streaming/video/ffmpeg-renderers/mmal.cpp
HEADERS += streaming/video/ffmpeg-renderers/mmal.h
}
win32 {
libdrm {
message(DRM renderer selected)
DEFINES += HAVE_DRM
SOURCES += streaming/video/ffmpeg-renderers/drm.cpp
HEADERS += streaming/video/ffmpeg-renderers/drm.h
}
config_EGL {
message(EGL renderer selected)
CONFIG += egl
DEFINES += HAVE_EGL
SOURCES += \
streaming/video/ffmpeg-renderers/eglvid.cpp \
streaming/video/ffmpeg-renderers/egl_extensions.cpp
HEADERS += streaming/video/ffmpeg-renderers/eglvid.h
}
config_SL {
message(Steam Link build configuration selected)
DEFINES += STEAM_LINK HAVE_SLVIDEO HAVE_SLAUDIO
LIBS += -lSLVideo -lSLAudio
SOURCES += \
streaming/video/slvid.cpp \
streaming/audio/renderers/slaud.cpp
HEADERS += \
streaming/video/slvid.h \
streaming/audio/renderers/slaud.h
}
win32:!winrt {
message(DXVA2 renderer selected)
SOURCES += \
@@ -218,12 +288,10 @@ macx {
message(VideoToolbox renderer selected)
SOURCES += \
streaming/video/ffmpeg-renderers/vt.mm \
streaming/video/ffmpeg-renderers/pacer/displaylinkvsyncsource.mm
streaming/video/ffmpeg-renderers/vt.mm
HEADERS += \
streaming/video/ffmpeg-renderers/vt.h \
streaming/video/ffmpeg-renderers/pacer/displaylinkvsyncsource.h
streaming/video/ffmpeg-renderers/vt.h
}
soundio {
message(libsoundio audio renderer selected)
@@ -232,6 +300,12 @@ soundio {
SOURCES += streaming/audio/renderers/soundioaudiorenderer.cpp
HEADERS += streaming/audio/renderers/soundioaudiorenderer.h
}
discord-rpc {
message(Discord integration enabled)
LIBS += -ldiscord-rpc
DEFINES += HAVE_DISCORD
}
RESOURCES += \
resources.qrc \
@@ -257,12 +331,14 @@ else:unix: LIBS += -L$$OUT_PWD/../qmdnsengine/ -lqmdnsengine
INCLUDEPATH += $$PWD/../qmdnsengine/qmdnsengine/src/include $$PWD/../qmdnsengine
DEPENDPATH += $$PWD/../qmdnsengine/qmdnsengine/src/include $$PWD/../qmdnsengine
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
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
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
@@ -271,11 +347,13 @@ else:unix: LIBS += -L$$OUT_PWD/../h264bitstream/ -lh264bitstream
INCLUDEPATH += $$PWD/../h264bitstream/h264bitstream
DEPENDPATH += $$PWD/../h264bitstream/h264bitstream
win32:CONFIG(release, debug|release): LIBS += -L$$OUT_PWD/../AntiHooking/release/ -lAntiHooking
else:win32:CONFIG(debug, debug|release): LIBS += -L$$OUT_PWD/../AntiHooking/debug/ -lAntiHooking
!winrt {
win32:CONFIG(release, debug|release): LIBS += -L$$OUT_PWD/../AntiHooking/release/ -lAntiHooking
else:win32:CONFIG(debug, debug|release): LIBS += -L$$OUT_PWD/../AntiHooking/debug/ -lAntiHooking
INCLUDEPATH += $$PWD/../AntiHooking
DEPENDPATH += $$PWD/../AntiHooking
INCLUDEPATH += $$PWD/../AntiHooking
DEPENDPATH += $$PWD/../AntiHooking
}
unix:!macx: {
isEmpty(PREFIX) {
@@ -299,10 +377,7 @@ unix:!macx: {
appstream.files = deploy/linux/com.moonlight_stream.Moonlight.appdata.xml
appstream.path = $$PREFIX/$$DATADIR/metainfo/
appdata.files = SDL_GameControllerDB/gamecontrollerdb.txt
appdata.path = "$$PREFIX/$$DATADIR/Moonlight Game Streaming Project/Moonlight/"
INSTALLS += target appdata desktop icons appstream
INSTALLS += target desktop icons appstream
}
win32 {
RC_ICONS = moonlight.ico
@@ -314,18 +389,25 @@ win32 {
QMAKE_LFLAGS += /MANIFEST:embed /MANIFESTINPUT:$${PWD}/Moonlight.exe.manifest
}
macx {
QMAKE_INFO_PLIST = $$PWD/Info.plist
# Create Info.plist in object dir with the correct version string
system(cp $$PWD/Info.plist $$OUT_PWD/Info.plist)
system(sed -i -e 's/VERSION/$$cat(version.txt)/g' $$OUT_PWD/Info.plist)
APP_BUNDLE_RESOURCES.files = moonlight.icns SDL_GameControllerDB/gamecontrollerdb.txt
QMAKE_INFO_PLIST = $$OUT_PWD/Info.plist
APP_BUNDLE_RESOURCES.files = moonlight.icns
APP_BUNDLE_RESOURCES.path = Contents/Resources
APP_BUNDLE_FRAMEWORKS.files = $$files(../libs/mac/Frameworks/*.framework, true)
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_RESOURCES APP_BUNDLE_FRAMEWORKS
APP_BUNDLE_PLIST.files = $$OUT_PWD/Info.plist
APP_BUNDLE_PLIST.path = Contents
QMAKE_BUNDLE_DATA += APP_BUNDLE_RESOURCES APP_BUNDLE_FRAMEWORKS APP_BUNDLE_PLIST
QMAKE_RPATHDIR += @executable_path/../Frameworks
}
VERSION = 0.7.0
DEFINES += VERSION_STR=\\\"0.7.0\\\"
VERSION = "$$cat(version.txt)"
DEFINES += VERSION_STR=\\\"$$cat(version.txt)\\\"
+24 -4
View File
@@ -28,7 +28,15 @@ AutoUpdateChecker::AutoUpdateChecker(QObject *parent) :
void AutoUpdateChecker::start()
{
#if defined(Q_OS_WIN32) || defined(Q_OS_DARWIN) // Only run update checker on platforms without auto-update
#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);
QT_WARNING_POP
#endif
// We'll get a callback when this is finished
QUrl url("https://moonlight-stream.org/updates/qt.json");
m_Nam.get(QNetworkRequest(url));
@@ -43,6 +51,17 @@ void AutoUpdateChecker::parseStringToVersionQuad(QString& string, QVector<int>&
}
}
QString AutoUpdateChecker::getPlatform()
{
#if defined(STEAM_LINK)
return QStringLiteral("steamlink");
#elif defined(APP_IMAGE)
return QStringLiteral("appimage");
#else
return QSysInfo::productType();
#endif
}
void AutoUpdateChecker::handleUpdateCheckRequestFinished(QNetworkReply* reply)
{
Q_ASSERT(reply->isFinished());
@@ -88,7 +107,7 @@ void AutoUpdateChecker::handleUpdateCheckRequestFinished(QNetworkReply* reply)
}
if (updateObj["arch"] == QSysInfo::buildCpuArchitecture() &&
updateObj["platform"] == QSysInfo::productType()) {
updateObj["platform"] == getPlatform()) {
qDebug() << "Found update manifest match for current platform";
QString latestVersion = updateObj["version"].toString();
@@ -116,7 +135,8 @@ void AutoUpdateChecker::handleUpdateCheckRequestFinished(QNetworkReply* reply)
if (currentVer < latestVer) {
qDebug() << "Update available";
emit onUpdateAvailable(updateObj["browser_url"].toString());
emit onUpdateAvailable(updateObj["version"].toString(),
updateObj["browser_url"].toString());
return;
}
else if (currentVer > latestVer) {
@@ -136,7 +156,7 @@ void AutoUpdateChecker::handleUpdateCheckRequestFinished(QNetworkReply* reply)
}
qWarning() << "No entry in update manifest found for current platform: "
<< QSysInfo::buildCpuArchitecture() << QSysInfo::productType();
<< QSysInfo::buildCpuArchitecture() << getPlatform();
}
else {
qWarning() << "Update checking failed with error: " << reply->error();
+3 -1
View File
@@ -12,7 +12,7 @@ public:
Q_INVOKABLE void start();
signals:
void onUpdateAvailable(QString url);
void onUpdateAvailable(QString newVersion, QString url);
private slots:
void handleUpdateCheckRequestFinished(QNetworkReply* reply);
@@ -20,6 +20,8 @@ private slots:
private:
void parseStringToVersionQuad(QString& string, QVector<int>& version);
QString getPlatform();
QVector<int> m_CurrentVersionQuad;
QNetworkAccessManager m_Nam;
};
+21 -8
View File
@@ -71,10 +71,10 @@ private:
QUrl BoxArtManager::loadBoxArt(NvComputer* computer, NvApp& app)
{
// Try to open the cached file
QString cacheFilePath = getFilePathForBoxArt(computer, app.id);
if (QFile::exists(cacheFilePath)) {
return QUrl::fromLocalFile(cacheFilePath);
// Try to open the cached file if it exists and contains data
QFile cacheFile(getFilePathForBoxArt(computer, app.id));
if (cacheFile.exists() && cacheFile.size() > 0) {
return QUrl::fromLocalFile(cacheFile.fileName());
}
// If we get here, we need to fetch asynchronously.
@@ -87,17 +87,26 @@ QUrl BoxArtManager::loadBoxArt(NvComputer* computer, NvApp& app)
return QUrl("qrc:/res/no_app_image.png");
}
void BoxArtManager::deleteBoxArt(NvComputer* computer)
{
QDir dir(Path::getBoxArtCacheDir());
// Delete everything in this computer's box art directory
if (dir.cd(computer->uuid)) {
dir.removeRecursively();
}
}
void BoxArtManager::handleBoxArtLoadComplete(NvComputer* computer, NvApp app, QUrl image)
{
if (image.isEmpty()) {
image = QUrl("qrc:/res/no_app_image.png");
if (!image.isEmpty()) {
emit boxArtLoadComplete(computer, app, image);
}
emit boxArtLoadComplete(computer, app, image);
}
QUrl BoxArtManager::loadBoxArtFromNetwork(NvComputer* computer, int appId)
{
NvHTTP http(computer->activeAddress);
NvHTTP http(computer->activeAddress, computer->serverCert);
QString cachePath = getFilePathForBoxArt(computer, appId);
QImage image;
@@ -110,6 +119,10 @@ QUrl BoxArtManager::loadBoxArtFromNetwork(NvComputer* computer, int appId)
if (image.save(cachePath)) {
return QUrl::fromLocalFile(cachePath);
}
else {
// A failed save() may leave a zero byte file. Make sure that's removed.
QFile(cachePath).remove();
}
}
return QUrl();
+4
View File
@@ -18,6 +18,10 @@ public:
QUrl
loadBoxArt(NvComputer* computer, NvApp& app);
static
void
deleteBoxArt(NvComputer* computer);
signals:
void
boxArtLoadComplete(NvComputer* computer, NvApp app, QUrl image);
+307 -146
View File
@@ -1,4 +1,5 @@
#include "computermanager.h"
#include "boxartmanager.h"
#include "nvhttp.h"
#include "settings/streamingpreferences.h"
@@ -7,6 +8,7 @@
#include <QThread>
#include <QThreadPool>
#include <QCoreApplication>
#define SER_HOSTS "hosts"
@@ -27,16 +29,16 @@ public:
private:
bool tryPollComputer(QString address, bool& changed)
{
NvHTTP http(address);
NvHTTP http(address, m_Computer->serverCert);
QString serverInfo;
try {
serverInfo = http.getServerInfo(NvHTTP::NvLogLevel::NONE);
serverInfo = http.getServerInfo(NvHTTP::NvLogLevel::NVLL_NONE, true);
} catch (...) {
return false;
}
NvComputer newState(address, serverInfo);
NvComputer newState(address, serverInfo, QSslCertificate());
// Ensure the machine that responded is the one we intended to contact
if (m_Computer->uuid != newState.uuid) {
@@ -52,7 +54,7 @@ private:
{
Q_ASSERT(m_Computer->activeAddress != nullptr);
NvHTTP http(m_Computer->activeAddress);
NvHTTP http(m_Computer->activeAddress, m_Computer->serverCert);
QVector<NvApp> appList;
@@ -66,12 +68,7 @@ private:
}
QWriteLocker lock(&m_Computer->lock);
if (m_Computer->appList != appList) {
m_Computer->appList = appList;
m_Computer->sortAppList();
changed = true;
}
changed = m_Computer->updateAppList(appList);
return true;
}
@@ -83,7 +80,7 @@ private:
bool stateChanged = false;
bool online = false;
bool wasOnline = m_Computer->state == NvComputer::CS_ONLINE;
for (int i = 0; i < TRIES_BEFORE_OFFLINING && !online; i++) {
for (int i = 0; i < (wasOnline ? TRIES_BEFORE_OFFLINING : 1) && !online; i++) {
for (auto& address : m_Computer->uniqueAddresses()) {
if (isInterruptionRequested()) {
return;
@@ -130,8 +127,12 @@ private:
emit computerStateChanged(m_Computer);
}
// Wait a bit to poll again
QThread::sleep(3);
// Wait a bit to poll again, but do it in 100 ms chunks
// so we can be interrupted reasonably quickly.
// FIXME: QWaitCondition would be better.
for (int i = 0; i < 30 && !isInterruptionRequested(); i++) {
QThread::msleep(100);
}
}
}
@@ -157,6 +158,13 @@ ComputerManager::ComputerManager(QObject *parent)
m_KnownHosts[computer->uuid] = computer;
}
settings.endArray();
// To quit in a timely manner, we must block additional requests
// 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(), SIGNAL(aboutToQuit()), this, SLOT(handleAboutToQuit()));
}
ComputerManager::~ComputerManager()
@@ -174,38 +182,19 @@ ComputerManager::~ComputerManager()
delete m_MdnsBrowser;
m_MdnsBrowser = nullptr;
{
QMutableMapIterator<QString, QThread*> i(m_PollThreads);
// Interrupt all polling threads
while (i.hasNext()) {
i.next();
i.value()->requestInterruption();
}
// Wait for all threads to terminate before destroying
// the NvComputer objects.
i.toFront();
while (i.hasNext()) {
i.next();
QThread* thread = i.value();
thread->wait();
delete thread;
i.remove();
}
// Interrupt polling
for (ComputerPollingEntry* entry : m_PollEntries) {
entry->interrupt();
}
{
QMutableMapIterator<QString, NvComputer*> i(m_KnownHosts);
// Delete all polling entries (and associated threads)
for (ComputerPollingEntry* entry : m_PollEntries) {
delete entry;
}
// Destroy all NvComputer objects
while (i.hasNext()) {
i.next();
delete i.value();
i.remove();
}
// Destroy all NvComputer objects now that polling is halted
for (NvComputer* computer : m_KnownHosts) {
delete computer;
}
}
@@ -216,13 +205,50 @@ void ComputerManager::saveHosts()
settings.remove(SER_HOSTS);
settings.beginWriteArray(SER_HOSTS);
for (int i = 0; i < m_KnownHosts.count(); i++) {
settings.setArrayIndex(i);
m_KnownHosts[m_KnownHosts.keys()[i]]->serialize(settings);
int i = 0;
for (const NvComputer* computer : m_KnownHosts) {
settings.setArrayIndex(i++);
computer->serialize(settings);
}
settings.endArray();
}
QHostAddress ComputerManager::getBestGlobalAddressV6(QVector<QHostAddress> &addresses)
{
for (const QHostAddress& address : addresses) {
if (address.protocol() == QAbstractSocket::IPv6Protocol) {
if (address.isInSubnet(QHostAddress("fe80::"), 10)) {
// Link-local
continue;
}
if (address.isInSubnet(QHostAddress("fec0::"), 10)) {
qInfo() << "Ignoring site-local address:" << address;
continue;
}
if (address.isInSubnet(QHostAddress("fc00::"), 7)) {
qInfo() << "Ignoring ULA:" << address;
continue;
}
if (address.isInSubnet(QHostAddress("2002::"), 16)) {
qInfo() << "Ignoring 6to4 address:" << address;
continue;
}
if (address.isInSubnet(QHostAddress("2001::"), 32)) {
qInfo() << "Ignoring Teredo address:" << address;
continue;
}
return address;
}
}
return QHostAddress();
}
void ComputerManager::startPolling()
{
QWriteLocker lock(&m_Lock);
@@ -240,9 +266,9 @@ void ComputerManager::startPolling()
this, [this](const QMdnsEngine::Service& service) {
qInfo() << "Discovered mDNS host:" << service.hostname();
MdnsPendingComputer* pendingComputer = new MdnsPendingComputer(&m_MdnsServer, &m_MdnsCache, service);
connect(pendingComputer, SIGNAL(resolvedv4(MdnsPendingComputer*,QHostAddress)),
this, SLOT(handleMdnsServiceResolved(MdnsPendingComputer*,QHostAddress)));
MdnsPendingComputer* pendingComputer = new MdnsPendingComputer(&m_MdnsServer, service);
connect(pendingComputer, &MdnsPendingComputer::resolvedHost,
this, &ComputerManager::handleMdnsServiceResolved);
m_PendingResolution.append(pendingComputer);
});
}
@@ -265,24 +291,58 @@ void ComputerManager::startPollingComputer(NvComputer* computer)
return;
}
if (m_PollThreads.contains(computer->uuid)) {
Q_ASSERT(m_PollThreads[computer->uuid]->isRunning());
return;
ComputerPollingEntry* pollingEntry;
if (!m_PollEntries.contains(computer->uuid)) {
pollingEntry = m_PollEntries[computer->uuid] = new ComputerPollingEntry();
}
else {
pollingEntry = m_PollEntries[computer->uuid];
}
PcMonitorThread* thread = new PcMonitorThread(computer);
connect(thread, SIGNAL(computerStateChanged(NvComputer*)),
this, SLOT(handleComputerStateChanged(NvComputer*)));
m_PollThreads[computer->uuid] = thread;
thread->start();
if (!pollingEntry->isActive()) {
PcMonitorThread* thread = new PcMonitorThread(computer);
connect(thread, SIGNAL(computerStateChanged(NvComputer*)),
this, SLOT(handleComputerStateChanged(NvComputer*)));
pollingEntry->setActiveThread(thread);
thread->start();
}
}
void ComputerManager::handleMdnsServiceResolved(MdnsPendingComputer* computer,
const QHostAddress& address)
QVector<QHostAddress>& addresses)
{
qInfo() << "Resolved" << computer->hostname() << "to" << address.toString();
QHostAddress v6Global = getBestGlobalAddressV6(addresses);
bool added = false;
addNewHost(address.toString(), true);
// Add the host using the IPv4 address
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(address.toString(), true, v6Global);
added = true;
break;
}
}
if (!added) {
// If we get here, there wasn't an IPv4 address so we'll do it v6-only
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(address.toString(), true, v6Global);
added = true;
break;
}
}
}
}
m_PendingResolution.removeOne(computer);
computer->deleteLater();
@@ -317,34 +377,26 @@ public:
void run()
{
QThread* pollingThread;
ComputerPollingEntry* pollingEntry;
// Only do the minimum amount of work while holding the writer lock.
// We must release it before calling saveHosts().
{
QWriteLocker lock(&m_ComputerManager->m_Lock);
pollingThread = m_ComputerManager->m_PollThreads[m_Computer->uuid];
pollingEntry = m_ComputerManager->m_PollEntries.take(m_Computer->uuid);
m_ComputerManager->m_PollThreads.remove(m_Computer->uuid);
m_ComputerManager->m_KnownHosts.remove(m_Computer->uuid);
}
// Persist the new host list
m_ComputerManager->saveHosts();
// Delete the polling thread
if (pollingThread != nullptr) {
pollingThread->requestInterruption();
// Delete the polling entry first. This will stop all polling threads too.
delete pollingEntry;
// We must wait here because we're going to delete computer
// and we can't do that out from underneath the poller.
pollingThread->wait();
// The thread is safe to delete now
Q_ASSERT(pollingThread->isFinished());
delete pollingThread;
}
// Delete cached box art
BoxArtManager::deleteBoxArt(m_Computer);
// Finally, delete the computer itself. This must be done
// last because the polling thread might be using it.
@@ -363,6 +415,39 @@ void ComputerManager::deleteHost(NvComputer* computer)
QThreadPool::globalInstance()->start(new DeferredHostDeletionTask(this, computer));
}
void ComputerManager::renameHost(NvComputer* computer, QString name)
{
{
QWriteLocker(&computer->lock);
computer->name = name;
computer->hasCustomName = true;
}
// Notify the UI of the state change
handleComputerStateChanged(computer);
}
void ComputerManager::clientSideAttributeUpdated(NvComputer* computer)
{
// Persist the change
saveHosts();
// Notify the UI of the state change
handleComputerStateChanged(computer);
}
void ComputerManager::handleAboutToQuit()
{
QWriteLocker lock(&m_Lock);
// Interrupt polling threads immediately, so they
// avoid making additional requests while quitting
for (ComputerPollingEntry* entry : m_PollEntries) {
entry->interrupt();
}
}
class PendingPairingTask : public QObject, public QRunnable
{
Q_OBJECT
@@ -385,7 +470,7 @@ private:
NvPairingManager pairingManager(m_Computer->activeAddress);
try {
NvPairingManager::PairState result = pairingManager.pair(m_Computer->appVersion, m_Pin);
NvPairingManager::PairState result = pairingManager.pair(m_Computer->appVersion, m_Pin, m_Computer->serverCert);
switch (result)
{
case NvPairingManager::PairState::PIN_WRONG:
@@ -402,7 +487,7 @@ private:
break;
}
} catch (const GfeHttpResponseException& e) {
emit pairingCompleted(m_Computer, e.toQString());
emit pairingCompleted(m_Computer, "GeForce Experience returned error: " + e.toQString());
} catch (const QtNetworkReplyException& e) {
emit pairingCompleted(m_Computer, e.toQString());
}
@@ -438,7 +523,7 @@ signals:
private:
void run()
{
NvHTTP http(m_Computer->activeAddress);
NvHTTP http(m_Computer->activeAddress, m_Computer->serverCert);
try {
if (m_Computer->currentGameId != 0) {
@@ -499,20 +584,8 @@ void ComputerManager::stopPollingAsync()
m_MdnsBrowser = nullptr;
// Interrupt all threads, but don't wait for them to terminate
QMutableMapIterator<QString, QThread*> i(m_PollThreads);
while (i.hasNext()) {
i.next();
QThread* thread = i.value();
// Let this thread delete itself when it's finished
connect(thread, SIGNAL(finished()),
thread, SLOT(deleteLater()));
// The threads will delete themselves when they terminate,
// but we remove them from the polling threads map here.
i.value()->requestInterruption();
i.remove();
for (ComputerPollingEntry* entry : m_PollEntries) {
entry->interrupt();
}
}
@@ -521,9 +594,10 @@ class PendingAddTask : public QObject, public QRunnable
Q_OBJECT
public:
PendingAddTask(ComputerManager* computerManager, QString address, bool mdns)
PendingAddTask(ComputerManager* computerManager, QString address, QHostAddress mdnsIpv6Address, bool mdns)
: m_ComputerManager(computerManager),
m_Address(address),
m_MdnsIpv6Address(mdnsIpv6Address),
m_Mdns(mdns)
{
connect(this, &PendingAddTask::computerAddCompleted,
@@ -533,17 +607,13 @@ public:
}
signals:
void computerAddCompleted(QVariant success);
void computerAddCompleted(QVariant success, QVariant detectedPortBlocking);
void computerStateChanged(NvComputer* computer);
private:
void run()
QString fetchServerInfo(NvHTTP& http)
{
NvHTTP http(m_Address);
qInfo() << "Processing new PC at" << m_Address << "from" << (m_Mdns ? "mDNS" : "user");
QString serverInfo;
try {
// There's a race condition between GameStream servers reporting presence over
@@ -551,12 +621,12 @@ private:
// around this issue, we will issue the request again after a few seconds if
// we see a ServiceUnavailableError error.
try {
serverInfo = http.getServerInfo(NvHTTP::NvLogLevel::VERBOSE);
serverInfo = http.getServerInfo(NvHTTP::NVLL_VERBOSE);
} catch (const QtNetworkReplyException& e) {
if (e.getError() == QNetworkReply::ServiceUnavailableError) {
qWarning() << "Retrying request in 5 seconds after ServiceUnavailableError";
QThread::sleep(5);
serverInfo = http.getServerInfo(NvHTTP::NvLogLevel::VERBOSE);
serverInfo = http.getServerInfo(NvHTTP::NVLL_VERBOSE);
qInfo() << "Retry successful";
}
else {
@@ -564,85 +634,176 @@ private:
throw e;
}
}
return serverInfo;
} catch (...) {
if (!m_Mdns) {
emit computerAddCompleted(false);
StreamingPreferences prefs;
int portTestResult;
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,
ML_PORT_FLAG_TCP_47984 | ML_PORT_FLAG_TCP_47989);
}
else {
portTestResult = 0;
}
emit computerAddCompleted(false, portTestResult != 0 && portTestResult != ML_TEST_RESULT_INCONCLUSIVE);
}
return QString();
}
}
void run()
{
NvHTTP http(m_Address, QSslCertificate());
qInfo() << "Processing new PC at" << m_Address << "from" << (m_Mdns ? "mDNS" : "user") << m_MdnsIpv6Address;
// Perform initial serverinfo fetch over HTTP since we don't know which cert to use
QString serverInfo = fetchServerInfo(http);
if (serverInfo.isEmpty() && !m_MdnsIpv6Address.isNull()) {
// Retry using the global IPv6 address if the IPv4 or link-local IPv6 address fails
http.setAddress(m_MdnsIpv6Address.toString());
serverInfo = fetchServerInfo(http);
}
if (serverInfo.isEmpty()) {
return;
}
NvComputer* newComputer = new NvComputer(m_Address, serverInfo);
// Create initial newComputer using HTTP serverinfo with no pinned cert
NvComputer* newComputer = new NvComputer(http.address(), serverInfo, QSslCertificate());
// Check if we have a record of this host UUID to pull the pinned cert
NvComputer* existingComputer;
{
QReadLocker lock(&m_ComputerManager->m_Lock);
existingComputer = m_ComputerManager->m_KnownHosts.value(newComputer->uuid);
if (existingComputer != nullptr) {
http.setServerCert(existingComputer->serverCert);
}
}
// Fetch serverinfo again over HTTPS with the pinned cert
if (existingComputer != nullptr) {
serverInfo = fetchServerInfo(http);
if (serverInfo.isEmpty()) {
return;
}
// Update the polled computer with the HTTPS information
NvComputer httpsComputer(http.address(), serverInfo, QSslCertificate());
newComputer->update(httpsComputer);
}
// Update addresses depending on the context
if (m_Mdns) {
newComputer->localAddress = m_Address;
// Get the WAN IP address using STUN if we're on mDNS
quint32 addr;
int err = LiFindExternalAddressIP4("stun.stunprotocol.org", 3478, &addr);
if (err == 0) {
newComputer->remoteAddress = QHostAddress(qFromBigEndian(addr)).toString();
// Only update local address if we actually reached the PC via this address.
// If we reached it via the IPv6 address after the local address failed,
// don't store the non-working local address.
if (http.address() == m_Address) {
newComputer->localAddress = m_Address;
}
else {
qWarning() << "STUN failed to get WAN address:" << err;
// Get the WAN IP address using STUN if we're on mDNS over IPv4
if (QHostAddress(newComputer->localAddress).protocol() == QAbstractSocket::IPv4Protocol) {
quint32 addr;
int err = LiFindExternalAddressIP4("stun.moonlight-stream.org", 3478, &addr);
if (err == 0) {
newComputer->remoteAddress = QHostAddress(qFromBigEndian(addr)).toString();
}
else {
qWarning() << "STUN failed to get WAN address:" << err;
}
}
if (!m_MdnsIpv6Address.isNull()) {
Q_ASSERT(m_MdnsIpv6Address.protocol() == QAbstractSocket::IPv6Protocol);
newComputer->ipv6Address = m_MdnsIpv6Address.toString();
}
}
else {
newComputer->manualAddress = m_Address;
}
// Check if this PC already exists
QWriteLocker lock(&m_ComputerManager->m_Lock);
NvComputer* existingComputer = m_ComputerManager->m_KnownHosts[newComputer->uuid];
if (existingComputer != nullptr) {
// Fold it into the existing PC
bool changed = existingComputer->update(*newComputer);
delete newComputer;
QHostAddress hostAddress(m_Address);
bool addressIsSiteLocalV4 =
hostAddress.isInSubnet(QHostAddress("10.0.0.0"), 8) ||
hostAddress.isInSubnet(QHostAddress("172.16.0.0"), 12) ||
hostAddress.isInSubnet(QHostAddress("192.168.0.0"), 16);
// Drop the lock before notifying
lock.unlock();
{
// Check if this PC already exists
QWriteLocker lock(&m_ComputerManager->m_Lock);
NvComputer* existingComputer = m_ComputerManager->m_KnownHosts.value(newComputer->uuid);
if (existingComputer != nullptr) {
// Fold it into the existing PC
bool changed = existingComputer->update(*newComputer);
delete newComputer;
// For non-mDNS clients, let them know it succeeded
if (!m_Mdns) {
emit computerAddCompleted(true);
// Drop the lock before notifying
lock.unlock();
// For non-mDNS clients, let them know it succeeded
if (!m_Mdns) {
emit computerAddCompleted(true, false);
}
// Tell our client if something changed
if (changed) {
qInfo() << existingComputer->name << "is now at" << existingComputer->activeAddress;
emit computerStateChanged(existingComputer);
}
}
else {
// Store this in our active sets
m_ComputerManager->m_KnownHosts[newComputer->uuid] = newComputer;
// Tell our client if something changed
if (changed) {
qInfo() << existingComputer->name << "is now at" << existingComputer->activeAddress;
emit computerStateChanged(existingComputer);
// Start polling if enabled (write lock required)
m_ComputerManager->startPollingComputer(newComputer);
// Drop the lock before notifying
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->isReachableOverVpn()) {
quint32 addr;
int err = LiFindExternalAddressIP4("stun.moonlight-stream.org", 3478, &addr);
if (err == 0) {
lock.relock();
newComputer->remoteAddress = QHostAddress(qFromBigEndian(addr)).toString();
lock.unlock();
}
else {
qWarning() << "STUN failed to get WAN address:" << err;
}
}
// For non-mDNS clients, let them know it succeeded
if (!m_Mdns) {
emit computerAddCompleted(true, false);
}
// Tell our client about this new PC
emit computerStateChanged(newComputer);
}
}
else {
// Store this in our active sets
m_ComputerManager->m_KnownHosts[newComputer->uuid] = newComputer;
// Start polling if enabled (write lock required)
m_ComputerManager->startPollingComputer(newComputer);
// Drop the lock before notifying
lock.unlock();
// For non-mDNS clients, let them know it succeeded
if (!m_Mdns) {
emit computerAddCompleted(true);
}
// Tell our client about this new PC
emit computerStateChanged(newComputer);
}
}
ComputerManager* m_ComputerManager;
QString m_Address;
QHostAddress m_MdnsIpv6Address;
bool m_Mdns;
};
void ComputerManager::addNewHost(QString address, bool mdns)
void ComputerManager::addNewHost(QString address, bool mdns, QHostAddress mdnsIpv6Address)
{
// Punt to a worker thread to avoid stalling the
// UI while waiting for serverinfo query to complete
PendingAddTask* addTask = new PendingAddTask(this, address, mdns);
PendingAddTask* addTask = new PendingAddTask(this, address, mdnsIpv6Address, mdns);
QThreadPool::globalInstance()->start(addTask);
}
+123 -14
View File
@@ -13,6 +13,7 @@
#include <QReadWriteLock>
#include <QSettings>
#include <QRunnable>
#include <QTimer>
class MdnsPendingComputer : public QObject
{
@@ -20,13 +21,18 @@ class MdnsPendingComputer : public QObject
public:
explicit MdnsPendingComputer(QMdnsEngine::Server* server,
QMdnsEngine::Cache* cache,
const QMdnsEngine::Service& service)
: m_Hostname(service.hostname()),
m_Resolver(server, m_Hostname, cache)
m_Server(server),
m_Resolver(nullptr)
{
connect(&m_Resolver, SIGNAL(resolved(QHostAddress)),
this, SLOT(handleResolved(QHostAddress)));
// Start resolving
resolve();
}
virtual ~MdnsPendingComputer()
{
delete m_Resolver;
}
QString hostname()
@@ -35,20 +41,115 @@ public:
}
private slots:
void handleResolved(const QHostAddress& address)
void handleResolvedTimeout()
{
if (address.protocol() == QAbstractSocket::IPv4Protocol) {
m_Resolver.disconnect();
emit resolvedv4(this, address);
if (m_Addresses.isEmpty()) {
// Try again
qInfo() << "Resolving" << hostname() << "timed out. Retrying...";
resolve();
}
else {
Q_ASSERT(!m_Addresses.isEmpty());
emit resolvedHost(this, m_Addresses);
}
}
void handleResolvedAddress(const QHostAddress& address)
{
qInfo() << "Resolved" << hostname() << "to" << address;
m_Addresses.push_back(address);
}
signals:
void resolvedv4(MdnsPendingComputer*, const QHostAddress&);
void resolvedHost(MdnsPendingComputer*,QVector<QHostAddress>&);
private:
void resolve()
{
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, SLOT(handleResolvedTimeout()));
}
QByteArray m_Hostname;
QMdnsEngine::Resolver m_Resolver;
QMdnsEngine::Server* m_Server;
QMdnsEngine::Resolver* m_Resolver;
QVector<QHostAddress> m_Addresses;
};
class ComputerPollingEntry
{
public:
ComputerPollingEntry()
: m_ActiveThread(nullptr)
{
}
virtual ~ComputerPollingEntry()
{
interrupt();
// interrupt() should have taken care of this
Q_ASSERT(m_ActiveThread == nullptr);
for (QThread* thread : m_InactiveList) {
thread->wait();
delete thread;
}
}
bool isActive()
{
cleanInactiveList();
return m_ActiveThread != nullptr;
}
void setActiveThread(QThread* thread)
{
cleanInactiveList();
Q_ASSERT(!isActive());
m_ActiveThread = thread;
}
void interrupt()
{
cleanInactiveList();
if (m_ActiveThread != nullptr) {
// Interrupt the active thread
m_ActiveThread->requestInterruption();
// Place it on the inactive list awaiting death
m_InactiveList.append(m_ActiveThread);
m_ActiveThread = nullptr;
}
}
private:
void cleanInactiveList()
{
QMutableListIterator<QThread*> i(m_InactiveList);
// Reap any threads that have finished
while (i.hasNext()) {
i.next();
QThread* thread = i.value();
if (thread->isFinished()) {
delete thread;
i.remove();
}
}
}
QThread* m_ActiveThread;
QList<QThread*> m_InactiveList;
};
class ComputerManager : public QObject
@@ -67,7 +168,7 @@ public:
Q_INVOKABLE void stopPollingAsync();
Q_INVOKABLE void addNewHost(QString address, bool mdns);
Q_INVOKABLE void addNewHost(QString address, bool mdns, QHostAddress mdnsIpv6Address = QHostAddress());
void pairHost(NvComputer* computer, QString pin);
@@ -78,29 +179,37 @@ public:
// computer is deleted inside this call
void deleteHost(NvComputer* computer);
void renameHost(NvComputer* computer, QString name);
void clientSideAttributeUpdated(NvComputer* computer);
signals:
void computerStateChanged(NvComputer* computer);
void pairingCompleted(NvComputer* computer, QString error);
void computerAddCompleted(QVariant success);
void computerAddCompleted(QVariant success, QVariant detectedPortBlocking);
void quitAppCompleted(QVariant error);
private slots:
void handleAboutToQuit();
void handleComputerStateChanged(NvComputer* computer);
void handleMdnsServiceResolved(MdnsPendingComputer* computer, const QHostAddress& address);
void handleMdnsServiceResolved(MdnsPendingComputer* computer, QVector<QHostAddress>& addresses);
private:
void saveHosts();
QHostAddress getBestGlobalAddressV6(QVector<QHostAddress>& addresses);
void startPollingComputer(NvComputer* computer);
int m_PollingRef;
QReadWriteLock m_Lock;
QMap<QString, NvComputer*> m_KnownHosts;
QMap<QString, QThread*> m_PollThreads;
QMap<QString, ComputerPollingEntry*> m_PollEntries;
QMdnsEngine::Server m_MdnsServer;
QMdnsEngine::Browser* m_MdnsBrowser;
QMdnsEngine::Cache m_MdnsCache;
+12 -5
View File
@@ -39,11 +39,18 @@ void ComputerSeeker::onComputerUpdated(NvComputer *computer)
bool ComputerSeeker::matchComputer(NvComputer *computer) const
{
QString value = m_ComputerName.toLower();
return computer->name.toLower() == value ||
computer->localAddress.toLower() == value ||
computer->remoteAddress.toLower() == value ||
computer->manualAddress.toLower() == value ||
computer->uuid.toLower() == value;
if (computer->name.toLower() == value || computer->uuid.toLower() == value) {
return true;
}
for (const QString& addr : computer->uniqueAddresses()) {
if (addr.toLower() == value) {
return true;
}
}
return false;
}
bool ComputerSeeker::isOnline(NvComputer *computer) const
+12 -15
View File
@@ -5,7 +5,6 @@
#include <openssl/pem.h>
#include <openssl/rsa.h>
#include <openssl/bn.h>
#include <openssl/x509.h>
#include <openssl/rand.h>
@@ -32,20 +31,19 @@ void IdentityManager::createCredentials(QSettings& settings)
X509* cert = X509_new();
THROW_BAD_ALLOC_IF_NULL(cert);
EVP_PKEY* pk = EVP_PKEY_new();
EVP_PKEY_CTX* ctx = EVP_PKEY_CTX_new_id(EVP_PKEY_RSA, NULL);
THROW_BAD_ALLOC_IF_NULL(ctx);
EVP_PKEY_keygen_init(ctx);
EVP_PKEY_CTX_set_rsa_keygen_bits(ctx, 2048);
// pk must be initialized on input
EVP_PKEY* pk = NULL;
EVP_PKEY_keygen(ctx, &pk);
EVP_PKEY_CTX_free(ctx);
THROW_BAD_ALLOC_IF_NULL(pk);
BIGNUM* bne = BN_new();
THROW_BAD_ALLOC_IF_NULL(bne);
RSA* rsa = RSA_new();
THROW_BAD_ALLOC_IF_NULL(rsa);
BN_set_word(bne, RSA_F4);
RSA_generate_key_ex(rsa, 2048, bne, nullptr);
EVP_PKEY_assign_RSA(pk, rsa);
X509_set_version(cert, 2);
ASN1_INTEGER_set(X509_get_serialNumber(cert), 0);
#if OPENSSL_VERSION_NUMBER < 0x10100000L
@@ -75,7 +73,7 @@ void IdentityManager::createCredentials(QSettings& settings)
-1, -1, 0);
X509_set_issuer_name(cert, name);
X509_sign(cert, pk, EVP_sha1());
X509_sign(cert, pk, EVP_sha256());
BIO* biokey = BIO_new(BIO_s_mem());
THROW_BAD_ALLOC_IF_NULL(biokey);
@@ -94,7 +92,6 @@ void IdentityManager::createCredentials(QSettings& settings)
X509_free(cert);
EVP_PKEY_free(pk);
BN_free(bne);
BIO_free(biokey);
BIO_free(biocert);
+25
View File
@@ -0,0 +1,25 @@
#include "nvapp.h"
#define SER_APPNAME "name"
#define SER_APPID "id"
#define SER_APPHDR "hdr"
#define SER_APPCOLLECTOR "appcollector"
#define SER_HIDDEN "hidden"
NvApp::NvApp(QSettings& settings)
{
name = settings.value(SER_APPNAME).toString();
id = settings.value(SER_APPID).toInt();
hdrSupported = settings.value(SER_APPHDR).toBool();
isAppCollectorGame = settings.value(SER_APPCOLLECTOR).toBool();
hidden = settings.value(SER_HIDDEN).toBool();
}
void NvApp::serialize(QSettings& settings) const
{
settings.setValue(SER_APPNAME, name);
settings.setValue(SER_APPID, id);
settings.setValue(SER_APPHDR, hdrSupported);
settings.setValue(SER_APPCOLLECTOR, isAppCollectorGame);
settings.setValue(SER_HIDDEN, hidden);
}
+40
View File
@@ -0,0 +1,40 @@
#pragma once
#include <QSettings>
class NvApp
{
public:
NvApp() {}
explicit NvApp(QSettings& settings);
bool operator==(const NvApp& other) const
{
return id == other.id &&
name == other.name &&
hdrSupported == other.hdrSupported &&
isAppCollectorGame == other.isAppCollectorGame &&
hidden == other.hidden;
}
bool operator!=(const NvApp& other) const
{
return !operator==(other);
}
bool isInitialized()
{
return id != 0 && !name.isEmpty();
}
void
serialize(QSettings& settings) const;
int id = 0;
QString name;
bool hdrSupported = false;
bool isAppCollectorGame = false;
bool hidden = false;
};
Q_DECLARE_METATYPE(NvApp)
+176 -31
View File
@@ -1,7 +1,10 @@
#include "nvcomputer.h"
#include "nvapp.h"
#include <QUdpSocket>
#include <QHostInfo>
#include <QNetworkInterface>
#include <QNetworkProxy>
#define SER_NAME "hostname"
#define SER_UUID "uuid"
@@ -9,31 +12,28 @@
#define SER_LOCALADDR "localaddress"
#define SER_REMOTEADDR "remoteaddress"
#define SER_MANUALADDR "manualaddress"
#define SER_IPV6ADDR "ipv6address"
#define SER_APPLIST "apps"
#define SER_APPNAME "name"
#define SER_APPID "id"
#define SER_APPHDR "hdr"
#define SER_SRVCERT "srvcert"
#define SER_CUSTOMNAME "customname"
NvComputer::NvComputer(QSettings& settings)
{
this->name = settings.value(SER_NAME).toString();
this->uuid = settings.value(SER_UUID).toString();
this->hasCustomName = settings.value(SER_CUSTOMNAME).toBool();
this->macAddress = settings.value(SER_MAC).toByteArray();
this->localAddress = settings.value(SER_LOCALADDR).toString();
this->remoteAddress = settings.value(SER_REMOTEADDR).toString();
this->ipv6Address = settings.value(SER_IPV6ADDR).toString();
this->manualAddress = settings.value(SER_MANUALADDR).toString();
this->serverCert = QSslCertificate(settings.value(SER_SRVCERT).toByteArray());
int appCount = settings.beginReadArray(SER_APPLIST);
for (int i = 0; i < appCount; i++) {
NvApp app;
settings.setArrayIndex(i);
app.name = settings.value(SER_APPNAME).toString();
app.id = settings.value(SER_APPID).toInt();
app.hdrSupported = settings.value(SER_APPHDR).toBool();
NvApp app(settings);
this->appList.append(app);
}
settings.endArray();
@@ -51,16 +51,19 @@ NvComputer::NvComputer(QSettings& settings)
this->gpuModel = nullptr;
}
void NvComputer::serialize(QSettings& settings)
void NvComputer::serialize(QSettings& settings) const
{
QReadLocker lock(&this->lock);
settings.setValue(SER_NAME, name);
settings.setValue(SER_CUSTOMNAME, hasCustomName);
settings.setValue(SER_UUID, uuid);
settings.setValue(SER_MAC, macAddress);
settings.setValue(SER_LOCALADDR, localAddress);
settings.setValue(SER_REMOTEADDR, remoteAddress);
settings.setValue(SER_IPV6ADDR, ipv6Address);
settings.setValue(SER_MANUALADDR, manualAddress);
settings.setValue(SER_SRVCERT, serverCert.toPem());
// Avoid deleting an existing applist if we couldn't get one
if (!appList.isEmpty()) {
@@ -68,10 +71,7 @@ void NvComputer::serialize(QSettings& settings)
settings.beginWriteArray(SER_APPLIST);
for (int i = 0; i < appList.count(); i++) {
settings.setArrayIndex(i);
settings.setValue(SER_APPNAME, appList[i].name);
settings.setValue(SER_APPID, appList[i].id);
settings.setValue(SER_APPHDR, appList[i].hdrSupported);
appList[i].serialize(settings);
}
settings.endArray();
}
@@ -84,8 +84,11 @@ void NvComputer::sortAppList()
});
}
NvComputer::NvComputer(QString address, QString serverInfo)
NvComputer::NvComputer(QString address, QString serverInfo, QSslCertificate serverCert)
{
this->serverCert = serverCert;
this->hasCustomName = false;
this->name = NvHTTP::getXmlString(serverInfo, "hostname");
if (this->name.isEmpty()) {
this->name = "UNKNOWN";
@@ -123,7 +126,12 @@ NvComputer::NvComputer(QString address, QString serverInfo)
mode2.width * mode2.height * mode2.refreshRate;
});
// We can get an IPv4 loopback address if we're using the GS IPv6 Forwarder
this->localAddress = NvHTTP::getXmlString(serverInfo, "LocalIP");
if (this->localAddress.startsWith("127.")) {
this->localAddress = QString();
}
this->remoteAddress = NvHTTP::getXmlString(serverInfo, "ExternalIP");
this->pairState = NvHTTP::getXmlString(serverInfo, "PairStatus") == "1" ?
PS_PAIRED : PS_NOT_PAIRED;
@@ -149,8 +157,9 @@ bool NvComputer::wake()
}
const quint16 WOL_PORTS[] = {
7, 9, // Standard WOL ports
47998, 47999, 48000, // Ports opened by GFE
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)
};
// Create the WoL payload
@@ -167,6 +176,32 @@ bool NvComputer::wake()
QVector<QString> addressList = uniqueAddresses();
addressList.append("255.255.255.255");
// Try to broadcast on all available NICs
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) {
continue;
}
QHostAddress allNodesMulticast("FF02::1");
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());
}
// Skip IPv6 which doesn't support broadcast
if (!addr.broadcast().isNull()) {
addressList.append(addr.broadcast().toString());
}
}
if (!allNodesMulticast.scopeId().isEmpty()) {
addressList.append(allNodesMulticast.toString());
}
}
// Try all unique address strings or host names
bool success = false;
for (QString& addressString : addressList) {
@@ -181,16 +216,14 @@ bool NvComputer::wake()
for (QHostAddress& address : hostInfo.addresses()) {
QUdpSocket sock;
// Bind to any address on the correct protocol
if (sock.bind(address.protocol() == QUdpSocket::IPv4Protocol ?
QHostAddress::AnyIPv4 : QHostAddress::AnyIPv6)) {
// Send to all ports
for (quint16 port : WOL_PORTS) {
if (sock.writeDatagram(wolPayload, address, port)) {
qInfo().nospace().noquote() << "Send WoL packet to " << name << " via " << address.toString() << ":" << port;
success = true;
}
// 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;
}
else {
qWarning() << "Send failed:" << sock.error();
}
}
}
@@ -199,7 +232,101 @@ bool NvComputer::wake()
return success;
}
QVector<QString> NvComputer::uniqueAddresses()
bool NvComputer::isReachableOverVpn()
{
if (activeAddress.isEmpty()) {
return false;
}
QTcpSocket s;
s.setProxy(QNetworkProxy::NoProxy);
s.connectToHost(activeAddress, 47984);
if (s.waitForConnected(3000)) {
Q_ASSERT(!s.localAddress().isNull());
for (const QNetworkInterface& nic : QNetworkInterface::allInterfaces()) {
// Ensure the interface is up
if ((nic.flags() & QNetworkInterface::IsUp) == 0) {
continue;
}
for (const QNetworkAddressEntry& addr : nic.addressEntries()) {
if (addr.ip() == s.localAddress()) {
qInfo() << "Found matching interface:" << nic.humanReadableName() << nic.hardwareAddress() << nic.flags();
#if QT_VERSION >= QT_VERSION_CHECK(5, 11, 0)
qInfo() << "Interface Type:" << nic.type();
qInfo() << "Interface MTU:" << nic.maximumTransmissionUnit();
if (nic.type() == QNetworkInterface::Virtual ||
nic.type() == QNetworkInterface::Ppp) {
// Treat PPP and virtual interfaces as likely VPNs
return true;
}
if (nic.maximumTransmissionUnit() != 0 && nic.maximumTransmissionUnit() < 1500) {
// Treat MTUs under 1500 as likely VPNs
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 true;
}
if (nic.hardwareAddress().startsWith("00:FF", Qt::CaseInsensitive)) {
// OpenVPN TAP interfaces have a MAC address starting with 00:FF on Windows
return true;
}
if (nic.humanReadableName().startsWith("ZeroTier")) {
// ZeroTier interfaces always start with "ZeroTier"
return true;
}
if (nic.humanReadableName().contains("VPN")) {
// This one is just a final heuristic if all else fails
return true;
}
// Didn't meet any of our VPN heuristics
return false;
}
}
}
qWarning() << "No match found for address:" << s.localAddress();
return false;
}
else {
// If we fail to connect, just pretend that it's not a VPN
return false;
}
}
bool NvComputer::updateAppList(QVector<NvApp> newAppList) {
if (appList == newAppList) {
return false;
}
// Propagate client-side attributes to the new app list
for (const NvApp& existingApp : appList) {
for (NvApp& newApp : newAppList) {
if (existingApp.id == newApp.id) {
newApp.hidden = existingApp.hidden;
}
}
}
appList = newAppList;
sortAppList();
return true;
}
QVector<QString> NvComputer::uniqueAddresses() const
{
QVector<QString> uniqueAddressList;
@@ -207,6 +334,7 @@ QVector<QString> NvComputer::uniqueAddresses()
uniqueAddressList.append(activeAddress);
uniqueAddressList.append(localAddress);
uniqueAddressList.append(remoteAddress);
uniqueAddressList.append(ipv6Address);
uniqueAddressList.append(manualAddress);
// Prune duplicates (always giving precedence to the first)
@@ -255,10 +383,21 @@ bool NvComputer::update(NvComputer& that)
changed = true; \
}
ASSIGN_IF_CHANGED(name);
#define ASSIGN_IF_CHANGED_AND_NONNULL(field) \
if (!that.field.isNull() && \
this->field != that.field) { \
this->field = that.field; \
changed = true; \
}
if (!hasCustomName) {
// Only overwrite the name if it's not custom
ASSIGN_IF_CHANGED(name);
}
ASSIGN_IF_CHANGED_AND_NONEMPTY(macAddress);
ASSIGN_IF_CHANGED_AND_NONEMPTY(localAddress);
ASSIGN_IF_CHANGED_AND_NONEMPTY(remoteAddress);
ASSIGN_IF_CHANGED_AND_NONEMPTY(ipv6Address);
ASSIGN_IF_CHANGED_AND_NONEMPTY(manualAddress);
ASSIGN_IF_CHANGED(pairState);
ASSIGN_IF_CHANGED(serverCodecModeSupport);
@@ -269,7 +408,13 @@ bool NvComputer::update(NvComputer& that)
ASSIGN_IF_CHANGED(appVersion);
ASSIGN_IF_CHANGED(maxLumaPixelsHEVC);
ASSIGN_IF_CHANGED(gpuModel);
ASSIGN_IF_CHANGED_AND_NONEMPTY(appList);
ASSIGN_IF_CHANGED_AND_NONNULL(serverCert);
ASSIGN_IF_CHANGED_AND_NONEMPTY(displayModes);
if (!that.appList.isEmpty()) {
// updateAppList() handles merging client-side attributes
updateAppList(that.appList);
}
return changed;
}
+12 -4
View File
@@ -16,10 +16,12 @@ class NvComputer
private:
void sortAppList();
bool updateAppList(QVector<NvApp> newAppList);
bool pendingQuit;
public:
explicit NvComputer(QString address, QString serverInfo);
explicit NvComputer(QString address, QString serverInfo, QSslCertificate serverCert);
explicit NvComputer(QSettings& settings);
@@ -29,11 +31,14 @@ public:
bool
wake();
bool
isReachableOverVpn();
QVector<QString>
uniqueAddresses();
uniqueAddresses() const;
void
serialize(QSettings& settings);
serialize(QSettings& settings) const;
enum PairState
{
@@ -64,12 +69,15 @@ public:
// Persisted traits
QString localAddress;
QString remoteAddress;
QString ipv6Address;
QString manualAddress;
QByteArray macAddress;
QString name;
bool hasCustomName;
QString uuid;
QSslCertificate serverCert;
QVector<NvApp> appList;
// Synchronization
QReadWriteLock lock;
mutable QReadWriteLock lock;
};
+166 -90
View File
@@ -12,23 +12,47 @@
#include <QtEndian>
#include <QNetworkProxy>
#define FAST_FAIL_TIMEOUT_MS 2000
#define REQUEST_TIMEOUT_MS 5000
#define LAUNCH_TIMEOUT_MS 120000
#define RESUME_TIMEOUT_MS 30000
#define QUIT_TIMEOUT_MS 30000
NvHTTP::NvHTTP(QString address) :
m_Address(address)
NvHTTP::NvHTTP(QString address, QSslCertificate serverCert) :
m_ServerCert(serverCert)
{
Q_ASSERT(!address.isEmpty());
m_BaseUrlHttp.setScheme("http");
m_BaseUrlHttps.setScheme("https");
m_BaseUrlHttp.setHost(address);
m_BaseUrlHttps.setHost(address);
m_BaseUrlHttp.setPort(47989);
m_BaseUrlHttps.setPort(47984);
setAddress(address);
// Never use a proxy server
QNetworkProxy noProxy(QNetworkProxy::NoProxy);
m_Nam.setProxy(noProxy);
connect(&m_Nam, &QNetworkAccessManager::sslErrors, this, &NvHTTP::handleSslErrors);
}
void NvHTTP::setServerCert(QSslCertificate serverCert)
{
m_ServerCert = serverCert;
}
void NvHTTP::setAddress(QString address)
{
Q_ASSERT(!address.isEmpty());
m_Address = address;
m_BaseUrlHttp.setHost(address);
m_BaseUrlHttps.setHost(address);
}
QString NvHTTP::address()
{
return m_Address;
}
QVector<int>
@@ -69,68 +93,58 @@ NvHTTP::getCurrentGame(QString serverInfo)
}
QString
NvHTTP::getServerInfo(NvLogLevel logLevel)
NvHTTP::getServerInfo(NvLogLevel logLevel, bool fastFail)
{
QString serverInfo;
try
// Check if we have a pinned cert for this host yet
if (!m_ServerCert.isNull())
{
// Always try HTTPS first, since it properly reports
// pairing status (and a few other attributes).
serverInfo = openConnectionToString(m_BaseUrlHttps,
"serverinfo",
nullptr,
true,
logLevel);
// Throws if the request failed
verifyResponseStatus(serverInfo);
}
catch (const GfeHttpResponseException& e)
{
if (e.getStatusCode() == 401)
try
{
// Certificate validation error, fallback to HTTP
serverInfo = openConnectionToString(m_BaseUrlHttp,
// Always try HTTPS first, since it properly reports
// pairing status (and a few other attributes).
serverInfo = openConnectionToString(m_BaseUrlHttps,
"serverinfo",
nullptr,
true,
fastFail ? FAST_FAIL_TIMEOUT_MS : REQUEST_TIMEOUT_MS,
logLevel);
// Throws if the request failed
verifyResponseStatus(serverInfo);
}
else
catch (const GfeHttpResponseException& e)
{
// Rethrow real errors
throw e;
if (e.getStatusCode() == 401)
{
// Certificate validation error, fallback to HTTP
serverInfo = openConnectionToString(m_BaseUrlHttp,
"serverinfo",
nullptr,
fastFail ? FAST_FAIL_TIMEOUT_MS : REQUEST_TIMEOUT_MS,
logLevel);
verifyResponseStatus(serverInfo);
}
else
{
// Rethrow real errors
throw e;
}
}
}
else
{
// Only use HTTP prior to pairing
serverInfo = openConnectionToString(m_BaseUrlHttp,
"serverinfo",
nullptr,
fastFail ? FAST_FAIL_TIMEOUT_MS : REQUEST_TIMEOUT_MS,
logLevel);
verifyResponseStatus(serverInfo);
}
return serverInfo;
}
static QString
getSurroundAudioInfoString(int audioConfig)
{
int channelMask;
int channelCount;
switch (audioConfig)
{
case AUDIO_CONFIGURATION_STEREO:
channelCount = 2;
channelMask = 0x3;
break;
case AUDIO_CONFIGURATION_51_SURROUND:
channelCount = 6;
channelMask = 0xFC;
break;
default:
Q_ASSERT(false);
return 0;
}
return QString::number(channelMask << 16 | channelCount);
}
void
NvHTTP::launchApp(int appId,
PSTREAM_CONFIGURATION streamConfig,
@@ -149,7 +163,11 @@ NvHTTP::launchApp(int appId,
"appid="+QString::number(appId)+
"&mode="+QString::number(streamConfig->width)+"x"+
QString::number(streamConfig->height)+"x"+
QString::number(streamConfig->fps)+
// 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.
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)+
@@ -157,10 +175,10 @@ NvHTTP::launchApp(int appId,
"&hdrMode=1&clientHdrCapVersion=0&clientHdrCapSupportedFlagsInUint32=0&clientHdrCapMetaDataId=NV_STATIC_METADATA_TYPE_1&clientHdrCapDisplayData=0x0x0x0x0x0x0x0x0x0x0" :
"")+
"&localAudioPlayMode="+QString::number(localAudio ? 1 : 0)+
"&surroundAudioInfo="+getSurroundAudioInfoString(streamConfig->audioConfiguration)+
"&surroundAudioInfo="+QString::number(SURROUNDAUDIOINFO_FROM_AUDIO_CONFIGURATION(streamConfig->audioConfiguration))+
"&remoteControllersBitmap="+QString::number(gamepadMask)+
"&gcmap="+QString::number(gamepadMask),
false);
LAUNCH_TIMEOUT_MS);
// Throws if the request failed
verifyResponseStatus(response);
@@ -179,8 +197,8 @@ NvHTTP::resumeApp(PSTREAM_CONFIGURATION streamConfig)
"resume",
"rikey="+QString(QByteArray(streamConfig->remoteInputAesKey, sizeof(streamConfig->remoteInputAesKey)).toHex())+
"&rikeyid="+QString::number(riKeyId)+
"&surroundAudioInfo="+getSurroundAudioInfoString(streamConfig->audioConfiguration),
false);
"&surroundAudioInfo="+QString::number(SURROUNDAUDIOINFO_FROM_AUDIO_CONFIGURATION(streamConfig->audioConfiguration)),
RESUME_TIMEOUT_MS);
// Throws if the request failed
verifyResponseStatus(response);
@@ -193,14 +211,14 @@ NvHTTP::quitApp()
openConnectionToString(m_BaseUrlHttps,
"cancel",
nullptr,
false);
QUIT_TIMEOUT_MS);
// Throws if the request failed
verifyResponseStatus(response);
// Newer GFE versions will just return success even if quitting fails
// if we're not the original requestor.
if (getCurrentGame(getServerInfo(NvHTTP::ERROR)) != 0) {
if (getCurrentGame(getServerInfo(NvHTTP::NVLL_ERROR)) != 0) {
// Generate a synthetic GfeResponseException letting the caller know
// that they can't kill someone else's stream.
throw GfeHttpResponseException(599, "");
@@ -216,16 +234,16 @@ NvHTTP::getDisplayModeList(QString serverInfo)
while (!xmlReader.atEnd()) {
while (xmlReader.readNextStartElement()) {
QStringRef name = xmlReader.name();
if (xmlReader.name() == "DisplayMode") {
if (name == "DisplayMode") {
modes.append(NvDisplayMode());
}
else if (xmlReader.name() == "Width") {
else if (name == "Width") {
modes.last().width = xmlReader.readElementText().toInt();
}
else if (xmlReader.name() == "Height") {
else if (name == "Height") {
modes.last().height = xmlReader.readElementText().toInt();
}
else if (xmlReader.name() == "RefreshRate") {
else if (name == "RefreshRate") {
modes.last().refreshRate = xmlReader.readElementText().toInt();
}
}
@@ -240,8 +258,8 @@ NvHTTP::getAppList()
QString appxml = openConnectionToString(m_BaseUrlHttps,
"applist",
nullptr,
true,
NvLogLevel::ERROR);
REQUEST_TIMEOUT_MS,
NvLogLevel::NVLL_ERROR);
verifyResponseStatus(appxml);
QXmlStreamReader xmlReader(appxml);
@@ -249,7 +267,7 @@ NvHTTP::getAppList()
while (!xmlReader.atEnd()) {
while (xmlReader.readNextStartElement()) {
QStringRef name = xmlReader.name();
if (xmlReader.name() == "App") {
if (name == "App") {
// We must have a valid app before advancing to the next one
if (!apps.isEmpty() && !apps.last().isInitialized()) {
qWarning() << "Invalid applist XML";
@@ -258,15 +276,18 @@ NvHTTP::getAppList()
}
apps.append(NvApp());
}
else if (xmlReader.name() == "AppTitle") {
else if (name == "AppTitle") {
apps.last().name = xmlReader.readElementText();
}
else if (xmlReader.name() == "ID") {
else if (name == "ID") {
apps.last().id = xmlReader.readElementText().toInt();
}
else if (xmlReader.name() == "IsHdrSupported") {
else if (name == "IsHdrSupported") {
apps.last().hdrSupported = xmlReader.readElementText() == "1";
}
else if (name == "IsAppCollectorGame") {
apps.last().isAppCollectorGame = xmlReader.readElementText() == "1";
}
}
}
@@ -282,7 +303,10 @@ NvHTTP::verifyResponseStatus(QString xml)
{
if (xmlReader.name() == "root")
{
int statusCode = xmlReader.attributes().value("status_code").toInt();
// 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()
// and cast the result to an int instead.
int statusCode = (int)xmlReader.attributes().value("status_code").toUInt();
if (statusCode == 200)
{
// Successful
@@ -295,6 +319,12 @@ NvHTTP::verifyResponseStatus(QString xml)
// 401 is expected for unpaired PCs when we fetch serverinfo over HTTPS
qWarning() << "Request failed:" << statusCode << statusMessage;
}
if (statusCode == -1 && statusMessage == "Invalid") {
// Special case handling an audio capture error which GFE doesn't
// provide any useful status message for.
statusCode = 418;
statusMessage = "Missing audio capture device. Reinstalling GeForce Experience should resolve this error.";
}
throw GfeHttpResponseException(statusCode, statusMessage);
}
}
@@ -308,8 +338,8 @@ NvHTTP::getBoxArt(int appId)
"appasset",
"appid="+QString::number(appId)+
"&AssetType=2&AssetIdx=0",
true,
NvLogLevel::VERBOSE);
REQUEST_TIMEOUT_MS,
NvLogLevel::NVLL_VERBOSE);
QImage image = QImageReader(reply).read();
delete reply;
@@ -351,14 +381,36 @@ NvHTTP::getXmlString(QString xml,
return nullptr;
}
void NvHTTP::handleSslErrors(QNetworkReply* reply, const QList<QSslError>& errors)
{
bool ignoreErrors = true;
if (m_ServerCert.isNull()) {
// We should never make an HTTPS request without a cert
Q_ASSERT(!m_ServerCert.isNull());
return;
}
for (auto error : errors) {
if (m_ServerCert != error.certificate()) {
ignoreErrors = false;
break;
}
}
if (ignoreErrors) {
reply->ignoreSslErrors(errors);
}
}
QString
NvHTTP::openConnectionToString(QUrl baseUrl,
QString command,
QString arguments,
bool enableTimeout,
int timeoutMs,
NvLogLevel logLevel)
{
QNetworkReply* reply = openConnection(baseUrl, command, arguments, enableTimeout, logLevel);
QNetworkReply* reply = openConnection(baseUrl, command, arguments, timeoutMs, logLevel);
QString ret;
QTextStream stream(reply);
@@ -373,34 +425,43 @@ QNetworkReply*
NvHTTP::openConnection(QUrl baseUrl,
QString command,
QString arguments,
bool enableTimeout,
int timeoutMs,
NvLogLevel logLevel)
{
// Build a URL for the request
QUrl url(baseUrl);
url.setPath("/" + command);
url.setQuery("uniqueid=" + IdentityManager::get()->getUniqueId() +
"&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 = QNetworkRequest(url);
QNetworkRequest request(url);
// Add our client certificate
request.setSslConfiguration(IdentityManager::get()->getSslConfig());
QNetworkReply* reply = m_Nam.get(request);
#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
// Ignore self-signed certificate errors (since GFE uses them)
reply->ignoreSslErrors();
QNetworkReply* reply = m_Nam.get(request);
// Run the request with a timeout if requested
QEventLoop loop;
QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
if (enableTimeout)
{
QTimer::singleShot(REQUEST_TIMEOUT_MS, &loop, SLOT(quit()));
connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
connect(QCoreApplication::instance(), SIGNAL(aboutToQuit()), &loop, SLOT(quit()));
if (timeoutMs) {
QTimer::singleShot(timeoutMs, &loop, SLOT(quit()));
}
if (logLevel >= NvLogLevel::VERBOSE) {
if (logLevel >= NvLogLevel::NVLL_VERBOSE) {
qInfo() << "Executing request:" << url.toString();
}
loop.exec(QEventLoop::ExcludeUserInputEvents);
@@ -408,7 +469,7 @@ NvHTTP::openConnection(QUrl baseUrl,
// Abort the request if it timed out
if (!reply->isFinished())
{
if (logLevel >= NvLogLevel::ERROR) {
if (logLevel >= NvLogLevel::NVLL_ERROR) {
qWarning() << "Aborting timed out request for" << url.toString();
}
reply->abort();
@@ -421,12 +482,27 @@ NvHTTP::openConnection(QUrl baseUrl,
// Handle error
if (reply->error() != QNetworkReply::NoError)
{
if (logLevel >= NvLogLevel::ERROR) {
if (logLevel >= NvLogLevel::NVLL_ERROR) {
qWarning() << command << " request failed with error " << reply->error();
}
QtNetworkReplyException exception(reply->error(), reply->errorString());
delete reply;
throw exception;
if (reply->error() == QNetworkReply::SslHandshakeFailedError) {
// This will trigger falling back to HTTP for the serverinfo query
// then pairing again to get the updated certificate.
GfeHttpResponseException exception(401, "Server certificate mismatch");
delete reply;
throw exception;
}
else if (reply->error() == QNetworkReply::OperationCanceledError) {
QtNetworkReplyException exception(QNetworkReply::TimeoutError, "Request timed out");
delete reply;
throw exception;
}
else {
QtNetworkReplyException exception(reply->error(), reply->errorString());
delete reply;
throw exception;
}
}
return reply;
+22 -29
View File
@@ -1,6 +1,7 @@
#pragma once
#include "identitymanager.h"
#include "nvapp.h"
#include <Limelight.h>
@@ -8,26 +9,6 @@
#include <QNetworkAccessManager>
#include <QNetworkReply>
class NvApp
{
public:
bool operator==(const NvApp& other) const
{
return id == other.id;
}
bool isInitialized()
{
return id != 0 && !name.isEmpty();
}
int id;
QString name;
bool hdrSupported;
};
Q_DECLARE_METATYPE(NvApp)
class NvDisplayMode
{
public:
@@ -113,23 +94,25 @@ private:
QString m_ErrorText;
};
class NvHTTP
class NvHTTP : public QObject
{
Q_OBJECT
public:
enum NvLogLevel {
NONE,
ERROR,
VERBOSE
NVLL_NONE,
NVLL_ERROR,
NVLL_VERBOSE
};
explicit NvHTTP(QString address);
explicit NvHTTP(QString address, QSslCertificate serverCert);
static
int
getCurrentGame(QString serverInfo);
QString
getServerInfo(NvLogLevel logLevel);
getServerInfo(NvLogLevel logLevel, bool fastFail = false);
static
void
@@ -149,8 +132,14 @@ public:
openConnectionToString(QUrl baseUrl,
QString command,
QString arguments,
bool enableTimeout,
NvLogLevel logLevel = NvLogLevel::VERBOSE);
int timeoutMs,
NvLogLevel logLevel = NvLogLevel::NVLL_VERBOSE);
void setServerCert(QSslCertificate serverCert);
void setAddress(QString address);
QString address();
static
QVector<int>
@@ -182,13 +171,17 @@ public:
QUrl m_BaseUrlHttp;
QUrl m_BaseUrlHttps;
private:
void
handleSslErrors(QNetworkReply* reply, const QList<QSslError>& errors);
QNetworkReply*
openConnection(QUrl baseUrl,
QString command,
QString arguments,
bool enableTimeout,
int timeoutMs,
NvLogLevel logLevel);
QString m_Address;
QNetworkAccessManager m_Nam;
QSslCertificate m_ServerCert;
};
+89 -45
View File
@@ -1,15 +1,18 @@
#include "nvpairingmanager.h"
#include "utils.h"
#include <stdexcept>
#include <openssl/bio.h>
#include <openssl/aes.h>
#include <openssl/rand.h>
#include <openssl/pem.h>
#include <openssl/x509.h>
#include <openssl/evp.h>
#define REQUEST_TIMEOUT_MS 5000
NvPairingManager::NvPairingManager(QString address) :
m_Http(address)
m_Http(address, QSslCertificate())
{
QByteArray cert = IdentityManager::get()->getCertificate();
BIO *bio = BIO_new_mem_buf(cert.data(), -1);
@@ -49,39 +52,63 @@ NvPairingManager::generateRandomBytes(int length)
}
QByteArray
NvPairingManager::encrypt(QByteArray plaintext, AES_KEY* key)
NvPairingManager::encrypt(const QByteArray& plaintext, const QByteArray& key)
{
QByteArray ciphertext(plaintext.size(), 0);
EVP_CIPHER_CTX* cipher;
int ciphertextLen;
for (int i = 0; i < plaintext.size(); i += 16)
{
AES_encrypt(reinterpret_cast<unsigned char*>(&plaintext.data()[i]),
reinterpret_cast<unsigned char*>(&ciphertext.data()[i]),
key);
}
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);
EVP_EncryptUpdate(cipher,
reinterpret_cast<unsigned char*>(ciphertext.data()),
&ciphertextLen,
reinterpret_cast<const unsigned char*>(plaintext.data()),
plaintext.length());
Q_ASSERT(ciphertextLen == ciphertext.length());
EVP_CIPHER_CTX_free(cipher);
return ciphertext;
}
QByteArray
NvPairingManager::decrypt(QByteArray ciphertext, AES_KEY* key)
NvPairingManager::decrypt(const QByteArray& ciphertext, const QByteArray& key)
{
QByteArray plaintext(ciphertext.size(), 0);
EVP_CIPHER_CTX* cipher;
int plaintextLen;
for (int i = 0; i < plaintext.size(); i += 16)
{
AES_decrypt(reinterpret_cast<unsigned char*>(&ciphertext.data()[i]),
reinterpret_cast<unsigned char*>(&plaintext.data()[i]),
key);
}
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);
EVP_DecryptUpdate(cipher,
reinterpret_cast<unsigned char*>(plaintext.data()),
&plaintextLen,
reinterpret_cast<const unsigned char*>(ciphertext.data()),
ciphertext.length());
Q_ASSERT(plaintextLen == plaintext.length());
EVP_CIPHER_CTX_free(cipher);
return plaintext;
}
QByteArray
NvPairingManager::getSignatureFromPemCert(QByteArray certificate)
NvPairingManager::getSignatureFromPemCert(const QByteArray& certificate)
{
#if (OPENSSL_VERSION_NUMBER < 0x10100000L)
BIO* bio = BIO_new_mem_buf(const_cast<char*>(certificate.data()), -1);
#else
BIO* bio = BIO_new_mem_buf(certificate.data(), -1);
#endif
THROW_BAD_ALLOC_IF_NULL(bio);
X509* cert = PEM_read_bio_X509(bio, nullptr, nullptr, nullptr);
@@ -105,9 +132,13 @@ NvPairingManager::getSignatureFromPemCert(QByteArray certificate)
}
bool
NvPairingManager::verifySignature(QByteArray data, QByteArray signature, QByteArray serverCertificate)
NvPairingManager::verifySignature(const QByteArray& data, const QByteArray& signature, const QByteArray& serverCertificate)
{
#if (OPENSSL_VERSION_NUMBER < 0x10100000L)
BIO* bio = BIO_new_mem_buf(const_cast<char*>(serverCertificate.data()), -1);
#else
BIO* bio = BIO_new_mem_buf(serverCertificate.data(), -1);
#endif
THROW_BAD_ALLOC_IF_NULL(bio);
X509* cert = PEM_read_bio_X509(bio, nullptr, nullptr, nullptr);
@@ -121,7 +152,7 @@ NvPairingManager::verifySignature(QByteArray data, QByteArray signature, QByteAr
EVP_DigestVerifyInit(mdctx, nullptr, EVP_sha256(), nullptr, pubKey);
EVP_DigestVerifyUpdate(mdctx, data.data(), data.length());
int result = EVP_DigestVerifyFinal(mdctx, reinterpret_cast<unsigned char*>(signature.data()), signature.length());
int result = EVP_DigestVerifyFinal(mdctx, reinterpret_cast<unsigned char*>(const_cast<char*>(signature.data())), signature.length());
EVP_PKEY_free(pubKey);
EVP_MD_CTX_destroy(mdctx);
@@ -131,7 +162,7 @@ NvPairingManager::verifySignature(QByteArray data, QByteArray signature, QByteAr
}
QByteArray
NvPairingManager::signMessage(QByteArray message)
NvPairingManager::signMessage(const QByteArray& message)
{
EVP_MD_CTX *ctx = EVP_MD_CTX_create();
THROW_BAD_ALLOC_IF_NULL(ctx);
@@ -141,7 +172,7 @@ NvPairingManager::signMessage(QByteArray message)
EVP_DigestInit_ex(ctx, md, NULL);
EVP_DigestSignInit(ctx, NULL, md, NULL, m_PrivateKey);
EVP_DigestSignUpdate(ctx, reinterpret_cast<unsigned char*>(message.data()), message.length());
EVP_DigestSignUpdate(ctx, reinterpret_cast<unsigned char*>(const_cast<char*>(message.data())), message.length());
size_t signatureLength = 0;
EVP_DigestSignFinal(ctx, NULL, &signatureLength);
@@ -155,13 +186,13 @@ NvPairingManager::signMessage(QByteArray message)
}
QByteArray
NvPairingManager::saltPin(QByteArray salt, QString pin)
NvPairingManager::saltPin(const QByteArray& salt, QString pin)
{
return QByteArray().append(salt).append(pin.toLatin1());
}
NvPairingManager::PairState
NvPairingManager::pair(QString appVersion, QString pin)
NvPairingManager::pair(QString appVersion, QString pin, QSslCertificate& serverCert)
{
int serverMajorVersion = NvHTTP::parseQuad(appVersion).at(0);
qInfo() << "Pairing with server generation:" << serverMajorVersion;
@@ -184,15 +215,14 @@ NvPairingManager::pair(QString appVersion, QString pin)
QByteArray salt = generateRandomBytes(16);
QByteArray saltedPin = saltPin(salt, pin);
AES_KEY encKey, decKey;
AES_set_decrypt_key(reinterpret_cast<const unsigned char*>(QCryptographicHash::hash(saltedPin, hashAlgo).data()), 128, &decKey);
AES_set_encrypt_key(reinterpret_cast<const unsigned char*>(QCryptographicHash::hash(saltedPin, hashAlgo).data()), 128, &encKey);
QByteArray aesKey = QCryptographicHash::hash(saltedPin, hashAlgo).data();
aesKey.truncate(16);
QString getCert = m_Http.openConnectionToString(m_Http.m_BaseUrlHttp,
"pair",
"devicename=roth&updateState=1&phrase=getservercert&salt=" +
salt.toHex() + "&clientcert=" + IdentityManager::get()->getCertificate().toHex(),
false);
0);
NvHTTP::verifyResponseStatus(getCert);
if (NvHTTP::getXmlString(getCert, "paired") != "1")
{
@@ -200,30 +230,42 @@ NvPairingManager::pair(QString appVersion, QString pin)
return PairState::FAILED;
}
QByteArray serverCert = NvHTTP::getXmlStringFromHex(getCert, "plaincert");
if (serverCert == nullptr)
QByteArray serverCertStr = NvHTTP::getXmlStringFromHex(getCert, "plaincert");
if (serverCertStr == nullptr)
{
qCritical() << "Server likely already pairing";
m_Http.openConnectionToString(m_Http.m_BaseUrlHttp, "unpair", nullptr, true);
m_Http.openConnectionToString(m_Http.m_BaseUrlHttp, "unpair", nullptr, REQUEST_TIMEOUT_MS);
return PairState::ALREADY_IN_PROGRESS;
}
serverCert = QSslCertificate(serverCertStr);
if (serverCert.isNull()) {
Q_ASSERT(!serverCert.isNull());
qCritical() << "Failed to parse plaincert";
m_Http.openConnectionToString(m_Http.m_BaseUrlHttp, "unpair", nullptr, REQUEST_TIMEOUT_MS);
return PairState::FAILED;
}
// Pin this cert for TLS
m_Http.setServerCert(serverCert);
QByteArray randomChallenge = generateRandomBytes(16);
QByteArray encryptedChallenge = encrypt(randomChallenge, &encKey);
QByteArray encryptedChallenge = encrypt(randomChallenge, aesKey);
QString challengeXml = m_Http.openConnectionToString(m_Http.m_BaseUrlHttp,
"pair",
"devicename=roth&updateState=1&clientchallenge=" +
encryptedChallenge.toHex(),
true);
REQUEST_TIMEOUT_MS);
NvHTTP::verifyResponseStatus(challengeXml);
if (NvHTTP::getXmlString(challengeXml, "paired") != "1")
{
qCritical() << "Failed pairing at stage #2";
m_Http.openConnectionToString(m_Http.m_BaseUrlHttp, "unpair", nullptr, true);
m_Http.openConnectionToString(m_Http.m_BaseUrlHttp, "unpair", nullptr, REQUEST_TIMEOUT_MS);
return PairState::FAILED;
}
QByteArray challengeResponseData = decrypt(m_Http.getXmlStringFromHex(challengeXml, "challengeresponse"), &decKey);
QByteArray challengeResponseData = decrypt(m_Http.getXmlStringFromHex(challengeXml, "challengeresponse"), aesKey);
QByteArray clientSecretData = generateRandomBytes(16);
QByteArray challengeResponse;
QByteArray serverResponse(challengeResponseData.data(), hashLength);
@@ -242,17 +284,19 @@ NvPairingManager::pair(QString appVersion, QString pin)
challengeResponse.append(reinterpret_cast<char*>(asnSignature->data), asnSignature->length);
challengeResponse.append(clientSecretData);
QByteArray encryptedChallengeResponseHash = encrypt(QCryptographicHash::hash(challengeResponse, hashAlgo), &encKey);
QByteArray paddedHash = QCryptographicHash::hash(challengeResponse, hashAlgo);
paddedHash.resize(32);
QByteArray encryptedChallengeResponseHash = encrypt(paddedHash, aesKey);
QString respXml = m_Http.openConnectionToString(m_Http.m_BaseUrlHttp,
"pair",
"devicename=roth&updateState=1&serverchallengeresp=" +
encryptedChallengeResponseHash.toHex(),
true);
REQUEST_TIMEOUT_MS);
NvHTTP::verifyResponseStatus(respXml);
if (NvHTTP::getXmlString(respXml, "paired") != "1")
{
qCritical() << "Failed pairing at stage #3";
m_Http.openConnectionToString(m_Http.m_BaseUrlHttp, "unpair", nullptr, true);
m_Http.openConnectionToString(m_Http.m_BaseUrlHttp, "unpair", nullptr, REQUEST_TIMEOUT_MS);
return PairState::FAILED;
}
@@ -262,21 +306,21 @@ NvPairingManager::pair(QString appVersion, QString pin)
if (!verifySignature(serverSecret,
serverSignature,
serverCert))
serverCertStr))
{
qCritical() << "MITM detected";
m_Http.openConnectionToString(m_Http.m_BaseUrlHttp, "unpair", nullptr, true);
m_Http.openConnectionToString(m_Http.m_BaseUrlHttp, "unpair", nullptr, REQUEST_TIMEOUT_MS);
return PairState::FAILED;
}
QByteArray expectedResponseData;
expectedResponseData.append(randomChallenge);
expectedResponseData.append(getSignatureFromPemCert(serverCert));
expectedResponseData.append(getSignatureFromPemCert(serverCertStr));
expectedResponseData.append(serverSecret);
if (QCryptographicHash::hash(expectedResponseData, hashAlgo) != serverResponse)
{
qCritical() << "Incorrect PIN";
m_Http.openConnectionToString(m_Http.m_BaseUrlHttp, "unpair", nullptr, true);
m_Http.openConnectionToString(m_Http.m_BaseUrlHttp, "unpair", nullptr, REQUEST_TIMEOUT_MS);
return PairState::PIN_WRONG;
}
@@ -288,24 +332,24 @@ NvPairingManager::pair(QString appVersion, QString pin)
"pair",
"devicename=roth&updateState=1&clientpairingsecret=" +
clientPairingSecret.toHex(),
true);
REQUEST_TIMEOUT_MS);
NvHTTP::verifyResponseStatus(secretRespXml);
if (NvHTTP::getXmlString(secretRespXml, "paired") != "1")
{
qCritical() << "Failed pairing at stage #4";
m_Http.openConnectionToString(m_Http.m_BaseUrlHttp, "unpair", nullptr, true);
m_Http.openConnectionToString(m_Http.m_BaseUrlHttp, "unpair", nullptr, REQUEST_TIMEOUT_MS);
return PairState::FAILED;
}
QString pairChallengeXml = m_Http.openConnectionToString(m_Http.m_BaseUrlHttps,
"pair",
"devicename=roth&updateState=1&phrase=pairchallenge",
true);
REQUEST_TIMEOUT_MS);
NvHTTP::verifyResponseStatus(pairChallengeXml);
if (NvHTTP::getXmlString(pairChallengeXml, "paired") != "1")
{
qCritical() << "Failed pairing at stage #5";
m_Http.openConnectionToString(m_Http.m_BaseUrlHttp, "unpair", nullptr, true);
m_Http.openConnectionToString(m_Http.m_BaseUrlHttp, "unpair", nullptr, REQUEST_TIMEOUT_MS);
return PairState::FAILED;
}
+7 -8
View File
@@ -3,7 +3,6 @@
#include "identitymanager.h"
#include "nvhttp.h"
#include <openssl/aes.h>
#include <openssl/x509.h>
#include <openssl/evp.h>
@@ -23,29 +22,29 @@ public:
~NvPairingManager();
PairState
pair(QString appVersion, QString pin);
pair(QString appVersion, QString pin, QSslCertificate& serverCert);
private:
QByteArray
generateRandomBytes(int length);
QByteArray
saltPin(QByteArray salt, QString pin);
saltPin(const QByteArray& salt, QString pin);
QByteArray
encrypt(QByteArray plaintext, AES_KEY* key);
encrypt(const QByteArray& plaintext, const QByteArray& key);
QByteArray
decrypt(QByteArray ciphertext, AES_KEY* key);
decrypt(const QByteArray& ciphertext, const QByteArray& key);
QByteArray
getSignatureFromPemCert(QByteArray certificate);
getSignatureFromPemCert(const QByteArray& certificate);
bool
verifySignature(QByteArray data, QByteArray signature, QByteArray serverCertificate);
verifySignature(const QByteArray& data, const QByteArray& signature, const QByteArray& serverCertificate);
QByteArray
signMessage(QByteArray message);
signMessage(const QByteArray& message);
NvHTTP m_Http;
X509* m_Cert;
+67
View File
@@ -0,0 +1,67 @@
#include "richpresencemanager.h"
#include <QDebug>
RichPresenceManager::RichPresenceManager(StreamingPreferences& prefs, QString gameName)
: m_DiscordActive(false)
{
#ifdef HAVE_DISCORD
if (prefs.richPresence) {
DiscordEventHandlers handlers = {};
handlers.ready = discordReady;
handlers.disconnected = discordDisconnected;
handlers.errored = discordErrored;
Discord_Initialize("594668102021677159", &handlers, 0, nullptr);
m_DiscordActive = true;
}
if (m_DiscordActive) {
QByteArray stateStr = (QString("Streaming ") + gameName).toUtf8();
DiscordRichPresence discordPresence = {};
discordPresence.state = stateStr.data();
discordPresence.startTimestamp = time(nullptr);
discordPresence.largeImageKey = "icon";
Discord_UpdatePresence(&discordPresence);
}
#else
Q_UNUSED(prefs)
Q_UNUSED(gameName)
#endif
}
RichPresenceManager::~RichPresenceManager()
{
#ifdef HAVE_DISCORD
if (m_DiscordActive) {
Discord_ClearPresence();
Discord_Shutdown();
}
#endif
}
void RichPresenceManager::runCallbacks()
{
#ifdef HAVE_DISCORD
if (m_DiscordActive) {
Discord_RunCallbacks();
}
#endif
}
#ifdef HAVE_DISCORD
void RichPresenceManager::discordReady(const DiscordUser* request)
{
qInfo() << "Discord integration ready for user:" << request->username;
}
void RichPresenceManager::discordDisconnected(int errorCode, const char *message)
{
qInfo() << "Discord integration disconnected:" << errorCode << message;
}
void RichPresenceManager::discordErrored(int errorCode, const char *message)
{
qWarning() << "Discord integration error:" << errorCode << message;
}
#endif
+26
View File
@@ -0,0 +1,26 @@
#pragma once
#include "settings/streamingpreferences.h"
#ifdef HAVE_DISCORD
#include <discord_rpc.h>
#endif
class RichPresenceManager
{
public:
RichPresenceManager(StreamingPreferences& prefs, QString gameName);
~RichPresenceManager();
void runCallbacks();
private:
#ifdef HAVE_DISCORD
static void discordReady(const DiscordUser* request);
static void discordDisconnected(int errorCode, const char* message);
static void discordErrored(int errorCode, const char* message);
#endif
bool m_DiscordActive;
};
+145
View File
@@ -0,0 +1,145 @@
#include "systemproperties.h"
#include "utils.h"
#include <QGuiApplication>
#include "streaming/session.h"
#include "streaming/streamutils.h"
SystemProperties::SystemProperties()
{
versionString = QString(VERSION_STR);
hasWindowManager = WMUtils::isRunningWindowManager();
isRunningWayland = WMUtils::isRunningWayland();
isRunningXWayland = isRunningWayland && QGuiApplication::platformName() == "xcb";
#ifdef Q_OS_WIN32
isWow64 = QSysInfo::currentCpuArchitecture() != QSysInfo::buildCpuArchitecture();
#else
isWow64 = false;
#endif
#ifndef STEAM_LINK
// Assume we can probably launch a browser if we're in a GUI environment
hasBrowser = hasWindowManager;
#else
hasBrowser = false;
#endif
#ifdef HAVE_DISCORD
hasDiscordIntegration = true;
#else
hasDiscordIntegration = false;
#endif
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());
}
QRect SystemProperties::getDesktopResolution(int displayIndex)
{
// 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
return monitorNativeResolutions.value(displayIndex);
}
void SystemProperties::querySdlVideoInfo()
{
monitorDesktopResolutions.clear();
monitorNativeResolutions.clear();
hasHardwareAcceleration = false;
// Never let the maximum drop below 60 FPS
maximumStreamingFrameRate = 60;
if (SDL_InitSubSystem(SDL_INIT_VIDEO) != 0) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
"SDL_InitSubSystem(SDL_INIT_VIDEO) failed: %s",
SDL_GetError());
return;
}
SDL_DisplayMode bestMode;
for (int displayIndex = 0; displayIndex < SDL_GetNumVideoDisplays(); displayIndex++) {
SDL_DisplayMode desktopMode;
int err;
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));
}
else {
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION,
"Skipping resolution over 8K: %dx%d",
desktopMode.w, desktopMode.h);
}
// Start at desktop mode and work our way up
bestMode = desktopMode;
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) {
if (mode.refresh_rate > bestMode.refresh_rate) {
bestMode = mode;
}
}
}
}
maximumStreamingFrameRate = qMax(maximumStreamingFrameRate, bestMode.refresh_rate);
}
}
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, maximumResolution);
SDL_DestroyWindow(testWindow);
SDL_QuitSubSystem(SDL_INIT_VIDEO);
}
+50
View File
@@ -0,0 +1,50 @@
#pragma once
#include <QObject>
#include <QRect>
class SystemProperties : public QObject
{
Q_OBJECT
public:
SystemProperties();
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)
Q_PROPERTY(bool hasWindowManager MEMBER hasWindowManager CONSTANT)
Q_PROPERTY(bool hasBrowser MEMBER hasBrowser CONSTANT)
Q_PROPERTY(bool hasDiscordIntegration MEMBER hasDiscordIntegration CONSTANT)
Q_PROPERTY(QString unmappedGamepads MEMBER unmappedGamepads NOTIFY unmappedGamepadsChanged)
Q_PROPERTY(int maximumStreamingFrameRate MEMBER maximumStreamingFrameRate CONSTANT)
Q_PROPERTY(QSize maximumResolution MEMBER maximumResolution CONSTANT)
Q_PROPERTY(QString versionString MEMBER versionString CONSTANT)
Q_INVOKABLE QRect getDesktopResolution(int displayIndex);
Q_INVOKABLE QRect getNativeResolution(int displayIndex);
signals:
void unmappedGamepadsChanged();
private:
void querySdlVideoInfo();
bool hasHardwareAcceleration;
bool rendererAlwaysFullScreen;
bool isRunningWayland;
bool isRunningXWayland;
bool isWow64;
bool hasWindowManager;
bool hasBrowser;
bool hasDiscordIntegration;
QString unmappedGamepads;
int maximumStreamingFrameRate;
QSize maximumResolution;
QList<QRect> monitorDesktopResolutions;
QList<QRect> monitorNativeResolutions;
QString versionString;
};
+47 -14
View File
@@ -59,7 +59,7 @@ public:
void showMessage(QString message, MessageType type) const
{
#if defined(Q_OS_WIN)
#if defined(Q_OS_WIN32)
UINT flags = MB_OK | MB_TOPMOST | MB_SETFOREGROUND;
flags |= (type == Info ? MB_ICONINFORMATION : MB_ICONERROR);
QString title = "Moonlight";
@@ -172,20 +172,31 @@ GlobalCommandLineParser::ParseResult GlobalCommandLineParser::parse(const QStrin
parser.addPositionalArgument("action", "Action to execute", "<action>");
parser.parse(args);
auto posArgs = parser.positionalArguments();
QString action = posArgs.isEmpty() ? QString() : posArgs.first().toLower();
if (action == "") {
if (posArgs.isEmpty()) {
// This method will not return and terminates the process if --version
// or --help is specified
parser.handleHelpAndVersionOptions();
parser.handleUnknownOptions();
return NormalStartRequested;
} else if (action == "quit") {
return QuitRequested;
} else if (action == "stream") {
return StreamRequested;
} else {
parser.showError(QString("Invalid action: %1").arg(action));
}
else {
// If users supply arguments that accept values prior to the "quit"
// or "stream" positional arguments, we will not be able to correctly
// parse the value out of the input because this QCommandLineParser
// doesn't know about all of the options that "quit" and "stream"
// commands can accept. To work around this issue, we just look
// for "quit" or "stream" positional arguments anywhere.
for (int i = 0; i < posArgs.size(); i++) {
QString action = posArgs.at(i).toLower();
if (action == "quit") {
return QuitRequested;
} else if (action == "stream") {
return StreamRequested;
}
}
parser.showError(QString("Invalid action"));
}
}
@@ -241,6 +252,7 @@ StreamCommandLineParser::StreamCommandLineParser()
m_AudioConfigMap = {
{"stereo", StreamingPreferences::AC_STEREO},
{"5.1-surround", StreamingPreferences::AC_51_SURROUND},
{"7.1-surround", StreamingPreferences::AC_71_SURROUND},
};
m_VideoCodecMap = {
{"auto", StreamingPreferences::VCC_AUTO},
@@ -249,8 +261,8 @@ StreamCommandLineParser::StreamCommandLineParser()
};
m_VideoDecoderMap = {
{"auto", StreamingPreferences::VDS_AUTO},
{"software", StreamingPreferences::VDS_FORCE_HARDWARE},
{"hardware", StreamingPreferences::VDS_FORCE_SOFTWARE},
{"software", StreamingPreferences::VDS_FORCE_SOFTWARE},
{"hardware", StreamingPreferences::VDS_FORCE_HARDWARE},
};
}
@@ -280,13 +292,17 @@ void StreamCommandLineParser::parse(const QStringList &args, StreamingPreference
parser.addToggleOption("vsync", "V-Sync");
parser.addValueOption("fps", "FPS");
parser.addValueOption("bitrate", "bitrate in Kbps");
parser.addValueOption("packet-size", "video packet size");
parser.addChoiceOption("display-mode", "display mode", m_WindowModeMap.keys());
parser.addChoiceOption("audio-config", "audio config", m_AudioConfigMap.keys());
parser.addToggleOption("multi-controller", "multiple controller support");
parser.addToggleOption("quit-after", "quit app after session");
parser.addToggleOption("mouse-acceleration", "mouse acceleration");
parser.addToggleOption("absolute-mouse", "remote desktop optimized mouse control");
parser.addToggleOption("mouse-buttons-swap", "left and right mouse buttons swap");
parser.addToggleOption("touchscreen-trackpad", "touchscreen in trackpad mode");
parser.addToggleOption("game-optimization", "game optimizations");
parser.addToggleOption("audio-on-host", "audio on host PC");
parser.addToggleOption("frame-pacing", "frame pacing");
parser.addChoiceOption("video-codec", "video codec", m_VideoCodecMap.keys());
parser.addChoiceOption("video-decoder", "video decoder", m_VideoDecoderMap.keys());
@@ -344,6 +360,14 @@ void StreamCommandLineParser::parse(const QStringList &args, StreamingPreference
preferences->width, preferences->height, preferences->fps);
}
// Resolve --packet-size option
if (parser.isSet("packet-size")) {
preferences->packetSize = parser.getIntOption("packet-size");
if (preferences->packetSize < 1024) {
parser.showError("Packet size must be greater than 1024 bytes");
}
}
// Resolve --display option
if (parser.isSet("display-mode")) {
preferences->windowMode = mapValue(m_WindowModeMap, parser.getChoiceOptionValue("display-mode"));
@@ -363,8 +387,14 @@ void StreamCommandLineParser::parse(const QStringList &args, StreamingPreference
// Resolve --quit-after and --no-quit-after options
preferences->quitAppAfter = parser.getToggleOptionValue("quit-after", preferences->quitAppAfter);
// Resolve --mouse-acceleration and --no-mouse-acceleration options
preferences->mouseAcceleration = parser.getToggleOptionValue("mouse-acceleration", preferences->mouseAcceleration);
// Resolve --absolute-mouse and --no-absolute-mouse options
preferences->absoluteMouseMode = parser.getToggleOptionValue("absolute-mouse", preferences->absoluteMouseMode);
// Resolve --mouse-buttons-swap and --no-mouse-buttons-swap options
preferences->swapMouseButtons = parser.getToggleOptionValue("mouse-buttons-swap", preferences->swapMouseButtons);
// Resolve --touchscreen-trackpad and --no-touchscreen-trackpad options
preferences->absoluteTouchMode = !parser.getToggleOptionValue("touchscreen-trackpad", !preferences->absoluteTouchMode);
// Resolve --game-optimization and --no-game-optimization options
preferences->gameOptimizations = parser.getToggleOptionValue("game-optimization", preferences->gameOptimizations);
@@ -372,6 +402,9 @@ void StreamCommandLineParser::parse(const QStringList &args, StreamingPreference
// Resolve --audio-on-host and --no-audio-on-host options
preferences->playAudioOnHost = parser.getToggleOptionValue("audio-on-host", preferences->playAudioOnHost);
// Resolve --frame-pacing and --no-frame-pacing options
preferences->framePacing = parser.getToggleOptionValue("frame-pacing", preferences->framePacing);
// Resolve --video-codec option
if (parser.isSet("video-codec")) {
preferences->videoCodecConfig = mapValue(m_VideoCodecMap, parser.getChoiceOptionValue("video-codec"));
@@ -4,18 +4,20 @@
<metadata_license>CC0-1.0</metadata_license>
<project_license>GPL-3.0+</project_license>
<name>Moonlight</name>
<summary>Stream games from your NVIDIA GameStream-enabled PC</summary>
<summary>Play games remotely from your NVIDIA GameStream-enabled PC</summary>
<description>
<p>Moonlight can stream games and other applications from a PC with an NVIDIA GeForce GTX 600-series or higher GPU and GeForce Experience 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>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 and VDPAU support</li>
<li>5.1 surround sound audio support</li>
<li>Hardware accelerated video decoding with VAAPI, VDPAU, and NVDEC support</li>
<li>7.1 surround sound audio support</li>
<li>Support for both pointer capture (for games) and direct mouse control (for remote desktop)</li>
<li>Direct touchscreen mouse control</li>
<li>HEVC support for better video compression efficiency</li>
<li>Gamepad support with SDL mapping compatibility</li>
<li>Gamepad support with force feedback for up to 4 players</li>
</ul>
</description>
@@ -33,6 +35,246 @@
</screenshots>
<releases>
<release version="2.2.0" date="2020-09-10">
<description>
<p>New features:</p>
<ul>
<li>Added the ability to hide unwanted apps and games</li>
<li>Added a network test to determine if your Internet connection is blocking Moonlight</li>
<li>Added the option to swap mouse buttons</li>
<li>Added codec and resolution to the on-screen performance stats</li>
<li>Added a warning if the connection is too unstable to receive any complete video frames</li>
<li>Added a Discord link to the toolbar in settings</li>
<li>Enabled the new EGL renderer by default on Linux</li>
</ul>
<p>Bugfixes:</p>
<ul>
<li>Fixed streaming over networks that block QoS-tagged packets</li>
<li>Selecting a frame rate higher than 60 FPS no longer sets the host desktop to 720p</li>
<li>Right-side modifier keys no longer press the corresponding left-side keys too</li>
<li>Fixed mouse position never reaching the edge of the screen with certain desktop resolutions</li>
<li>Improved synchronization between host and client mouse cursor in remote desktop mouse mode</li>
<li>Cached box art is now deleted when the PC is removed from Moonlight</li>
<li>Fixed several CLI options not properly overriding GUI options</li>
<li>Updated included gamepad mappings</li>
<li>Updated to Qt 5.15.1</li>
</ul>
</description>
</release>
<release version="2.1.0" date="2020-05-17">
<description>
<p>New features:</p>
<ul>
<li>Remote desktop mode now allows interaction with the host without having to click to focus the Moonlight window first</li>
<li>Added a new EGL renderer for improved performance on Wayland and XWayland</li>
<li>Added the option to toggle between direct touchscreen mode and the old trackpad mode</li>
<li>Added the option to rename host PCs</li>
<li>Added the ability to scroll the settings page with the right analog stick</li>
<li>Various UI improvements</li>
</ul>
<p>Bugfixes:</p>
<ul>
<li>Fixed unreliable mouse capture when the stream begins</li>
<li>Fixed cursor being trapped in full-screen mode even when the mouse wasn't captured</li>
<li>Fixed key presses not being sent to the host if the Super/Meta/Windows key is pressed</li>
<li>Updated included gamepad mappings</li>
</ul>
</description>
</release>
<release version="2.0.0" date="2020-04-28">
<description>
<p>New features:</p>
<ul>
<li>Remote desktop-optimized mouse mode which doesn't require capturing the mouse cursor</li>
<li>Touchscreen input now directly controls the mouse cursor</li>
<li>7.1 surround sound support</li>
</ul>
<p>Bugfixes:</p>
<ul>
<li>Improved performance on some lossy networks</li>
<li>Fixed disconnect delay when streaming from GeForce Experience 3.20.3.63</li>
<li>Fixed frame rate not exceeding 60 when streaming from GeForce Experience 3.20.3.63</li>
<li>Fixed parsing of command-line options when passing flags prior to the action</li>
<li>Fixed an issue that may cause excessive mDNS network traffic while Moonlight is running</li>
<li>Fixed hardware decoding on Intel GPUs running Mesa 20.0 and/or the Iris driver</li>
<li>Fixed hardware decoding on Comet Lake and later Intel GPUs using the iHD VA-API driver</li>
<li>Fixed hardware decoding on AMD Radeon GPUs with XWayland</li>
<li>Fixed a crash when using the iHD VA-API driver on Wayland</li>
<li>Fixed delay after exiting the stream on Wayland</li>
<li>Updated included gamepad mappings</li>
</ul>
</description>
</release>
<release version="1.2.0" date="2019-12-17">
<description>
<p>Bugfixes:</p>
<ul>
<li>Improved video encoding efficiency</li>
<li>Improved performance when streaming over a VPN</li>
<li>Fixed RTSP handshake error on certain networks</li>
<li>Fixed rumble not working on certain gamepads</li>
<li>Fixed pairing error when double-clicking on an unpaired PC</li>
<li>Updated included SDL gamepad mappings</li>
</ul>
</description>
</release>
<release version="1.1.1" date="2019-09-29">
<description>
<p>Bugfixes:</p>
<ul>
<li>Improved reliability of public IP address detection</li>
<li>Fixed connecting to a host PC with multiple network connections</li>
<li>Fixed a hang after exiting a full-screen stream with GNOME on Wayland</li>
<li>Fixed gamepad hotplugging</li>
<li>Updated to SDL 2.0.10</li>
<li>Updated to Qt 5.13.1</li>
</ul>
</description>
</release>
<release version="1.1.0" date="2019-08-05">
<description>
<p>New features:</p>
<ul>
<li>Added support for NVDEC for NVIDIA GPUs on Wayland</li>
<li>Added an option to disable gamepad mouse mode for games that require holding the Start button</li>
<li>Added automatic detection of IPv6 addresses for Internet streaming over IPv6 networks</li>
</ul>
<p>Bugfixes:</p>
<ul>
<li>Improved speed and reliability of automatic PC detection on the local network</li>
<li>Fixed audio latency increasing under certain network conditions</li>
<li>Fixed 5.1 surround sound sometimes causing no audio to play when streaming over the Internet</li>
<li>Fixed graceful termination of games not being detected properly on GFE 3.19</li>
<li>Fixed several audio issues on Linux by switching back to SDL for audio</li>
<li>Changed client certificate signature algorithm from SHA-1 to SHA-256 for Debian Buster compatibility</li>
<li>Updated included gamepad mappings</li>
</ul>
</description>
</release>
<release version="1.0.1" date="2019-05-27">
<description>
<p>Bugfixes:</p>
<ul>
<li>Fixed broken video on GeForce Experience 3.19</li>
</ul>
</description>
</release>
<release version="1.0.0" date="2019-05-21">
<description>
<p>New features:</p>
<ul>
<li>Mouse mode for gamepads (Press and hold Start to toggle)</li>
<li>Improved gamepad UI navigation</li>
</ul>
<p>Bugfixes:</p>
<ul>
<li>Fixed duplicate non-working gamepads appearing on the host</li>
<li>Fixed excessive frame queue delay on macOS</li>
<li>Fixed excessive audio latency on Steam Link</li>
<li>Fixed hiding mouse cursor after streaming on Steam Link</li>
<li>Fixed incorrect receive time stats on 32-bit platforms</li>
<li>Added UDP ports 48002 and 48010 for Wake-on-LAN</li>
<li>Updated included gamepad mappings</li>
</ul>
</description>
</release>
<release version="0.10.1" date="2019-04-28">
<description>
<p>New features:</p>
<ul>
<li>Video performance optimizations</li>
<li>VAAPI support on Wayland</li>
</ul>
<p>Bugfixes:</p>
<ul>
<li>Fixed a crash when attempting to dismiss the connection terminated dialog</li>
<li>Fixed a crash when using the overlay on the software decoder</li>
<li>Fixed software decoder not displaying output in some cases</li>
<li>Fixed some minor UI issues on the PC grid</li>
<li>Improved visibility of toolbar highlights</li>
</ul>
</description>
</release>
<release version="0.10.0" date="2019-04-07">
<description>
<p>New features:</p>
<ul>
<li>Redesigned App Grid with larger game artwork and less blank space</li>
<li>Redesigned UI dialogs using Material Design</li>
<li>Added a connection warning overlay (which can be disabled in settings)</li>
<li>Streaming window no longer minimizes when it loses focus in full-screen mode</li>
<li>The Steam Link device is now a supported platform</li>
</ul>
<p>Bugfixes:</p>
<ul>
<li>Fixed several bugs that could cause UI hangs or lag</li>
<li>Fixed rumble support on gamepads with limited rumble motor control</li>
<li>Fixed increased memory usage if the software renderer gets delayed</li>
<li>Fixed crashes on certain desktop configurations when loading the UI</li>
<li>Fixed handling of pairing certificates with a bogus date</li>
</ul>
</description>
</release>
<release version="0.9.1" date="2019-02-17">
<description>
<p>New features:</p>
<ul>
<li>Added gamepad rumble support</li>
<li>Added a dedicated quit button to the running app tile</li>
<li>Reduced video latency on Windows and Linux</li>
<li>Added a performance overlay for software decoding</li>
</ul>
<p>Bugfixes:</p>
<ul>
<li>Fixed delayed first video frame with GFE 3.17</li>
<li>Fixed erroneously setting host resolution to 720p in certain configurations</li>
<li>The connection termination dialog is no longer displayed for intentional termination</li>
<li>Fixed some gamepads only functioning for UI navigation and not in game</li>
<li>Fixed audio latency increasing when switching audio devices</li>
<li>Fixed VDPAU scaling behavior on AMD cards</li>
<li>Fixed several bugs in gamepad navigation behavior</li>
<li>Work around a bug in QGnomePlatform that breaks dialog rendering on Linux</li>
<li>Updated included SDL gamepad mappings</li>
<li>Fixed hotkey behavior on non-latin keyboards</li>
<li>Fixed incorrect frame drop percentages in debug stats</li>
</ul>
</description>
</release>
<release version="0.8.1" date="2019-01-08">
<description>
<p>New features:</p>
<ul>
<li>Stricter adherence to the specified bitrate when streaming over the Internet</li>
</ul>
<p>Bugfixes:</p>
<ul>
<li>Fixed audio crackling that impacted certain systems</li>
<li>Fixed Wake-on-LAN packets failing to send on some systems</li>
<li>Reduced audio latency when resuming a session where audio is already playing</li>
<li>Added option to enable the old SDL audio renderer by setting ML_AUDIO=SDL</li>
<li>Updated to use the new Qt 5.12 Flatpak runtime</li>
<li>Updated to FFmpeg 4.1</li>
<li>Minor UI tweaks</li>
</ul>
</description>
</release>
<release version="0.8.0" date="2018-12-25">
<description>
<p>New features:</p>
<ul>
<li>Improved security of pairing - After this update, you must re-pair with your PC!</li>
<li>Enabled quitting games started by other Moonlight clients also running this update</li>
</ul>
<p>Bugfixes:</p>
<ul>
<li>Fixed the video bitrate slider not working above certain values on GFE 3.16</li>
<li>Fixed broken Bluetooth audio with PulseAudio</li>
<li>Reduced audio latency</li>
<li>Fixed some non-gamepad devices triggering the unmapped gamepad dialog box</li>
<li>Minor UI tweaks</li>
</ul>
</description>
</release>
<release version="0.7.0" date="2018-12-05">
<description>
<p>New features:</p>
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.9 KiB

+23
View File
@@ -0,0 +1,23 @@
#!/bin/sh
# The default HOME is not persistent, so override
# it to a path on the onboard flash. Otherwise our
# pairing data will be lost each reboot.
HOME=/usr/local/moonlight
# For a seamless transition across the Qt 5.9 -> Qt 5.14 boundary,
# we bundle binaries built with both Qt 5.9 and Qt 5.14 and pick
# the correct one at runtime.
if [ -d "/usr/local/Qt-5.14.1" ]; then
BIN="moonlight"
else
BIN="moonlight59"
fi
# 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
echo Launching $BIN
exec nice -n -10 ./bin/$BIN > /tmp/moonlight.log
+3
View File
@@ -0,0 +1,3 @@
name=Moonlight
icon=moonlight.png
run=moonlight.sh
+178 -94
View File
@@ -1,29 +1,22 @@
import QtQuick 2.9
import QtQuick.Dialogs 1.2
import QtQuick.Controls 2.2
import AppModel 1.0
import ComputerManager 1.0
import SdlGamepadKeyNavigation 1.0
GridView {
CenteredGridView {
property int computerIndex
property AppModel appModel : createModel()
property bool activated
property bool showHiddenGames
id: appGrid
focus: true
activeFocusOnTab: true
anchors.fill: parent
anchors.leftMargin: (parent.width % (cellWidth + anchors.rightMargin)) / 2
anchors.topMargin: 20
anchors.rightMargin: 5
anchors.bottomMargin: 5
cellWidth: 225; cellHeight: 385;
// The StackView will trigger a visibility change when
// we're pushed onto it, causing our onVisibleChanged
// routine to run, but only if we start as invisible
visible: false
topMargin: 20
bottomMargin: 5
cellWidth: 230; cellHeight: 297;
function computerLost()
{
@@ -32,85 +25,152 @@ GridView {
}
Component.onCompleted: {
// Don't show any highlighted item until interacting with them
// Don't show any highlighted item until interacting with them.
// We do this here instead of onActivated to avoid losing the user's
// selection when backing out of a different page of the app.
currentIndex = -1
}
SdlGamepadKeyNavigation {
id: gamepadKeyNav
StackView.onActivated: {
appModel.computerLost.connect(computerLost)
activated = true
// Highlight the first item if a gamepad is connected
if (currentIndex == -1 && SdlGamepadKeyNavigation.getConnectedGamepads() > 0) {
currentIndex = 0
}
}
onVisibleChanged: {
if (visible) {
appModel.computerLost.connect(computerLost)
gamepadKeyNav.enable()
}
else {
appModel.computerLost.disconnect(computerLost)
gamepadKeyNav.disable()
}
StackView.onDeactivating: {
appModel.computerLost.disconnect(computerLost)
activated = false
}
function createModel()
{
var model = Qt.createQmlObject('import AppModel 1.0; AppModel {}', parent, '')
model.initialize(ComputerManager, computerIndex)
model.initialize(ComputerManager, computerIndex, showHiddenGames)
return model
}
model: appModel
delegate: NavigableItemDelegate {
width: 200; height: 335;
width: 220; height: 287;
grid: appGrid
// Dim the app if it's hidden
opacity: model.hidden ? 0.4 : 1.0
Image {
property bool isPlaceholder: false
id: appIcon
anchors.horizontalCenter: parent.horizontalCenter;
y: 20
anchors.horizontalCenter: parent.horizontalCenter
y: 10
source: model.boxart
sourceSize {
width: 150
height: 200
}
width: sourceSize.width
height: sourceSize.height
fillMode: Image.Pad
}
Image {
id: runningIcon
anchors.centerIn: appIcon
visible: model.running
source: "qrc:/res/baseline-play_circle_filled_white-48px.svg"
sourceSize {
width: 75
height: 75
}
}
onSourceSizeChanged: {
if ((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
}
else
{
isPlaceholder = false
}
Label {
id: appNameText
text: model.name
width: parent.width
height: 125
anchors.top: appIcon.bottom
font.pointSize: 22
horizontalAlignment: Text.AlignHCenter
wrapMode: Text.Wrap
elide: Text.ElideRight
width = 200
height = 267
}
// Display a tooltip with the full name if it's truncated
ToolTip.text: model.name
ToolTip.delay: 1000
ToolTip.timeout: 5000
ToolTip.visible: (parent.hovered || parent.highlighted) && truncated
ToolTip.visible: (parent.hovered || parent.highlighted) && (!appNameText.visible || appNameText.truncated)
}
ToolButton {
id: resumeButton
anchors.horizontalCenterOffset: appIcon.isPlaceholder ? -47 : 0
anchors.verticalCenterOffset: appIcon.isPlaceholder ? -75 : -60
anchors.centerIn: appIcon
visible: model.running
implicitWidth: 125
implicitHeight: 125
Image {
source: "qrc:/res/baseline-play_circle_filled_white-48px.svg"
anchors.centerIn: parent
sourceSize {
width: 75
height: 75
}
}
onClicked: {
launchOrResumeSelectedApp()
}
ToolTip.text: "Resume Game"
ToolTip.delay: 1000
ToolTip.timeout: 3000
ToolTip.visible: hovered
}
ToolButton {
id: quitButton
anchors.horizontalCenterOffset: appIcon.isPlaceholder ? 47 : 0
anchors.verticalCenterOffset: appIcon.isPlaceholder ? -75 : 60
anchors.centerIn: appIcon
visible: model.running
implicitWidth: 125
implicitHeight: 125
Image {
source: "qrc:/res/baseline-cancel-24px.svg"
anchors.centerIn: parent
sourceSize {
width: 75
height: 75
}
}
onClicked: {
doQuitGame()
}
ToolTip.text: "Quit Game"
ToolTip.delay: 1000
ToolTip.timeout: 3000
ToolTip.visible: hovered
}
Label {
id: appNameText
visible: appIcon.isPlaceholder
text: model.name
width: appIcon.width
height: model.running ? 175 : appIcon.height
leftPadding: 20
rightPadding: 20
anchors.left: appIcon.left
anchors.right: appIcon.right
anchors.bottom: appIcon.bottom
font.pointSize: 22
verticalAlignment: Text.AlignVCenter
horizontalAlignment: Text.AlignHCenter
wrapMode: Text.Wrap
elide: Text.ElideRight
}
function launchOrResumeSelectedApp()
{
var runningIndex = appModel.getRunningAppIndex()
if (runningIndex >= 0 && runningIndex !== index) {
var runningId = appModel.getRunningAppId()
if (runningId !== 0 && runningId !== model.appid) {
quitAppDialog.appName = appModel.getRunningAppName()
quitAppDialog.segueToStream = true
quitAppDialog.nextAppName = model.name
@@ -125,55 +185,91 @@ GridView {
}
onClicked: {
// Nothing is running or this app is running
launchOrResumeSelectedApp()
// Only allow clicking on the box art for non-running games.
// For running games, buttons will appear to resume or quit which
// will handle starting the game and clicks on the box art will
// be ignored.
if (!model.running) {
launchOrResumeSelectedApp()
}
}
onPressAndHold: {
// popup() ensures the menu appears under the mouse cursor
if (appContextMenu.popup) {
appContextMenu.popup()
}
else {
// Qt 5.9 doesn't have popup()
appContextMenu.open()
}
}
MouseArea {
anchors.fill: parent
acceptedButtons: Qt.RightButton
acceptedButtons: Qt.RightButton;
onClicked: {
// popup() ensures the menu appears under the mouse cursor
appContextMenu.popup()
parent.onPressAndHold()
}
}
Keys.onReturnPressed: {
// Open the app context menu if activated via the gamepad or keyboard
// for running games. If the game isn't running, the above onClicked
// method will handle the launch.
if (model.running) {
// This will be keyboard/gamepad driven so use
// open() instead of popup()
appContextMenu.open()
}
}
Keys.onMenuPressed: {
// We must use open() here so the menu is positioned on
// the ItemDelegate and not where the mouse cursor is
appContextMenu.open()
if (model.running) {
// This will be keyboard/gamepad driven so use
// open() instead of popup()
appContextMenu.open()
}
}
Menu {
function doQuitGame() {
quitAppDialog.appName = appModel.getRunningAppName()
quitAppDialog.segueToStream = false
quitAppDialog.open()
}
NavigableMenu {
id: appContextMenu
NavigableMenuItem {
parentMenu: appContextMenu
text: model.running ? "Resume Game" : "Launch Game"
onTriggered: {
appContextMenu.close()
launchOrResumeSelectedApp()
}
onTriggered: launchOrResumeSelectedApp()
}
NavigableMenuItem {
parentMenu: appContextMenu
text: "Quit Game"
onTriggered: {
quitAppDialog.appName = appModel.getRunningAppName()
quitAppDialog.segueToStream = false
quitAppDialog.open()
}
onTriggered: doQuitGame()
visible: model.running
}
NavigableMenuItem {
parentMenu: appContextMenu
checkable: true
checked: model.hidden
text: "Hide Game"
onTriggered: appModel.setAppHidden(model.index, !model.hidden)
visible: !model.running || model.hidden
}
}
}
MessageDialog {
NavigableMessageDialog {
id: quitAppDialog
modality:Qt.WindowModal
property string appName : ""
property bool segueToStream : false
property string nextAppName: ""
property int nextAppIndex: 0
text:"Are you sure you want to quit " + appName +"? Any unsaved progress will be lost."
standardButtons: StandardButton.Yes | StandardButton.No
standardButtons: Dialog.Yes | Dialog.No
function quitApp() {
var component = Qt.createComponent("QuitSegue.qml")
@@ -195,20 +291,8 @@ GridView {
appModel.quitRunningApp()
}
onYes: quitApp()
// For keyboard/gamepad navigation
onAccepted: quitApp()
}
ScrollBar.vertical: ScrollBar {
parent: appGrid.parent
anchors {
top: appGrid.top
left: appGrid.right
bottom: appGrid.bottom
leftMargin: -10
}
}
ScrollBar.vertical: ScrollBar {}
}
+14 -1
View File
@@ -1,11 +1,15 @@
import QtQuick 2.9
import QtQuick.Controls 2.2
import SdlGamepadKeyNavigation 1.0
// https://stackoverflow.com/questions/45029968/how-do-i-set-the-combobox-width-to-fit-the-largest-item
ComboBox {
property int textWidth
property int desiredWidth : leftPadding + textWidth + indicator.width + rightPadding
property int maximumWidth : parent.width
implicitWidth: leftPadding + textWidth + indicator.width + rightPadding
implicitWidth: desiredWidth < maximumWidth ? desiredWidth : maximumWidth
TextMetrics {
id: popupMetrics
@@ -28,4 +32,13 @@ ComboBox {
textWidth = Math.max(popupMetrics.width, textWidth)
}
}
popup.onAboutToShow: {
// Switch to normal navigation for combo boxes
SdlGamepadKeyNavigation.setUiNavMode(false)
}
popup.onAboutToHide: {
SdlGamepadKeyNavigation.setUiNavMode(true)
}
}
+43
View File
@@ -0,0 +1,43 @@
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
property real horizontalMargin: itemsPerRow < count && availableWidth >= cellWidth ?
(availableWidth % cellWidth) / 2 : minMargin
function updateMargins() {
leftMargin = horizontalMargin
rightMargin = horizontalMargin
if (hasBrokenMargins) {
anchors.leftMargin = leftMargin
anchors.rightMargin = rightMargin
}
}
onHorizontalMarginChanged: {
updateMargins()
}
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()
}
boundsBehavior: Flickable.OvershootBounds
}
+5 -18
View File
@@ -1,13 +1,10 @@
import QtQuick 2.0
import QtQuick.Controls 2.2
import QtQuick.Dialogs 1.2
import ComputerManager 1.0
import Session 1.0
Item {
anchors.fill: parent
function onSearchingComputer() {
stageLabel.text = "Establishing connection to PC..."
}
@@ -21,13 +18,8 @@ Item {
errorDialog.open()
}
// The StackView will trigger a visibility change when
// we're pushed onto it, causing our onVisibleChanged
// routine to run, but only if we start as invisible
visible: false
onVisibleChanged: {
if (visible && !launcher.isExecuted()) {
StackView.onActivated: {
if (!launcher.isExecuted()) {
toolBar.visible = false
launcher.searchingComputer.connect(onSearchingComputer)
launcher.quittingApp.connect(onQuittingApp)
@@ -55,16 +47,11 @@ Item {
}
}
MessageDialog {
ErrorMessageDialog {
id: errorDialog
modality:Qt.WindowModal
icon: StandardIcon.Critical
standardButtons: StandardButton.Ok
onVisibleChanged: {
if (!visible) {
Qt.quit()
}
onClosed: {
Qt.quit()
}
}
}
+15 -43
View File
@@ -1,13 +1,10 @@
import QtQml 2.2
import QtQuick 2.0
import QtQuick.Controls 2.2
import QtQuick.Dialogs 1.2
import ComputerManager 1.0
import SdlGamepadKeyNavigation 1.0
Item {
visible: false
function onSearchingComputer() {
stageLabel.text = "Establishing connection to PC..."
}
@@ -36,9 +33,14 @@ Item {
quitAppDialog.open()
}
onVisibleChanged: {
if (visible && !launcher.isExecuted()) {
StackView.onActivated: {
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)
@@ -66,26 +68,18 @@ Item {
}
}
MessageDialog {
ErrorMessageDialog {
id: errorDialog
modality:Qt.WindowModal
icon: StandardIcon.Critical
standardButtons: StandardButton.Ok | StandardButton.Help
onHelp: {
Qt.openUrlExternally("https://github.com/moonlight-stream/moonlight-docs/wiki/Troubleshooting");
}
onVisibleChanged: {
if (!visible) {
Qt.quit();
}
onClosed: {
Qt.quit();
}
}
MessageDialog {
NavigableMessageDialog {
id: quitAppDialog
modality:Qt.WindowModal
text:"Are you sure you want to quit " + appName +"? Any unsaved progress will be lost."
standardButtons: StandardButton.Yes | StandardButton.No
standardButtons: Dialog.Yes | Dialog.No
property string appName : ""
function quitApp() {
@@ -96,29 +90,7 @@ Item {
launcher.quitRunningApp()
}
onYes: quitApp()
// For keyboard/gamepad navigation
onAccepted: quitApp()
// Exit process if app quit is rejected (reacts also to closing of the
// dialog from title bar's close button).
// Note: this depends on undocumented behavior of visibleChanged()
// signal being emitted before yes() or accepted() has been emitted.
onVisibleChanged: {
if (!visible) {
quitTimer.start()
}
}
Component.onCompleted: {
yes.connect(quitTimer.stop)
accepted.connect(quitTimer.stop)
}
}
Timer {
id: quitTimer
interval: 100
onTriggered: Qt.quit()
onRejected: Qt.quit()
}
}
+8
View File
@@ -0,0 +1,8 @@
import QtQuick 2.0
import QtQuick.Controls 2.2
import SystemProperties 1.0
NavigableMessageDialog {
standardButtons: Dialog.Ok | (SystemProperties.hasBrowser ? Dialog.Help : 0)
}
+17
View File
@@ -0,0 +1,17 @@
import QtQuick 2.0
import QtQuick.Controls 2.2
Dialog {
parent: overlay
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()
}
}
+8
View File
@@ -0,0 +1,8 @@
import QtQuick 2.0
import QtQuick.Controls 2.2
Menu {
onOpened: {
itemAt(0).forceActiveFocus(Qt.TabFocusReason)
}
}
+16
View File
@@ -2,11 +2,27 @@ 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
focusPolicy: visible ? Qt.TabFocus : Qt.NoFocus
onTriggered: {
// We must close the context menu first or
// it can steal focus from any dialogs that
// onTriggered may spawn.
parentMenu.close()
}
Keys.onReturnPressed: {
triggered()
}
Keys.onEscapePressed: {
parentMenu.close()
}
}
+74
View File
@@ -0,0 +1,74 @@
import QtQuick 2.0
import QtQuick.Controls 2.2
import QtQuick.Layouts 1.2
NavigableDialog {
id: dialog
property alias text: dialogLabel.dialogText
property alias showSpinner: dialogSpinner.visible
property alias imageSrc: dialogImage.source
property string helpText
property string helpUrl : "https://github.com/moonlight-stream/moonlight-docs/wiki/Troubleshooting"
property string helpTextSeparator : " "
onOpened: {
// Force keyboard focus on the label so keyboard navigation works
dialogLabel.forceActiveFocus()
}
RowLayout {
spacing: 10
BusyIndicator {
id: dialogSpinner
visible: false
}
Image {
id: dialogImage
source: (standardButtons & Dialog.Yes) ?
"qrc:/res/baseline-help_outline-24px.svg" :
"qrc:/res/baseline-error_outline-24px.svg"
sourceSize {
// The icon should be square so use the height as the width too
width: 50
height: 50
}
visible: !showSpinner
}
Label {
property string dialogText
id: dialogLabel
text: dialogText + ((helpText && (standardButtons & Dialog.Help)) ? (helpTextSeparator + helpText) : "")
wrapMode: Text.Wrap
elide: Label.ElideRight
// Cap the width so the dialog doesn't grow horizontally forever. This
// will cause word wrap to kick in.
Layout.maximumWidth: 400
Layout.maximumHeight: 400
Keys.onReturnPressed: {
accept()
}
Keys.onEscapePressed: {
reject()
}
}
}
footer: DialogButtonBox {
id: dialogButtonBox
standardButtons: dialog.standardButtons
onHelpRequested: {
Qt.openUrlExternally(helpUrl)
close()
}
}
}
+19
View File
@@ -2,8 +2,27 @@ import QtQuick 2.0
import QtQuick.Controls 2.2
ToolButton {
property string iconSource
activeFocusOnTab: true
// 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.
background.width: (parent.height - parent.anchors.bottomMargin - parent.anchors.topMargin) * 0.60
background.height: (parent.height - parent.anchors.bottomMargin - parent.anchors.topMargin) * 0.60
Keys.onReturnPressed: {
clicked()
}
+207 -111
View File
@@ -1,8 +1,6 @@
import QtQuick 2.9
import QtQuick.Controls 2.2
import QtQuick.Dialogs 1.2
import QtQuick.Layouts 1.3
import QtQuick.Window 2.2
import ComputerModel 1.0
@@ -10,48 +8,44 @@ import ComputerManager 1.0
import StreamingPreferences 1.0
import SdlGamepadKeyNavigation 1.0
GridView {
CenteredGridView {
property ComputerModel computerModel : createModel()
id: pcGrid
focus: true
activeFocusOnTab: true
anchors.fill: parent
anchors.leftMargin: (parent.width % (cellWidth + anchors.rightMargin)) / 2
anchors.topMargin: 20
anchors.rightMargin: 5
anchors.bottomMargin: 5
cellWidth: 350; cellHeight: 350;
topMargin: 20
bottomMargin: 5
cellWidth: 310; cellHeight: 330;
objectName: "Computers"
// The StackView will trigger a visibility change when
// we're pushed onto it, causing our onVisibleChanged
// routine to run, but only if we start as invisible
visible: false
StreamingPreferences {
id: prefs
}
SdlGamepadKeyNavigation {
id: gamepadKeyNav
}
onVisibleChanged: {
if (visible) {
gamepadKeyNav.enable()
}
else {
gamepadKeyNav.disable()
}
}
Component.onCompleted: {
// Don't show any highlighted item until interacting with them.
// We do this here instead of onActivated to avoid losing the user's
// selection when backing out of a different page of the app.
currentIndex = -1
}
// Note: Any initialization done here that is critical for streaming must
// also be done in CliStartStreamSegue.qml, since this code does not run
// for command-line initiated streams.
StackView.onActivated: {
// Setup signals on CM
ComputerManager.computerAddCompleted.connect(addComplete)
// Don't show any highlighted item until interacting with them
currentIndex = -1
// 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) {
currentIndex = 0
}
}
StackView.onDeactivating: {
ComputerManager.computerAddCompleted.disconnect(addComplete)
}
function pairingComplete(error)
@@ -62,14 +56,23 @@ GridView {
// Display a failed dialog if we got an error
if (error !== undefined) {
errorDialog.text = error
errorDialog.helpText = ""
errorDialog.open()
}
}
function addComplete(success)
function addComplete(success, detectedPortBlocking)
{
if (!success) {
errorDialog.text = "Unable to connect to the specified PC. Click the Help button for possible solutions."
errorDialog.text = "Unable to connect to the specified PC."
if (detectedPortBlocking) {
errorDialog.text += "\n\nThis PC's Internet connection is blocking Moonlight. Streaming over the Internet may not work while connected to this network."
}
else {
errorDialog.helpText = "Click the Help button for possible solutions."
}
errorDialog.open()
}
}
@@ -79,21 +82,41 @@ GridView {
var model = Qt.createQmlObject('import ComputerModel 1.0; ComputerModel {}', parent, '')
model.initialize(ComputerManager)
model.pairingCompleted.connect(pairingComplete)
model.connectionTestCompleted.connect(testConnectionDialog.connectionTestComplete)
return model
}
Row {
anchors.centerIn: parent
spacing: 5
visible: pcGrid.count === 0
BusyIndicator {
id: searchSpinner
visible: StreamingPreferences.enableMdns
}
Label {
height: searchSpinner.height
elide: Label.ElideRight
text: StreamingPreferences.enableMdns ? "Searching for PCs with NVIDIA GameStream enabled..."
: "Automatic PC discovery is disabled. Add your PC manually."
font.pointSize: 20
verticalAlignment: Text.AlignVCenter
wrapMode: Text.Wrap
}
}
model: computerModel
delegate: NavigableItemDelegate {
width: 300; height: 300;
width: 300; height: 320;
grid: pcGrid
Image {
id: pcIcon
anchors.horizontalCenter: parent.horizontalCenter
source: {
model.addPc ? "qrc:/res/ic_add_to_queue_white_48px.svg" : "qrc:/res/ic_tv_white_48px.svg"
}
source: "qrc:/res/desktop_windows-48px.svg"
sourceSize {
width: 200
height: 200
@@ -105,8 +128,8 @@ GridView {
id: stateIcon
anchors.horizontalCenter: pcIcon.horizontalCenter
anchors.verticalCenter: pcIcon.verticalCenter
anchors.verticalCenterOffset: -10
visible: !model.addPc && !model.statusUnknown && (!model.online || !model.paired)
anchors.verticalCenterOffset: -15
visible: !model.statusUnknown && (!model.online || !model.paired)
source: !model.online ? "qrc:/res/baseline-warning-24px.svg" : "qrc:/res/baseline-lock-24px.svg"
sourceSize {
width: 75
@@ -118,10 +141,10 @@ GridView {
id: statusUnknownSpinner
anchors.horizontalCenter: pcIcon.horizontalCenter
anchors.verticalCenter: pcIcon.verticalCenter
anchors.verticalCenterOffset: -10
anchors.verticalCenterOffset: -15
width: 75
height: 75
visible: !model.addPc && model.statusUnknown
visible: model.statusUnknown
}
Label {
@@ -130,19 +153,61 @@ GridView {
width: parent.width
anchors.top: pcIcon.bottom
anchors.bottom: parent.bottom
font.pointSize: 36
horizontalAlignment: Text.AlignHCenter
wrapMode: Text.Wrap
elide: Text.ElideRight
}
Menu {
NavigableMenu {
id: pcContextMenu
NavigableMenuItem {
text: "Wake PC"
onTriggered: computerModel.wakeComputer(index)
visible: !model.addPc && !model.online && model.wakeable
parentMenu: pcContextMenu
text: "View Apps"
onTriggered: {
var component = Qt.createComponent("AppView.qml")
var appView = component.createObject(stackView, {"computerIndex": index, "objectName": model.name})
stackView.push(appView)
}
visible: model.online && model.paired
}
NavigableMenuItem {
parentMenu: pcContextMenu
text: "View Hidden Apps"
onTriggered: {
var component = Qt.createComponent("AppView.qml")
var appView = component.createObject(stackView, {"computerIndex": index, "objectName": model.name, "showHiddenGames": true})
stackView.push(appView)
}
visible: model.online && model.paired
}
NavigableMenuItem {
parentMenu: pcContextMenu
text: "Wake PC"
onTriggered: computerModel.wakeComputer(index)
visible: !model.online && model.wakeable
}
NavigableMenuItem {
parentMenu: pcContextMenu
text: "Test Network"
onTriggered: {
computerModel.testConnectionForComputer(index)
testConnectionDialog.open()
}
}
NavigableMenuItem {
parentMenu: pcContextMenu
text: "Rename PC"
onTriggered: {
renamePcDialog.pcIndex = index
renamePcDialog.originalName = model.name
renamePcDialog.open()
}
}
NavigableMenuItem {
parentMenu: pcContextMenu
text: "Delete PC"
onTriggered: {
deletePcDialog.pcIndex = index
@@ -153,10 +218,7 @@ GridView {
}
onClicked: {
if (model.addPc) {
addPcDialog.open()
}
else if (model.online) {
if (model.online) {
if (model.paired) {
// go to game view
var component = Qt.createComponent("AppView.qml")
@@ -165,7 +227,7 @@ GridView {
}
else {
if (!model.busy) {
var pin = ("0000" + Math.floor(Math.random() * 10000)).slice(-4)
var pin = computerModel.generatePinString()
// Kick off pairing in the background
computerModel.pairComputer(index, pin)
@@ -176,7 +238,8 @@ GridView {
}
else {
// cannot pair while something is streaming or attempting to pair
errorDialog.text = "This PC is currently busy. Make sure to quit any running games and try again."
errorDialog.text = "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()
}
}
@@ -186,111 +249,144 @@ GridView {
}
}
onPressAndHold: {
// popup() ensures the menu appears under the mouse cursor
if (pcContextMenu.popup) {
pcContextMenu.popup()
}
else {
// Qt 5.9 doesn't have popup()
pcContextMenu.open()
}
}
MouseArea {
anchors.fill: parent
acceptedButtons: Qt.RightButton;
onClicked: {
if (!model.addPc) {
// popup() ensures the menu appears under the mouse cursor
pcContextMenu.popup()
}
parent.onPressAndHold()
}
}
Keys.onMenuPressed: {
if (!model.addPc) {
// We must use open() here so the menu is positioned on
// the ItemDelegate and not where the mouse cursor is
pcContextMenu.open()
}
// We must use open() here so the menu is positioned on
// the ItemDelegate and not where the mouse cursor is
pcContextMenu.open()
}
}
MessageDialog {
ErrorMessageDialog {
id: errorDialog
// don't allow edits to the rest of the window while open
modality:Qt.WindowModal
icon: StandardIcon.Critical
standardButtons: StandardButton.Ok | StandardButton.Help
onHelp: {
// Using Setup-Guide here instead of Troubleshooting because it's likely that users
// will arrive here by forgetting to enable GameStream or not forwarding ports.
Qt.openUrlExternally("https://github.com/moonlight-stream/moonlight-docs/wiki/Setup-Guide");
}
// Using Setup-Guide here instead of Troubleshooting because it's likely that users
// will arrive here by forgetting to enable GameStream or not forwarding ports.
helpUrl: "https://github.com/moonlight-stream/moonlight-docs/wiki/Setup-Guide"
}
MessageDialog {
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
modality:Qt.WindowModal
property string pin : "0000"
text:"Please enter " + pin + " on your GameStream PC. This dialog will close when pairing is completed."
standardButtons: StandardButton.Cancel
standardButtons: Dialog.Cancel
onRejected: {
// FIXME: We should interrupt pairing here
}
}
MessageDialog {
NavigableMessageDialog {
id: deletePcDialog
// don't allow edits to the rest of the window while open
modality:Qt.WindowModal
property int pcIndex : -1;
text:"Are you sure you want to remove this PC?"
standardButtons: StandardButton.Yes | StandardButton.No
standardButtons: Dialog.Yes | Dialog.No
function deletePc() {
console.log("deleting PC pairing for PC at index: " + pcIndex)
computerModel.deleteComputer(pcIndex);
}
onYes: deletePc()
// For keyboard/gamepad activation
onAccepted: deletePc()
}
Dialog {
id: addPcDialog
property string label: "Enter the IP address of your GameStream PC"
property string hint: "192.168.1.100"
property alias editText : editTextItem
NavigableMessageDialog {
id: testConnectionDialog
closePolicy: Popup.CloseOnEscape
standardButtons: Dialog.Ok
standardButtons: StandardButton.Ok | StandardButton.Cancel
onVisibleChanged: {
editTextItem.focus = true
editTextItem.selectAll()
onAboutToShow: {
testConnectionDialog.text = "Moonlight is testing your network connection to determine if NVIDIA GameStream is blocked.\n\nThis may take a few seconds…"
showSpinner = true
}
function connectionTestComplete(result, blockedPorts)
{
if (result === -1) {
text = "The network test could not be performed because none of Moonlight's connection testing servers were reachable from this PC. Check your Internet connection or try again later."
imageSrc = "qrc:/res/baseline-warning-24px.svg"
}
else if (result === 0) {
text = "This network does not appear to be blocking Moonlight. If you still have trouble connecting, check your PC's firewall settings.\n\nIf you are trying to stream over the Internet, install the Moonlight Internet Hosting Tool on your gaming PC and run the included Internet Streaming Tester to check your gaming PC's Internet connection."
imageSrc = "qrc:/res/baseline-check_circle_outline-24px.svg"
}
else {
text = "Your PC's current network connection seems to be blocking Moonlight. Streaming over the Internet may not work while connected to this network.\n\nThe following network ports were blocked:\n"
text += blockedPorts
imageSrc = "qrc:/res/baseline-error_outline-24px.svg"
}
// Stop showing the spinner and show the image instead
showSpinner = false
}
}
NavigableDialog {
id: renamePcDialog
property string label: "Enter the new name for this PC:"
property string originalName
property int pcIndex : -1;
standardButtons: Dialog.Ok | Dialog.Cancel
onOpened: {
// Force keyboard focus on the textbox so keyboard navigation works
editText.forceActiveFocus()
}
onClosed: {
editText.clear()
}
onAccepted: {
ComputerManager.addNewHost(editText.text, false)
if (editText.text) {
computerModel.renameComputer(pcIndex, editText.text)
}
}
ColumnLayout {
Text {
id: addPcDialogLabel
text: addPcDialog.label
Label {
text: renamePcDialog.label
font.bold: true
}
Rectangle {
implicitWidth: parent.parent.width
height: editTextItem.height
TextInput {
id: editTextItem
inputMethodHints: Qt.ImhPreferUppercase
text: addPcDialog.hint
TextField {
id: editText
placeholderText: renamePcDialog.originalName
Layout.fillWidth: true
focus: true
Keys.onReturnPressed: {
renamePcDialog.accept()
}
}
}
}
ScrollBar.vertical: ScrollBar {
parent: pcGrid.parent
anchors {
top: pcGrid.top
left: pcGrid.right
bottom: pcGrid.bottom
leftMargin: -10
}
}
ScrollBar.vertical: ScrollBar {}
}
+20 -25
View File
@@ -1,6 +1,5 @@
import QtQuick 2.0
import QtQuick.Controls 2.2
import QtQuick.Dialogs 1.2
import ComputerManager 1.0
import Session 1.0
@@ -12,13 +11,6 @@ Item {
property string stageText : "Quitting " + appName + "..."
anchors.fill: parent
// The StackView will trigger a visibility change when
// we're pushed onto it, causing our onVisibleChanged
// routine to run, but only if we start as invisible
visible: false
function quitAppCompleted(error)
{
// Display a failed dialog if we got an error
@@ -27,26 +19,32 @@ Item {
errorDialog.open()
}
// Exit this view
stackView.pop()
// If we're supposed to launch another game after this, do so now
if (error === undefined && nextSession !== null) {
var component = Qt.createComponent("StreamSegue.qml")
var segue = component.createObject(stackView, {"appName": nextAppName, "session": nextSession})
stackView.push(segue)
stackView.replace(segue)
}
else {
// Exit this view
stackView.pop()
}
}
onVisibleChanged: {
if (visible) {
// Connect the quit completion signal
ComputerManager.quitAppCompleted.connect(quitAppCompleted)
}
else {
// Disconnect the signal
ComputerManager.quitAppCompleted.disconnect(quitAppCompleted)
}
StackView.onActivated: {
// Hide the toolbar before we start loading
toolBar.visible = false
// Connect the quit completion signal
ComputerManager.quitAppCompleted.connect(quitAppCompleted)
}
StackView.onDeactivating: {
// Show the toolbar again
toolBar.visible = true
// Disconnect the signal
ComputerManager.quitAppCompleted.disconnect(quitAppCompleted)
}
Row {
@@ -68,10 +66,7 @@ Item {
}
}
MessageDialog {
ErrorMessageDialog {
id: errorDialog
modality:Qt.WindowModal
icon: StandardIcon.Critical
standardButtons: StandardButton.Ok
}
}
+291 -124
View File
@@ -4,61 +4,51 @@ import QtQuick.Controls 2.2
import StreamingPreferences 1.0
import ComputerManager 1.0
import SdlGamepadKeyNavigation 1.0
import SystemProperties 1.0
Flickable {
id: settingsPage
objectName: "Settings"
anchors.fill: parent
boundsBehavior: Flickable.OvershootBounds
contentWidth: settingsColumn1.width > settingsColumn2.width ? settingsColumn1.width : settingsColumn2.width
contentHeight: settingsColumn1.height > settingsColumn2.height ? settingsColumn1.height : settingsColumn2.height
ScrollBar.vertical: ScrollBar {
parent: settingsPage.parent
anchors {
top: settingsPage.top
left: settingsPage.right
bottom: settingsPage.bottom
left: parent.right
leftMargin: -10
}
}
StreamingPreferences {
id: prefs
}
StackView.onActivated: {
// This enables Tab and BackTab based navigation rather than arrow keys.
// It is required to shift focus between controls on the settings page.
SdlGamepadKeyNavigation.setUiNavMode(true)
// The StackView will trigger a visibility change when
// we're pushed onto it, causing our onVisibleChanged
// routine to run, but only if we start as invisible
visible: false
SdlGamepadKeyNavigation {
id: gamepadKeyNav
}
onVisibleChanged: {
if (visible) {
gamepadKeyNav.setSettingsMode(true)
gamepadKeyNav.enable()
}
else {
gamepadKeyNav.disable()
// Highlight the first item if a gamepad is connected
if (SdlGamepadKeyNavigation.getConnectedGamepads() > 0) {
resolutionComboBox.forceActiveFocus(Qt.TabFocus)
}
}
Component.onDestruction: {
prefs.save()
StackView.onDeactivating: {
SdlGamepadKeyNavigation.setUiNavMode(false)
// Save the prefs so the Session can observe the changes
StreamingPreferences.save()
}
Column {
padding: 10
id: settingsColumn1
width: settingsPage.width / 2 - padding
width: settingsPage.width / 2
spacing: 15
GroupBox {
id: basicSettingsGroupBox
width: (parent.width - 2 * parent.padding)
width: (parent.width - (parent.leftPadding + parent.rightPadding))
padding: 12
title: "<font color=\"skyblue\">Basic Settings</font>"
font.pointSize: 12
@@ -85,6 +75,7 @@ Flickable {
Row {
spacing: 5
width: parent.width
AutoResizingComboBox {
// ignore setting the index at first, and actually set it when the component is loaded
@@ -97,11 +88,11 @@ Flickable {
// Some platforms have different desktop resolutions
// and native resolutions (like macOS with Retina displays)
if (displayResIndex == 0) {
screenRect = prefs.getDesktopResolution(displayIndex)
if (displayResIndex === 0) {
screenRect = SystemProperties.getDesktopResolution(displayIndex)
}
else {
screenRect = prefs.getNativeResolution(displayIndex)
screenRect = SystemProperties.getNativeResolution(displayIndex)
}
if (screenRect.width === 0) {
@@ -138,10 +129,24 @@ Flickable {
}
}
// Prune resolutions that are over the decoder's maximum
var max_pixels = SystemProperties.maximumResolution.width * SystemProperties.maximumResolution.height;
if (max_pixels > 0) {
for (var j = 0; j < resolutionComboBox.count; j++) {
var existing_width = parseInt(resolutionListModel.get(j).video_width);
var existing_height = parseInt(resolutionListModel.get(j).video_height);
if (existing_width * existing_height > max_pixels) {
resolutionListModel.remove(j)
j--
}
}
}
// load the saved width/height, and iterate through the ComboBox until a match is found
// and set it to that index.
var saved_width = prefs.width
var saved_height = prefs.height
var saved_width = StreamingPreferences.width
var saved_height = StreamingPreferences.height
currentIndex = 0
for (var i = 0; i < resolutionListModel.count; i++) {
var el_width = parseInt(resolutionListModel.get(i).video_width);
@@ -158,6 +163,7 @@ Flickable {
}
id: resolutionComboBox
maximumWidth: parent.width / 2
textRole: "text"
model: ListModel {
id: resolutionListModel
@@ -190,12 +196,14 @@ Flickable {
var selectedHeight = parseInt(resolutionListModel.get(currentIndex).video_height)
// Only modify the bitrate if the values actually changed
if (prefs.width !== selectedWidth || prefs.height !== selectedHeight) {
prefs.width = selectedWidth
prefs.height = selectedHeight
if (StreamingPreferences.width !== selectedWidth || StreamingPreferences.height !== selectedHeight) {
StreamingPreferences.width = selectedWidth
StreamingPreferences.height = selectedHeight
prefs.bitrateKbps = prefs.getDefaultBitrate(prefs.width, prefs.height, prefs.fps);
slider.value = prefs.bitrateKbps
StreamingPreferences.bitrateKbps = StreamingPreferences.getDefaultBitrate(StreamingPreferences.width,
StreamingPreferences.height,
StreamingPreferences.fps);
slider.value = StreamingPreferences.bitrateKbps
}
}
}
@@ -204,15 +212,14 @@ Flickable {
function createModel() {
var fpsListModel = Qt.createQmlObject('import QtQuick 2.0; ListModel {}', parent, '')
// Get the max supported FPS on this system
var max_fps = prefs.getMaximumStreamingFrameRate();
var max_fps = SystemProperties.maximumStreamingFrameRate
// Default entries
fpsListModel.append({"text": "30 FPS", "video_fps": "30"})
fpsListModel.append({"text": "60 FPS", "video_fps": "60"})
// Add unsupported FPS values that come before the display max FPS
if (prefs.unsupportedFps) {
if (StreamingPreferences.unsupportedFps) {
if (max_fps > 90) {
fpsListModel.append({"text": "90 FPS (Unsupported)", "video_fps": "90"})
}
@@ -225,7 +232,7 @@ Flickable {
// handle wonky displays that report just over 60 Hz.
if (max_fps > 64) {
// Mark any FPS value greater than 120 as unsupported
if (prefs.unsupportedFps && max_fps > 120) {
if (StreamingPreferences.unsupportedFps && max_fps > 120) {
fpsListModel.append({"text": max_fps+" FPS (Unsupported)", "video_fps": ""+max_fps})
}
else if (max_fps > 120) {
@@ -237,7 +244,7 @@ Flickable {
}
// Add unsupported FPS values that come after the display max FPS
if (prefs.unsupportedFps) {
if (StreamingPreferences.unsupportedFps) {
if (max_fps < 90) {
fpsListModel.append({"text": "90 FPS (Unsupported)", "video_fps": "90"})
}
@@ -252,7 +259,7 @@ Flickable {
function reinitialize() {
model = createModel()
var saved_fps = prefs.fps
var saved_fps = StreamingPreferences.fps
currentIndex = 0
for (var i = 0; i < model.count; i++) {
var el_fps = parseInt(model.get(i).video_fps);
@@ -273,17 +280,20 @@ Flickable {
}
id: fpsComboBox
maximumWidth: parent.width / 2
textRole: "text"
// ::onActivated must be used, as it only listens for when the index is changed by a human
onActivated : {
var selectedFps = parseInt(model.get(currentIndex).video_fps)
// Only modify the bitrate if the values actually changed
if (prefs.fps !== selectedFps) {
prefs.fps = selectedFps
if (StreamingPreferences.fps !== selectedFps) {
StreamingPreferences.fps = selectedFps
prefs.bitrateKbps = prefs.getDefaultBitrate(prefs.width, prefs.height, prefs.fps);
slider.value = prefs.bitrateKbps
StreamingPreferences.bitrateKbps = StreamingPreferences.getDefaultBitrate(StreamingPreferences.width,
StreamingPreferences.height,
StreamingPreferences.fps);
slider.value = StreamingPreferences.bitrateKbps
}
}
}
@@ -300,16 +310,15 @@ Flickable {
Label {
width: parent.width
id: bitrateDesc
text: qsTr("Lower bitrate to reduce lag and stuttering. Raise bitrate to increase image quality.")
text: qsTr("Lower the bitrate on slower connections. Raise the bitrate to increase image quality.")
font.pointSize: 9
wrapMode: Text.Wrap
}
Slider {
id: slider
wheelEnabled: true
value: prefs.bitrateKbps
value: StreamingPreferences.bitrateKbps
stepSize: 500
from : 500
@@ -320,7 +329,7 @@ Flickable {
onValueChanged: {
bitrateTitle.text = "Video bitrate: " + (value / 1000.0) + " Mbps"
prefs.bitrateKbps = value
StreamingPreferences.bitrateKbps = value
}
}
@@ -335,25 +344,40 @@ Flickable {
AutoResizingComboBox {
// ignore setting the index at first, and actually set it when the component is loaded
Component.onCompleted: {
var savedWm = prefs.windowMode
currentIndex = 0
// Set the recommended option based on the OS
for (var i = 0; i < windowModeListModel.count; i++) {
var thisWm = windowModeListModel.get(i).val;
if (savedWm === thisWm) {
currentIndex = i
if (thisWm === StreamingPreferences.recommendedFullScreenMode) {
windowModeListModel.get(i).text += " (Recommended)"
windowModeListModel.move(i, 0, 1);
break
}
}
currentIndex = 0
if (SystemProperties.hasWindowManager && !SystemProperties.rendererAlwaysFullScreen) {
var savedWm = StreamingPreferences.windowMode
for (var i = 0; i < windowModeListModel.count; i++) {
var thisWm = windowModeListModel.get(i).val;
if (savedWm === thisWm) {
currentIndex = i
break
}
}
}
activated(currentIndex)
}
id: windowModeComboBox
enabled: SystemProperties.hasWindowManager && !SystemProperties.rendererAlwaysFullScreen
hoverEnabled: true
textRole: "text"
model: ListModel {
id: windowModeListModel
ListElement {
text: "Full-screen (Recommended)"
text: "Full-screen"
val: StreamingPreferences.WM_FULLSCREEN
}
ListElement {
@@ -366,7 +390,7 @@ Flickable {
}
}
onActivated: {
prefs.windowMode = windowModeListModel.get(currentIndex).val
StreamingPreferences.windowMode = windowModeListModel.get(currentIndex).val
}
ToolTip.delay: 1000
@@ -377,12 +401,13 @@ Flickable {
CheckBox {
id: vsyncCheck
width: parent.width
hoverEnabled: true
text: "Enable V-Sync"
text: "V-Sync"
font.pointSize: 12
checked: prefs.enableVsync
checked: StreamingPreferences.enableVsync
onCheckedChanged: {
prefs.enableVsync = checked
StreamingPreferences.enableVsync = checked
}
ToolTip.delay: 1000
@@ -390,13 +415,30 @@ Flickable {
ToolTip.visible: hovered
ToolTip.text: "Disabling V-Sync allows sub-frame rendering latency, but it can display visible tearing"
}
CheckBox {
id: framePacingCheck
width: parent.width
hoverEnabled: true
text: "Frame pacing"
font.pointSize: 12
enabled: StreamingPreferences.enableVsync
checked: StreamingPreferences.enableVsync && StreamingPreferences.framePacing
onCheckedChanged: {
StreamingPreferences.framePacing = checked
}
ToolTip.delay: 1000
ToolTip.timeout: 5000
ToolTip.visible: hovered
ToolTip.text: "Frame pacing reduces micro-stutter by delaying frames that come in too early"
}
}
}
GroupBox {
id: audioSettingsGroupBox
width: (parent.width - 2 * parent.padding)
width: (parent.width - (parent.leftPadding + parent.rightPadding))
padding: 12
title: "<font color=\"skyblue\">Audio Settings</font>"
font.pointSize: 12
@@ -416,7 +458,7 @@ Flickable {
AutoResizingComboBox {
// ignore setting the index at first, and actually set it when the component is loaded
Component.onCompleted: {
var saved_audio = prefs.audioConfig
var saved_audio = StreamingPreferences.audioConfig
currentIndex = 0
for (var i = 0; i < audioListModel.count; i++) {
var el_audio = audioListModel.get(i).val;
@@ -440,10 +482,14 @@ Flickable {
text: "5.1 surround sound"
val: StreamingPreferences.AC_51_SURROUND
}
ListElement {
text: "7.1 surround sound"
val: StreamingPreferences.AC_71_SURROUND
}
}
// ::onActivated must be used, as it only listens for when the index is changed by a human
onActivated : {
prefs.audioConfig = audioListModel.get(currentIndex).val
StreamingPreferences.audioConfig = audioListModel.get(currentIndex).val
}
}
@@ -452,7 +498,7 @@ Flickable {
GroupBox {
id: uiSettingsGroupBox
width: (parent.width - 2 * parent.padding)
width: (parent.width - (parent.leftPadding + parent.rightPadding))
padding: 12
title: "<font color=\"skyblue\">UI Settings</font>"
font.pointSize: 12
@@ -463,26 +509,58 @@ Flickable {
CheckBox {
id: startMaximizedCheck
width: parent.width
text: "Maximize Moonlight window on startup"
font.pointSize: 12
checked: !prefs.startWindowed
enabled: SystemProperties.hasWindowManager
checked: !StreamingPreferences.startWindowed || !SystemProperties.hasWindowManager
onCheckedChanged: {
prefs.startWindowed = !checked
StreamingPreferences.startWindowed = !checked
}
}
CheckBox {
id: connectionWarningsCheck
width: parent.width
text: "Show connection quality warnings"
font.pointSize: 12
checked: StreamingPreferences.connectionWarnings
onCheckedChanged: {
StreamingPreferences.connectionWarnings = checked
}
}
CheckBox {
visible: SystemProperties.hasDiscordIntegration
id: discordPresenceCheck
width: parent.width
text: "Discord Rich Presence integration"
font.pointSize: 12
checked: StreamingPreferences.richPresence
onCheckedChanged: {
StreamingPreferences.richPresence = checked
}
ToolTip.delay: 1000
ToolTip.timeout: 5000
ToolTip.visible: hovered
ToolTip.text: "Updates your Discord status to display the name of the game you're streaming."
}
}
}
}
Column {
padding: 10
rightPadding: 20
anchors.left: settingsColumn1.right
id: settingsColumn2
width: settingsPage.width / 2 - padding
width: settingsPage.width / 2
spacing: 15
GroupBox {
id: gamepadSettingsGroupBox
width: (parent.width - parent.padding)
width: (parent.width - (parent.leftPadding + parent.rightPadding))
padding: 12
title: "<font color=\"skyblue\">Input Settings</font>"
font.pointSize: 12
@@ -493,11 +571,12 @@ Flickable {
CheckBox {
id: singleControllerCheck
width: parent.width
text: "Force gamepad #1 always present"
font.pointSize: 12
checked: !prefs.multiController
checked: !StreamingPreferences.multiController
onCheckedChanged: {
prefs.multiController = !checked
StreamingPreferences.multiController = !checked
}
ToolTip.delay: 1000
@@ -508,26 +587,80 @@ Flickable {
}
CheckBox {
id: rawInputCheck
id: absoluteMouseCheck
hoverEnabled: true
text: "Raw mouse input"
width: parent.width
text: "Optimize mouse for remote desktop instead of games"
font.pointSize: 12
checked: !prefs.mouseAcceleration
enabled: SystemProperties.hasWindowManager
checked: StreamingPreferences.absoluteMouseMode && SystemProperties.hasWindowManager
onCheckedChanged: {
prefs.mouseAcceleration = !checked
StreamingPreferences.absoluteMouseMode = checked
}
ToolTip.delay: 1000
ToolTip.timeout: 5000
ToolTip.visible: hovered
ToolTip.text: "This enables mouse control without capturing the client's mouse cursor. It will not work in most games.\n
You can toggle this while streaming using Ctrl+Alt+Shift+M."
}
CheckBox {
id: absoluteTouchCheck
hoverEnabled: true
width: parent.width
text: "Use touchscreen as a trackpad"
font.pointSize: 12
checked: !StreamingPreferences.absoluteTouchMode
onCheckedChanged: {
StreamingPreferences.absoluteTouchMode = !checked
}
ToolTip.delay: 1000
ToolTip.timeout: 5000
ToolTip.visible: hovered
ToolTip.text: "When checked, the touchscreen acts like a trackpad. When unchecked, the touchscreen will directly control the mouse pointer."
}
CheckBox {
id: gamepadMouseCheck
hoverEnabled: true
width: parent.width
text: "Gamepad mouse mode support"
font.pointSize: 12
checked: StreamingPreferences.gamepadMouse
onCheckedChanged: {
StreamingPreferences.gamepadMouse = checked
}
ToolTip.delay: 1000
ToolTip.timeout: 3000
ToolTip.visible: hovered
ToolTip.text: "When checked, mouse input is not accelerated or scaled by the OS before passing to Moonlight"
ToolTip.text: "When enabled, holding the Start button will toggle mouse mode"
}
CheckBox {
id: swapMouseButtonsCheck
hoverEnabled: true
width: parent.width
text: "Swap mouse buttons"
font.pointSize: 12
checked: StreamingPreferences.swapMouseButtons
onCheckedChanged: {
StreamingPreferences.swapMouseButtons = checked
}
ToolTip.delay: 1000
ToolTip.timeout: 3000
ToolTip.visible: hovered
ToolTip.text: "When checked, swap the left and right mouse buttons"
}
}
}
GroupBox {
id: hostSettingsGroupBox
width: (parent.width - parent.padding)
width: (parent.width - (parent.leftPadding + parent.rightPadding))
padding: 12
title: "<font color=\"skyblue\">Host Settings</font>"
font.pointSize: 12
@@ -538,29 +671,47 @@ Flickable {
CheckBox {
id: optimizeGameSettingsCheck
text: "Optimize game settings"
width: parent.width
text: "Optimize game settings for streaming"
font.pointSize: 12
checked: prefs.gameOptimizations
checked: StreamingPreferences.gameOptimizations
onCheckedChanged: {
prefs.gameOptimizations = checked
StreamingPreferences.gameOptimizations = checked
}
}
CheckBox {
id: audioPcCheck
width: parent.width
text: "Play audio on host PC"
font.pointSize: 12
checked: prefs.playAudioOnHost
checked: StreamingPreferences.playAudioOnHost
onCheckedChanged: {
prefs.playAudioOnHost = checked
StreamingPreferences.playAudioOnHost = checked
}
}
CheckBox {
id: quitAppAfter
width: parent.width
text: "Quit app on host PC after ending stream"
font.pointSize: 12
checked: StreamingPreferences.quitAppAfter
onCheckedChanged: {
StreamingPreferences.quitAppAfter = checked
}
ToolTip.delay: 1000
ToolTip.timeout: 5000
ToolTip.visible: hovered
ToolTip.text: "This will close the app or game you are streaming when you end your stream. You will lose any unsaved progress!"
}
}
}
GroupBox {
id: advancedSettingsGroupBox
width: (parent.width - parent.padding)
width: (parent.width - (parent.leftPadding + parent.rightPadding))
padding: 12
title: "<font color=\"skyblue\">Advanced Settings</font>"
font.pointSize: 12
@@ -580,7 +731,7 @@ Flickable {
AutoResizingComboBox {
// ignore setting the index at first, and actually set it when the component is loaded
Component.onCompleted: {
var saved_vds = prefs.videoDecoderSelection
var saved_vds = StreamingPreferences.videoDecoderSelection
currentIndex = 0
for (var i = 0; i < decoderListModel.count; i++) {
var el_vds = decoderListModel.get(i).val;
@@ -611,7 +762,7 @@ Flickable {
}
// ::onActivated must be used, as it only listens for when the index is changed by a human
onActivated : {
prefs.videoDecoderSelection = decoderListModel.get(currentIndex).val
StreamingPreferences.videoDecoderSelection = decoderListModel.get(currentIndex).val
}
}
@@ -626,7 +777,7 @@ Flickable {
AutoResizingComboBox {
// ignore setting the index at first, and actually set it when the component is loaded
Component.onCompleted: {
var saved_vcc = prefs.videoCodecConfig
var saved_vcc = StreamingPreferences.videoCodecConfig
currentIndex = 0
for(var i = 0; i < codecListModel.count; i++) {
var el_vcc = codecListModel.get(i).val;
@@ -647,68 +798,84 @@ Flickable {
val: StreamingPreferences.VCC_AUTO
}
ListElement {
text: "Force H.264"
text: "H.264"
val: StreamingPreferences.VCC_FORCE_H264
}
ListElement {
text: "Force HEVC"
text: "HEVC (H.265)"
val: StreamingPreferences.VCC_FORCE_HEVC
}
// HDR seems to be broken in GFE 3.14.1, and even when that's fixed
// we'll probably need to gate this feature on OS support in our
// renderers.
/* ListElement {
text: "Force HEVC HDR"
/*ListElement {
text: "HEVC HDR (Experimental)"
val: StreamingPreferences.VCC_FORCE_HEVC_HDR
} */
}*/
}
// ::onActivated must be used, as it only listens for when the index is changed by a human
onActivated : {
prefs.videoCodecConfig = codecListModel.get(currentIndex).val
StreamingPreferences.videoCodecConfig = codecListModel.get(currentIndex).val
}
}
CheckBox {
id: unlockUnsupportedFps
width: parent.width
text: "Unlock unsupported FPS options"
font.pointSize: 12
checked: prefs.unsupportedFps
checked: StreamingPreferences.unsupportedFps
onCheckedChanged: {
prefs.unsupportedFps = checked
// This is called on init, so only do the work if we've
// actually changed the value.
if (StreamingPreferences.unsupportedFps != checked) {
StreamingPreferences.unsupportedFps = checked
// The selectable FPS values depend on whether
// this option is enabled or not
fpsComboBox.reinitialize()
}
}
CheckBox {
id: enableMdns
text: "Automatically find PCs on the local network (Recommended)"
font.pointSize: 12
checked: prefs.enableMdns
onCheckedChanged: {
prefs.enableMdns = checked
// We must save the updated preference to ensure
// ComputerManager can observe the change internally.
prefs.save()
// Restart polling so the mDNS change takes effect
if (window.pollingActive) {
ComputerManager.stopPollingAsync()
ComputerManager.startPolling()
// The selectable FPS values depend on whether
// this option is enabled or not
fpsComboBox.reinitialize()
}
}
}
CheckBox {
id: quitAppAfter
text: "Quit app after quitting session"
id: enableMdns
width: parent.width
text: "Automatically find PCs on the local network (Recommended)"
font.pointSize: 12
checked: prefs.quitAppAfter
checked: StreamingPreferences.enableMdns
onCheckedChanged: {
prefs.quitAppAfter = checked
// This is called on init, so only do the work if we've
// actually changed the value.
if (StreamingPreferences.enableMdns != checked) {
StreamingPreferences.enableMdns = checked
// We must save the updated preference to ensure
// ComputerManager can observe the change internally.
StreamingPreferences.save()
// Restart polling so the mDNS change takes effect
if (window.pollingActive) {
ComputerManager.stopPollingAsync()
ComputerManager.startPolling()
}
}
}
}
CheckBox {
id: detectNetworkBlocking
width: parent.width
text: "Automatically detect blocked connections (Recommended)"
font.pointSize: 12
checked: StreamingPreferences.detectNetworkBlocking
onCheckedChanged: {
// This is called on init, so only do the work if we've
// actually changed the value.
if (StreamingPreferences.detectNetworkBlocking != checked) {
StreamingPreferences.detectNetworkBlocking = checked
// We must save the updated preference to ensure
// ComputerManager can observe the change internally.
StreamingPreferences.save()
}
}
}
}
+66 -61
View File
@@ -1,9 +1,7 @@
import QtQuick 2.0
import QtQuick.Controls 2.2
import QtQuick.Dialogs 1.2
import QtQuick.Window 2.2
import ComputerManager 1.0
import SdlGamepadKeyNavigation 1.0
import Session 1.0
@@ -13,13 +11,6 @@ Item {
property string stageText : "Starting " + appName + "..."
property bool quitAfter : false
anchors.fill: parent
// The StackView will trigger a visibility change when
// we're pushed onto it, causing our onVisibleChanged
// routine to run, but only if we start as invisible
visible: false
function stageStarting(stage)
{
// Update the spinner text
@@ -28,8 +19,8 @@ Item {
function stageFailed(stage, errorCode)
{
errorDialog.text = "Starting " + stage + " failed: Error " + errorCode
errorDialog.open()
// Display the error dialog after Session::exec() returns
streamSegueErrorDialog.text = "Starting " + stage + " failed: Error " + errorCode
}
function connectionStarted()
@@ -38,6 +29,7 @@ Item {
// see them briefly when we pop off the StackView
stageSpinner.visible = false
stageLabel.visible = false
hintText.visible = false
// Hide the window now that streaming has begun
window.visible = false
@@ -46,7 +38,7 @@ Item {
function displayLaunchError(text)
{
// Display the error dialog after Session::exec() returns
errorDialog.text = text
streamSegueErrorDialog.text = text
}
function displayLaunchWarning(text)
@@ -54,7 +46,7 @@ Item {
// 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.3; ToolTip {}', parent, '')
var toast = Qt.createQmlObject('import QtQuick.Controls 2.2; ToolTip {}', parent, '')
toast.text = text
toast.timeout = 3000
toast.visible = true
@@ -70,12 +62,20 @@ Item {
window.visible = true
}
function sessionFinished()
function sessionFinished(portTestResult)
{
if (portTestResult !== 0 && portTestResult !== -1 && streamSegueErrorDialog.text) {
streamSegueErrorDialog.text += "\n\nThis PC's Internet connection is blocking Moonlight. Streaming over the Internet may not work while connected to this network."
}
// Enable GUI gamepad usage now
SdlGamepadKeyNavigation.enable()
if (quitAfter) {
if (errorDialog.text) {
if (streamSegueErrorDialog.text) {
// Quit when the error dialog is acknowledged
errorDialog.open()
streamSegueErrorDialog.quitAfter = quitAfter
streamSegueErrorDialog.open()
}
else {
// Quit immediately
@@ -92,48 +92,73 @@ Item {
// the Qt UI is visible again to prevent losing
// focus on the dialog which would impact gamepad
// users.
if (errorDialog.text) {
errorDialog.open()
if (streamSegueErrorDialog.text) {
streamSegueErrorDialog.quitAfter = quitAfter
streamSegueErrorDialog.open()
}
}
}
// It's important that we don't call enable() here
// or it may interfere with the Session instance
// getting notified of initial connected gamepads.
SdlGamepadKeyNavigation {
id: gamepadKeyNav
StackView.onDeactivating: {
// Show the toolbar again when popped off the stack
toolBar.visible = true
// Enable GUI gamepad usage now
SdlGamepadKeyNavigation.enable()
}
onVisibleChanged: {
if (visible) {
// Hide the toolbar before we start loading
toolBar.visible = false
StackView.onActivated: {
// Hide the toolbar before we start loading
toolBar.visible = false
// Hook up our signals
session.stageStarting.connect(stageStarting)
session.stageFailed.connect(stageFailed)
session.connectionStarted.connect(connectionStarted)
session.displayLaunchError.connect(displayLaunchError)
session.displayLaunchWarning.connect(displayLaunchWarning)
session.quitStarting.connect(quitStarting)
session.sessionFinished.connect(sessionFinished)
// Kick off the stream
spinnerTimer.start()
streamLoader.active = true
}
Timer {
id: spinnerTimer
// Display the spinner appearance a bit to allow us to reach
// the code in Session.exec() that pumps the event loop.
// If we display it immediately, it will briefly hang in the
// middle of the animation on Windows, which looks very
// obviously broken.
interval: 100
onTriggered: stageSpinner.running = true
}
Loader {
id: streamLoader
active: false
asynchronous: true
onLoaded: {
// Set the hint text. We do this here rather than
// in the hintText control itself to synchronize
// with Session.exec() which requires no concurrent
// gamepad usage.
hintText.text = gamepadKeyNav.getConnectedGamepads() > 0 ?
hintText.text = SdlGamepadKeyNavigation.getConnectedGamepads() > 0 ?
"Tip: Press Start+Select+L1+R1 to disconnect your session" :
"Tip: Press Ctrl+Alt+Shift+Q to disconnect your session"
// Hook up our signals
session.stageStarting.connect(stageStarting)
session.stageFailed.connect(stageFailed)
session.connectionStarted.connect(connectionStarted)
session.displayLaunchError.connect(displayLaunchError)
session.displayLaunchWarning.connect(displayLaunchWarning)
session.quitStarting.connect(quitStarting)
session.sessionFinished.connect(sessionFinished)
// Stop GUI gamepad usage now
SdlGamepadKeyNavigation.disable()
// Run the streaming session to completion
session.exec(Screen.virtualX, Screen.virtualY)
}
else if (!quitAfter) {
// Show the toolbar again when we become hidden
toolBar.visible = true
}
sourceComponent: Item {}
}
Row {
@@ -142,6 +167,7 @@ Item {
BusyIndicator {
id: stageSpinner
running: false
}
Label {
@@ -165,25 +191,4 @@ Item {
wrapMode: Text.Wrap
}
MessageDialog {
id: errorDialog
modality:Qt.WindowModal
icon: StandardIcon.Critical
standardButtons: StandardButton.Ok | StandardButton.Help
onAccepted: {
if (quitAfter) {
Qt.quit()
}
}
onHelp: {
Qt.openUrlExternally("https://github.com/moonlight-stream/moonlight-docs/wiki/Troubleshooting");
if (quitAfter) {
Qt.quit()
}
}
}
}
+133 -32
View File
@@ -7,7 +7,7 @@ AppModel::AppModel(QObject *parent)
this, &AppModel::handleBoxArtLoaded);
}
void AppModel::initialize(ComputerManager* computerManager, int computerIndex)
void AppModel::initialize(ComputerManager* computerManager, int computerIndex, bool showHiddenGames)
{
m_ComputerManager = computerManager;
connect(m_ComputerManager, &ComputerManager::computerStateChanged,
@@ -15,29 +15,23 @@ void AppModel::initialize(ComputerManager* computerManager, int computerIndex)
Q_ASSERT(computerIndex < m_ComputerManager->getComputers().count());
m_Computer = m_ComputerManager->getComputers().at(computerIndex);
m_Apps = m_Computer->appList;
m_CurrentGameId = m_Computer->currentGameId;
m_ShowHiddenGames = showHiddenGames;
updateAppList(m_Computer->appList);
}
int AppModel::getRunningAppIndex()
int AppModel::getRunningAppId()
{
if (m_CurrentGameId != 0) {
for (int i = 0; i < m_Apps.count(); i++) {
if (m_Apps[i].id == m_CurrentGameId) {
return i;
}
}
}
return -1;
return m_CurrentGameId;
}
QString AppModel::getRunningAppName()
{
if (m_CurrentGameId != 0) {
for (int i = 0; i < m_Apps.count(); i++) {
if (m_Apps[i].id == m_CurrentGameId) {
return m_Apps[i].name;
for (int i = 0; i < m_AllApps.count(); i++) {
if (m_AllApps[i].id == m_CurrentGameId) {
return m_AllApps[i].name;
}
}
}
@@ -47,8 +41,8 @@ QString AppModel::getRunningAppName()
Session* AppModel::createSessionForApp(int appIndex)
{
Q_ASSERT(appIndex < m_Apps.count());
NvApp app = m_Apps.at(appIndex);
Q_ASSERT(appIndex < m_VisibleApps.count());
NvApp app = m_VisibleApps.at(appIndex);
return new Session(m_Computer, app);
}
@@ -60,7 +54,7 @@ int AppModel::rowCount(const QModelIndex &parent) const
if (parent.isValid())
return 0;
return m_Apps.count();
return m_VisibleApps.count();
}
QVariant AppModel::data(const QModelIndex &index, int role) const
@@ -68,8 +62,8 @@ QVariant AppModel::data(const QModelIndex &index, int role) const
if (!index.isValid())
return QVariant();
Q_ASSERT(index.row() < m_Apps.count());
NvApp app = m_Apps.at(index.row());
Q_ASSERT(index.row() < m_VisibleApps.count());
NvApp app = m_VisibleApps.at(index.row());
switch (role)
{
@@ -80,6 +74,10 @@ QVariant AppModel::data(const QModelIndex &index, int role) const
case BoxArtRole:
// FIXME: const-correctness
return const_cast<BoxArtManager&>(m_BoxArtManager).loadBoxArt(m_Computer, app);
case HiddenRole:
return app.hidden;
case AppIdRole:
return app.id;
default:
return QVariant();
}
@@ -92,6 +90,8 @@ QHash<int, QByteArray> AppModel::roleNames() const
names[NameRole] = "name";
names[RunningRole] = "running";
names[BoxArtRole] = "boxart";
names[HiddenRole] = "hidden";
names[AppIdRole] = "appid";
return names;
}
@@ -101,6 +101,112 @@ void AppModel::quitRunningApp()
m_ComputerManager->quitRunningApp(m_Computer);
}
bool AppModel::isAppCurrentlyVisible(const NvApp& app)
{
for (const NvApp& visibleApp : m_VisibleApps) {
if (app.id == visibleApp.id) {
return true;
}
}
return false;
}
QVector<NvApp> AppModel::getVisibleApps(const QVector<NvApp>& appList)
{
QVector<NvApp> visibleApps;
for (const NvApp& app : appList) {
// Don't immediately hide games that were previously visible. This
// allows users to easily uncheck the "Hide App" checkbox if they
// check it by mistake.
if (m_ShowHiddenGames || !app.hidden || isAppCurrentlyVisible(app)) {
visibleApps.append(app);
}
}
return visibleApps;
}
void AppModel::updateAppList(QVector<NvApp> newList)
{
m_AllApps = newList;
QVector<NvApp> newVisibleList = getVisibleApps(newList);
// Process removals and updates first
for (int i = 0; i < m_VisibleApps.count(); i++) {
const NvApp& existingApp = m_VisibleApps.at(i);
bool found = false;
for (const NvApp& newApp : newVisibleList) {
if (existingApp.id == newApp.id) {
// If the data changed, update it in our list
if (existingApp != newApp) {
m_VisibleApps.replace(i, newApp);
emit dataChanged(createIndex(i, 0), createIndex(i, 0));
}
found = true;
break;
}
}
if (!found) {
beginRemoveRows(QModelIndex(), i, i);
m_VisibleApps.removeAt(i);
endRemoveRows();
i--;
}
}
// Process additions now
for (const NvApp& newApp : newVisibleList) {
int insertionIndex = m_VisibleApps.size();
bool found = false;
for (int i = 0; i < m_VisibleApps.count(); i++) {
const NvApp& existingApp = m_VisibleApps.at(i);
if (existingApp.id == newApp.id) {
found = true;
break;
}
else if (existingApp.name.toLower() > newApp.name.toLower()) {
insertionIndex = i;
break;
}
}
if (!found) {
beginInsertRows(QModelIndex(), insertionIndex, insertionIndex);
m_VisibleApps.insert(insertionIndex, newApp);
endInsertRows();
}
}
Q_ASSERT(newVisibleList == m_VisibleApps);
}
void AppModel::setAppHidden(int appIndex, bool hidden)
{
Q_ASSERT(appIndex < m_VisibleApps.count());
int appId = m_VisibleApps.at(appIndex).id;
{
QWriteLocker lock(&m_Computer->lock);
for (NvApp& app : m_Computer->appList) {
if (app.id == appId) {
app.hidden = hidden;
break;
}
}
}
m_ComputerManager->clientSideAttributeUpdated(m_Computer);
}
void AppModel::handleComputerStateChanged(NvComputer* computer)
{
// Ignore updates for computers that aren't ours
@@ -119,20 +225,15 @@ void AppModel::handleComputerStateChanged(NvComputer* computer)
// First, process additions/removals from the app list. This
// is required because the new game may now be running, so
// we can't check that first.
if (computer->appList != m_Apps) {
// Just reset the whole thing if the list changes
beginResetModel();
m_Apps = computer->appList;
m_CurrentGameId = computer->currentGameId;
endResetModel();
return;
if (computer->appList != m_AllApps) {
updateAppList(computer->appList);
}
// Finally, process changes to the active app
if (computer->currentGameId != m_CurrentGameId) {
// First, invalidate the running state of newly running game
for (int i = 0; i < m_Apps.count(); i++) {
if (m_Apps[i].id == computer->currentGameId) {
for (int i = 0; i < m_VisibleApps.count(); i++) {
if (m_VisibleApps[i].id == computer->currentGameId) {
emit dataChanged(createIndex(i, 0),
createIndex(i, 0),
QVector<int>() << RunningRole);
@@ -142,8 +243,8 @@ void AppModel::handleComputerStateChanged(NvComputer* computer)
// Next, invalidate the running state of the old game (if it exists)
if (m_CurrentGameId != 0) {
for (int i = 0; i < m_Apps.count(); i++) {
if (m_Apps[i].id == m_CurrentGameId) {
for (int i = 0; i < m_VisibleApps.count(); i++) {
if (m_VisibleApps[i].id == m_CurrentGameId) {
emit dataChanged(createIndex(i, 0),
createIndex(i, 0),
QVector<int>() << RunningRole);
@@ -161,7 +262,7 @@ void AppModel::handleBoxArtLoaded(NvComputer* computer, NvApp app, QUrl /* image
{
Q_ASSERT(computer == m_Computer);
int index = m_Apps.indexOf(app);
int index = m_VisibleApps.indexOf(app);
// Make sure we're not delivering a callback to an app that's already been removed
if (index >= 0) {
+15 -4
View File
@@ -14,23 +14,27 @@ class AppModel : public QAbstractListModel
{
NameRole = Qt::UserRole,
RunningRole,
BoxArtRole
BoxArtRole,
HiddenRole,
AppIdRole,
};
public:
explicit AppModel(QObject *parent = nullptr);
// Must be called before any QAbstractListModel functions
Q_INVOKABLE void initialize(ComputerManager* computerManager, int computerIndex);
Q_INVOKABLE void initialize(ComputerManager* computerManager, int computerIndex, bool showHiddenGames);
Q_INVOKABLE Session* createSessionForApp(int appIndex);
Q_INVOKABLE int getRunningAppIndex();
Q_INVOKABLE int getRunningAppId();
Q_INVOKABLE QString getRunningAppName();
Q_INVOKABLE void quitRunningApp();
Q_INVOKABLE void setAppHidden(int appIndex, bool hidden);
QVariant data(const QModelIndex &index, int role) const override;
int rowCount(const QModelIndex &parent) const override;
@@ -46,9 +50,16 @@ signals:
void computerLost();
private:
void updateAppList(QVector<NvApp> newList);
QVector<NvApp> getVisibleApps(const QVector<NvApp>& appList);
bool isAppCurrentlyVisible(const NvApp& app);
NvComputer* m_Computer;
BoxArtManager m_BoxArtManager;
ComputerManager* m_ComputerManager;
QVector<NvApp> m_Apps;
QVector<NvApp> m_VisibleApps, m_AllApps;
int m_CurrentGameId;
bool m_ShowHiddenGames;
};
+67 -17
View File
@@ -2,6 +2,8 @@
#include <QThreadPool>
#include <random>
ComputerModel::ComputerModel(QObject* object)
: QAbstractListModel(object) {}
@@ -22,18 +24,6 @@ QVariant ComputerModel::data(const QModelIndex& index, int role) const
return QVariant();
}
if (index.row() == m_Computers.count()) {
// We insert a synthetic item at the end for the Add PC option
switch (role) {
case NameRole:
return "Add PC";
case AddPcRole:
return true;
default:
return QVariant();
}
}
Q_ASSERT(index.row() < m_Computers.count());
NvComputer* computer = m_Computers[index.row()];
@@ -50,8 +40,6 @@ QVariant ComputerModel::data(const QModelIndex& index, int role) const
return computer->currentGameId != 0;
case WakeableRole:
return !computer->macAddress.isEmpty();
case AddPcRole:
return false;
case StatusUnknownRole:
return computer->state == NvComputer::CS_UNKNOWN;
default:
@@ -67,8 +55,7 @@ int ComputerModel::rowCount(const QModelIndex& parent) const
return 0;
}
// Add PC placeholder counts as 1
return m_Computers.count() + 1;
return m_Computers.count();
}
QHash<int, QByteArray> ComputerModel::roleNames() const
@@ -79,7 +66,6 @@ QHash<int, QByteArray> ComputerModel::roleNames() const
names[OnlineRole] = "online";
names[PairedRole] = "paired";
names[BusyRole] = "busy";
names[AddPcRole] = "addPc";
names[WakeableRole] = "wakeable";
names[StatusUnknownRole] = "statusUnknown";
@@ -144,6 +130,69 @@ void ComputerModel::wakeComputer(int computerIndex)
QThreadPool::globalInstance()->start(wakeTask);
}
void ComputerModel::renameComputer(int computerIndex, QString name)
{
Q_ASSERT(computerIndex < m_Computers.count());
m_ComputerManager->renameHost(m_Computers[computerIndex], name);
}
// TODO: Use QRandomGenerator when we drop Qt 5.9 support
QString ComputerModel::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
{
Q_OBJECT
public:
void run()
{
unsigned int portTestResult = LiTestClientConnectivity("qt.conntest.moonlight-stream.org", 443, ML_PORT_FLAG_ALL);
if (portTestResult == ML_TEST_RESULT_INCONCLUSIVE) {
emit connectionTestCompleted(-1, QString());
}
else {
QString blockedPorts;
for (int i = 0; i < 32; i++) {
if (portTestResult & (1 << i)) {
if (!blockedPorts.isEmpty()) {
blockedPorts += "\n";
}
if (LiGetProtocolFromPortFlagIndex(i) == 17 /* IPPROTO_UDP */) {
blockedPorts += "UDP ";
}
else {
blockedPorts += "TCP ";
}
blockedPorts += QString::number(LiGetPortFromPortFlagIndex(i));
}
}
emit connectionTestCompleted(portTestResult, blockedPorts);
}
}
signals:
void connectionTestCompleted(int result, QString blockedPorts);
};
void ComputerModel::testConnectionForComputer(int)
{
DeferredTestConnectionTask* testConnectionTask = new DeferredTestConnectionTask();
QObject::connect(testConnectionTask, &DeferredTestConnectionTask::connectionTestCompleted,
this, &ComputerModel::connectionTestCompleted);
QThreadPool::globalInstance()->start(testConnectionTask);
}
void ComputerModel::pairComputer(int computerIndex, QString pin)
{
Q_ASSERT(computerIndex < m_Computers.count());
@@ -174,3 +223,4 @@ void ComputerModel::handleComputerStateChanged(NvComputer* computer)
}
}
#include "computermodel.moc"
+8 -2
View File
@@ -14,8 +14,7 @@ class ComputerModel : public QAbstractListModel
PairedRole,
BusyRole,
WakeableRole,
StatusUnknownRole,
AddPcRole
StatusUnknownRole
};
public:
@@ -32,14 +31,21 @@ public:
Q_INVOKABLE void deleteComputer(int computerIndex);
Q_INVOKABLE QString generatePinString();
Q_INVOKABLE void pairComputer(int computerIndex, QString pin);
Q_INVOKABLE void testConnectionForComputer(int computerIndex);
Q_INVOKABLE void wakeComputer(int computerIndex);
Q_INVOKABLE void renameComputer(int computerIndex, QString name);
Q_INVOKABLE Session* createSessionForCurrentGame(int computerIndex);
signals:
void pairingCompleted(QVariant error);
void connectionTestCompleted(int result, QString blockedPorts);
private slots:
void handleComputerStateChanged(NvComputer* computer);
+186 -110
View File
@@ -1,14 +1,13 @@
import QtQuick 2.9
import QtQuick.Controls 2.2
import QtQuick.Dialogs 1.2
import QtQuick.Layouts 1.3
import QtQuick.Window 2.2
import QtQuick.Controls.Material 2.1
import ComputerManager 1.0
import AutoUpdateChecker 1.0
import StreamingPreferences 1.0
import SystemProperties 1.0
import SdlGamepadKeyNavigation 1.0
ApplicationWindow {
property bool pollingActive: false
@@ -18,14 +17,7 @@ ApplicationWindow {
width: 1280
height: 600
visibility: prefs.startWindowed ? "Windowed" : "Maximized"
Material.theme: Material.Dark
Material.accent: Material.Purple
StreamingPreferences {
id: prefs
}
visibility: (SystemProperties.hasWindowManager && StreamingPreferences.startWindowed) ? "Windowed" : "Maximized"
StackView {
id: stackView
@@ -142,19 +134,20 @@ ApplicationWindow {
// onAfterRendering call and potentially reenter this code.
initialized = true;
if (prefs.isRunningWayland()) {
waylandDialog.open()
}
else if (prefs.isWow64()) {
if (SystemProperties.isWow64) {
wow64Dialog.open()
}
else if (!prefs.hasAnyHardwareAcceleration()) {
noHwDecoderDialog.open()
else if (!SystemProperties.hasHardwareAcceleration) {
if (SystemProperties.isRunningXWayland) {
xWaylandDialog.open()
}
else {
noHwDecoderDialog.open()
}
}
var unmappedGamepads = prefs.getUnmappedGamepads()
if (unmappedGamepads) {
unmappedGamepadDialog.unmappedGamepads = unmappedGamepads
if (SystemProperties.unmappedGamepads) {
unmappedGamepadDialog.unmappedGamepads = SystemProperties.unmappedGamepads
unmappedGamepadDialog.open()
}
}
@@ -178,28 +171,32 @@ ApplicationWindow {
header: ToolBar {
id: toolBar
height: 60
anchors.topMargin: 5
anchors.bottomMargin: 5
Label {
id: titleLabel
visible: toolBar.width > 700
anchors.fill: parent
text: stackView.currentItem.objectName
font.pointSize: 20
elide: Label.ElideRight
horizontalAlignment: Qt.AlignHCenter
verticalAlignment: Qt.AlignVCenter
}
RowLayout {
spacing: 20
anchors.leftMargin: 10
anchors.rightMargin: 10
anchors.fill: parent
NavigableToolButton {
// Only make the button visible if the user has navigated somewhere.
visible: stackView.depth > 1
// FIXME: We're using an Image here rather than icon.source because
// icons don't work on Qt 5.9 LTS.
Image {
source: "qrc:/res/arrow_left.svg"
anchors.centerIn: parent
sourceSize {
// The icon should be square so use the height as the width too
width: toolBar.height - toolBar.anchors.bottomMargin - toolBar.anchors.topMargin
height: toolBar.height - toolBar.anchors.bottomMargin - toolBar.anchors.topMargin
}
}
iconSource: "qrc:/res/arrow_left.svg"
onClicked: stackView.pop()
@@ -208,14 +205,75 @@ ApplicationWindow {
}
}
// This label will appear when the window gets too small and
// we need to ensure the toolbar controls don't collide
Label {
id: titleLabel
text: stackView.currentItem.objectName
font.pointSize: 15
id: titleRowLabel
font.pointSize: titleLabel.font.pointSize
elide: Label.ElideRight
horizontalAlignment: Qt.AlignHCenter
verticalAlignment: Qt.AlignVCenter
Layout.fillWidth: true
// We need this label to always be visible so it can occupy
// the remaining space in the RowLayout. To "hide" it, we
// just set the text to empty string.
text: !titleLabel.visible ? stackView.currentItem.objectName : ""
}
Label {
id: versionLabel
visible: stackView.currentItem.objectName === "Settings"
text: "Version " + SystemProperties.versionString
font.pointSize: 12
horizontalAlignment: Qt.AlignRight
verticalAlignment: Qt.AlignVCenter
}
NavigableToolButton {
id: discordButton
visible: SystemProperties.hasBrowser &&
stackView.currentItem.objectName === "Settings"
iconSource: "qrc:/res/Discord-Logo-White.svg"
ToolTip.delay: 1000
ToolTip.timeout: 3000
ToolTip.visible: hovered
ToolTip.text: "Join our community on Discord"
// TODO need to make sure browser is brought to foreground.
onClicked: Qt.openUrlExternally("https://moonlight-stream.org/discord");
Keys.onDownPressed: {
stackView.currentItem.forceActiveFocus(Qt.TabFocus)
}
}
NavigableToolButton {
id: addPcButton
visible: stackView.currentItem.objectName === "Computers"
iconSource: "qrc:/res/ic_add_to_queue_white_48px.svg"
ToolTip.delay: 1000
ToolTip.timeout: 3000
ToolTip.visible: hovered
ToolTip.text: "Add PC manually" + (newPcShortcut.nativeText ? (" ("+newPcShortcut.nativeText+")") : "")
Shortcut {
id: newPcShortcut
sequence: StandardKey.New
onActivated: addPcButton.clicked()
}
onClicked: {
addPcDialog.open()
}
Keys.onDownPressed: {
stackView.currentItem.forceActiveFocus(Qt.TabFocus)
}
}
NavigableToolButton {
@@ -223,28 +281,25 @@ ApplicationWindow {
id: updateButton
Image {
source: "qrc:/res/update.svg"
anchors.centerIn: parent
sourceSize {
width: toolBar.height - toolBar.anchors.bottomMargin - toolBar.anchors.topMargin
height: toolBar.height - toolBar.anchors.bottomMargin - toolBar.anchors.topMargin
}
}
iconSource: "qrc:/res/update.svg"
ToolTip.delay: 1000
ToolTip.timeout: 3000
ToolTip.visible: hovered
ToolTip.text: "Update available for Moonlight"
ToolTip.visible: hovered || visible
// Invisible until we get a callback notifying us that
// an update is available
visible: false
onClicked: Qt.openUrlExternally(browserUrl);
onClicked: {
if (SystemProperties.hasBrowser) {
Qt.openUrlExternally(browserUrl);
}
}
function updateAvailable(url)
function updateAvailable(version, url)
{
ToolTip.text = "Update available for Moonlight: Version " + version
updateButton.browserUrl = url
updateButton.visible = true
}
@@ -261,15 +316,9 @@ ApplicationWindow {
NavigableToolButton {
id: helpButton
visible: SystemProperties.hasBrowser
Image {
source: "qrc:/res/question_mark.svg"
anchors.centerIn: parent
sourceSize {
width: toolBar.height - toolBar.anchors.bottomMargin - toolBar.anchors.topMargin
height: toolBar.height - toolBar.anchors.bottomMargin - toolBar.anchors.topMargin
}
}
iconSource: "qrc:/res/question_mark.svg"
ToolTip.delay: 1000
ToolTip.timeout: 3000
@@ -299,14 +348,7 @@ ApplicationWindow {
ToolTip.visible: hovered
ToolTip.text: "Gamepad Mapper"
Image {
source: "qrc:/res/ic_videogame_asset_white_48px.svg"
anchors.centerIn: parent
sourceSize {
width: toolBar.height - toolBar.anchors.bottomMargin - toolBar.anchors.topMargin
height: toolBar.height - toolBar.anchors.bottomMargin - toolBar.anchors.topMargin
}
}
iconSource: "qrc:/res/ic_videogame_asset_white_48px.svg"
onClicked: navigateTo("qrc:/gui/GamepadMapper.qml", "Gamepad Mapping")
@@ -318,14 +360,7 @@ ApplicationWindow {
NavigableToolButton {
id: settingsButton
Image {
source: "qrc:/res/settings.svg"
anchors.centerIn: parent
sourceSize {
width: toolBar.height - toolBar.anchors.bottomMargin - toolBar.anchors.topMargin
height: toolBar.height - toolBar.anchors.bottomMargin - toolBar.anchors.topMargin
}
}
iconSource: "qrc:/res/settings.svg"
onClicked: navigateTo("qrc:/gui/SettingsView.qml", "Settings")
@@ -347,67 +382,108 @@ ApplicationWindow {
}
}
MessageDialog {
ErrorMessageDialog {
id: noHwDecoderDialog
modality:Qt.WindowModal
icon: StandardIcon.Warning
standardButtons: StandardButton.Ok | StandardButton.Help
text: "No functioning hardware accelerated H.264 video decoder was detected by Moonlight. " +
"Your streaming performance may be severely degraded in this configuration. " +
"Click the Help button for more information on solving this problem."
onHelp: {
Qt.openUrlExternally("https://github.com/moonlight-stream/moonlight-docs/wiki/Fixing-Hardware-Decoding-Problems");
}
"Your streaming performance may be severely degraded in this configuration."
helpText: "Click the Help button for more information on solving this problem."
helpUrl: "https://github.com/moonlight-stream/moonlight-docs/wiki/Fixing-Hardware-Decoding-Problems"
}
MessageDialog {
id: waylandDialog
modality:Qt.WindowModal
icon: StandardIcon.Warning
standardButtons: StandardButton.Ok | StandardButton.Help
text: "Moonlight does not support hardware acceleration on Wayland. Continuing on Wayland may result in poor streaming performance. " +
"Please switch to an X session for optimal performance."
onHelp: {
Qt.openUrlExternally("https://github.com/moonlight-stream/moonlight-docs/wiki/Fixing-Hardware-Decoding-Problems");
}
ErrorMessageDialog {
id: xWaylandDialog
text: "Hardware acceleration doesn't work on XWayland. Continuing on XWayland may result in poor streaming performance. " +
"Try running with QT_QPA_PLATFORM=wayland or switch to X11."
helpText: "Click the Help button for more information."
helpUrl: "https://github.com/moonlight-stream/moonlight-docs/wiki/Fixing-Hardware-Decoding-Problems"
}
MessageDialog {
NavigableMessageDialog {
id: wow64Dialog
modality:Qt.WindowModal
icon: StandardIcon.Warning
standardButtons: StandardButton.Ok | StandardButton.Cancel
standardButtons: Dialog.Ok | Dialog.Cancel
text: "This PC is running a 64-bit version of Windows. Please download the x64 version of Moonlight for the best streaming performance."
onAccepted: {
Qt.openUrlExternally("https://github.com/moonlight-stream/moonlight-qt/releases");
}
}
MessageDialog {
ErrorMessageDialog {
id: unmappedGamepadDialog
property string unmappedGamepads : ""
modality:Qt.WindowModal
icon: StandardIcon.Warning
standardButtons: StandardButton.Ok | StandardButton.Help
text: "Moonlight detected gamepads without a proper mapping. " +
"The following gamepads will not function until this is resolved: " + unmappedGamepads + "\n\n" +
"Click the Help button for information on how to map your gamepads."
onHelp: {
Qt.openUrlExternally("https://github.com/moonlight-stream/moonlight-docs/wiki/Gamepad-Mapping");
}
text: "Moonlight detected gamepads without a mapping:\n" + unmappedGamepads
helpTextSeparator: "\n\n"
helpText: "Click the Help button for information on how to map your gamepads."
helpUrl: "https://github.com/moonlight-stream/moonlight-docs/wiki/Gamepad-Mapping"
}
// This dialog appears when quitting via keyboard or gamepad button
MessageDialog {
NavigableMessageDialog {
id: quitConfirmationDialog
modality:Qt.WindowModal
icon: StandardIcon.Warning
standardButtons: StandardButton.Yes | StandardButton.No
standardButtons: Dialog.Yes | Dialog.No
text: "Are you sure you want to quit?"
onYes: Qt.quit()
// For keyboard/gamepad navigation
onAccepted: Qt.quit()
}
// HACK: This belongs in StreamSegue but keeping a dialog around after the parent
// dies can trigger bugs in Qt 5.12 that cause the app to crash. For now, we will
// host this dialog in a QML component that is never destroyed.
//
// To repro: Start a stream, cut the network connection to trigger the "Connection
// terminated" dialog, wait until the app grid times out back to the PC grid, then
// try to dismiss the dialog.
ErrorMessageDialog {
id: streamSegueErrorDialog
property bool quitAfter: false
onClosed: {
if (quitAfter) {
Qt.quit()
}
// StreamSegue assumes its dialog will be re-created each time we
// start streaming, so fake it by wiping out the text each time.
text = ""
}
}
NavigableDialog {
id: addPcDialog
property string label: "Enter the IP address of your GameStream PC:"
standardButtons: Dialog.Ok | Dialog.Cancel
onOpened: {
// Force keyboard focus on the textbox so keyboard navigation works
editText.forceActiveFocus()
}
onClosed: {
editText.clear()
}
onAccepted: {
if (editText.text) {
ComputerManager.addNewHost(editText.text, false)
}
}
ColumnLayout {
Label {
text: addPcDialog.label
font.bold: true
}
TextField {
id: editText
Layout.fillWidth: true
focus: true
Keys.onReturnPressed: {
addPcDialog.accept()
}
}
}
}
}
+55 -42
View File
@@ -10,7 +10,7 @@
SdlGamepadKeyNavigation::SdlGamepadKeyNavigation()
: m_Enabled(false),
m_SettingsMode(false),
m_UiNavMode(false),
m_LastAxisNavigationEventTime(0)
{
m_PollingTimer = new QTimer(this);
@@ -91,6 +91,12 @@ void SdlGamepadKeyNavigation::onPollingTimerFired()
while (SDL_PollEvent(&event)) {
switch (event.type) {
case SDL_QUIT:
// SDL may send us a quit event since we initialize
// the video subsystem on startup. If we get one,
// forward it on for Qt to take care of.
QCoreApplication::instance()->quit();
break;
case SDL_CONTROLLERBUTTONDOWN:
case SDL_CONTROLLERBUTTONUP:
{
@@ -100,7 +106,7 @@ void SdlGamepadKeyNavigation::onPollingTimerFired()
switch (event.cbutton.button) {
case SDL_CONTROLLER_BUTTON_DPAD_UP:
if (m_SettingsMode) {
if (m_UiNavMode) {
// Back-tab
sendKey(type, Qt::Key_Tab, Qt::ShiftModifier);
}
@@ -109,7 +115,7 @@ void SdlGamepadKeyNavigation::onPollingTimerFired()
}
break;
case SDL_CONTROLLER_BUTTON_DPAD_DOWN:
if (m_SettingsMode) {
if (m_UiNavMode) {
sendKey(type, Qt::Key_Tab);
}
else {
@@ -118,24 +124,12 @@ void SdlGamepadKeyNavigation::onPollingTimerFired()
break;
case SDL_CONTROLLER_BUTTON_DPAD_LEFT:
sendKey(type, Qt::Key_Left);
if (m_SettingsMode) {
// Some settings controls respond to left/right (like the slider)
// and others respond to up/down (like combo boxes). They seem to
// be mutually exclusive though so let's just send both.
sendKey(type, Qt::Key_Up);
}
break;
case SDL_CONTROLLER_BUTTON_DPAD_RIGHT:
sendKey(type, Qt::Key_Right);
if (m_SettingsMode) {
// Some settings controls respond to left/right (like the slider)
// and others respond to up/down (like combo boxes). They seem to
// be mutually exclusive though so let's just send both.
sendKey(type, Qt::Key_Down);
}
break;
case SDL_CONTROLLER_BUTTON_A:
if (m_SettingsMode) {
if (m_UiNavMode) {
sendKey(type, Qt::Key_Space);
}
else {
@@ -177,7 +171,7 @@ void SdlGamepadKeyNavigation::onPollingTimerFired()
// Do nothing
}
else if (leftY < -30000) {
if (m_SettingsMode) {
if (m_UiNavMode) {
// Back-tab
sendKey(QEvent::Type::KeyPress, Qt::Key_Tab, Qt::ShiftModifier);
sendKey(QEvent::Type::KeyRelease, Qt::Key_Tab, Qt::ShiftModifier);
@@ -190,7 +184,7 @@ void SdlGamepadKeyNavigation::onPollingTimerFired()
m_LastAxisNavigationEventTime = SDL_GetTicks();
}
else if (leftY > 30000) {
if (m_SettingsMode) {
if (m_UiNavMode) {
sendKey(QEvent::Type::KeyPress, Qt::Key_Tab);
sendKey(QEvent::Type::KeyRelease, Qt::Key_Tab);
}
@@ -204,28 +198,37 @@ void SdlGamepadKeyNavigation::onPollingTimerFired()
else if (leftX < -30000) {
sendKey(QEvent::Type::KeyPress, Qt::Key_Left);
sendKey(QEvent::Type::KeyRelease, Qt::Key_Left);
if (m_SettingsMode) {
// Some settings controls respond to left/right (like the slider)
// and others respond to up/down (like combo boxes). They seem to
// be mutually exclusive though so let's just send both.
sendKey(QEvent::Type::KeyPress, Qt::Key_Up);
sendKey(QEvent::Type::KeyRelease, Qt::Key_Up);
}
m_LastAxisNavigationEventTime = SDL_GetTicks();
}
else if (leftX > 30000) {
sendKey(QEvent::Type::KeyPress, Qt::Key_Right);
sendKey(QEvent::Type::KeyRelease, Qt::Key_Right);
if (m_SettingsMode) {
// Some settings controls respond to left/right (like the slider)
// and others respond to up/down (like combo boxes). They seem to
// be mutually exclusive though so let's just send both.
sendKey(QEvent::Type::KeyPress, Qt::Key_Down);
sendKey(QEvent::Type::KeyRelease, Qt::Key_Down);
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);
}
m_LastAxisNavigationEventTime = SDL_GetTicks();
if (rightY > 30000) {
wheelDelta.setY(-30);
}
else if (rightY < -30000) {
wheelDelta.setY(30);
}
if (!wheelDelta.isNull()) {
sendWheel(wheelDelta);
}
}
}
}
@@ -240,19 +243,30 @@ void SdlGamepadKeyNavigation::sendKey(QEvent::Type type, Qt::Key key, Qt::Keyboa
}
}
void SdlGamepadKeyNavigation::setSettingsMode(bool settingsMode)
void SdlGamepadKeyNavigation::sendWheel(QPoint& angleDelta)
{
m_SettingsMode = settingsMode;
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);
}
}
void SdlGamepadKeyNavigation::setUiNavMode(bool uiNavMode)
{
m_UiNavMode = uiNavMode;
}
int SdlGamepadKeyNavigation::getConnectedGamepads()
{
if (SDL_InitSubSystem(SDL_INIT_GAMECONTROLLER) != 0) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
"SDL_InitSubSystem(SDL_INIT_GAMECONTROLLER) failed: %s",
SDL_GetError());
return 0;
}
Q_ASSERT(m_Enabled);
int count = 0;
for (int i = 0; i < SDL_NumJoysticks(); i++) {
@@ -261,6 +275,5 @@ int SdlGamepadKeyNavigation::getConnectedGamepads()
}
}
SDL_QuitSubSystem(SDL_INIT_GAMECONTROLLER);
return count;
}
+3 -2
View File
@@ -18,12 +18,13 @@ public:
Q_INVOKABLE void disable();
Q_INVOKABLE void setSettingsMode(bool settingsMode);
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 sendWheel(QPoint& angleDelta);
private slots:
void onPollingTimerFired();
@@ -32,6 +33,6 @@ private:
QTimer* m_PollingTimer;
QList<SDL_GameController*> m_Gamepads;
bool m_Enabled;
bool m_SettingsMode;
bool m_UiNavMode;
Uint32 m_LastAxisNavigationEventTime;
};
+200 -28
View File
@@ -6,6 +6,11 @@
#include <QMutex>
#include <QtDebug>
#include <QNetworkProxyFactory>
#include <QPalette>
#include <QFont>
#include <QCursor>
#include <QElapsedTimer>
#include <QFile>
// Don't let SDL hook our main function, since Qt is already
// doing the same thing. This needs to be before any headers
@@ -17,17 +22,21 @@
#include "streaming/video/ffmpeg.h"
#endif
#ifdef Q_OS_WIN32
#if defined(Q_OS_WIN32)
#include "antihookingprotection.h"
#elif defined(Q_OS_LINUX)
#include <openssl/ssl.h>
#endif
#include "cli/quitstream.h"
#include "cli/startstream.h"
#include "cli/commandlineparser.h"
#include "path.h"
#include "utils.h"
#include "gui/computermodel.h"
#include "gui/appmodel.h"
#include "backend/autoupdatechecker.h"
#include "backend/systemproperties.h"
#include "streaming/session.h"
#include "settings/streamingpreferences.h"
#include "gui/sdlgamepadkeynavigation.h"
@@ -48,7 +57,7 @@
#endif
#ifdef USE_CUSTOM_LOGGER
static QTime s_LoggerTime;
static QElapsedTimer s_LoggerTime;
static QTextStream s_LoggerStream(stdout);
static QMutex s_LoggerLock;
#ifdef LOG_TO_FILE
@@ -67,7 +76,12 @@ void logToLoggerStream(QString& message)
return;
}
else if (s_LogLinesWritten == MAX_LOG_LINES) {
s_LoggerStream << "Log size limit reached!" << endl;
s_LoggerStream << "Log size limit reached!";
#if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0)
s_LoggerStream << Qt::endl;
#else
s_LoggerStream << endl;
#endif
s_LogLimitReached = true;
return;
}
@@ -223,6 +237,8 @@ LONG WINAPI UnhandledExceptionHandler(struct _EXCEPTION_POINTERS *ExceptionInfo)
int main(int argc, char *argv[])
{
SDL_SetMainReady();
// Set the app version for the QCommandLineParser's showVersion() command
QCoreApplication::setApplicationVersion(VERSION_STR);
@@ -272,17 +288,48 @@ int main(int argc, char *argv[])
SetUnhandledExceptionFilter(UnhandledExceptionHandler);
#endif
#ifdef Q_OS_WIN32
#if defined(Q_OS_WIN32)
// Force AntiHooking.dll to be statically imported and loaded
// by ntdll by calling a dummy function.
AntiHookingDummyImport();
#elif defined(Q_OS_LINUX)
// Force libssl.so to be directly linked to our binary, so
// linuxdeployqt can find it and include it in our AppImage.
// QtNetwork will pull it in via dlopen().
SSL_free(nullptr);
#endif
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
// Avoid using High DPI on EGLFS. It breaks font rendering.
// https://bugreports.qt.io/browse/QTBUG-64377
//
// NB: We can't use QGuiApplication::platformName() here because it is only
// set once the QGuiApplication is created, which is too late to enable High DPI :(
if (WMUtils::isRunningWindowManager()) {
// Enable High DPI support
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
#if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0)
// Enable fractional High DPI scaling on Qt 5.14 and later
QGuiApplication::setHighDpiScaleFactorRoundingPolicy(Qt::HighDpiScaleFactorRoundingPolicy::PassThrough);
#endif
}
else {
#ifndef STEAM_LINK
if (!qEnvironmentVariableIsSet("QT_QPA_PLATFORM")) {
qInfo() << "Unable to detect Wayland or X11, so EGLFS will be used by default. Set QT_QPA_PLATFORM to override this.";
qputenv("QT_QPA_PLATFORM", "eglfs");
if (!QFile("/dev/dri").exists()) {
qWarning() << "Unable to find a KMSDRM display device!";
qWarning() << "On the Raspberry Pi, you must enable the 'fake KMS' driver in raspi-config to use Moonlight outside of the GUI environment.";
}
}
#endif
}
// This avoids using the default keychain for SSL, which may cause
// password prompts on macOS.
qputenv("QT_SSL_USE_TEMPORARY_KEYCHAIN", QByteArray("1"));
qputenv("QT_SSL_USE_TEMPORARY_KEYCHAIN", "1");
#ifdef Q_OS_WIN32
if (!qEnvironmentVariableIsSet("QT_OPENGL")) {
@@ -303,15 +350,116 @@ int main(int argc, char *argv[])
// Register custom metatypes for use in signals
qRegisterMetaType<NvApp>("NvApp");
SDL_version compileVersion;
SDL_VERSION(&compileVersion);
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION,
"Compiled with SDL %d.%d.%d",
compileVersion.major, compileVersion.minor, compileVersion.patch);
SDL_version runtimeVersion;
SDL_GetVersion(&runtimeVersion);
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION,
"Running with SDL %d.%d.%d",
runtimeVersion.major, runtimeVersion.minor, runtimeVersion.patch);
// Allow the display to sleep by default. We will manually use SDL_DisableScreenSaver()
// and SDL_EnableScreenSaver() when appropriate. This hint must be set before
// initializing the SDL video subsystem to have any effect.
SDL_SetHint(SDL_HINT_VIDEO_ALLOW_SCREENSAVER, "1");
// For SDL backends that support it, use double buffering instead of triple buffering
// to save a frame of latency. This doesn't matter for MMAL or DRM renderers since they
// are drawing directly to the screen without involving SDL, but it may matter for other
// future KMSDRM platforms that use SDL for rendering.
SDL_SetHint(SDL_HINT_VIDEO_DOUBLE_BUFFER, "1");
if (SDL_InitSubSystem(SDL_INIT_TIMER) != 0) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
"SDL_InitSubSystem(SDL_INIT_TIMER) failed: %s",
SDL_GetError());
return -1;
}
#ifdef STEAM_LINK
// Steam Link requires that we initialize video before creating our
// QGuiApplication in order to configure the framebuffer correctly.
if (SDL_InitSubSystem(SDL_INIT_VIDEO) != 0) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
"SDL_InitSubSystem(SDL_INIT_VIDEO) failed: %s",
SDL_GetError());
return -1;
}
#endif
// Use atexit() to ensure SDL_Quit() is called. This avoids
// racing with object destruction where SDL may be used.
atexit(SDL_Quit);
// Avoid the default behavior of changing the timer resolution to 1 ms.
// We don't want this all the time that Moonlight is open. We will set
// it manually when we start streaming.
SDL_SetHint(SDL_HINT_TIMER_RESOLUTION, "0");
// Disable minimize on focus loss by default. Users seem to want this off by default.
SDL_SetHint(SDL_HINT_VIDEO_MINIMIZE_ON_FOCUS_LOSS, "0");
// SDL 2.0.12 changes the default behavior to use the button label rather than the button
// position as most other software does. Set this back to 0 to stay consistent with prior
// releases of Moonlight.
SDL_SetHint("SDL_GAMECONTROLLER_USE_BUTTON_LABELS", "0");
#ifdef QT_DEBUG
// Allow thread naming using exceptions on debug builds. SDL doesn't use SEH
// when throwing the exceptions, so we don't enable it for release builds out
// of caution.
SDL_SetHint(SDL_HINT_WINDOWS_DISABLE_THREAD_NAMING, "0");
#endif
QGuiApplication app(argc, argv);
// After the QGuiApplication is created, the platform stuff will be initialized
// and we can set the SDL video driver to match Qt.
if (WMUtils::isRunningWayland() && QGuiApplication::platformName() == "xcb") {
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION,
"Detected XWayland. This will probably break hardware decoding! Try running with QT_QPA_PLATFORM=wayland or switch to X11.");
}
else if (QGuiApplication::platformName().startsWith("wayland")) {
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Detected Wayland");
qputenv("SDL_VIDEODRIVER", "wayland");
}
#ifdef STEAM_LINK
// Qt 5.9 from the Steam Link SDK is not able to load any fonts
// since the Steam Link doesn't include any of the ones it looks
// for. We know it has NotoSans so we will explicitly ask for that.
if (app.font().family().isEmpty()) {
qWarning() << "SL HACK: No default font - using NotoSans";
QFont fon("NotoSans");
app.setFont(fon);
}
// Move the mouse to the bottom right so it's invisible when using
// gamepad-only navigation.
QCursor().setPos(0xFFFF, 0xFFFF);
#elif !SDL_VERSION_ATLEAST(2, 0, 11) && defined(Q_OS_LINUX) && (defined(__arm__) || defined(__aarch64__))
if (qgetenv("SDL_VIDEO_GL_DRIVER").isEmpty() && QGuiApplication::platformName() == "eglfs") {
// Look for Raspberry Pi GLES libraries. SDL 2.0.10 and earlier needs some help finding
// the correct libraries for the KMSDRM backend if not compiled with the RPI backend enabled.
if (SDL_LoadObject("libbrcmGLESv2.so") != nullptr) {
qputenv("SDL_VIDEO_GL_DRIVER", "libbrcmGLESv2.so");
}
else if (SDL_LoadObject("/opt/vc/lib/libbrcmGLESv2.so") != nullptr) {
qputenv("SDL_VIDEO_GL_DRIVER", "/opt/vc/lib/libbrcmGLESv2.so");
}
}
#endif
app.setWindowIcon(QIcon(":/res/moonlight.svg"));
// Register our C++ types for QML
qmlRegisterType<ComputerModel>("ComputerModel", 1, 0, "ComputerModel");
qmlRegisterType<AppModel>("AppModel", 1, 0, "AppModel");
qmlRegisterType<StreamingPreferences>("StreamingPreferences", 1, 0, "StreamingPreferences");
qmlRegisterType<SdlGamepadKeyNavigation>("SdlGamepadKeyNavigation", 1, 0, "SdlGamepadKeyNavigation");
qmlRegisterUncreatableType<Session>("Session", 1, 0, "Session", "Session cannot be created from QML");
qmlRegisterSingletonType<ComputerManager>("ComputerManager", 1, 0,
"ComputerManager",
@@ -323,8 +471,48 @@ int main(int argc, char *argv[])
[](QQmlEngine*, QJSEngine*) -> QObject* {
return new AutoUpdateChecker();
});
qmlRegisterSingletonType<SystemProperties>("SystemProperties", 1, 0,
"SystemProperties",
[](QQmlEngine*, QJSEngine*) -> QObject* {
return new SystemProperties();
});
qmlRegisterSingletonType<SdlGamepadKeyNavigation>("SdlGamepadKeyNavigation", 1, 0,
"SdlGamepadKeyNavigation",
[](QQmlEngine*, QJSEngine*) -> QObject* {
return new SdlGamepadKeyNavigation();
});
qmlRegisterSingletonType<StreamingPreferences>("StreamingPreferences", 1, 0,
"StreamingPreferences",
[](QQmlEngine*, QJSEngine*) -> QObject* {
return new StreamingPreferences();
});
QQuickStyle::setStyle("Material");
// Create the identity manager on the main thread
IdentityManager::get();
#ifndef Q_OS_WINRT
// Use the dense material dark theme by default
if (!qEnvironmentVariableIsSet("QT_QUICK_CONTROLS_STYLE")) {
qputenv("QT_QUICK_CONTROLS_STYLE", "Material");
}
#else
// Use universal dark on WinRT
if (!qEnvironmentVariableIsSet("QT_QUICK_CONTROLS_STYLE")) {
qputenv("QT_QUICK_CONTROLS_STYLE", "Universal");
}
#endif
if (!qEnvironmentVariableIsSet("QT_QUICK_CONTROLS_MATERIAL_THEME")) {
qputenv("QT_QUICK_CONTROLS_MATERIAL_THEME", "Dark");
}
if (!qEnvironmentVariableIsSet("QT_QUICK_CONTROLS_MATERIAL_ACCENT")) {
qputenv("QT_QUICK_CONTROLS_MATERIAL_ACCENT", "Purple");
}
if (!qEnvironmentVariableIsSet("QT_QUICK_CONTROLS_MATERIAL_VARIANT")) {
qputenv("QT_QUICK_CONTROLS_MATERIAL_VARIANT", "Dense");
}
if (!qEnvironmentVariableIsSet("QT_QUICK_CONTROLS_UNIVERSAL_THEME")) {
qputenv("QT_QUICK_CONTROLS_UNIVERSAL_THEME", "Dark");
}
QQmlApplicationEngine engine;
QString initialView;
@@ -332,11 +520,11 @@ int main(int argc, char *argv[])
GlobalCommandLineParser parser;
switch (parser.parse(app.arguments())) {
case GlobalCommandLineParser::NormalStartRequested:
initialView = "PcView.qml";
initialView = "qrc:/gui/PcView.qml";
break;
case GlobalCommandLineParser::StreamRequested:
{
initialView = "CliStartStreamSegue.qml";
initialView = "qrc:/gui/CliStartStreamSegue.qml";
StreamingPreferences* preferences = new StreamingPreferences(&app);
StreamCommandLineParser streamParser;
streamParser.parse(app.arguments(), preferences);
@@ -348,7 +536,7 @@ int main(int argc, char *argv[])
}
case GlobalCommandLineParser::QuitRequested:
{
initialView = "CliQuitStreamSegue.qml";
initialView = "qrc:/gui/CliQuitStreamSegue.qml";
QuitCommandLineParser quitParser;
quitParser.parse(app.arguments());
auto launcher = new CliQuitStream::Launcher(quitParser.getHost(), &app);
@@ -364,22 +552,6 @@ int main(int argc, char *argv[])
if (engine.rootObjects().isEmpty())
return -1;
SDL_SetMainReady();
if (SDL_Init(SDL_INIT_TIMER) != 0) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
"SDL_Init() failed: %s",
SDL_GetError());
}
// Use atexit() to ensure SDL_Quit() is called. This avoids
// racing with object destruction where SDL may be used.
atexit(SDL_Quit);
// Avoid the default behavior of changing the timer resolution to 1 ms.
// We don't want this all the time that Moonlight is open. We will set
// it manually when we start streaming.
SDL_SetHint(SDL_HINT_TIMER_RESOLUTION, "0");
int err = app.exec();
// Give worker tasks time to properly exit. Fixes PendingQuitTask
Binary file not shown.
BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 345 KiB

After

Width:  |  Height:  |  Size: 328 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.4 KiB

After

Width:  |  Height:  |  Size: 2.6 KiB

+18 -17
View File
@@ -8,7 +8,6 @@
QString Path::s_LogDir;
QString Path::s_BoxArtCacheDir;
const QString Path::k_GameControllerMappingFile("gamecontrollerdb.txt");
QString Path::getLogDir()
{
@@ -22,40 +21,42 @@ QString Path::getBoxArtCacheDir()
return s_BoxArtCacheDir;
}
QString Path::getGamepadMappingFile()
QByteArray Path::readDataFile(QString fileName)
{
QFile dataFile(getDataFilePath(fileName));
dataFile.open(QIODevice::ReadOnly);
return dataFile.readAll();
}
QString Path::getDataFilePath(QString fileName)
{
QString candidatePath;
// Check the current directory first
candidatePath = QDir(QDir::currentPath()).absoluteFilePath(k_GameControllerMappingFile);
candidatePath = QDir(QDir::currentPath()).absoluteFilePath(fileName);
if (QFile::exists(candidatePath)) {
qInfo() << "Found" << fileName << "at" << candidatePath;
return candidatePath;
}
// Now check the data directories (for Linux, in particular)
candidatePath = QStandardPaths::locate(QStandardPaths::DataLocation, k_GameControllerMappingFile);
candidatePath = QStandardPaths::locate(QStandardPaths::DataLocation, fileName);
if (!candidatePath.isEmpty() && QFile::exists(candidatePath)) {
qInfo() << "Found" << fileName << "at" << candidatePath;
return candidatePath;
}
// Now try the directory of our app installation (for Windows, if current dir doesn't find it)
candidatePath = QDir(QCoreApplication::applicationDirPath()).absoluteFilePath(k_GameControllerMappingFile);
candidatePath = QDir(QCoreApplication::applicationDirPath()).absoluteFilePath(fileName);
if (QFile::exists(candidatePath)) {
qInfo() << "Found" << fileName << "at" << candidatePath;
return candidatePath;
}
// Now try the Resources folder in our app bundle for macOS
QDir dir = QDir(QCoreApplication::applicationDirPath());
dir.cdUp();
dir.cd("Resources");
dir.filePath(k_GameControllerMappingFile);
candidatePath = dir.absoluteFilePath(k_GameControllerMappingFile);
if (QFile::exists(candidatePath)) {
return candidatePath;
}
// Couldn't find it
return QString();
// Return the QRC embedded copy
candidatePath = ":/data/" + fileName;
qInfo() << "Found" << fileName << "at" << candidatePath;
return QString(candidatePath);
}
void Path::initialize(bool portable)
+4 -2
View File
@@ -9,12 +9,14 @@ public:
static QString getBoxArtCacheDir();
static QString getGamepadMappingFile();
static QByteArray readDataFile(QString fileName);
// Only safe to use directly for Qt classes
static QString getDataFilePath(QString fileName);
static void initialize(bool portable);
private:
static QString s_LogDir;
static QString s_BoxArtCacheDir;
static const QString k_GameControllerMappingFile;
};
+5
View File
@@ -13,5 +13,10 @@
<file>gui/CliQuitStreamSegue.qml</file>
<file>gui/CliStartStreamSegue.qml</file>
<file>gui/AutoResizingComboBox.qml</file>
<file>gui/NavigableMenu.qml</file>
<file>gui/ErrorMessageDialog.qml</file>
<file>gui/NavigableMessageDialog.qml</file>
<file>gui/NavigableDialog.qml</file>
<file>gui/CenteredGridView.qml</file>
</qresource>
</RCC>
+1
View File
@@ -0,0 +1 @@
<svg id="Layer_1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 245 240"><style>.st0{fill:#FFFFFF;}</style><path class="st0" d="M104.4 103.9c-5.7 0-10.2 5-10.2 11.1s4.6 11.1 10.2 11.1c5.7 0 10.2-5 10.2-11.1.1-6.1-4.5-11.1-10.2-11.1zM140.9 103.9c-5.7 0-10.2 5-10.2 11.1s4.6 11.1 10.2 11.1c5.7 0 10.2-5 10.2-11.1s-4.5-11.1-10.2-11.1z"/><path class="st0" d="M189.5 20h-134C44.2 20 35 29.2 35 40.6v135.2c0 11.4 9.2 20.6 20.5 20.6h113.4l-5.3-18.5 12.8 11.9 12.1 11.2 21.5 19V40.6c0-11.4-9.2-20.6-20.5-20.6zm-38.6 130.6s-3.6-4.3-6.6-8.1c13.1-3.7 18.1-11.9 18.1-11.9-4.1 2.7-8 4.6-11.5 5.9-5 2.1-9.8 3.5-14.5 4.3-9.6 1.8-18.4 1.3-25.9-.1-5.7-1.1-10.6-2.7-14.7-4.3-2.3-.9-4.8-2-7.3-3.4-.3-.2-.6-.3-.9-.5-.2-.1-.3-.2-.4-.3-1.8-1-2.8-1.7-2.8-1.7s4.8 8 17.5 11.8c-3 3.8-6.7 8.3-6.7 8.3-22.1-.7-30.5-15.2-30.5-15.2 0-32.2 14.4-58.3 14.4-58.3 14.4-10.8 28.1-10.5 28.1-10.5l1 1.2c-18 5.2-26.3 13.1-26.3 13.1s2.2-1.2 5.9-2.9c10.7-4.7 19.2-6 22.7-6.3.6-.1 1.1-.2 1.7-.2 6.1-.8 13-1 20.2-.2 9.5 1.1 19.7 3.9 30.1 9.6 0 0-7.9-7.5-24.9-12.7l1.4-1.6s13.7-.3 28.1 10.5c0 0 14.4 26.1 14.4 58.3 0 0-8.5 14.5-30.6 15.2z"/></svg>

After

Width:  |  Height:  |  Size: 1.1 KiB

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="#fff"><path d="M12 2C6.47 2 2 6.47 2 12s4.47 10 10 10 10-4.47 10-10S17.53 2 12 2zm5 13.59L15.59 17 12 13.41 8.41 17 7 15.59 10.59 12 7 8.41 8.41 7 12 10.59 15.59 7 17 8.41 13.41 12 17 15.59z"/><path d="M0 0h24v24H0z" fill="none"/></svg>

After

Width:  |  Height:  |  Size: 325 B

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 0 24 24" width="24" fill="#FFFFFF"><path d="M0 0h24v24H0V0zm0 0h24v24H0V0z" fill="none"/><path d="M16.59 7.58L10 14.17l-3.59-3.58L5 12l5 5 8-8zM12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8z"/></svg>

After

Width:  |  Height:  |  Size: 339 B

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="#FFFFFF"><path fill="none" d="M0 0h24v24H0V0z"/><path d="M11 15h2v2h-2zm0-8h2v6h-2zm.99-5C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2zM12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8z"/></svg>

After

Width:  |  Height:  |  Size: 323 B

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="#FFFFFF"><path fill="none" d="M0 0h24v24H0z"/><path d="M11 18h2v-2h-2v2zm1-16C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8zm0-14c-2.21 0-4 1.79-4 4h2c0-1.1.9-2 2-2s2 .9 2 2c0 2-3 1.75-3 5h2c0-2.25 3-2.5 3-5 0-2.21-1.79-4-4-4z"/></svg>

After

Width:  |  Height:  |  Size: 397 B

+4
View File
@@ -0,0 +1,4 @@
<svg xmlns="http://www.w3.org/2000/svg" fill="#FFFFFF" width="48" height="48" viewBox="0 0 24 24">
<path fill="none" d="M0 0h24v24H0V0z"/>
<path d="M21 2H3c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h7v2H8v2h8v-2h-2v-2h7c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm0 14H3V4h18v12z"/>
</svg>

After

Width:  |  Height:  |  Size: 276 B

@@ -1,4 +0,0 @@
<svg fill="#FFFFFF" height="48" viewBox="0 0 24 24" width="48" xmlns="http://www.w3.org/2000/svg">
<path d="M0 0h24v24H0z" fill="none"/>
<path d="M7 11v2h10v-2H7zm5-9C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8z"/>
</svg>

Before

Width:  |  Height:  |  Size: 303 B

@@ -1,9 +0,0 @@
<svg fill="#FFFFFF" height="48" viewBox="0 0 24 24" width="48" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<defs>
<path d="M0 0h24v24H0V0z" id="a"/>
</defs>
<clipPath id="b">
<use overflow="visible" xlink:href="#a"/>
</clipPath>
<path clip-path="url(#b)" d="M21 3H3c-1.11 0-2 .89-2 2v12c0 1.1.89 2 2 2h5v2h8v-2h5c1.1 0 1.99-.9 1.99-2L23 5c0-1.11-.9-2-2-2zm0 14H3V5h18v12zm-5-7v2H8v-2h8z"/>
</svg>

Before

Width:  |  Height:  |  Size: 467 B

-4
View File
@@ -1,4 +0,0 @@
<svg fill="#FFFFFF" height="48" viewBox="0 0 24 24" width="48" xmlns="http://www.w3.org/2000/svg">
<path d="M0 0h24v24H0z" fill="none"/>
<path d="M21 3H3c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h5v2h8v-2h5c1.1 0 1.99-.9 1.99-2L23 5c0-1.1-.9-2-2-2zm0 14H3V5h18v12z"/>
</svg>

Before

Width:  |  Height:  |  Size: 273 B

+1 -69
View File
@@ -1,69 +1 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg"
id="svg3761"
viewBox="0 0 680 680"
height="680"
width="680"
version="1.0">
<metadata
id="metadata3767">
<rdf:RDF>
<cc:Work
rdf:about="">
<dc:format>image/svg+xml</dc:format>
<dc:type
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
<dc:title></dc:title>
</cc:Work>
</rdf:RDF>
</metadata>
<defs
id="defs3765" />
<g
id="g3759"
transform="translate(-135,491) scale(0.100000,-0.100000)">
<circle
id="circle3741"
fill="#565C64"
r="3400"
cy="1505"
cx="4755" />
<path
id="path3743"
style="fill:#ffffff"
d="M4550 4230 c-582 -48 -1123 -271 -1568 -646 l-84 -70 869 -869 c477 -477 871 -868 876 -868 4 0 6 552 5 1228 l-3 1227 -25 1 c-14 0 -45 -1 -70 -3z" />
<path
id="path3745"
style="fill:#ffffff"
d="M4867 4230 c-10 -9 -9 -2453 1 -2453 4 0 398 391 875 868 l869 869 -84 70 c-344 290 -749 492 -1178 587 -166 36 -469 74 -483 59z" />
<path
id="path3747"
style="fill:#ffffff"
d="M2673 3275 c-241 -285 -412 -595 -526 -953 -63 -196 -111 -458 -119 -640 l-3 -70 1228 -3 c675 -1 1227 1 1227 5 0 5 -391 399 -868 876 l-869 869 -70 -84z" />
<path
id="path3749"
style="fill:#ffffff"
d="M5898 2490 c-478 -477 -868 -871 -868 -876 0 -4 552 -6 1228 -5 l1227 3 -3 70 c-14 326 -124 729 -287 1055 -91 182 -259 430 -387 573 l-43 48 -867 -868z" />
<path
id="path3751"
style="fill:#ffffff"
d="M2026 1388 c-7 -11 10 -198 30 -321 76 -486 291 -952 617 -1338 l70 -84 869 869 c477 477 868 871 868 875 0 11 -2448 10 -2454 -1z" />
<path
id="path3753"
style="fill:#ffffff"
d="M5030 1390 c0 -5 391 -399 868 -876 l869 -869 70 84 c241 285 412 595 526 953 63 196 111 458 119 640 l3 70 -1227 3 c-676 1 -1228 -1 -1228 -5z" />
<path
id="path3755"
style="fill:#ffffff"
d="M3767 359 l-869 -869 84 -70 c285 -241 595 -412 953 -526 196 -63 458 -111 640 -119 l70 -3 3 1228 c1 675 -1 1227 -5 1227 -5 0 -399 -391 -876 -868z" />
<path
id="path3757"
style="fill:#ffffff"
d="M4862 0 l3 -1228 70 3 c182 8 444 56 640 119 358 114 668 285 953 526 l84 70 -869 869 c-477 477 -871 868 -876 868 -4 0 -6 -552 -5 -1227z" />
</g>
</svg>
<?xml version="1.0" standalone="no"?><!-- Generator: Gravit.io --><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" style="isolation:isolate" viewBox="0 0 256 256" width="256" height="256"><g><circle vector-effect="non-scaling-stroke" cx="128" cy="128" r="128" fill="rgb(86,92,100)"/><circle vector-effect="non-scaling-stroke" cx="128.00000000000003" cy="128.00000000000003" r="96" fill="rgb(255,255,255)"/><path d=" M 137.66 132 L 224 132 L 224 124 L 137.66 124 L 198.71 62.95 L 193.05 57.29 L 132 118.34 L 132 32 L 124 32 L 124 118.34 L 62.95 57.29 L 57.29 62.95 L 118.34 124 L 32 124 L 32 132 L 118.34 132 L 57.29 193.05 L 62.95 198.71 L 124 137.66 L 124 224 L 132 224 L 132 137.66 L 193.05 198.71 L 198.71 193.05 L 137.66 132 Z " fill-rule="evenodd" fill="rgb(86,92,100)"/></g></svg>

Before

Width:  |  Height:  |  Size: 2.6 KiB

After

Width:  |  Height:  |  Size: 820 B

+12 -3
View File
@@ -1,18 +1,27 @@
<RCC>
<qresource prefix="/">
<file>res/ic_remove_circle_outline_white_48px.svg</file>
<file>res/ic_remove_from_queue_white_48px.svg</file>
<file>res/ic_videogame_asset_white_48px.svg</file>
<file>res/ic_tv_white_48px.svg</file>
<file>res/desktop_windows-48px.svg</file>
<file>res/ic_add_to_queue_white_48px.svg</file>
<file>res/baseline-lock-24px.svg</file>
<file>res/baseline-play_circle_filled_white-48px.svg</file>
<file>res/baseline-warning-24px.svg</file>
<file>res/baseline-cancel-24px.svg</file>
<file>res/no_app_image.png</file>
<file>res/settings.svg</file>
<file>res/arrow_left.svg</file>
<file>res/question_mark.svg</file>
<file>res/moonlight.svg</file>
<file>res/update.svg</file>
<file>res/baseline-help_outline-24px.svg</file>
<file>res/baseline-error_outline-24px.svg</file>
<file>res/baseline-check_circle_outline-24px.svg</file>
<file>res/Discord-Logo-White.svg</file>
</qresource>
<qresource prefix="/data">
<file alias="gamecontrollerdb.txt">SDL_GameControllerDB/gamecontrollerdb.txt</file>
<file alias="ModeSeven.ttf">ModeSeven.ttf</file>
<file alias="egl.frag">shaders/egl.frag</file>
<file alias="egl.vert">shaders/egl.vert</file>
</qresource>
</RCC>
+13 -12
View File
@@ -26,7 +26,13 @@ MappingManager::MappingManager()
settings.endArray();
// Finally load mappings from SDL_HINT_GAMECONTROLLERCONFIG
QStringList sdlMappings = QString::fromLocal8Bit(SDL_GetHint(SDL_HINT_GAMECONTROLLERCONFIG)).split('\n', QString::SkipEmptyParts);
QStringList sdlMappings =
QString::fromLocal8Bit(SDL_GetHint(SDL_HINT_GAMECONTROLLERCONFIG))
#if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0)
.split('\n', Qt::SkipEmptyParts);
#else
.split('\n', QString::SkipEmptyParts);
#endif
for (QString sdlMapping : sdlMappings) {
SdlGamepadMapping mapping(sdlMapping);
addMapping(mapping);
@@ -54,15 +60,10 @@ void MappingManager::save()
void MappingManager::applyMappings()
{
QString mappingFile = Path::getGamepadMappingFile();
if (!mappingFile.isEmpty()) {
std::string mappingFileNative = QDir::toNativeSeparators(mappingFile).toStdString();
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION,
"Loading gamepad mappings from: %s",
mappingFileNative.c_str());
int newMappings = SDL_GameControllerAddMappingsFromFile(mappingFileNative.c_str());
QByteArray mappingData = Path::readDataFile("gamecontrollerdb.txt");
if (!mappingData.isEmpty()) {
int newMappings = SDL_GameControllerAddMappingsFromRW(
SDL_RWFromConstMem(mappingData.constData(), mappingData.size()), 1);
if (newMappings < 0) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
"Error loading gamepad mappings: %s",
@@ -75,8 +76,8 @@ void MappingManager::applyMappings()
}
}
else {
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION,
"No gamepad mapping file found");
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
"Unable to load gamepad mapping file");
}
QList<SdlGamepadMapping> mappings = m_Mappings.values();
+51 -128
View File
@@ -1,6 +1,4 @@
#include "streamingpreferences.h"
#include "streaming/session.h"
#include "streaming/streamutils.h"
#include <QSettings>
@@ -21,8 +19,19 @@
#define SER_UNSUPPORTEDFPS "unsupportedfps"
#define SER_MDNS "mdns"
#define SER_QUITAPPAFTER "quitAppAfter"
#define SER_MOUSEACCELERATION "mouseacceleration"
#define SER_ABSMOUSEMODE "mouseacceleration"
#define SER_ABSTOUCHMODE "abstouchmode"
#define SER_STARTWINDOWED "startwindowed"
#define SER_FRAMEPACING "framepacing"
#define SER_CONNWARNINGS "connwarnings"
#define SER_RICHPRESENCE "richpresence"
#define SER_GAMEPADMOUSE "gamepadmouse"
#define SER_DEFAULTVER "defaultver"
#define SER_PACKETSIZE "packetsize"
#define SER_DETECTNETBLOCKING "detectnetblocking"
#define SER_SWAPMOUSEBUTTONS "swapmousebuttons"
#define CURRENT_DEFAULT_VER 1
StreamingPreferences::StreamingPreferences(QObject *parent)
: QObject(parent)
@@ -34,6 +43,14 @@ void StreamingPreferences::reload()
{
QSettings settings;
int defaultVer = settings.value(SER_DEFAULTVER, 0).toInt();
#ifdef Q_OS_DARWIN
recommendedFullScreenMode = WindowMode::WM_FULLSCREEN_DESKTOP;
#else
recommendedFullScreenMode = WindowMode::WM_FULLSCREEN;
#endif
width = settings.value(SER_WIDTH, 1280).toInt();
height = settings.value(SER_HEIGHT, 720).toInt();
fps = settings.value(SER_FPS, 60).toInt();
@@ -45,8 +62,16 @@ void StreamingPreferences::reload()
unsupportedFps = settings.value(SER_UNSUPPORTEDFPS, false).toBool();
enableMdns = settings.value(SER_MDNS, true).toBool();
quitAppAfter = settings.value(SER_QUITAPPAFTER, false).toBool();
mouseAcceleration = settings.value(SER_MOUSEACCELERATION, false).toBool();
startWindowed = settings.value(SER_STARTWINDOWED, false).toBool();
absoluteMouseMode = settings.value(SER_ABSMOUSEMODE, false).toBool();
absoluteTouchMode = settings.value(SER_ABSTOUCHMODE, true).toBool();
startWindowed = settings.value(SER_STARTWINDOWED, true).toBool();
framePacing = settings.value(SER_FRAMEPACING, false).toBool();
connectionWarnings = settings.value(SER_CONNWARNINGS, true).toBool();
richPresence = settings.value(SER_RICHPRESENCE, true).toBool();
gamepadMouse = settings.value(SER_GAMEPADMOUSE, true).toBool();
detectNetworkBlocking = settings.value(SER_DETECTNETBLOCKING, true).toBool();
packetSize = settings.value(SER_PACKETSIZE, 0).toInt();
swapMouseButtons = settings.value(SER_SWAPMOUSEBUTTONS, false).toBool();
audioConfig = static_cast<AudioConfig>(settings.value(SER_AUDIOCFG,
static_cast<int>(AudioConfig::AC_STEREO)).toInt());
videoCodecConfig = static_cast<VideoCodecConfig>(settings.value(SER_VIDEOCFG,
@@ -56,7 +81,17 @@ void StreamingPreferences::reload()
windowMode = static_cast<WindowMode>(settings.value(SER_WINDOWMODE,
// Try to load from the old preference value too
static_cast<int>(settings.value(SER_FULLSCREEN, true).toBool() ?
WindowMode::WM_FULLSCREEN : WindowMode::WM_WINDOWED)).toInt());
recommendedFullScreenMode : WindowMode::WM_WINDOWED)).toInt());
// Perform default settings updates as required based on last default version
if (defaultVer == 0) {
#ifdef Q_OS_DARWIN
// Update window mode setting on macOS from full-screen (old default) to borderless windowed (new default)
if (windowMode == WindowMode::WM_FULLSCREEN) {
windowMode = WindowMode::WM_FULLSCREEN_DESKTOP;
}
#endif
}
}
void StreamingPreferences::save()
@@ -74,133 +109,21 @@ void StreamingPreferences::save()
settings.setValue(SER_UNSUPPORTEDFPS, unsupportedFps);
settings.setValue(SER_MDNS, enableMdns);
settings.setValue(SER_QUITAPPAFTER, quitAppAfter);
settings.setValue(SER_MOUSEACCELERATION, mouseAcceleration);
settings.setValue(SER_ABSMOUSEMODE, absoluteMouseMode);
settings.setValue(SER_ABSTOUCHMODE, absoluteTouchMode);
settings.setValue(SER_STARTWINDOWED, startWindowed);
settings.setValue(SER_FRAMEPACING, framePacing);
settings.setValue(SER_CONNWARNINGS, connectionWarnings);
settings.setValue(SER_RICHPRESENCE, richPresence);
settings.setValue(SER_GAMEPADMOUSE, gamepadMouse);
settings.setValue(SER_PACKETSIZE, packetSize);
settings.setValue(SER_DETECTNETBLOCKING, detectNetworkBlocking);
settings.setValue(SER_AUDIOCFG, static_cast<int>(audioConfig));
settings.setValue(SER_VIDEOCFG, static_cast<int>(videoCodecConfig));
settings.setValue(SER_VIDEODEC, static_cast<int>(videoDecoderSelection));
settings.setValue(SER_WINDOWMODE, static_cast<int>(windowMode));
}
bool StreamingPreferences::hasAnyHardwareAcceleration()
{
// Always use VDS_AUTO to avoid spamming the user with warnings
// if they've forced software decoding.
return Session::isHardwareDecodeAvailable(VDS_AUTO,
VIDEO_FORMAT_H264,
1920, 1080, 60);
}
bool StreamingPreferences::isRunningWayland()
{
return qgetenv("XDG_SESSION_TYPE") == QByteArray("wayland");
}
bool StreamingPreferences::isWow64()
{
#ifdef Q_OS_WIN32
return QSysInfo::currentCpuArchitecture() != QSysInfo::buildCpuArchitecture();
#else
return false;
#endif
}
QString StreamingPreferences::getUnmappedGamepads()
{
return SdlInputHandler::getUnmappedGamepads();
}
int StreamingPreferences::getMaximumStreamingFrameRate()
{
// Never let the maximum drop below 60 FPS
int maxFrameRate = 60;
if (SDL_InitSubSystem(SDL_INIT_VIDEO) != 0) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
"SDL_InitSubSystem(SDL_INIT_VIDEO) failed: %s",
SDL_GetError());
return maxFrameRate;
}
SDL_DisplayMode mode, bestMode, desktopMode;
for (int displayIndex = 0; displayIndex < SDL_GetNumVideoDisplays(); displayIndex++) {
// Get the native desktop resolution
if (StreamUtils::getRealDesktopMode(displayIndex, &desktopMode)) {
// Start at desktop mode and work our way up
bestMode = desktopMode;
for (int i = 0; i < SDL_GetNumDisplayModes(displayIndex); i++) {
if (SDL_GetDisplayMode(displayIndex, i, &mode) == 0) {
if (mode.w == desktopMode.w && mode.h == desktopMode.h) {
if (mode.refresh_rate > bestMode.refresh_rate) {
bestMode = mode;
}
}
}
}
maxFrameRate = qMax(maxFrameRate, bestMode.refresh_rate);
}
}
SDL_QuitSubSystem(SDL_INIT_VIDEO);
return maxFrameRate;
}
QRect StreamingPreferences::getDesktopResolution(int displayIndex)
{
if (SDL_InitSubSystem(SDL_INIT_VIDEO) != 0) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
"SDL_InitSubSystem(SDL_INIT_VIDEO) failed: %s",
SDL_GetError());
return QRect();
}
if (displayIndex >= SDL_GetNumVideoDisplays()) {
SDL_QuitSubSystem(SDL_INIT_VIDEO);
return QRect();
}
SDL_DisplayMode mode;
int err = SDL_GetDesktopDisplayMode(displayIndex, &mode);
SDL_QuitSubSystem(SDL_INIT_VIDEO);
if (err == 0) {
return QRect(0, 0, mode.w, mode.h);
}
else {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
"SDL_GetDesktopDisplayMode() failed: %s",
SDL_GetError());
return QRect();
}
}
QRect StreamingPreferences::getNativeResolution(int displayIndex)
{
if (SDL_InitSubSystem(SDL_INIT_VIDEO) != 0) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
"SDL_InitSubSystem(SDL_INIT_VIDEO) failed: %s",
SDL_GetError());
return QRect();
}
if (displayIndex >= SDL_GetNumVideoDisplays()) {
SDL_QuitSubSystem(SDL_INIT_VIDEO);
return QRect();
}
SDL_DisplayMode mode;
bool success = StreamUtils::getRealDesktopMode(displayIndex, &mode);
SDL_QuitSubSystem(SDL_INIT_VIDEO);
if (success) {
return QRect(0, 0, mode.w, mode.h);
}
else {
return QRect();
}
settings.setValue(SER_DEFAULTVER, CURRENT_DEFAULT_VER);
settings.setValue(SER_SWAPMOUSEBUTTONS, swapMouseButtons);
}
int StreamingPreferences::getDefaultBitrate(int width, int height, int fps)
+29 -18
View File
@@ -15,26 +15,13 @@ public:
Q_INVOKABLE void save();
Q_INVOKABLE static bool hasAnyHardwareAcceleration();
Q_INVOKABLE static bool isRunningWayland();
Q_INVOKABLE static bool isWow64();
Q_INVOKABLE static int getMaximumStreamingFrameRate();
Q_INVOKABLE QRect getDesktopResolution(int displayIndex);
Q_INVOKABLE QRect getNativeResolution(int displayIndex);
Q_INVOKABLE QString getUnmappedGamepads();
void reload();
enum AudioConfig
{
AC_STEREO,
AC_51_SURROUND
AC_51_SURROUND,
AC_71_SURROUND
};
Q_ENUM(AudioConfig)
@@ -74,12 +61,20 @@ public:
Q_PROPERTY(bool unsupportedFps MEMBER unsupportedFps NOTIFY unsupportedFpsChanged)
Q_PROPERTY(bool enableMdns MEMBER enableMdns NOTIFY enableMdnsChanged)
Q_PROPERTY(bool quitAppAfter MEMBER quitAppAfter NOTIFY quitAppAfterChanged)
Q_PROPERTY(bool mouseAcceleration MEMBER mouseAcceleration NOTIFY mouseAccelerationChanged)
Q_PROPERTY(bool absoluteMouseMode MEMBER absoluteMouseMode NOTIFY absoluteMouseModeChanged)
Q_PROPERTY(bool absoluteTouchMode MEMBER absoluteTouchMode NOTIFY absoluteTouchModeChanged)
Q_PROPERTY(bool startWindowed MEMBER startWindowed NOTIFY startWindowedChanged)
Q_PROPERTY(bool framePacing MEMBER framePacing NOTIFY framePacingChanged)
Q_PROPERTY(bool connectionWarnings MEMBER connectionWarnings NOTIFY connectionWarningsChanged)
Q_PROPERTY(bool richPresence MEMBER richPresence NOTIFY richPresenceChanged)
Q_PROPERTY(bool gamepadMouse MEMBER gamepadMouse NOTIFY gamepadMouseChanged)
Q_PROPERTY(bool detectNetworkBlocking MEMBER detectNetworkBlocking NOTIFY detectNetworkBlockingChanged);
Q_PROPERTY(AudioConfig audioConfig MEMBER audioConfig NOTIFY audioConfigChanged)
Q_PROPERTY(VideoCodecConfig videoCodecConfig MEMBER videoCodecConfig NOTIFY videoCodecConfigChanged)
Q_PROPERTY(VideoDecoderSelection videoDecoderSelection MEMBER videoDecoderSelection NOTIFY videoDecoderSelectionChanged)
Q_PROPERTY(WindowMode windowMode MEMBER windowMode NOTIFY windowModeChanged)
Q_PROPERTY(WindowMode recommendedFullScreenMode MEMBER recommendedFullScreenMode CONSTANT)
Q_PROPERTY(bool swapMouseButtons MEMBER swapMouseButtons NOTIFY mouseButtonsChanged)
// Directly accessible members for preferences
int width;
@@ -93,12 +88,21 @@ public:
bool unsupportedFps;
bool enableMdns;
bool quitAppAfter;
bool mouseAcceleration;
bool absoluteMouseMode;
bool absoluteTouchMode;
bool startWindowed;
bool framePacing;
bool connectionWarnings;
bool richPresence;
bool gamepadMouse;
bool detectNetworkBlocking;
bool swapMouseButtons;
int packetSize;
AudioConfig audioConfig;
VideoCodecConfig videoCodecConfig;
VideoDecoderSelection videoDecoderSelection;
WindowMode windowMode;
WindowMode recommendedFullScreenMode;
signals:
void displayModeChanged();
@@ -110,11 +114,18 @@ signals:
void unsupportedFpsChanged();
void enableMdnsChanged();
void quitAppAfterChanged();
void mouseAccelerationChanged();
void absoluteMouseModeChanged();
void absoluteTouchModeChanged();
void audioConfigChanged();
void videoCodecConfigChanged();
void videoDecoderSelectionChanged();
void windowModeChanged();
void startWindowedChanged();
void framePacingChanged();
void connectionWarningsChanged();
void richPresenceChanged();
void gamepadMouseChanged();
void detectNetworkBlockingChanged();
void mouseButtonsChanged();
};
+21
View File
@@ -0,0 +1,21 @@
#version 300 es
#extension GL_OES_EGL_image_external : require
precision mediump float;
out vec4 FragColor;
in vec2 vTextCoord;
uniform mat3 yuvmat;
uniform vec3 offset;
uniform samplerExternalOES plane1;
uniform samplerExternalOES plane2;
void main() {
vec3 YCbCr = vec3(
texture2D(plane1, vTextCoord)[0],
texture2D(plane2, vTextCoord).xy
);
YCbCr -= offset;
FragColor = vec4(clamp(yuvmat * YCbCr, 0.0, 1.0), 1.0f);
}
+10
View File
@@ -0,0 +1,10 @@
#version 300 es
layout (location = 0) in vec2 aPosition; // 2D: X,Y
layout (location = 1) in vec2 aTexCoord;
out vec2 vTextCoord;
void main() {
vTextCoord = aTexCoord;
gl_Position = vec4(aPosition, 0, 1);
}
+161 -60
View File
@@ -3,53 +3,114 @@
#ifdef HAVE_SOUNDIO
#include "renderers/soundioaudiorenderer.h"
#else
#include "renderers/sdl.h"
#endif
#ifdef HAVE_SLAUDIO
#include "renderers/slaud.h"
#endif
#include "renderers/sdl.h"
#include <Limelight.h>
IAudioRenderer* Session::createAudioRenderer()
{
#ifdef HAVE_SOUNDIO
return new SoundIoAudioRenderer();
#else
return new SdlAudioRenderer();
#endif
#define TRY_INIT_RENDERER(renderer, opusConfig) \
{ \
IAudioRenderer* __renderer = new renderer(); \
if (__renderer->prepareForPlayback(opusConfig)) \
return __renderer; \
delete __renderer; \
}
bool Session::testAudio(int audioConfiguration)
IAudioRenderer* Session::createAudioRenderer(const POPUS_MULTISTREAM_CONFIGURATION opusConfig)
{
IAudioRenderer* audioRenderer;
audioRenderer = createAudioRenderer();
if (audioRenderer == nullptr) {
return false;
// Handle explicit ML_AUDIO setting and fail if the requested backend fails
QString mlAudio = qgetenv("ML_AUDIO").toLower();
if (mlAudio == "sdl") {
TRY_INIT_RENDERER(SdlAudioRenderer, opusConfig)
return nullptr;
}
#ifdef HAVE_SOUNDIO
else if (mlAudio == "libsoundio") {
TRY_INIT_RENDERER(SoundIoAudioRenderer, opusConfig)
return nullptr;
}
#endif
#if defined(HAVE_SLAUDIO)
else if (mlAudio == "slaudio") {
TRY_INIT_RENDERER(SLAudioRenderer, opusConfig)
return nullptr;
}
#endif
else if (!mlAudio.isEmpty()) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
"Unknown audio backend: %s",
SDL_getenv("ML_AUDIO"));
return nullptr;
}
// -------------- Automatic backend selection below this line ---------------
#if defined(HAVE_SLAUDIO)
// Steam Link should always have SLAudio
TRY_INIT_RENDERER(SLAudioRenderer, opusConfig)
#endif
#if !defined(Q_OS_WIN32) && !defined(Q_OS_DARWIN)
// Linux defaults to SDL due to persistent glitching issues under libsoundio.
// Platforms that libsoundio doesn't support also default to SDL.
TRY_INIT_RENDERER(SdlAudioRenderer, opusConfig)
#ifdef HAVE_SOUNDIO
TRY_INIT_RENDERER(SoundIoAudioRenderer, opusConfig)
#endif
#else
// Windows and macOS default to libsoundio and fall back to SDL
#ifdef HAVE_SOUNDIO
TRY_INIT_RENDERER(SoundIoAudioRenderer, opusConfig)
#endif
TRY_INIT_RENDERER(SdlAudioRenderer, opusConfig)
#endif
return nullptr;
}
int Session::getAudioRendererCapabilities(int audioConfiguration)
{
// Build a fake OPUS_MULTISTREAM_CONFIGURATION to give
// the renderer the channel count and sample rate.
OPUS_MULTISTREAM_CONFIGURATION opusConfig = {};
opusConfig.sampleRate = 48000;
opusConfig.samplesPerFrame = 240;
opusConfig.channelCount = CHANNEL_COUNT_FROM_AUDIO_CONFIGURATION(audioConfiguration);
switch (audioConfiguration)
{
case AUDIO_CONFIGURATION_STEREO:
opusConfig.channelCount = 2;
break;
case AUDIO_CONFIGURATION_51_SURROUND:
opusConfig.channelCount = 6;
break;
default:
SDL_assert(false);
return false;
IAudioRenderer* audioRenderer = createAudioRenderer(&opusConfig);
if (audioRenderer == nullptr) {
return 0;
}
bool ret = audioRenderer->prepareForPlayback(&opusConfig);
int caps = audioRenderer->getCapabilities();
delete audioRenderer;
return ret;
return caps;
}
bool Session::testAudio(int audioConfiguration)
{
// Build a fake OPUS_MULTISTREAM_CONFIGURATION to give
// the renderer the channel count and sample rate.
OPUS_MULTISTREAM_CONFIGURATION opusConfig = {};
opusConfig.sampleRate = 48000;
opusConfig.samplesPerFrame = 240;
opusConfig.channelCount = CHANNEL_COUNT_FROM_AUDIO_CONFIGURATION(audioConfiguration);
IAudioRenderer* audioRenderer = createAudioRenderer(&opusConfig);
if (audioRenderer == nullptr) {
return false;
}
delete audioRenderer;
return true;
}
int Session::arInit(int /* audioConfiguration */,
@@ -60,30 +121,34 @@ int Session::arInit(int /* audioConfiguration */,
SDL_memcpy(&s_ActiveSession->m_AudioConfig, opusConfig, sizeof(*opusConfig));
s_ActiveSession->m_AudioRenderer = s_ActiveSession->createAudioRenderer(&s_ActiveSession->m_AudioConfig);
if (s_ActiveSession->m_AudioRenderer == nullptr) {
return -2;
}
// Allow the chosen renderer to remap Opus channels as needed to ensure proper output
s_ActiveSession->m_AudioRenderer->remapChannels(&s_ActiveSession->m_AudioConfig);
// Create the Opus decoder with the renderer's preferred channel mapping
s_ActiveSession->m_OpusDecoder =
opus_multistream_decoder_create(opusConfig->sampleRate,
opusConfig->channelCount,
opusConfig->streams,
opusConfig->coupledStreams,
opusConfig->mapping,
opus_multistream_decoder_create(s_ActiveSession->m_AudioConfig.sampleRate,
s_ActiveSession->m_AudioConfig.channelCount,
s_ActiveSession->m_AudioConfig.streams,
s_ActiveSession->m_AudioConfig.coupledStreams,
s_ActiveSession->m_AudioConfig.mapping,
&error);
if (s_ActiveSession->m_OpusDecoder == NULL) {
delete s_ActiveSession->m_AudioRenderer;
s_ActiveSession->m_AudioRenderer = nullptr;
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
"Failed to create decoder: %d",
error);
return -1;
}
s_ActiveSession->m_AudioRenderer = s_ActiveSession->createAudioRenderer();
if (!s_ActiveSession->m_AudioRenderer->prepareForPlayback(opusConfig)) {
delete s_ActiveSession->m_AudioRenderer;
opus_multistream_decoder_destroy(s_ActiveSession->m_OpusDecoder);
return -2;
}
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION,
"Audio stream has %d channels",
opusConfig->channelCount);
s_ActiveSession->m_AudioConfig.channelCount);
return 0;
}
@@ -101,8 +166,11 @@ void Session::arDecodeAndPlaySample(char* sampleData, int sampleLength)
{
int samplesDecoded;
// Set this thread to high priority to reduce
// the chance of missing our sample delivery time
#ifndef STEAM_LINK
// Set this thread to high priority to reduce the chance of missing
// our sample delivery time. On Steam Link, this causes starvation
// of other threads due to severely restricted CPU time available,
// so we will skip it on that platform.
if (s_ActiveSession->m_AudioSampleCount == 0) {
if (SDL_SetThreadPriority(SDL_THREAD_PRIORITY_HIGH) < 0) {
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION,
@@ -110,29 +178,54 @@ void Session::arDecodeAndPlaySample(char* sampleData, int sampleLength)
SDL_GetError());
}
}
#endif
// See if we need to drop this sample
if (s_ActiveSession->m_DropAudioEndTime != 0) {
if (SDL_TICKS_PASSED(SDL_GetTicks(), s_ActiveSession->m_DropAudioEndTime)) {
// Avoid calling SDL_GetTicks() now
s_ActiveSession->m_DropAudioEndTime = 0;
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION,
"Audio drop window has ended");
}
else {
// We're still in the drop window
return;
}
}
s_ActiveSession->m_AudioSampleCount++;
if (s_ActiveSession->m_AudioRenderer != nullptr) {
int desiredSize = sizeof(short) * s_ActiveSession->m_AudioConfig.samplesPerFrame * s_ActiveSession->m_AudioConfig.channelCount;
void* buffer = s_ActiveSession->m_AudioRenderer->getAudioBuffer(&desiredSize);
if (buffer == nullptr) {
return;
}
samplesDecoded = opus_multistream_decode(s_ActiveSession->m_OpusDecoder,
(unsigned char*)sampleData,
sampleLength,
s_ActiveSession->m_OpusDecodeBuffer,
SAMPLES_PER_FRAME,
(short*)buffer,
desiredSize / sizeof(short) / s_ActiveSession->m_AudioConfig.channelCount,
0);
// Update desiredSize with the number of bytes actually populated by the decoding operation
if (samplesDecoded > 0) {
if (!s_ActiveSession->m_AudioRenderer->submitAudio(s_ActiveSession->m_OpusDecodeBuffer,
static_cast<int>(
sizeof(short) *
samplesDecoded *
s_ActiveSession->m_AudioConfig.channelCount))) {
SDL_assert(desiredSize >= (int)(sizeof(short) * samplesDecoded * s_ActiveSession->m_AudioConfig.channelCount));
desiredSize = sizeof(short) * samplesDecoded * s_ActiveSession->m_AudioConfig.channelCount;
}
else {
desiredSize = 0;
}
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION,
"Reinitializing audio renderer after failure");
if (!s_ActiveSession->m_AudioRenderer->submitAudio(desiredSize)) {
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION,
"Reinitializing audio renderer after failure");
delete s_ActiveSession->m_AudioRenderer;
s_ActiveSession->m_AudioRenderer = nullptr;
}
delete s_ActiveSession->m_AudioRenderer;
s_ActiveSession->m_AudioRenderer = nullptr;
}
}
@@ -141,10 +234,18 @@ void Session::arDecodeAndPlaySample(char* sampleData, int sampleLength)
// safe to reinitialize here because we can't be torn down while
// the audio decoder/playback thread is still alive.
if (s_ActiveSession->m_AudioRenderer == nullptr && (s_ActiveSession->m_AudioSampleCount % 200) == 0) {
s_ActiveSession->m_AudioRenderer = s_ActiveSession->createAudioRenderer();
if (!s_ActiveSession->m_AudioRenderer->prepareForPlayback(&s_ActiveSession->m_AudioConfig)) {
delete s_ActiveSession->m_AudioRenderer;
s_ActiveSession->m_AudioRenderer = nullptr;
}
// Since we're doing this inline and audio initialization takes time, we need
// to drop samples to account for the time we've spent blocking audio rendering
// so we return to real-time playback and don't accumulate latency.
Uint32 audioReinitStartTime = SDL_GetTicks();
s_ActiveSession->m_AudioRenderer = s_ActiveSession->createAudioRenderer(&s_ActiveSession->m_AudioConfig);
Uint32 audioReinitStopTime = SDL_GetTicks();
s_ActiveSession->m_DropAudioEndTime = audioReinitStopTime + (audioReinitStopTime - audioReinitStartTime);
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION,
"Audio reinitialization took %d ms - starting drop window",
audioReinitStopTime - audioReinitStartTime);
}
}
+15 -4
View File
@@ -2,9 +2,6 @@
#include <Limelight.h>
#define MAX_CHANNELS 6
#define SAMPLES_PER_FRAME 240
class IAudioRenderer
{
public:
@@ -12,6 +9,20 @@ public:
virtual bool prepareForPlayback(const OPUS_MULTISTREAM_CONFIGURATION* opusConfig) = 0;
virtual void* getAudioBuffer(int* size) = 0;
// Return false if an unrecoverable error has occurred and the renderer must be reinitialized
virtual bool submitAudio(short* audioBuffer, int audioSize) = 0;
virtual bool submitAudio(int bytesWritten) = 0;
virtual int getCapabilities() = 0;
virtual void remapChannels(POPUS_MULTISTREAM_CONFIGURATION) {
// Use default channel mapping:
// 0 - Front Left
// 1 - Front Right
// 2 - Center
// 3 - LFE
// 4 - Surround Left
// 5 - Surround Right
}
};
+7 -6
View File
@@ -12,13 +12,14 @@ public:
virtual bool prepareForPlayback(const OPUS_MULTISTREAM_CONFIGURATION* opusConfig);
virtual bool submitAudio(short* audioBuffer, int audioSize);
virtual void* getAudioBuffer(int* size);
virtual bool submitAudio(int bytesWritten);
virtual int getCapabilities();
private:
SDL_AudioDeviceID m_AudioDevice;
Uint32 m_ChannelCount;
Uint32 m_PendingDrops;
Uint32 m_PendingHardDrops;
Uint32 m_SampleIndex;
Uint32 m_BaselinePendingData;
void* m_AudioBuffer;
int m_FrameSize;
};
+73 -80
View File
@@ -4,21 +4,42 @@
#include <SDL.h>
#include <QtGlobal>
#define MIN_QUEUED_FRAMES 2
#define MAX_QUEUED_FRAMES 4
#define STOP_THE_WORLD_LIMIT 20
#define DROP_RATIO_DENOM 32
#include <QFile>
#include <QTextStream>
SdlAudioRenderer::SdlAudioRenderer()
: m_AudioDevice(0),
m_ChannelCount(0),
m_PendingDrops(0),
m_PendingHardDrops(0),
m_SampleIndex(0),
m_BaselinePendingData(0)
m_AudioBuffer(nullptr)
{
SDL_assert(!SDL_WasInit(SDL_INIT_AUDIO));
#ifdef HAVE_MMAL
// HACK: PulseAudio on Raspberry Pi suffers from horrible underruns,
// so switch to ALSA if we detect that we're on a Pi. We need to
// actually set a bogus PULSE_SERVER so it doesn't try to get smart on us
// and find PA anyway. SDL_AUDIODRIVER=pulseaudio can override this logic.
if (qgetenv("SDL_AUDIODRIVER").toLower() != "pulseaudio") {
QFile file("/proc/cpuinfo");
if (file.open(QIODevice::ReadOnly | QFile::Text)) {
QTextStream textStream(&file);
if (textStream.readAll().contains("Raspberry Pi")) {
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION,
"Avoiding PulseAudio on Raspberry Pi");
qputenv("PULSE_SERVER", "");
if (SDL_InitSubSystem(SDL_INIT_AUDIO) != 0) {
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION,
"ALSA failed; falling back to default");
qunsetenv("PULSE_SERVER");
}
else {
SDL_QuitSubSystem(SDL_INIT_AUDIO);
}
}
}
}
#endif
if (SDL_InitSubSystem(SDL_INIT_AUDIO) != 0) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
"SDL_InitSubSystem(SDL_INIT_AUDIO) failed: %s",
@@ -40,48 +61,35 @@ bool SdlAudioRenderer::prepareForPlayback(const OPUS_MULTISTREAM_CONFIGURATION*
// frames contain a non-power of 2 number of samples,
// so the slop would require buffering another full frame.
// Specifying non-Po2 seems to work for our supported platforms.
want.samples = SAMPLES_PER_FRAME;
want.samples = opusConfig->samplesPerFrame;
m_FrameSize = opusConfig->samplesPerFrame * sizeof(short) * opusConfig->channelCount;
m_AudioDevice = SDL_OpenAudioDevice(NULL, 0, &want, &have, 0);
if (m_AudioDevice == 0) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
"Failed to open audio device: %s",
SDL_GetError());
SDL_QuitSubSystem(SDL_INIT_AUDIO);
return false;
}
m_AudioBuffer = malloc(m_FrameSize);
if (m_AudioBuffer == nullptr) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
"Failed to allocate audio buffer");
return false;
}
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION,
"Desired audio buffer: %u samples (%lu bytes)",
"Desired audio buffer: %u samples (%u bytes)",
want.samples,
want.samples * sizeof(short) * want.channels);
want.samples * (Uint32)sizeof(short) * want.channels);
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION,
"Obtained audio buffer: %u samples (%u bytes)",
have.samples,
have.size);
// SDL counts pending samples in the queued
// audio size using the WASAPI backend. This
// includes silence, which can throw off our
// pending data count. Get a baseline so we
// can exclude that data.
m_BaselinePendingData = 0;
#ifdef Q_OS_WIN32
for (int i = 0; i < 100; i++) {
m_BaselinePendingData = qMax(m_BaselinePendingData, SDL_GetQueuedAudioSize(m_AudioDevice));
SDL_Delay(10);
}
#endif
m_BaselinePendingData *= 2;
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION,
"Baseline pending audio data: %d bytes",
m_BaselinePendingData);
m_ChannelCount = opusConfig->channelCount;
m_SampleIndex = 0;
m_PendingDrops = m_PendingHardDrops = 0;
// Start playback
SDL_PauseAudioDevice(m_AudioDevice, 0);
@@ -96,60 +104,39 @@ SdlAudioRenderer::~SdlAudioRenderer()
SDL_CloseAudioDevice(m_AudioDevice);
}
if (m_AudioBuffer != nullptr) {
free(m_AudioBuffer);
}
SDL_QuitSubSystem(SDL_INIT_AUDIO);
SDL_assert(!SDL_WasInit(SDL_INIT_AUDIO));
}
bool SdlAudioRenderer::submitAudio(short* audioBuffer, int audioSize)
void* SdlAudioRenderer::getAudioBuffer(int*)
{
m_SampleIndex++;
return m_AudioBuffer;
}
Uint32 queuedAudio = SDL_GetQueuedAudioSize(m_AudioDevice);
if (queuedAudio > m_BaselinePendingData) {
queuedAudio -= m_BaselinePendingData;
}
else {
queuedAudio = 0;
}
Uint32 framesQueued = queuedAudio / (SAMPLES_PER_FRAME * m_ChannelCount * sizeof(short));
// We must check this prior to the below checks to ensure we don't
// underflow if framesQueued - m_PendingHardDrops < 0.
if (framesQueued <= MIN_QUEUED_FRAMES) {
m_PendingDrops = m_PendingHardDrops = 0;
}
// Pend enough drops to get us back to MIN_QUEUED_FRAMES, checking first
// to ensure we don't underflow.
else if (framesQueued > m_PendingHardDrops &&
framesQueued - m_PendingHardDrops > STOP_THE_WORLD_LIMIT) {
m_PendingHardDrops = framesQueued - MIN_QUEUED_FRAMES;
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION,
"Pending hard drop of %u audio frames",
m_PendingHardDrops);
}
// If we're under the stop the world limit, we can drop samples
// gracefully over the next little while.
else if (framesQueued > m_PendingHardDrops + m_PendingDrops &&
framesQueued - m_PendingHardDrops - m_PendingDrops > MAX_QUEUED_FRAMES) {
m_PendingDrops = framesQueued - MIN_QUEUED_FRAMES;
}
// Determine if this frame should be dropped
if (m_PendingHardDrops != 0) {
// Hard drops happen all at once to forcefully
// resync with the source.
m_PendingHardDrops--;
return true;
}
else if (m_PendingDrops != 0 && m_SampleIndex % DROP_RATIO_DENOM == 0) {
// Normal drops are interspersed with the audio data
// to hide the glitches.
m_PendingDrops--;
bool SdlAudioRenderer::submitAudio(int bytesWritten)
{
if (bytesWritten == 0) {
// Nothing to do
return true;
}
if (SDL_QueueAudio(m_AudioDevice, audioBuffer, audioSize) < 0) {
// Don't queue if there's already more than 30 ms of audio data waiting
// in Moonlight's audio queue.
if (LiGetPendingAudioDuration() > 30) {
return true;
}
// Provide backpressure on the queue to ensure too many frames don't build up
// in SDL's audio queue.
while (SDL_GetQueuedAudioSize(m_AudioDevice) / m_FrameSize > 10) {
SDL_Delay(1);
}
if (SDL_QueueAudio(m_AudioDevice, m_AudioBuffer, bytesWritten) < 0) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
"Failed to queue audio sample: %s",
SDL_GetError());
@@ -157,3 +144,9 @@ bool SdlAudioRenderer::submitAudio(short* audioBuffer, int audioSize)
return true;
}
int SdlAudioRenderer::getCapabilities()
{
// Direct submit can't be used because we use LiGetPendingAudioDuration()
return CAPABILITY_SUPPORTS_ARBITRARY_AUDIO_DURATION;
}
+145
View File
@@ -0,0 +1,145 @@
#include "slaud.h"
#include <SDL.h>
SLAudioRenderer::SLAudioRenderer()
: m_AudioContext(nullptr),
m_AudioStream(nullptr),
m_AudioBuffer(nullptr)
{
SLAudio_SetLogFunction(SLAudioRenderer::slLogCallback, nullptr);
}
bool SLAudioRenderer::prepareForPlayback(const OPUS_MULTISTREAM_CONFIGURATION* opusConfig)
{
m_AudioContext = SLAudio_CreateContext();
if (m_AudioContext == nullptr) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
"SLAudio_CreateContext() failed");
return false;
}
// This number is pretty conservative (especially for surround), but
// it's hard to avoid since we get crushed by CPU limitations.
m_MaxQueuedAudioMs = 40 * opusConfig->channelCount / 2;
m_AudioBufferSize = opusConfig->samplesPerFrame * sizeof(short) * opusConfig->channelCount;
m_AudioStream = SLAudio_CreateStream(m_AudioContext,
opusConfig->sampleRate,
opusConfig->channelCount,
m_AudioBufferSize,
1);
if (m_AudioStream == nullptr) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
"SLAudio_CreateStream() failed");
return false;
}
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION,
"Using SLAudio renderer with %d samples per frame",
opusConfig->samplesPerFrame);
return true;
}
void SLAudioRenderer::remapChannels(POPUS_MULTISTREAM_CONFIGURATION opusConfig) {
OPUS_MULTISTREAM_CONFIGURATION originalConfig = *opusConfig;
// The Moonlight's default channel order is FL,FR,C,LFE,RL,RR,SL,SR
// SLAudio expects FL,C,FR,RL,RR,(SL,SR),LFE for 5.1/7.1 so we swap the channels around to match
if (opusConfig->channelCount == 3 || opusConfig->channelCount >= 6) {
// Swap FR and C
opusConfig->mapping[1] = originalConfig.mapping[2];
opusConfig->mapping[2] = originalConfig.mapping[1];
}
if (opusConfig->channelCount >= 6) {
// SLAudio expects the LFE channel at the end
opusConfig->mapping[opusConfig->channelCount - 1] = originalConfig.mapping[3];
// Slide the other channels down
memcpy(&opusConfig->mapping[3],
&originalConfig.mapping[4],
opusConfig->channelCount - 4);
}
}
void* SLAudioRenderer::getAudioBuffer(int* size)
{
SDL_assert(*size == m_AudioBufferSize);
if (m_AudioBuffer == nullptr) {
m_AudioBuffer = SLAudio_BeginFrame(m_AudioStream);
}
return m_AudioBuffer;
}
SLAudioRenderer::~SLAudioRenderer()
{
if (m_AudioBuffer != nullptr) {
memset(m_AudioBuffer, 0, m_AudioBufferSize);
SLAudio_SubmitFrame(m_AudioStream);
}
if (m_AudioStream != nullptr) {
SLAudio_FreeStream(m_AudioStream);
}
if (m_AudioContext != nullptr) {
SLAudio_FreeContext(m_AudioContext);
}
}
bool SLAudioRenderer::submitAudio(int bytesWritten)
{
if (bytesWritten == 0) {
// This buffer will be reused next time
return true;
}
if (LiGetPendingAudioDuration() < m_MaxQueuedAudioMs) {
SLAudio_SubmitFrame(m_AudioStream);
m_AudioBuffer = nullptr;
}
else {
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION,
"Too many queued audio frames: %d",
LiGetPendingAudioFrames());
}
return true;
}
int SLAudioRenderer::getCapabilities()
{
return CAPABILITY_SLOW_OPUS_DECODER | CAPABILITY_SUPPORTS_ARBITRARY_AUDIO_DURATION;
}
void SLAudioRenderer::slLogCallback(void*, ESLAudioLog logLevel, const char *message)
{
SDL_LogPriority priority;
switch (logLevel)
{
case k_ESLAudioLogError:
priority = SDL_LOG_PRIORITY_ERROR;
break;
case k_ESLAudioLogWarning:
priority = SDL_LOG_PRIORITY_WARN;
break;
case k_ESLAudioLogInfo:
priority = SDL_LOG_PRIORITY_INFO;
break;
default:
case k_ESLAudioLogDebug:
priority = SDL_LOG_PRIORITY_DEBUG;
break;
}
SDL_LogMessage(SDL_LOG_CATEGORY_APPLICATION,
priority,
"SLAudio: %s",
message);
}
+32
View File
@@ -0,0 +1,32 @@
#pragma once
#include "renderer.h"
#include <SLAudio.h>
class SLAudioRenderer : public IAudioRenderer
{
public:
SLAudioRenderer();
virtual ~SLAudioRenderer();
virtual bool prepareForPlayback(const OPUS_MULTISTREAM_CONFIGURATION* opusConfig);
virtual void* getAudioBuffer(int* size);
virtual bool submitAudio(int bytesWritten);
virtual int getCapabilities();
virtual void remapChannels(POPUS_MULTISTREAM_CONFIGURATION opusConfig);
private:
static void slLogCallback(void* context, ESLAudioLog logLevel, const char* message);
CSLAudioContext* m_AudioContext;
CSLAudioStream* m_AudioStream;
void* m_AudioBuffer;
int m_AudioBufferSize;
int m_MaxQueuedAudioMs;
};
@@ -4,19 +4,14 @@
#include <QtGlobal>
// This determines the size of the buffers we'll
// get from CoreAudio. Since GFE sends us packets
// in 5 ms chunks, we'll give them to the OS in
// buffers of the same size. It is also the minimum
// size that we will write when called to fill a buffer.
const double SoundIoAudioRenderer::k_RawSampleLengthSec = 0.005;
SoundIoAudioRenderer::SoundIoAudioRenderer()
: m_OpusChannelCount(0),
m_SoundIo(nullptr),
m_Device(nullptr),
m_OutputStream(nullptr),
m_RingBuffer(nullptr),
m_AudioPacketDuration(0),
m_Latency(0),
m_Errored(false)
{
@@ -24,6 +19,10 @@ SoundIoAudioRenderer::SoundIoAudioRenderer()
SoundIoAudioRenderer::~SoundIoAudioRenderer()
{
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION,
"Audio latency: %f",
m_Latency);
if (m_OutputStream != nullptr) {
soundio_outstream_destroy(m_OutputStream);
}
@@ -73,11 +72,17 @@ int SoundIoAudioRenderer::scoreChannelLayout(const struct SoundIoChannelLayout*
score++;
break;
// Score layouts using the back L/R as higher
// value than those using side L/R.
case SoundIoChannelIdBackLeft:
case SoundIoChannelIdBackRight:
score += 2;
if (opusConfig->channelCount == 6) {
// Score back channels higher in 5.1 mode to
// discourage selection of side channel layouts.
score += 2;
}
else {
// Score back channels normally for 7.1 mode
score++;
}
break;
default:
@@ -157,9 +162,11 @@ bool SoundIoAudioRenderer::prepareForPlayback(const OPUS_MULTISTREAM_CONFIGURATI
return false;
}
m_AudioPacketDuration = (opusConfig->samplesPerFrame / (opusConfig->sampleRate / 1000)) / 1000.0;
m_OutputStream->format = SoundIoFormatS16NE;
m_OutputStream->sample_rate = opusConfig->sampleRate;
m_OutputStream->software_latency = k_RawSampleLengthSec;
m_OutputStream->software_latency = m_AudioPacketDuration;
m_OutputStream->name = "Moonlight";
m_OutputStream->userdata = this;
m_OutputStream->error_callback = sioErrorCallback;
@@ -210,22 +217,51 @@ bool SoundIoAudioRenderer::prepareForPlayback(const OPUS_MULTISTREAM_CONFIGURATI
m_EffectiveLayout = m_OutputStream->layout;
for (int i = 0; i < m_EffectiveLayout.channel_count; i++) {
// Fixup the layout to use back L/R so our channel position
// logic in sioWriteCallback() works.
if (m_EffectiveLayout.channels[i] == SoundIoChannelIdSideLeft) {
m_EffectiveLayout.channels[i] = SoundIoChannelIdBackLeft;
if (opusConfig->channelCount == 6) {
// For 5.1, replace side L/R with back L/R so our channel position
// logic in sioWriteCallback() works.
if (m_EffectiveLayout.channels[i] == SoundIoChannelIdSideLeft) {
m_EffectiveLayout.channels[i] = SoundIoChannelIdBackLeft;
}
if (m_EffectiveLayout.channels[i] == SoundIoChannelIdSideRight) {
m_EffectiveLayout.channels[i] = SoundIoChannelIdBackRight;
}
}
if (m_EffectiveLayout.channels[i] == SoundIoChannelIdSideRight) {
m_EffectiveLayout.channels[i] = SoundIoChannelIdBackRight;
else if (opusConfig->channelCount == 8) {
// For 5.1, replace side L/R with LOC/ROC so our channel position
// logic in sioWriteCallback() works.
if (m_EffectiveLayout.channels[i] == SoundIoChannelIdSideLeft) {
m_EffectiveLayout.channels[i] = SoundIoChannelIdFrontLeftCenter;
}
if (m_EffectiveLayout.channels[i] == SoundIoChannelIdSideRight) {
m_EffectiveLayout.channels[i] = SoundIoChannelIdFrontRightCenter;
}
}
}
// Buffer up to 6 packets of audio (30 ms) to smooth
// out network packet delivery jitter
int packetsToBuffer;
if (m_SoundIo->current_backend == SoundIoBackendWasapi) {
// 15 ms buffer seems to be fine for WASAPI
packetsToBuffer = (int)ceil(0.015 / m_AudioPacketDuration);
}
else {
// 30 ms buffer on CoreAudio to avoid glitching on macOS
packetsToBuffer = (int)ceil(0.030 / m_AudioPacketDuration);
}
// Always buffer at least 2 packets
packetsToBuffer = qMax(2, packetsToBuffer);
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION,
"Audio buffer size: %f seconds",
packetsToBuffer * m_AudioPacketDuration);
m_RingBuffer = soundio_ring_buffer_create(m_SoundIo,
m_OutputStream->bytes_per_sample *
m_OpusChannelCount *
SAMPLES_PER_FRAME * 6);
opusConfig->samplesPerFrame *
packetsToBuffer);
if (m_RingBuffer == nullptr) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
"soundio_ring_buffer_create() failed");
@@ -240,18 +276,16 @@ bool SoundIoAudioRenderer::prepareForPlayback(const OPUS_MULTISTREAM_CONFIGURATI
return false;
}
// HACK: For some reason, a constant latency hangs around in the audio pipeline
// unless we wait for the audio stream to drain before actually submitting any samples.
// This is a gross hack, but it works remarkably well.
SDL_Delay(500);
return true;
}
bool SoundIoAudioRenderer::submitAudio(short* audioBuffer, int audioSize)
void* SoundIoAudioRenderer::getAudioBuffer(int* size)
{
if (m_Errored) {
return false;
}
// Flush events to update with new device arrivals
soundio_flush_events(m_SoundIo);
// We must always write a full frame of audio. If we don't,
// the reader will get out of sync with the writer and our
// channels will get all mixed up. To ensure this is always
@@ -259,13 +293,36 @@ bool SoundIoAudioRenderer::submitAudio(short* audioBuffer, int audioSize)
// of our frame size.
int bytesFree = soundio_ring_buffer_free_count(m_RingBuffer);
int bytesPerFrame = m_OpusChannelCount * m_OutputStream->bytes_per_sample;
int bytesToWrite = qMin(audioSize, (bytesFree / bytesPerFrame) * bytesPerFrame);
memcpy(soundio_ring_buffer_write_ptr(m_RingBuffer), audioBuffer, bytesToWrite);
soundio_ring_buffer_advance_write_ptr(m_RingBuffer, bytesToWrite);
*size = qMin(*size, (bytesFree / bytesPerFrame) * bytesPerFrame);
return soundio_ring_buffer_write_ptr(m_RingBuffer);
}
bool SoundIoAudioRenderer::submitAudio(int bytesWritten)
{
if (m_Errored) {
return false;
}
if (bytesWritten == 0) {
// Nothing to do
return true;
}
// Flush events to update with new device arrivals
soundio_flush_events(m_SoundIo);
// Advance the write pointer
soundio_ring_buffer_advance_write_ptr(m_RingBuffer, bytesWritten);
return true;
}
int SoundIoAudioRenderer::getCapabilities()
{
// TODO: Tweak buffer sizes then re-enable arbitrary audio duration
return CAPABILITY_DIRECT_SUBMIT /* | CAPABILITY_SUPPORTS_ARBITRARY_AUDIO_DURATION */;
}
void SoundIoAudioRenderer::sioErrorCallback(SoundIoOutStream* stream, int err)
{
auto me = reinterpret_cast<SoundIoAudioRenderer*>(stream->userdata);
@@ -330,41 +387,22 @@ void SoundIoAudioRenderer::sioWriteCallback(SoundIoOutStream* stream, int frameC
(me->m_OpusChannelCount * stream->bytes_per_sample);
int bytesRead = 0;
// Clamp framesLeft to frameCountMax
framesLeft = qMin(framesLeft, frameCountMax);
// Ensure we always write at least a buffer, even if it's silence, to avoid
// busy looping when no audio data is available while libsoundio tries to keep
// us from starving the output device.
frameCountMin = qMax(frameCountMin, (int)(stream->sample_rate * k_RawSampleLengthSec));
frameCountMin = qMax(frameCountMin, (int)(stream->sample_rate * me->m_AudioPacketDuration));
// Clamp frameCountMax to at least 2 packets or 20 ms to stop our latency from growing if audio packets lag.
// This makes sure that we never increase our latency far beyond what the sink is consuming.
frameCountMax = qMin(frameCountMax, (int)(stream->sample_rate * qMax(me->m_AudioPacketDuration * 2, 0.020)));
frameCountMin = qMin(frameCountMin, frameCountMax);
// Place an upper-bound on audio stream latency to
// avoid accumulating packets in queue-based backends
// like WASAPI, ALSA, and PulseAudio.
//
// This bound was set by testing on several Windows machines.
// The highest latency was found on a XPS 9343 running Windows 7
// in Steam Big Picture and the 5.1 audio test clip from Fraunhofer.
if (me->m_SoundIo->current_backend != SoundIoBackendCoreAudio && me->m_SoundIo->current_backend != SoundIoBackendJack) {
double latency;
if (soundio_outstream_get_latency(stream, &latency) == SoundIoErrorNone) {
if (latency > 0.050) {
// If our latency is higher than desired, drop these samples to gracefully lower
// the latency without glitching too much. Dropping the whole buffer causes
// a much more noticeable glitch. This approach also ensures that we don't
// accidentally underflow if the driver/kernel side is delayed and isn't
// consuming data fast enough. Dropping a frame at a time and re-evaluating
// each time ensures that we'll stop dropping if latency returns to normal.
readPtr += framesLeft * stream->bytes_per_sample * me->m_OpusChannelCount;
bytesRead += framesLeft * stream->bytes_per_sample * me->m_OpusChannelCount;
framesLeft = 0;
// Clamp framesLeft to frameCountMax
framesLeft = qMin(framesLeft, frameCountMax);
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION,
"Latency exceeded drop cap: %f",
latency);
}
}
// Track latency on queueing-based backends
if (me->m_SoundIo->current_backend != SoundIoBackendCoreAudio && me->m_SoundIo->current_backend != SoundIoBackendJack) {
soundio_outstream_get_latency(stream, &me->m_Latency);
}
for (;;) {
@@ -391,9 +429,8 @@ void SoundIoAudioRenderer::sioWriteCallback(SoundIoOutStream* stream, int frameC
for (int frame = 0; frame < frameCount; frame++) {
for (int ch = 0; ch < me->m_EffectiveLayout.channel_count; ch++) {
// SoundIoChannelId - 1 happens to match Moonlight's channel layout.
// For side L/R, this logic depends on us fixing those up
// in m_EffectiveLayout to back L/R.
// SoundIoChannelId - 1 happens to match Moonlight's channel layout
// after we've applied our fixups to m_EffectiveLayout for 5.1 and 7.1.
int readPtrChannel = me->m_EffectiveLayout.channels[ch] - 1;
if (frame >= framesLeft || readPtrChannel >= me->m_OpusChannelCount) {
@@ -13,7 +13,11 @@ public:
virtual bool prepareForPlayback(const OPUS_MULTISTREAM_CONFIGURATION* opusConfig);
virtual bool submitAudio(short* audioBuffer, int audioSize);
virtual void* getAudioBuffer(int* size);
virtual bool submitAudio(int bytesWritten);
virtual int getCapabilities();
private:
int scoreChannelLayout(const struct SoundIoChannelLayout* layout, const OPUS_MULTISTREAM_CONFIGURATION* opusConfig);
@@ -32,7 +36,7 @@ private:
struct SoundIoOutStream* m_OutputStream;
struct SoundIoRingBuffer* m_RingBuffer;
struct SoundIoChannelLayout m_EffectiveLayout;
double m_AudioPacketDuration;
double m_Latency;
bool m_Errored;
static const double k_RawSampleLengthSec;
};
-997
View File
@@ -1,997 +0,0 @@
#include <Limelight.h>
#include <SDL.h>
#include "streaming/session.h"
#include "settings/mappingmanager.h"
#include "path.h"
#include <QtGlobal>
#include <QDir>
#define VK_0 0x30
#define VK_A 0x41
// These are real Windows VK_* codes
#ifndef VK_F1
#define VK_F1 0x70
#define VK_F13 0x7C
#define VK_NUMPAD0 0x60
#endif
#define MOUSE_POLLING_INTERVAL 5
// How long the mouse button will be pressed for a tap to click gesture
#define TAP_BUTTON_RELEASE_DELAY 100
// How long the fingers must be stationary to start a drag
#define DRAG_ACTIVATION_DELAY 650
// How far the finger can move before it cancels a drag or tap
#define DEAD_ZONE_DELTA 0.1f
const int SdlInputHandler::k_ButtonMap[] = {
A_FLAG, B_FLAG, X_FLAG, Y_FLAG,
BACK_FLAG, SPECIAL_FLAG, PLAY_FLAG,
LS_CLK_FLAG, RS_CLK_FLAG,
LB_FLAG, RB_FLAG,
UP_FLAG, DOWN_FLAG, LEFT_FLAG, RIGHT_FLAG
};
SdlInputHandler::SdlInputHandler(StreamingPreferences& prefs, NvComputer*, int streamWidth, int streamHeight)
: m_MultiController(prefs.multiController),
m_MouseMoveTimer(0),
m_LeftButtonReleaseTimer(0),
m_RightButtonReleaseTimer(0),
m_DragTimer(0),
m_DragButton(0),
m_NumFingersDown(0),
m_StreamWidth(streamWidth),
m_StreamHeight(streamHeight)
{
// Allow gamepad input when the app doesn't have focus
SDL_SetHint(SDL_HINT_JOYSTICK_ALLOW_BACKGROUND_EVENTS, "1");
// If mouse acceleration is enabled, use relative mode warp (which
// is via normal motion events that are influenced by mouse acceleration).
// Otherwise, we'll use raw input capture which is straight from the device
// without modification by the OS.
SDL_SetHint(SDL_HINT_MOUSE_RELATIVE_MODE_WARP,
prefs.mouseAcceleration ? "1" : "0");
// We need to reinit this each time, since you only get
// an initial set of gamepad arrival events once per init.
SDL_assert(!SDL_WasInit(SDL_INIT_GAMECONTROLLER));
if (SDL_InitSubSystem(SDL_INIT_GAMECONTROLLER) != 0) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
"SDL_InitSubSystem(SDL_INIT_GAMECONTROLLER) failed: %s",
SDL_GetError());
}
MappingManager mappingManager;
mappingManager.applyMappings();
// Initialize the gamepad mask with currently attached gamepads to avoid
// causing gamepads to unexpectedly disappear and reappear on the host
// during stream startup as we detect currently attached gamepads one at a time.
m_GamepadMask = getAttachedGamepadMask();
SDL_zero(m_GamepadState);
SDL_zero(m_TouchDownEvent);
SDL_zero(m_CumulativeDelta);
SDL_AtomicSet(&m_MouseDeltaX, 0);
SDL_AtomicSet(&m_MouseDeltaY, 0);
m_MouseMoveTimer = SDL_AddTimer(MOUSE_POLLING_INTERVAL, SdlInputHandler::mouseMoveTimerCallback, this);
}
SdlInputHandler::~SdlInputHandler()
{
for (int i = 0; i < MAX_GAMEPADS; i++) {
if (m_GamepadState[i].controller != nullptr) {
SDL_GameControllerClose(m_GamepadState[i].controller);
}
}
SDL_RemoveTimer(m_MouseMoveTimer);
SDL_RemoveTimer(m_LeftButtonReleaseTimer);
SDL_RemoveTimer(m_RightButtonReleaseTimer);
SDL_RemoveTimer(m_DragTimer);
SDL_QuitSubSystem(SDL_INIT_GAMECONTROLLER);
SDL_assert(!SDL_WasInit(SDL_INIT_GAMECONTROLLER));
}
void SdlInputHandler::handleKeyEvent(SDL_KeyboardEvent* event)
{
short keyCode;
char modifiers;
// Check for our special key combos
if ((event->state == SDL_PRESSED) &&
(event->keysym.mod & KMOD_CTRL) &&
(event->keysym.mod & KMOD_ALT) &&
(event->keysym.mod & KMOD_SHIFT)) {
// Check for quit combo (Ctrl+Alt+Shift+Q)
if (event->keysym.sym == SDLK_q) {
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION,
"Detected quit key combo");
// Push a quit event to the main loop
SDL_Event event;
event.type = SDL_QUIT;
event.quit.timestamp = SDL_GetTicks();
SDL_PushEvent(&event);
return;
}
// Check for the unbind combo (Ctrl+Alt+Shift+Z)
else if (event->keysym.sym == SDLK_z) {
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION,
"Detected mouse capture toggle combo");
// Stop handling future input
SDL_SetRelativeMouseMode((SDL_bool)!SDL_GetRelativeMouseMode());
// Force raise all keys to ensure they aren't stuck,
// since we won't get their key up events.
raiseAllKeys();
return;
}
// Check for the full-screen combo (Ctrl+Alt+Shift+X)
else if (event->keysym.sym == SDLK_x) {
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION,
"Detected full-screen toggle combo");
Session::s_ActiveSession->toggleFullscreen();
// Force raise all keys just be safe across this full-screen/windowed
// transition just in case key events get lost.
raiseAllKeys();
return;
}
}
if (!SDL_GetRelativeMouseMode()) {
// Not capturing
return;
}
// Set modifier flags
modifiers = 0;
if (event->keysym.mod & KMOD_CTRL) {
modifiers |= MODIFIER_CTRL;
}
if (event->keysym.mod & KMOD_ALT) {
modifiers |= MODIFIER_ALT;
}
if (event->keysym.mod & KMOD_SHIFT) {
modifiers |= MODIFIER_SHIFT;
}
// Set keycode. We explicitly use scancode here because GFE will try to correct
// for AZERTY layouts on the host but it depends on receiving VK_ values matching
// a QWERTY layout to work.
if (event->keysym.scancode >= SDL_SCANCODE_1 && event->keysym.scancode <= SDL_SCANCODE_9) {
// SDL defines SDL_SCANCODE_0 > SDL_SCANCODE_9, so we need to handle that manually
keyCode = (event->keysym.scancode - SDL_SCANCODE_1) + VK_0 + 1;
}
else if (event->keysym.scancode >= SDL_SCANCODE_A && event->keysym.scancode <= SDL_SCANCODE_Z) {
keyCode = (event->keysym.scancode - SDL_SCANCODE_A) + VK_A;
}
else if (event->keysym.scancode >= SDL_SCANCODE_F1 && event->keysym.scancode <= SDL_SCANCODE_F12) {
keyCode = (event->keysym.scancode - SDL_SCANCODE_F1) + VK_F1;
}
else if (event->keysym.scancode >= SDL_SCANCODE_F13 && event->keysym.scancode <= SDL_SCANCODE_F24) {
keyCode = (event->keysym.scancode - SDL_SCANCODE_F13) + VK_F13;
}
else if (event->keysym.scancode >= SDL_SCANCODE_KP_1 && event->keysym.scancode <= SDL_SCANCODE_KP_9) {
// SDL defines SDL_SCANCODE_KP_0 > SDL_SCANCODE_KP_9, so we need to handle that manually
keyCode = (event->keysym.scancode - SDL_SCANCODE_KP_1) + VK_NUMPAD0 + 1;
}
else {
switch (event->keysym.scancode) {
case SDL_SCANCODE_BACKSPACE:
keyCode = 0x08;
break;
case SDL_SCANCODE_TAB:
keyCode = 0x09;
break;
case SDL_SCANCODE_CLEAR:
keyCode = 0x0C;
break;
case SDL_SCANCODE_KP_ENTER: // FIXME: Is this correct?
case SDL_SCANCODE_RETURN:
keyCode = 0x0D;
break;
case SDL_SCANCODE_PAUSE:
keyCode = 0x13;
break;
case SDL_SCANCODE_CAPSLOCK:
keyCode = 0x14;
break;
case SDL_SCANCODE_ESCAPE:
keyCode = 0x1B;
break;
case SDL_SCANCODE_SPACE:
keyCode = 0x20;
break;
case SDL_SCANCODE_PAGEUP:
keyCode = 0x21;
break;
case SDL_SCANCODE_PAGEDOWN:
keyCode = 0x22;
break;
case SDL_SCANCODE_END:
keyCode = 0x23;
break;
case SDL_SCANCODE_HOME:
keyCode = 0x24;
break;
case SDL_SCANCODE_LEFT:
keyCode = 0x25;
break;
case SDL_SCANCODE_UP:
keyCode = 0x26;
break;
case SDL_SCANCODE_RIGHT:
keyCode = 0x27;
break;
case SDL_SCANCODE_DOWN:
keyCode = 0x28;
break;
case SDL_SCANCODE_SELECT:
keyCode = 0x29;
break;
case SDL_SCANCODE_EXECUTE:
keyCode = 0x2B;
break;
case SDL_SCANCODE_PRINTSCREEN:
keyCode = 0x2C;
break;
case SDL_SCANCODE_INSERT:
keyCode = 0x2D;
break;
case SDL_SCANCODE_DELETE:
keyCode = 0x2E;
break;
case SDL_SCANCODE_HELP:
keyCode = 0x2F;
break;
case SDL_SCANCODE_KP_0:
// See comment above about why we only handle SDL_SCANCODE_KP_0 here
keyCode = VK_NUMPAD0;
break;
case SDL_SCANCODE_0:
// See comment above about why we only handle SDL_SCANCODE_0 here
keyCode = VK_0;
break;
case SDL_SCANCODE_KP_MULTIPLY:
keyCode = 0x6A;
break;
case SDL_SCANCODE_KP_PLUS:
keyCode = 0x6B;
break;
case SDL_SCANCODE_KP_COMMA:
keyCode = 0x6C;
break;
case SDL_SCANCODE_KP_MINUS:
keyCode = 0x6D;
break;
case SDL_SCANCODE_KP_PERIOD:
keyCode = 0x6E;
break;
case SDL_SCANCODE_KP_DIVIDE:
keyCode = 0x6F;
break;
case SDL_SCANCODE_NUMLOCKCLEAR:
keyCode = 0x90;
break;
case SDL_SCANCODE_SCROLLLOCK:
keyCode = 0x91;
break;
case SDL_SCANCODE_LSHIFT:
keyCode = 0xA0;
break;
case SDL_SCANCODE_RSHIFT:
keyCode = 0xA1;
break;
case SDL_SCANCODE_LCTRL:
keyCode = 0xA2;
break;
case SDL_SCANCODE_RCTRL:
keyCode = 0xA3;
break;
case SDL_SCANCODE_LALT:
keyCode = 0xA4;
break;
case SDL_SCANCODE_RALT:
keyCode = 0xA5;
break;
case SDL_SCANCODE_AC_BACK:
keyCode = 0xA6;
break;
case SDL_SCANCODE_AC_FORWARD:
keyCode = 0xA7;
break;
case SDL_SCANCODE_AC_REFRESH:
keyCode = 0xA8;
break;
case SDL_SCANCODE_AC_STOP:
keyCode = 0xA9;
break;
case SDL_SCANCODE_AC_SEARCH:
keyCode = 0xAA;
break;
case SDL_SCANCODE_AC_BOOKMARKS:
keyCode = 0xAB;
break;
case SDL_SCANCODE_AC_HOME:
keyCode = 0xAC;
break;
case SDL_SCANCODE_SEMICOLON:
keyCode = 0xBA;
break;
case SDL_SCANCODE_EQUALS:
keyCode = 0xBB;
break;
case SDL_SCANCODE_COMMA:
keyCode = 0xBC;
break;
case SDL_SCANCODE_MINUS:
keyCode = 0xBD;
break;
case SDL_SCANCODE_PERIOD:
keyCode = 0xBE;
break;
case SDL_SCANCODE_SLASH:
keyCode = 0xBF;
break;
case SDL_SCANCODE_GRAVE:
keyCode = 0xC0;
break;
case SDL_SCANCODE_LEFTBRACKET:
keyCode = 0xDB;
break;
case SDL_SCANCODE_BACKSLASH:
keyCode = 0xDC;
break;
case SDL_SCANCODE_RIGHTBRACKET:
keyCode = 0xDD;
break;
case SDL_SCANCODE_APOSTROPHE:
keyCode = 0xDE;
break;
case SDL_SCANCODE_NONUSBACKSLASH:
keyCode = 0xE2;
break;
default:
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION,
"Unhandled button event: %d",
event->keysym.scancode);
return;
}
}
// Track the key state so we always know which keys are down
if (event->state == SDL_PRESSED) {
m_KeysDown.insert(keyCode);
}
else {
m_KeysDown.remove(keyCode);
}
LiSendKeyboardEvent(keyCode,
event->state == SDL_PRESSED ?
KEY_ACTION_DOWN : KEY_ACTION_UP,
modifiers);
}
void SdlInputHandler::handleMouseButtonEvent(SDL_MouseButtonEvent* event)
{
int button;
// Capture the mouse again if clicked when unbound.
// We start capture on left button released instead of
// pressed to avoid sending an errant mouse button released
// event to the host when clicking into our window (since
// the pressed event was consumed by this code).
if (event->button == SDL_BUTTON_LEFT &&
event->state == SDL_RELEASED &&
!SDL_GetRelativeMouseMode()) {
SDL_SetRelativeMouseMode(SDL_TRUE);
return;
}
else if (!SDL_GetRelativeMouseMode()) {
// Not capturing
return;
}
else if (event->which == SDL_TOUCH_MOUSEID) {
// Ignore synthetic mouse events
return;
}
switch (event->button)
{
case SDL_BUTTON_LEFT:
button = BUTTON_LEFT;
break;
case SDL_BUTTON_MIDDLE:
button = BUTTON_MIDDLE;
break;
case SDL_BUTTON_RIGHT:
button = BUTTON_RIGHT;
break;
case SDL_BUTTON_X1:
button = BUTTON_X1;
break;
case SDL_BUTTON_X2:
button = BUTTON_X2;
break;
default:
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION,
"Unhandled button event: %d",
event->button);
return;
}
LiSendMouseButtonEvent(event->state == SDL_PRESSED ?
BUTTON_ACTION_PRESS :
BUTTON_ACTION_RELEASE,
button);
}
void SdlInputHandler::handleMouseMotionEvent(SDL_MouseMotionEvent* event)
{
if (!SDL_GetRelativeMouseMode()) {
// Not capturing
return;
}
else if (event->which == SDL_TOUCH_MOUSEID) {
// Ignore synthetic mouse events
return;
}
// Batch until the next mouse polling window or we'll get awful
// input lag everything except GFE 3.14 and 3.15.
SDL_AtomicAdd(&m_MouseDeltaX, event->xrel);
SDL_AtomicAdd(&m_MouseDeltaY, event->yrel);
}
void SdlInputHandler::handleMouseWheelEvent(SDL_MouseWheelEvent* event)
{
if (!SDL_GetRelativeMouseMode()) {
// Not capturing
return;
}
else if (event->which == SDL_TOUCH_MOUSEID) {
// Ignore synthetic mouse events
return;
}
if (event->y != 0) {
LiSendScrollEvent((signed char)event->y);
}
}
GamepadState*
SdlInputHandler::findStateForGamepad(SDL_JoystickID id)
{
int i;
for (i = 0; i < MAX_GAMEPADS; i++) {
if (m_GamepadState[i].jsId == id) {
SDL_assert(!m_MultiController || m_GamepadState[i].index == i);
return &m_GamepadState[i];
}
}
// This should only happen with > 4 gamepads
SDL_assert(SDL_NumJoysticks() > 4);
return nullptr;
}
void SdlInputHandler::sendGamepadState(GamepadState* state)
{
SDL_assert(m_GamepadMask == 0x1 || m_MultiController);
LiSendMultiControllerEvent(state->index,
m_GamepadMask,
state->buttons,
state->lt,
state->rt,
state->lsX,
state->lsY,
state->rsX,
state->rsY);
}
Uint32 SdlInputHandler::releaseLeftButtonTimerCallback(Uint32, void*)
{
LiSendMouseButtonEvent(BUTTON_ACTION_RELEASE, BUTTON_LEFT);
return 0;
}
Uint32 SdlInputHandler::releaseRightButtonTimerCallback(Uint32, void*)
{
LiSendMouseButtonEvent(BUTTON_ACTION_RELEASE, BUTTON_RIGHT);
return 0;
}
Uint32 SdlInputHandler::dragTimerCallback(Uint32, void *param)
{
auto me = reinterpret_cast<SdlInputHandler*>(param);
// Check how many fingers are down now to decide
// which button to hold down
if (me->m_NumFingersDown == 2) {
me->m_DragButton = BUTTON_RIGHT;
}
else if (me->m_NumFingersDown == 1) {
me->m_DragButton = BUTTON_LEFT;
}
LiSendMouseButtonEvent(BUTTON_ACTION_PRESS, me->m_DragButton);
return 0;
}
Uint32 SdlInputHandler::mouseMoveTimerCallback(Uint32 interval, void *param)
{
auto me = reinterpret_cast<SdlInputHandler*>(param);
short deltaX = (short)SDL_AtomicSet(&me->m_MouseDeltaX, 0);
short deltaY = (short)SDL_AtomicSet(&me->m_MouseDeltaY, 0);
if (deltaX != 0 || deltaY != 0) {
LiSendMouseMoveEvent(deltaX, deltaY);
}
return interval;
}
void SdlInputHandler::handleControllerAxisEvent(SDL_ControllerAxisEvent* event)
{
GamepadState* state = findStateForGamepad(event->which);
if (state == NULL) {
return;
}
switch (event->axis)
{
case SDL_CONTROLLER_AXIS_LEFTX:
state->lsX = event->value;
break;
case SDL_CONTROLLER_AXIS_LEFTY:
// Signed values have one more negative value than
// positive value, so inverting the sign on -32768
// could actually cause the value to overflow and
// wrap around to be negative again. Avoid that by
// capping the value at 32767.
state->lsY = -qMax(event->value, (short)-32767);
break;
case SDL_CONTROLLER_AXIS_RIGHTX:
state->rsX = event->value;
break;
case SDL_CONTROLLER_AXIS_RIGHTY:
state->rsY = -qMax(event->value, (short)-32767);
break;
case SDL_CONTROLLER_AXIS_TRIGGERLEFT:
state->lt = (unsigned char)(event->value * 255UL / 32767);
break;
case SDL_CONTROLLER_AXIS_TRIGGERRIGHT:
state->rt = (unsigned char)(event->value * 255UL / 32767);
break;
default:
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION,
"Unhandled controller axis: %d",
event->axis);
return;
}
sendGamepadState(state);
}
void SdlInputHandler::handleControllerButtonEvent(SDL_ControllerButtonEvent* event)
{
GamepadState* state = findStateForGamepad(event->which);
if (state == NULL) {
return;
}
if (event->state == SDL_PRESSED) {
state->buttons |= k_ButtonMap[event->button];
}
else {
state->buttons &= ~k_ButtonMap[event->button];
}
// Handle Start+Select+L1+R1 as a gamepad quit combo
if (state->buttons == (PLAY_FLAG | BACK_FLAG | LB_FLAG | RB_FLAG)) {
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION,
"Detected quit gamepad button combo");
// Push a quit event to the main loop
SDL_Event event;
event.type = SDL_QUIT;
event.quit.timestamp = SDL_GetTicks();
SDL_PushEvent(&event);
// Clear buttons down on this gameapd
LiSendMultiControllerEvent(state->index, m_GamepadMask,
0, 0, 0, 0, 0, 0, 0);
return;
}
sendGamepadState(state);
}
void SdlInputHandler::handleControllerDeviceEvent(SDL_ControllerDeviceEvent* event)
{
GamepadState* state;
if (event->type == SDL_CONTROLLERDEVICEADDED) {
int i;
const char* name;
SDL_GameController* controller;
const char* mapping;
char guidStr[33];
controller = SDL_GameControllerOpen(event->which);
if (controller == NULL) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
"Failed to open gamepad: %s",
SDL_GetError());
return;
}
#if SDL_VERSION_ATLEAST(2, 0, 9)
// Determine this player's preferred index
i = SDL_GameControllerGetPlayerIndex(controller);
if (i < 0 || i >= MAX_GAMEPADS || m_GamepadState[i].controller != NULL) {
// If the player index is unavailable or invalid, start searching from 0
i = 0;
}
#else
// SDL 2.0.8 and earlier has no player number hints
i = 0;
#endif
for (; i < MAX_GAMEPADS; i++) {
if (m_GamepadState[i].controller == NULL) {
// Found an empty slot
break;
}
}
if (i == MAX_GAMEPADS) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
"No open gamepad slots found!");
SDL_GameControllerClose(controller);
return;
}
state = &m_GamepadState[i];
if (m_MultiController) {
state->index = i;
}
else {
// Always player 1 in single controller mode
state->index = 0;
}
state->controller = controller;
state->jsId = SDL_JoystickInstanceID(SDL_GameControllerGetJoystick(state->controller));
SDL_JoystickGetGUIDString(SDL_JoystickGetGUID(SDL_GameControllerGetJoystick(state->controller)),
guidStr, sizeof(guidStr));
mapping = SDL_GameControllerMapping(state->controller);
name = SDL_GameControllerName(state->controller);
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION,
"Gamepad %d (player %d) is: %s (%s -> %s)",
i,
state->index,
name != nullptr ? name : "<null>",
guidStr,
mapping != nullptr ? mapping : "<null>");
if (mapping != nullptr) {
SDL_free((void*)mapping);
}
// Add this gamepad to the gamepad mask
if (m_MultiController) {
// NB: Don't assert that it's unset here because we will already
// have the mask set for initially attached gamepads to avoid confusing
// apps running on the host.
m_GamepadMask |= (1 << state->index);
}
else {
SDL_assert(m_GamepadMask == 0x1);
}
// Send an empty event to tell the PC we've arrived
sendGamepadState(state);
}
else if (event->type == SDL_CONTROLLERDEVICEREMOVED) {
state = findStateForGamepad(event->which);
if (state != NULL) {
SDL_GameControllerClose(state->controller);
// Remove this from the gamepad mask in MC-mode
if (m_MultiController) {
SDL_assert(m_GamepadMask & (1 << state->index));
m_GamepadMask &= ~(1 << state->index);
}
else {
SDL_assert(m_GamepadMask == 0x1);
}
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION,
"Gamepad %d is gone",
state->index);
// Send a final event to let the PC know this gamepad is gone
LiSendMultiControllerEvent(state->index, m_GamepadMask,
0, 0, 0, 0, 0, 0, 0);
// Clear all remaining state from this slot
SDL_memset(state, 0, sizeof(*state));
}
}
}
void SdlInputHandler::handleJoystickArrivalEvent(SDL_JoyDeviceEvent* event)
{
SDL_assert(event->type == SDL_JOYDEVICEADDED);
if (!SDL_IsGameController(event->which)) {
char guidStr[33];
SDL_JoystickGetGUIDString(SDL_JoystickGetDeviceGUID(event->which),
guidStr, sizeof(guidStr));
const char* name = SDL_JoystickNameForIndex(event->which);
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION,
"Joystick discovered with no mapping: %s %s",
name ? name : "<UNKNOWN>",
guidStr);
SDL_Joystick* joy = SDL_JoystickOpen(event->which);
if (joy != nullptr) {
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION,
"Number of axes: %d | Number of buttons: %d | Number of hats: %d",
SDL_JoystickNumAxes(joy), SDL_JoystickNumButtons(joy),
SDL_JoystickNumHats(joy));
SDL_JoystickClose(joy);
}
else {
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION,
"Unable to open joystick for query: %s",
SDL_GetError());
}
}
}
void SdlInputHandler::handleTouchFingerEvent(SDL_TouchFingerEvent* event)
{
int fingerIndex = -1;
// Observations on Windows 10: x and y appear to be relative to 0,0 of the window client area.
// Although SDL documentation states they are 0.0 - 1.0 float values, they can actually be higher
// or lower than those values as touch events continue for touches started within the client area that
// leave the client area during a drag motion.
// dx and dy are deltas from the last touch event, not the first touch down.
// Determine the index of this finger using our list
// of fingers that are currently active on screen.
// This is also required to handle finger up which
// where the finger will not be in SDL_GetTouchFinger()
// anymore.
if (event->type != SDL_FINGERDOWN) {
for (int i = 0; i < MAX_FINGERS; i++) {
if (event->fingerId == m_TouchDownEvent[i].fingerId) {
fingerIndex = i;
break;
}
}
}
else {
// Resolve the new finger by determining the ID of each
// finger on the display.
int numTouchFingers = SDL_GetNumTouchFingers(event->touchId);
for (int i = 0; i < numTouchFingers; i++) {
SDL_Finger* finger = SDL_GetTouchFinger(event->touchId, i);
SDL_assert(finger != nullptr);
if (finger != nullptr) {
if (finger->id == event->fingerId) {
fingerIndex = i;
break;
}
}
}
}
if (fingerIndex < 0 || fingerIndex >= MAX_FINGERS) {
// Too many fingers
return;
}
// Handle cursor motion based on the position of the
// primary finger on screen
if (fingerIndex == 0) {
// The event x and y values are relative to our window width
// and height. However, we want to scale them to be relative
// to the host resolution. Fortunately this is easy since we
// already have normalized values. We'll just multiply them
// by the stream dimensions to get real X and Y values rather
// than the client window dimensions.
short deltaX = static_cast<short>(event->dx * m_StreamWidth);
short deltaY = static_cast<short>(event->dy * m_StreamHeight);
if (deltaX != 0 || deltaY != 0) {
LiSendMouseMoveEvent(deltaX, deltaY);
}
}
// Start a drag timer when primary or secondary
// fingers go down
if (event->type == SDL_FINGERDOWN &&
(fingerIndex == 0 || fingerIndex == 1)) {
SDL_RemoveTimer(m_DragTimer);
m_DragTimer = SDL_AddTimer(DRAG_ACTIVATION_DELAY,
dragTimerCallback,
this);
}
if (event->type == SDL_FINGERMOTION) {
// Count the total cumulative dx/dy that the finger
// has moved.
m_CumulativeDelta[fingerIndex] += qAbs(event->x);
m_CumulativeDelta[fingerIndex] += qAbs(event->y);
// If it's outside the deadzone delta, cancel drags and taps
if (m_CumulativeDelta[fingerIndex] > DEAD_ZONE_DELTA) {
SDL_RemoveTimer(m_DragTimer);
m_DragTimer = 0;
// This effectively cancels the tap logic below
m_TouchDownEvent[fingerIndex].timestamp = 0;
}
}
if (event->type == SDL_FINGERUP) {
// Cancel the drag timer on finger up
SDL_RemoveTimer(m_DragTimer);
m_DragTimer = 0;
// Release any drag
if (m_DragButton != 0) {
LiSendMouseButtonEvent(BUTTON_ACTION_RELEASE, m_DragButton);
m_DragButton = 0;
}
// 2 finger tap
else if (event->timestamp - m_TouchDownEvent[1].timestamp < 250) {
// Zero timestamp of the primary finger to ensure we won't
// generate a left click if the primary finger comes up soon.
m_TouchDownEvent[0].timestamp = 0;
// Press down the right mouse button
LiSendMouseButtonEvent(BUTTON_ACTION_PRESS, BUTTON_RIGHT);
// Queue a timer to release it in 100 ms
SDL_RemoveTimer(m_RightButtonReleaseTimer);
m_RightButtonReleaseTimer = SDL_AddTimer(TAP_BUTTON_RELEASE_DELAY,
releaseRightButtonTimerCallback,
nullptr);
}
// 1 finger tap
else if (event->timestamp - m_TouchDownEvent[0].timestamp < 250) {
// Press down the left mouse button
LiSendMouseButtonEvent(BUTTON_ACTION_PRESS, BUTTON_LEFT);
// Queue a timer to release it in 100 ms
SDL_RemoveTimer(m_LeftButtonReleaseTimer);
m_LeftButtonReleaseTimer = SDL_AddTimer(TAP_BUTTON_RELEASE_DELAY,
releaseLeftButtonTimerCallback,
nullptr);
}
}
m_NumFingersDown = SDL_GetNumTouchFingers(event->touchId);
if (event->type == SDL_FINGERDOWN) {
m_TouchDownEvent[fingerIndex] = *event;
m_CumulativeDelta[fingerIndex] = 0;
}
else if (event->type == SDL_FINGERUP) {
m_TouchDownEvent[fingerIndex] = {};
}
}
int SdlInputHandler::getAttachedGamepadMask()
{
int count;
int mask;
if (!m_MultiController) {
// Player 1 is always present in non-MC mode
return 0x1;
}
// TODO: Use SDL_GameControllerGetPlayerIndex() for accurate indexes?
count = mask = 0;
for (int i = 0; i < SDL_NumJoysticks(); i++) {
if (SDL_IsGameController(i)) {
mask |= (1 << count++);
}
}
return mask;
}
void SdlInputHandler::raiseAllKeys()
{
if (m_KeysDown.isEmpty()) {
return;
}
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION,
"Raising %d keys",
m_KeysDown.count());
for (auto keyDown : m_KeysDown) {
LiSendKeyboardEvent(keyDown, KEY_ACTION_UP, 0);
}
m_KeysDown.clear();
}
QString SdlInputHandler::getUnmappedGamepads()
{
QString ret;
if (SDL_InitSubSystem(SDL_INIT_GAMECONTROLLER) != 0) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
"SDL_InitSubSystem(SDL_INIT_GAMECONTROLLER) failed: %s",
SDL_GetError());
}
MappingManager mappingManager;
mappingManager.applyMappings();
for (int i = 0; i < SDL_NumJoysticks(); i++) {
if (!SDL_IsGameController(i)) {
char guidStr[33];
SDL_JoystickGetGUIDString(SDL_JoystickGetDeviceGUID(i),
guidStr, sizeof(guidStr));
const char* name = SDL_JoystickNameForIndex(i);
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION,
"Unmapped joystick: %s %s",
name ? name : "<UNKNOWN>",
guidStr);
SDL_Joystick* joy = SDL_JoystickOpen(i);
if (joy != nullptr) {
int numButtons = SDL_JoystickNumButtons(joy);
int numHats = SDL_JoystickNumHats(joy);
int numAxes = SDL_JoystickNumAxes(joy);
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION,
"Number of axes: %d | Number of buttons: %d | Number of hats: %d",
numAxes, numButtons, numHats);
if (numAxes >= 4 && numButtons >= 8 && numHats <= 1) {
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION,
"Joystick likely to be an unmapped game controller");
if (!ret.isEmpty()) {
ret += ", ";
}
ret += name;
}
SDL_JoystickClose(joy);
}
else {
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION,
"Unable to open joystick for query: %s",
SDL_GetError());
}
}
}
SDL_QuitSubSystem(SDL_INIT_GAMECONTROLLER);
return ret;
}
+107
View File
@@ -0,0 +1,107 @@
#include "input.h"
#include <Limelight.h>
#include <SDL.h>
#include "streaming/streamutils.h"
#include <QtMath>
// How long the fingers must be stationary to start a right click
#define LONG_PRESS_ACTIVATION_DELAY 650
// How far the finger can move before it cancels a right click
#define LONG_PRESS_ACTIVATION_DELTA 0.01f
// How long the double tap deadzone stays in effect between touch up and touch down
#define DOUBLE_TAP_DEAD_ZONE_DELAY 250
// How far the finger can move before it can override the double tap deadzone
#define DOUBLE_TAP_DEAD_ZONE_DELTA 0.025f
Uint32 SdlInputHandler::longPressTimerCallback(Uint32, void*)
{
// Raise the left click and start a right click
LiSendMouseButtonEvent(BUTTON_ACTION_RELEASE, BUTTON_LEFT);
LiSendMouseButtonEvent(BUTTON_ACTION_PRESS, BUTTON_RIGHT);
return 0;
}
void SdlInputHandler::handleAbsoluteFingerEvent(SDL_TouchFingerEvent* event)
{
// Observations on Windows 10: x and y appear to be relative to 0,0 of the window client area.
// Although SDL documentation states they are 0.0 - 1.0 float values, they can actually be higher
// or lower than those values as touch events continue for touches started within the client area that
// leave the client area during a drag motion.
// dx and dy are deltas from the last touch event, not the first touch down.
// Ignore touch down events with more than one finger
if (event->type == SDL_FINGERDOWN && SDL_GetNumTouchFingers(event->touchId) > 1) {
return;
}
// Ignore touch move and touch up events from the non-primary finger
if (event->type != SDL_FINGERDOWN && event->fingerId != m_LastTouchDownEvent.fingerId) {
return;
}
SDL_Rect src, dst;
int windowWidth, windowHeight;
SDL_GetWindowSize(m_Window, &windowWidth, &windowHeight);
src.x = src.y = 0;
src.w = m_StreamWidth;
src.h = m_StreamHeight;
dst.x = dst.y = 0;
dst.w = windowWidth;
dst.h = windowHeight;
// Use the stream and window sizes to determine the video region
StreamUtils::scaleSourceToDestinationSurface(&src, &dst);
if (qSqrt(qPow(event->x - m_LastTouchDownEvent.x, 2) + qPow(event->y - m_LastTouchDownEvent.y, 2)) > LONG_PRESS_ACTIVATION_DELTA) {
// Moved too far since touch down. Cancel the long press timer.
SDL_RemoveTimer(m_LongPressTimer);
m_LongPressTimer = 0;
}
// Don't reposition for finger down events within the deadzone. This makes double-clicking easier.
if (event->type != SDL_FINGERDOWN ||
event->timestamp - m_LastTouchUpEvent.timestamp > DOUBLE_TAP_DEAD_ZONE_DELAY ||
qSqrt(qPow(event->x - m_LastTouchUpEvent.x, 2) + qPow(event->y - m_LastTouchUpEvent.y, 2)) > DOUBLE_TAP_DEAD_ZONE_DELTA) {
// Scale window-relative events to be video-relative and clamp to video region
short x = qMin(qMax((int)(event->x * windowWidth), dst.x), dst.x + dst.w);
short y = qMin(qMax((int)(event->y * windowHeight), dst.y), dst.y + dst.h);
// Update the cursor position relative to the video region
LiSendMousePositionEvent(x - dst.x, y - dst.y, dst.w, dst.h);
}
if (event->type == SDL_FINGERDOWN) {
m_LastTouchDownEvent = *event;
// Start/restart the long press timer
SDL_RemoveTimer(m_LongPressTimer);
m_LongPressTimer = SDL_AddTimer(LONG_PRESS_ACTIVATION_DELAY,
longPressTimerCallback,
nullptr);
// Left button down on finger down
LiSendMouseButtonEvent(BUTTON_ACTION_PRESS, BUTTON_LEFT);
}
else if (event->type == SDL_FINGERUP) {
m_LastTouchUpEvent = *event;
// Cancel the long press timer
SDL_RemoveTimer(m_LongPressTimer);
m_LongPressTimer = 0;
// Left button up on finger up
LiSendMouseButtonEvent(BUTTON_ACTION_RELEASE, BUTTON_LEFT);
// Raise right button too in case we triggered a long press gesture
LiSendMouseButtonEvent(BUTTON_ACTION_RELEASE, BUTTON_RIGHT);
}
}
+595
View File
@@ -0,0 +1,595 @@
#include "streaming/session.h"
#include <Limelight.h>
#include <SDL.h>
#include "settings/mappingmanager.h"
#include <QtMath>
// How long the Start button must be pressed to toggle mouse emulation
#define MOUSE_EMULATION_LONG_PRESS_TIME 750
// How long between polling the gamepad to send virtual mouse input
#define MOUSE_EMULATION_POLLING_INTERVAL 50
// Determines how fast the mouse will move each interval
#define MOUSE_EMULATION_MOTION_MULTIPLIER 4
// Determines the maximum motion amount before allowing movement
#define MOUSE_EMULATION_DEADZONE 2
// Haptic capabilities (in addition to those from SDL_HapticQuery())
#define ML_HAPTIC_GC_RUMBLE (1U << 16)
#define ML_HAPTIC_SIMPLE_RUMBLE (1U << 17)
const int SdlInputHandler::k_ButtonMap[] = {
A_FLAG, B_FLAG, X_FLAG, Y_FLAG,
BACK_FLAG, SPECIAL_FLAG, PLAY_FLAG,
LS_CLK_FLAG, RS_CLK_FLAG,
LB_FLAG, RB_FLAG,
UP_FLAG, DOWN_FLAG, LEFT_FLAG, RIGHT_FLAG
};
GamepadState*
SdlInputHandler::findStateForGamepad(SDL_JoystickID id)
{
int i;
for (i = 0; i < MAX_GAMEPADS; i++) {
if (m_GamepadState[i].jsId == id) {
SDL_assert(!m_MultiController || m_GamepadState[i].index == i);
return &m_GamepadState[i];
}
}
// This should only happen with > 4 gamepads
SDL_assert(SDL_NumJoysticks() > 4);
return nullptr;
}
void SdlInputHandler::sendGamepadState(GamepadState* state)
{
SDL_assert(m_GamepadMask == 0x1 || m_MultiController);
LiSendMultiControllerEvent(state->index,
m_GamepadMask,
state->buttons,
state->lt,
state->rt,
state->lsX,
state->lsY,
state->rsX,
state->rsY);
}
Uint32 SdlInputHandler::mouseEmulationTimerCallback(Uint32 interval, void *param)
{
auto gamepad = reinterpret_cast<GamepadState*>(param);
short rawX;
short rawY;
// Determine which analog stick is currently receiving the strongest input
if ((uint32_t)qAbs(gamepad->lsX) + qAbs(gamepad->lsY) > (uint32_t)qAbs(gamepad->rsX) + qAbs(gamepad->rsY)) {
rawX = gamepad->lsX;
rawY = -gamepad->lsY;
}
else {
rawX = gamepad->rsX;
rawY = -gamepad->rsY;
}
float deltaX;
float deltaY;
// Produce a base vector for mouse movement with increased speed as we deviate further from center
deltaX = qPow(rawX / 32766.0f * MOUSE_EMULATION_MOTION_MULTIPLIER, 3);
deltaY = qPow(rawY / 32766.0f * MOUSE_EMULATION_MOTION_MULTIPLIER, 3);
// Enforce deadzones
deltaX = qAbs(deltaX) > MOUSE_EMULATION_DEADZONE ? deltaX - MOUSE_EMULATION_DEADZONE : 0;
deltaY = qAbs(deltaY) > MOUSE_EMULATION_DEADZONE ? deltaY - MOUSE_EMULATION_DEADZONE : 0;
if (deltaX != 0 || deltaY != 0) {
LiSendMouseMoveEvent((short)deltaX, (short)deltaY);
}
return interval;
}
void SdlInputHandler::handleControllerAxisEvent(SDL_ControllerAxisEvent* event)
{
SDL_JoystickID gameControllerId = event->which;
GamepadState* state = findStateForGamepad(gameControllerId);
if (state == NULL) {
return;
}
// Batch all pending axis motion events for this gamepad to save CPU time
SDL_Event nextEvent;
for (;;) {
switch (event->axis)
{
case SDL_CONTROLLER_AXIS_LEFTX:
state->lsX = event->value;
break;
case SDL_CONTROLLER_AXIS_LEFTY:
// Signed values have one more negative value than
// positive value, so inverting the sign on -32768
// could actually cause the value to overflow and
// wrap around to be negative again. Avoid that by
// capping the value at 32767.
state->lsY = -qMax(event->value, (short)-32767);
break;
case SDL_CONTROLLER_AXIS_RIGHTX:
state->rsX = event->value;
break;
case SDL_CONTROLLER_AXIS_RIGHTY:
state->rsY = -qMax(event->value, (short)-32767);
break;
case SDL_CONTROLLER_AXIS_TRIGGERLEFT:
state->lt = (unsigned char)(event->value * 255UL / 32767);
break;
case SDL_CONTROLLER_AXIS_TRIGGERRIGHT:
state->rt = (unsigned char)(event->value * 255UL / 32767);
break;
default:
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION,
"Unhandled controller axis: %d",
event->axis);
return;
}
// Check for another event to batch with
if (SDL_PeepEvents(&nextEvent, 1, SDL_PEEKEVENT, SDL_CONTROLLERAXISMOTION, SDL_CONTROLLERAXISMOTION) <= 0) {
break;
}
event = &nextEvent.caxis;
if (event->which != gameControllerId) {
// Stop batching if a different gamepad interrupts us
break;
}
// Remove the next event to batch
SDL_PeepEvents(&nextEvent, 1, SDL_GETEVENT, SDL_CONTROLLERAXISMOTION, SDL_CONTROLLERAXISMOTION);
}
// Only send the gamepad state to the host if it's not in mouse emulation mode
if (state->mouseEmulationTimer == 0) {
sendGamepadState(state);
}
}
void SdlInputHandler::handleControllerButtonEvent(SDL_ControllerButtonEvent* event)
{
GamepadState* state = findStateForGamepad(event->which);
if (state == NULL) {
return;
}
if (event->state == SDL_PRESSED) {
state->buttons |= k_ButtonMap[event->button];
if (event->button == SDL_CONTROLLER_BUTTON_START) {
state->lastStartDownTime = SDL_GetTicks();
}
else if (state->mouseEmulationTimer != 0) {
if (event->button == SDL_CONTROLLER_BUTTON_A) {
LiSendMouseButtonEvent(BUTTON_ACTION_PRESS, BUTTON_LEFT);
}
else if (event->button == SDL_CONTROLLER_BUTTON_B) {
LiSendMouseButtonEvent(BUTTON_ACTION_PRESS, BUTTON_RIGHT);
}
else if (event->button == SDL_CONTROLLER_BUTTON_X) {
LiSendMouseButtonEvent(BUTTON_ACTION_PRESS, BUTTON_MIDDLE);
}
else if (event->button == SDL_CONTROLLER_BUTTON_LEFTSHOULDER) {
LiSendMouseButtonEvent(BUTTON_ACTION_PRESS, BUTTON_X1);
}
else if (event->button == SDL_CONTROLLER_BUTTON_RIGHTSHOULDER) {
LiSendMouseButtonEvent(BUTTON_ACTION_PRESS, BUTTON_X2);
}
else if (event->button == SDL_CONTROLLER_BUTTON_DPAD_UP) {
LiSendScrollEvent(1);
}
else if (event->button == SDL_CONTROLLER_BUTTON_DPAD_DOWN) {
LiSendScrollEvent(-1);
}
}
}
else {
state->buttons &= ~k_ButtonMap[event->button];
if (event->button == SDL_CONTROLLER_BUTTON_START) {
if (SDL_GetTicks() - state->lastStartDownTime > MOUSE_EMULATION_LONG_PRESS_TIME) {
if (state->mouseEmulationTimer != 0) {
SDL_RemoveTimer(state->mouseEmulationTimer);
state->mouseEmulationTimer = 0;
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION,
"Mouse emulation deactivated");
Session::get()->notifyMouseEmulationMode(false);
}
else if (m_GamepadMouse) {
// Send the start button up event to the host, since we won't do it below
sendGamepadState(state);
state->mouseEmulationTimer = SDL_AddTimer(MOUSE_EMULATION_POLLING_INTERVAL, SdlInputHandler::mouseEmulationTimerCallback, state);
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION,
"Mouse emulation active");
Session::get()->notifyMouseEmulationMode(true);
}
}
}
else if (state->mouseEmulationTimer != 0) {
if (event->button == SDL_CONTROLLER_BUTTON_A) {
LiSendMouseButtonEvent(BUTTON_ACTION_RELEASE, BUTTON_LEFT);
}
else if (event->button == SDL_CONTROLLER_BUTTON_B) {
LiSendMouseButtonEvent(BUTTON_ACTION_RELEASE, BUTTON_RIGHT);
}
else if (event->button == SDL_CONTROLLER_BUTTON_X) {
LiSendMouseButtonEvent(BUTTON_ACTION_RELEASE, BUTTON_MIDDLE);
}
else if (event->button == SDL_CONTROLLER_BUTTON_LEFTSHOULDER) {
LiSendMouseButtonEvent(BUTTON_ACTION_RELEASE, BUTTON_X1);
}
else if (event->button == SDL_CONTROLLER_BUTTON_RIGHTSHOULDER) {
LiSendMouseButtonEvent(BUTTON_ACTION_RELEASE, BUTTON_X2);
}
}
}
// Handle Start+Select+L1+R1 as a gamepad quit combo
if (state->buttons == (PLAY_FLAG | BACK_FLAG | LB_FLAG | RB_FLAG)) {
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION,
"Detected quit gamepad button combo");
// Push a quit event to the main loop
SDL_Event event;
event.type = SDL_QUIT;
event.quit.timestamp = SDL_GetTicks();
SDL_PushEvent(&event);
// Clear buttons down on this gameapd
LiSendMultiControllerEvent(state->index, m_GamepadMask,
0, 0, 0, 0, 0, 0, 0);
return;
}
// Only send the gamepad state to the host if it's not in mouse emulation mode
if (state->mouseEmulationTimer == 0) {
sendGamepadState(state);
}
}
void SdlInputHandler::handleControllerDeviceEvent(SDL_ControllerDeviceEvent* event)
{
GamepadState* state;
if (event->type == SDL_CONTROLLERDEVICEADDED) {
int i;
const char* name;
SDL_GameController* controller;
const char* mapping;
char guidStr[33];
uint32_t hapticCaps;
controller = SDL_GameControllerOpen(event->which);
if (controller == NULL) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
"Failed to open gamepad: %s",
SDL_GetError());
return;
}
// We used to use SDL_GameControllerGetPlayerIndex() here but that
// can lead to strange issues due to bugs in Windows where an Xbox
// controller will join as player 2, even though no player 1 controller
// is connected at all. This pretty much screws any attempt to use
// the gamepad in single player games, so just assign them in order from 0.
i = 0;
for (; i < MAX_GAMEPADS; i++) {
SDL_assert(m_GamepadState[i].controller != controller);
if (m_GamepadState[i].controller == NULL) {
// Found an empty slot
break;
}
}
if (i == MAX_GAMEPADS) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
"No open gamepad slots found!");
SDL_GameControllerClose(controller);
return;
}
state = &m_GamepadState[i];
if (m_MultiController) {
state->index = i;
#if SDL_VERSION_ATLEAST(2, 0, 12)
// This will change indicators on the controller to show the assigned
// player index. For Xbox 360 controllers, that means updating the LED
// ring to light up the corresponding quadrant for this player.
SDL_GameControllerSetPlayerIndex(controller, state->index);
#endif
}
else {
// Always player 1 in single controller mode
state->index = 0;
}
state->controller = controller;
state->jsId = SDL_JoystickInstanceID(SDL_GameControllerGetJoystick(state->controller));
#if SDL_VERSION_ATLEAST(2, 0, 9)
// Perform a tiny rumble to see if haptics are supported.
// NB: We cannot use zeros for rumble intensity or SDL will not actually call the JS driver
// and we'll get a (potentially false) success value returned.
hapticCaps = SDL_GameControllerRumble(controller, 1, 1, 1) == 0 ?
ML_HAPTIC_GC_RUMBLE : 0;
#else
state->haptic = SDL_HapticOpenFromJoystick(SDL_GameControllerGetJoystick(state->controller));
state->hapticEffectId = -1;
state->hapticMethod = GAMEPAD_HAPTIC_METHOD_NONE;
if (state->haptic != nullptr) {
// Query for supported haptic effects
hapticCaps = SDL_HapticQuery(state->haptic);
hapticCaps |= SDL_HapticRumbleSupported(state->haptic) ?
ML_HAPTIC_SIMPLE_RUMBLE : 0;
if ((SDL_HapticQuery(state->haptic) & SDL_HAPTIC_LEFTRIGHT) == 0) {
if (SDL_HapticRumbleSupported(state->haptic)) {
if (SDL_HapticRumbleInit(state->haptic) == 0) {
state->hapticMethod = GAMEPAD_HAPTIC_METHOD_SIMPLERUMBLE;
}
}
if (state->hapticMethod == GAMEPAD_HAPTIC_METHOD_NONE) {
SDL_HapticClose(state->haptic);
state->haptic = nullptr;
}
} else {
state->hapticMethod = GAMEPAD_HAPTIC_METHOD_LEFTRIGHT;
}
}
else {
hapticCaps = 0;
}
#endif
SDL_JoystickGetGUIDString(SDL_JoystickGetGUID(SDL_GameControllerGetJoystick(state->controller)),
guidStr, sizeof(guidStr));
mapping = SDL_GameControllerMapping(state->controller);
name = SDL_GameControllerName(state->controller);
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION,
"Gamepad %d (player %d) is: %s (haptic capabilities: 0x%x) (mapping: %s -> %s)",
i,
state->index,
name != nullptr ? name : "<null>",
hapticCaps,
guidStr,
mapping != nullptr ? mapping : "<null>");
if (mapping != nullptr) {
SDL_free((void*)mapping);
}
// Add this gamepad to the gamepad mask
if (m_MultiController) {
// NB: Don't assert that it's unset here because we will already
// have the mask set for initially attached gamepads to avoid confusing
// apps running on the host.
m_GamepadMask |= (1 << state->index);
}
else {
SDL_assert(m_GamepadMask == 0x1);
}
// Send an empty event to tell the PC we've arrived
sendGamepadState(state);
}
else if (event->type == SDL_CONTROLLERDEVICEREMOVED) {
state = findStateForGamepad(event->which);
if (state != NULL) {
if (state->mouseEmulationTimer != 0) {
Session::get()->notifyMouseEmulationMode(false);
SDL_RemoveTimer(state->mouseEmulationTimer);
}
SDL_GameControllerClose(state->controller);
#if !SDL_VERSION_ATLEAST(2, 0, 9)
if (state->haptic != nullptr) {
SDL_HapticClose(state->haptic);
}
#endif
// Remove this from the gamepad mask in MC-mode
if (m_MultiController) {
SDL_assert(m_GamepadMask & (1 << state->index));
m_GamepadMask &= ~(1 << state->index);
}
else {
SDL_assert(m_GamepadMask == 0x1);
}
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION,
"Gamepad %d is gone",
state->index);
// Send a final event to let the PC know this gamepad is gone
LiSendMultiControllerEvent(state->index, m_GamepadMask,
0, 0, 0, 0, 0, 0, 0);
// Clear all remaining state from this slot
SDL_memset(state, 0, sizeof(*state));
}
}
}
void SdlInputHandler::handleJoystickArrivalEvent(SDL_JoyDeviceEvent* event)
{
SDL_assert(event->type == SDL_JOYDEVICEADDED);
if (!SDL_IsGameController(event->which)) {
char guidStr[33];
SDL_JoystickGetGUIDString(SDL_JoystickGetDeviceGUID(event->which),
guidStr, sizeof(guidStr));
const char* name = SDL_JoystickNameForIndex(event->which);
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION,
"Joystick discovered with no mapping: %s %s",
name ? name : "<UNKNOWN>",
guidStr);
SDL_Joystick* joy = SDL_JoystickOpen(event->which);
if (joy != nullptr) {
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION,
"Number of axes: %d | Number of buttons: %d | Number of hats: %d",
SDL_JoystickNumAxes(joy), SDL_JoystickNumButtons(joy),
SDL_JoystickNumHats(joy));
SDL_JoystickClose(joy);
}
else {
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION,
"Unable to open joystick for query: %s",
SDL_GetError());
}
}
}
void SdlInputHandler::rumble(unsigned short controllerNumber, unsigned short lowFreqMotor, unsigned short highFreqMotor)
{
// Make sure the controller number is within our supported count
if (controllerNumber >= MAX_GAMEPADS) {
return;
}
#if SDL_VERSION_ATLEAST(2, 0, 9)
if (m_GamepadState[controllerNumber].controller != nullptr) {
SDL_GameControllerRumble(m_GamepadState[controllerNumber].controller, lowFreqMotor, highFreqMotor, 30000);
}
#else
// Check if the controller supports haptics (and if the controller exists at all)
SDL_Haptic* haptic = m_GamepadState[controllerNumber].haptic;
if (haptic == nullptr) {
return;
}
// Stop the last effect we played
if (m_GamepadState[controllerNumber].hapticMethod == GAMEPAD_HAPTIC_METHOD_LEFTRIGHT) {
if (m_GamepadState[controllerNumber].hapticEffectId >= 0) {
SDL_HapticDestroyEffect(haptic, m_GamepadState[controllerNumber].hapticEffectId);
}
} else if (m_GamepadState[controllerNumber].hapticMethod == GAMEPAD_HAPTIC_METHOD_SIMPLERUMBLE) {
SDL_HapticRumbleStop(haptic);
}
// If this callback is telling us to stop both motors, don't bother queuing a new effect
if (lowFreqMotor == 0 && highFreqMotor == 0) {
return;
}
if (m_GamepadState[controllerNumber].hapticMethod == GAMEPAD_HAPTIC_METHOD_LEFTRIGHT) {
SDL_HapticEffect effect;
SDL_memset(&effect, 0, sizeof(effect));
effect.type = SDL_HAPTIC_LEFTRIGHT;
// The effect should last until we are instructed to stop or change it
effect.leftright.length = SDL_HAPTIC_INFINITY;
// SDL haptics range from 0-32767 but XInput uses 0-65535, so divide by 2 to correct for SDL's scaling
effect.leftright.large_magnitude = lowFreqMotor / 2;
effect.leftright.small_magnitude = highFreqMotor / 2;
// Play the new effect
m_GamepadState[controllerNumber].hapticEffectId = SDL_HapticNewEffect(haptic, &effect);
if (m_GamepadState[controllerNumber].hapticEffectId >= 0) {
SDL_HapticRunEffect(haptic, m_GamepadState[controllerNumber].hapticEffectId, 1);
}
} else if (m_GamepadState[controllerNumber].hapticMethod == GAMEPAD_HAPTIC_METHOD_SIMPLERUMBLE) {
SDL_HapticRumblePlay(haptic,
std::min(1.0, (GAMEPAD_HAPTIC_SIMPLE_HIFREQ_MOTOR_WEIGHT*highFreqMotor +
GAMEPAD_HAPTIC_SIMPLE_LOWFREQ_MOTOR_WEIGHT*lowFreqMotor) / 65535.0),
SDL_HAPTIC_INFINITY);
}
#endif
}
QString SdlInputHandler::getUnmappedGamepads()
{
QString ret;
if (SDL_InitSubSystem(SDL_INIT_GAMECONTROLLER) != 0) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
"SDL_InitSubSystem(SDL_INIT_GAMECONTROLLER) failed: %s",
SDL_GetError());
}
MappingManager mappingManager;
mappingManager.applyMappings();
for (int i = 0; i < SDL_NumJoysticks(); i++) {
if (!SDL_IsGameController(i)) {
char guidStr[33];
SDL_JoystickGetGUIDString(SDL_JoystickGetDeviceGUID(i),
guidStr, sizeof(guidStr));
const char* name = SDL_JoystickNameForIndex(i);
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION,
"Unmapped joystick: %s %s",
name ? name : "<UNKNOWN>",
guidStr);
SDL_Joystick* joy = SDL_JoystickOpen(i);
if (joy != nullptr) {
int numButtons = SDL_JoystickNumButtons(joy);
int numHats = SDL_JoystickNumHats(joy);
int numAxes = SDL_JoystickNumAxes(joy);
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION,
"Number of axes: %d | Number of buttons: %d | Number of hats: %d",
numAxes, numButtons, numHats);
if ((numAxes >= 4 && numAxes <= 8) && numButtons >= 8 && numHats <= 1) {
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION,
"Joystick likely to be an unmapped game controller");
if (!ret.isEmpty()) {
ret += ", ";
}
ret += name;
}
SDL_JoystickClose(joy);
}
else {
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION,
"Unable to open joystick for query: %s",
SDL_GetError());
}
}
}
SDL_QuitSubSystem(SDL_INIT_GAMECONTROLLER);
return ret;
}
int SdlInputHandler::getAttachedGamepadMask()
{
int count;
int mask;
if (!m_MultiController) {
// Player 1 is always present in non-MC mode
return 0x1;
}
count = mask = 0;
for (int i = 0; i < SDL_NumJoysticks(); i++) {
if (SDL_IsGameController(i)) {
mask |= (1 << count++);
}
}
return mask;
}
+346
View File
@@ -0,0 +1,346 @@
#include <Limelight.h>
#include <SDL.h>
#include "streaming/session.h"
#include "settings/mappingmanager.h"
#include "path.h"
#include <QtGlobal>
#include <QDir>
#define MOUSE_POLLING_INTERVAL 5
SdlInputHandler::SdlInputHandler(StreamingPreferences& prefs, NvComputer*, int streamWidth, int streamHeight)
: m_MultiController(prefs.multiController),
m_GamepadMouse(prefs.gamepadMouse),
m_SwapMouseButtons(prefs.swapMouseButtons),
m_MouseMoveTimer(0),
m_MousePositionLock(0),
m_MouseWasInVideoRegion(false),
m_PendingMouseButtonsAllUpOnVideoRegionLeave(false),
m_FakeCaptureActive(false),
m_LongPressTimer(0),
m_StreamWidth(streamWidth),
m_StreamHeight(streamHeight),
m_AbsoluteMouseMode(prefs.absoluteMouseMode),
m_AbsoluteTouchMode(prefs.absoluteTouchMode),
m_PendingMouseLeaveButtonUp(0),
m_LeftButtonReleaseTimer(0),
m_RightButtonReleaseTimer(0),
m_DragTimer(0),
m_DragButton(0),
m_NumFingersDown(0)
{
// Allow gamepad input when the app doesn't have focus
SDL_SetHint(SDL_HINT_JOYSTICK_ALLOW_BACKGROUND_EVENTS, "1");
// If absolute mouse mode is enabled, use relative mode warp (which
// is via normal motion events that are influenced by mouse acceleration).
// Otherwise, we'll use raw input capture which is straight from the device
// without modification by the OS.
SDL_SetHintWithPriority(SDL_HINT_MOUSE_RELATIVE_MODE_WARP,
prefs.absoluteMouseMode ? "1" : "0",
SDL_HINT_OVERRIDE);
// Allow clicks to pass through to us when focusing the window. If we're in
// absolute mouse mode, this will avoid the user having to click twice to
// trigger a click on the host if the Moonlight window is not focused. In
// relative mode, the click event will trigger the mouse to be recaptured.
SDL_SetHint(SDL_HINT_MOUSE_FOCUS_CLICKTHROUGH, "1");
#if defined(Q_OS_DARWIN) && !SDL_VERSION_ATLEAST(2, 0, 10)
// SDL 2.0.9 on macOS has a broken HIDAPI mapping for the older Xbox One S
// firmware, so we have to disable HIDAPI for Xbox gamepads on macOS until
// SDL 2.0.10 where the bug is fixed.
// https://github.com/moonlight-stream/moonlight-qt/issues/133
// https://bugzilla.libsdl.org/show_bug.cgi?id=4395
SDL_SetHint(SDL_HINT_JOYSTICK_HIDAPI_XBOX, "0");
#endif
#if SDL_VERSION_ATLEAST(2, 0, 9)
// Enabling extended input reports allows rumble to function on Bluetooth PS4
// controllers, but breaks DirectInput applications. We will enable it because
// it's likely that working rumble is what the user is expecting. If they don't
// want this behavior, they can override it with the environment variable.
SDL_SetHint(SDL_HINT_JOYSTICK_HIDAPI_PS4_RUMBLE, "1");
#endif
m_OldIgnoreDevices = SDL_GetHint(SDL_HINT_GAMECONTROLLER_IGNORE_DEVICES);
m_OldIgnoreDevicesExcept = SDL_GetHint(SDL_HINT_GAMECONTROLLER_IGNORE_DEVICES_EXCEPT);
QString streamIgnoreDevices = qgetenv("STREAM_GAMECONTROLLER_IGNORE_DEVICES");
QString streamIgnoreDevicesExcept = qgetenv("STREAM_GAMECONTROLLER_IGNORE_DEVICES_EXCEPT");
if (!streamIgnoreDevices.isEmpty() && !streamIgnoreDevices.endsWith(',')) {
streamIgnoreDevices += ',';
}
streamIgnoreDevices += m_OldIgnoreDevices;
// For SDL_HINT_GAMECONTROLLER_IGNORE_DEVICES, we use the union of SDL_GAMECONTROLLER_IGNORE_DEVICES
// and STREAM_GAMECONTROLLER_IGNORE_DEVICES while streaming. STREAM_GAMECONTROLLER_IGNORE_DEVICES_EXCEPT
// overrides SDL_GAMECONTROLLER_IGNORE_DEVICES_EXCEPT while streaming.
SDL_SetHint(SDL_HINT_GAMECONTROLLER_IGNORE_DEVICES, streamIgnoreDevices.toUtf8());
SDL_SetHint(SDL_HINT_GAMECONTROLLER_IGNORE_DEVICES_EXCEPT, streamIgnoreDevicesExcept.toUtf8());
// We must initialize joystick explicitly before gamecontroller in order
// to ensure we receive gamecontroller attach events for gamepads where
// SDL doesn't have a built-in mapping. By starting joystick first, we
// can allow mapping manager to update the mappings before GC attach
// events are generated.
SDL_assert(!SDL_WasInit(SDL_INIT_JOYSTICK));
if (SDL_InitSubSystem(SDL_INIT_JOYSTICK) != 0) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
"SDL_InitSubSystem(SDL_INIT_JOYSTICK) failed: %s",
SDL_GetError());
}
MappingManager mappingManager;
mappingManager.applyMappings();
// Flush gamepad arrival and departure events which may be queued before
// starting the gamecontroller subsystem again. This prevents us from
// receiving duplicate arrival and departure events for the same gamepad.
SDL_FlushEvent(SDL_CONTROLLERDEVICEADDED);
SDL_FlushEvent(SDL_CONTROLLERDEVICEREMOVED);
// We need to reinit this each time, since you only get
// an initial set of gamepad arrival events once per init.
SDL_assert(!SDL_WasInit(SDL_INIT_GAMECONTROLLER));
if (SDL_InitSubSystem(SDL_INIT_GAMECONTROLLER) != 0) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
"SDL_InitSubSystem(SDL_INIT_GAMECONTROLLER) failed: %s",
SDL_GetError());
}
#if !SDL_VERSION_ATLEAST(2, 0, 9)
SDL_assert(!SDL_WasInit(SDL_INIT_HAPTIC));
if (SDL_InitSubSystem(SDL_INIT_HAPTIC) != 0) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
"SDL_InitSubSystem(SDL_INIT_HAPTIC) failed: %s",
SDL_GetError());
}
#endif
// Initialize the gamepad mask with currently attached gamepads to avoid
// causing gamepads to unexpectedly disappear and reappear on the host
// during stream startup as we detect currently attached gamepads one at a time.
m_GamepadMask = getAttachedGamepadMask();
SDL_zero(m_GamepadState);
SDL_zero(m_LastTouchDownEvent);
SDL_zero(m_LastTouchUpEvent);
SDL_zero(m_TouchDownEvent);
SDL_zero(m_MousePositionReport);
SDL_AtomicSet(&m_MouseDeltaX, 0);
SDL_AtomicSet(&m_MouseDeltaY, 0);
SDL_AtomicSet(&m_MousePositionUpdated, 0);
Uint32 pollingInterval = QString(qgetenv("MOUSE_POLLING_INTERVAL")).toUInt();
if (pollingInterval == 0) {
pollingInterval = MOUSE_POLLING_INTERVAL;
}
else {
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION,
"Using custom mouse polling interval: %u ms",
pollingInterval);
}
m_MouseMoveTimer = SDL_AddTimer(pollingInterval, SdlInputHandler::mouseMoveTimerCallback, this);
}
SdlInputHandler::~SdlInputHandler()
{
for (int i = 0; i < MAX_GAMEPADS; i++) {
if (m_GamepadState[i].mouseEmulationTimer != 0) {
Session::get()->notifyMouseEmulationMode(false);
SDL_RemoveTimer(m_GamepadState[i].mouseEmulationTimer);
}
#if !SDL_VERSION_ATLEAST(2, 0, 9)
if (m_GamepadState[i].haptic != nullptr) {
SDL_HapticClose(m_GamepadState[i].haptic);
}
#endif
if (m_GamepadState[i].controller != nullptr) {
SDL_GameControllerClose(m_GamepadState[i].controller);
}
}
SDL_RemoveTimer(m_MouseMoveTimer);
SDL_RemoveTimer(m_LongPressTimer);
SDL_RemoveTimer(m_LeftButtonReleaseTimer);
SDL_RemoveTimer(m_RightButtonReleaseTimer);
SDL_RemoveTimer(m_DragTimer);
#if !SDL_VERSION_ATLEAST(2, 0, 9)
SDL_QuitSubSystem(SDL_INIT_HAPTIC);
SDL_assert(!SDL_WasInit(SDL_INIT_HAPTIC));
#endif
SDL_QuitSubSystem(SDL_INIT_GAMECONTROLLER);
SDL_assert(!SDL_WasInit(SDL_INIT_GAMECONTROLLER));
SDL_QuitSubSystem(SDL_INIT_JOYSTICK);
SDL_assert(!SDL_WasInit(SDL_INIT_JOYSTICK));
// Return background event handling to off
SDL_SetHint(SDL_HINT_JOYSTICK_ALLOW_BACKGROUND_EVENTS, "0");
// Restore the ignored devices
SDL_SetHint(SDL_HINT_GAMECONTROLLER_IGNORE_DEVICES, m_OldIgnoreDevices.toUtf8());
SDL_SetHint(SDL_HINT_GAMECONTROLLER_IGNORE_DEVICES_EXCEPT, m_OldIgnoreDevicesExcept.toUtf8());
#ifdef STEAM_LINK
// Hide SDL's cursor on Steam Link after quitting the stream.
// FIXME: We should also do this for other situations where SDL
// and Qt will draw their own mouse cursors like KMSDRM or RPi
// video backends.
SDL_ShowCursor(SDL_DISABLE);
#endif
}
void SdlInputHandler::setWindow(SDL_Window *window)
{
m_Window = window;
}
void SdlInputHandler::raiseAllKeys()
{
if (m_KeysDown.isEmpty()) {
return;
}
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION,
"Raising %d keys",
m_KeysDown.count());
for (auto keyDown : m_KeysDown) {
LiSendKeyboardEvent(keyDown, KEY_ACTION_UP, 0);
}
m_KeysDown.clear();
}
void SdlInputHandler::notifyMouseLeave()
{
#ifdef Q_OS_WIN32
// SDL on Windows doesn't send the mouse button up until the mouse re-enters the window
// after leaving it. This breaks some of the Aero snap gestures, so we'll fake it here.
if (m_AbsoluteMouseMode && isCaptureActive()) {
// NB: Not using SDL_GetGlobalMouseState() because we want our state not the system's
Uint32 mouseState = SDL_GetMouseState(nullptr, nullptr);
for (Uint32 button = SDL_BUTTON_LEFT; button <= SDL_BUTTON_X2; button++) {
if (mouseState & SDL_BUTTON(button)) {
m_PendingMouseLeaveButtonUp = button;
break;
}
}
}
#endif
}
void SdlInputHandler::notifyFocusLost()
{
// Release mouse cursor when another window is activated (e.g. by using ALT+TAB).
// This lets user to interact with our window's title bar and with the buttons in it.
// Doing this while the window is full-screen breaks the transition out of FS
// (desktop and exclusive), so we must check for that before releasing mouse capture.
if (!(SDL_GetWindowFlags(m_Window) & SDL_WINDOW_FULLSCREEN) && !m_AbsoluteMouseMode) {
setCaptureActive(false);
}
// Raise all keys that are currently pressed. If we don't do this, certain keys
// used in shortcuts that cause focus loss (such as Alt+Tab) may get stuck down.
raiseAllKeys();
}
bool SdlInputHandler::isCaptureActive()
{
if (SDL_GetRelativeMouseMode()) {
return true;
}
// Some platforms don't support SDL_SetRelativeMouseMode
return m_FakeCaptureActive;
}
void SdlInputHandler::setCaptureActive(bool active)
{
if (active) {
// If we're in full-screen exclusive mode, grab the cursor so it can't accidentally leave our window.
if ((SDL_GetWindowFlags(m_Window) & SDL_WINDOW_FULLSCREEN_DESKTOP) == SDL_WINDOW_FULLSCREEN) {
SDL_SetWindowGrab(m_Window, SDL_TRUE);
}
if (!m_AbsoluteMouseMode) {
// If our window is occluded when mouse is captured, the mouse may
// get stuck on top of the occluding window and not be properly
// captured. We can avoid this by raising our window before we
// capture the mouse.
SDL_RaiseWindow(m_Window);
}
// If we're in relative mode, try to activate SDL's relative mouse mode
if (m_AbsoluteMouseMode || SDL_SetRelativeMouseMode(SDL_TRUE) < 0) {
// Relative mouse mode didn't work or was disabled, so we'll just hide the cursor
SDL_ShowCursor(SDL_DISABLE);
m_FakeCaptureActive = true;
}
// Synchronize the client and host cursor when activating absolute capture
if (m_AbsoluteMouseMode) {
int mouseX, mouseY;
int windowX, windowY;
// We have to use SDL_GetGlobalMouseState() because macOS may not reflect
// the new position of the mouse when outside the window.
SDL_GetGlobalMouseState(&mouseX, &mouseY);
// Convert global mouse state to window-relative
SDL_GetWindowPosition(m_Window, &windowX, &windowY);
mouseX -= windowX;
mouseY -= windowY;
if (isMouseInVideoRegion(mouseX, mouseY)) {
updateMousePositionReport(mouseX, mouseY);
}
}
}
else {
if (m_FakeCaptureActive) {
// Display the cursor again
SDL_ShowCursor(SDL_ENABLE);
m_FakeCaptureActive = false;
}
else {
SDL_SetRelativeMouseMode(SDL_FALSE);
}
// Allow the cursor to leave the bounds of our window again.
SDL_SetWindowGrab(m_Window, SDL_FALSE);
}
}
void SdlInputHandler::handleTouchFingerEvent(SDL_TouchFingerEvent* event)
{
#if SDL_VERSION_ATLEAST(2, 0, 10)
if (SDL_GetTouchDeviceType(event->touchId) != SDL_TOUCH_DEVICE_DIRECT) {
// Ignore anything that isn't a touchscreen. We may get callbacks
// for trackpads, but we want to handle those in the mouse path.
return;
}
#elif defined(Q_OS_DARWIN)
// SDL2 sends touch events from trackpads by default on
// macOS. This totally screws our actual mouse handling,
// so we must explicitly ignore touch events on macOS
// until SDL 2.0.10 where we have SDL_GetTouchDeviceType()
// to tell them apart.
return;
#endif
if (m_AbsoluteTouchMode) {
handleAbsoluteFingerEvent(event);
}
else {
handleRelativeFingerEvent(event);
}
}
@@ -5,11 +5,23 @@
#include <SDL.h>
#define SDL_CODE_HIDE_CURSOR 1
#define SDL_CODE_SHOW_CURSOR 2
struct GamepadState {
SDL_GameController* controller;
SDL_JoystickID jsId;
short index;
#if !SDL_VERSION_ATLEAST(2, 0, 9)
SDL_Haptic* haptic;
int hapticMethod;
int hapticEffectId;
#endif
SDL_TimerID mouseEmulationTimer;
uint32_t lastStartDownTime;
short buttons;
short lsX, lsY;
short rsX, rsY;
@@ -19,6 +31,13 @@ struct GamepadState {
#define MAX_GAMEPADS 4
#define MAX_FINGERS 2
#define GAMEPAD_HAPTIC_METHOD_NONE 0
#define GAMEPAD_HAPTIC_METHOD_LEFTRIGHT 1
#define GAMEPAD_HAPTIC_METHOD_SIMPLERUMBLE 2
#define GAMEPAD_HAPTIC_SIMPLE_HIFREQ_MOTOR_WEIGHT 0.33
#define GAMEPAD_HAPTIC_SIMPLE_LOWFREQ_MOTOR_WEIGHT 0.8
class SdlInputHandler
{
public:
@@ -27,6 +46,8 @@ public:
~SdlInputHandler();
void setWindow(SDL_Window* window);
void handleKeyEvent(SDL_KeyboardEvent* event);
void handleMouseButtonEvent(SDL_MouseButtonEvent* event);
@@ -43,12 +64,28 @@ public:
void handleJoystickArrivalEvent(SDL_JoyDeviceEvent* event);
void rumble(unsigned short controllerNumber, unsigned short lowFreqMotor, unsigned short highFreqMotor);
void handleTouchFingerEvent(SDL_TouchFingerEvent* event);
int getAttachedGamepadMask();
void raiseAllKeys();
void notifyMouseLeave();
void notifyFocusLost();
bool isCaptureActive();
void setCaptureActive(bool active);
bool isMouseInVideoRegion(int mouseX, int mouseY, int windowWidth = -1, int windowHeight = -1);
void updateMousePositionReport(int mouseX, int mouseY);
void flushMousePositionUpdate();
static
QString getUnmappedGamepads();
@@ -58,6 +95,19 @@ private:
void sendGamepadState(GamepadState* state);
void handleAbsoluteFingerEvent(SDL_TouchFingerEvent* event);
void handleRelativeFingerEvent(SDL_TouchFingerEvent* event);
static
Uint32 longPressTimerCallback(Uint32 interval, void* param);
static
Uint32 mouseMoveTimerCallback(Uint32 interval, void* param);
static
Uint32 mouseEmulationTimerCallback(Uint32 interval, void* param);
static
Uint32 releaseLeftButtonTimerCallback(Uint32 interval, void* param);
@@ -67,26 +117,45 @@ private:
static
Uint32 dragTimerCallback(Uint32 interval, void* param);
static
Uint32 mouseMoveTimerCallback(Uint32 interval, void* param);
SDL_Window* m_Window;
bool m_MultiController;
bool m_GamepadMouse;
bool m_SwapMouseButtons;
SDL_TimerID m_MouseMoveTimer;
SDL_atomic_t m_MouseDeltaX;
SDL_atomic_t m_MouseDeltaY;
SDL_SpinLock m_MousePositionLock;
struct {
int x, y;
int windowWidth, windowHeight;
} m_MousePositionReport;
SDL_atomic_t m_MousePositionUpdated;
bool m_MouseWasInVideoRegion;
bool m_PendingMouseButtonsAllUpOnVideoRegionLeave;
int m_GamepadMask;
GamepadState m_GamepadState[MAX_GAMEPADS];
QSet<short> m_KeysDown;
bool m_FakeCaptureActive;
QString m_OldIgnoreDevices;
QString m_OldIgnoreDevicesExcept;
SDL_TouchFingerEvent m_LastTouchDownEvent;
SDL_TouchFingerEvent m_LastTouchUpEvent;
SDL_TimerID m_LongPressTimer;
int m_StreamWidth;
int m_StreamHeight;
bool m_AbsoluteMouseMode;
bool m_AbsoluteTouchMode;
Uint32 m_PendingMouseLeaveButtonUp;
SDL_TouchFingerEvent m_TouchDownEvent[MAX_FINGERS];
float m_CumulativeDelta[MAX_FINGERS];
SDL_TimerID m_LeftButtonReleaseTimer;
SDL_TimerID m_RightButtonReleaseTimer;
SDL_TimerID m_DragTimer;
char m_DragButton;
int m_NumFingersDown;
int m_StreamWidth;
int m_StreamHeight;
static const int k_ButtonMap[];
};
+420
View File
@@ -0,0 +1,420 @@
#include "streaming/session.h"
#include <Limelight.h>
#include <SDL.h>
#include <QGuiApplication>
// Until we can fully capture these on all platforms (without conflicting with
// OS-provided shortcuts), we should avoid passing them through to the host.
//#define ENABLE_META
#define VK_0 0x30
#define VK_A 0x41
// These are real Windows VK_* codes
#ifndef VK_F1
#define VK_F1 0x70
#define VK_F13 0x7C
#define VK_NUMPAD0 0x60
#endif
void SdlInputHandler::handleKeyEvent(SDL_KeyboardEvent* event)
{
short keyCode;
char modifiers;
// Check for our special key combos
if ((event->state == SDL_PRESSED) &&
(event->keysym.mod & KMOD_CTRL) &&
(event->keysym.mod & KMOD_ALT) &&
(event->keysym.mod & KMOD_SHIFT)) {
// First we test the SDLK combos for matches,
// that way we ensure that latin keyboard users
// can match to the key they see on their keyboards.
// If nothing matches that, we'll then go on to
// checking scancodes so non-latin keyboard users
// can have working hotkeys (though possibly in
// odd positions). We must do all SDLK tests before
// any scancode tests to avoid issues in cases
// where the SDLK for one shortcut collides with
// the scancode of another.
// Check for quit combo (Ctrl+Alt+Shift+Q)
if (event->keysym.sym == SDLK_q) {
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION,
"Detected quit key combo (SDLK)");
// Push a quit event to the main loop
SDL_Event event;
event.type = SDL_QUIT;
event.quit.timestamp = SDL_GetTicks();
SDL_PushEvent(&event);
return;
}
// Check for the unbind combo (Ctrl+Alt+Shift+Z) unless on EGLFS which has no window manager
else if (event->keysym.sym == SDLK_z && QGuiApplication::platformName() != "eglfs") {
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION,
"Detected mouse capture toggle combo (SDLK)");
// Stop handling future input
setCaptureActive(!isCaptureActive());
// Force raise all keys to ensure they aren't stuck,
// since we won't get their key up events.
raiseAllKeys();
return;
}
// Check for the mouse mode combo (Ctrl+Alt+Shift+M) unless on EGLFS which has no window manager
else if (event->keysym.sym == SDLK_m && QGuiApplication::platformName() != "eglfs") {
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION,
"Detected mouse mode toggle combo (SDLK)");
// Uncapture input
setCaptureActive(false);
// Toggle mouse mode
m_AbsoluteMouseMode = !m_AbsoluteMouseMode;
// Recapture input
setCaptureActive(true);
return;
}
else if (event->keysym.sym == SDLK_x && QGuiApplication::platformName() != "eglfs") {
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION,
"Detected full-screen toggle combo (SDLK)");
Session::s_ActiveSession->toggleFullscreen();
// Force raise all keys just be safe across this full-screen/windowed
// transition just in case key events get lost.
raiseAllKeys();
return;
}
// Check for overlay combo (Ctrl+Alt+Shift+S)
else if (event->keysym.sym == SDLK_s) {
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION,
"Detected stats toggle combo (SDLK)");
// Toggle the stats overlay
Session::get()->getOverlayManager().setOverlayState(Overlay::OverlayDebug,
!Session::get()->getOverlayManager().isOverlayEnabled(Overlay::OverlayDebug));
// Force raise all keys just be safe across this full-screen/windowed
// transition just in case key events get lost.
raiseAllKeys();
return;
}
// Check for quit combo (Ctrl+Alt+Shift+Q)
else if (event->keysym.scancode == SDL_SCANCODE_Q) {
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION,
"Detected quit key combo (scancode)");
// Push a quit event to the main loop
SDL_Event event;
event.type = SDL_QUIT;
event.quit.timestamp = SDL_GetTicks();
SDL_PushEvent(&event);
return;
}
// Check for the unbind combo (Ctrl+Alt+Shift+Z)
else if (event->keysym.scancode == SDL_SCANCODE_Z && QGuiApplication::platformName() != "eglfs") {
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION,
"Detected mouse capture toggle combo (scancode)");
// Stop handling future input
setCaptureActive(!isCaptureActive());
// Force raise all keys to ensure they aren't stuck,
// since we won't get their key up events.
raiseAllKeys();
return;
}
// Check for the full-screen combo (Ctrl+Alt+Shift+X) unless on EGLFS which has no window manager
else if (event->keysym.scancode == SDL_SCANCODE_X && QGuiApplication::platformName() != "eglfs") {
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION,
"Detected full-screen toggle combo (scancode)");
Session::s_ActiveSession->toggleFullscreen();
// Force raise all keys just be safe across this full-screen/windowed
// transition just in case key events get lost.
raiseAllKeys();
return;
}
// Check for the mouse mode toggle combo (Ctrl+Alt+Shift+M) unless on EGLFS which has no window manager
else if (event->keysym.scancode == SDL_SCANCODE_M && QGuiApplication::platformName() != "eglfs") {
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION,
"Detected mouse mode toggle combo (scancode)");
// Uncapture input
setCaptureActive(false);
// Toggle mouse mode
m_AbsoluteMouseMode = !m_AbsoluteMouseMode;
// Recapture input
setCaptureActive(true);
return;
}
else if (event->keysym.scancode == SDL_SCANCODE_S) {
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION,
"Detected stats toggle combo (scancode)");
// Toggle the stats overlay
Session::get()->getOverlayManager().setOverlayState(Overlay::OverlayDebug,
!Session::get()->getOverlayManager().isOverlayEnabled(Overlay::OverlayDebug));
// Force raise all keys just be safe across this full-screen/windowed
// transition just in case key events get lost.
raiseAllKeys();
return;
}
}
if (event->repeat) {
// Ignore repeat key down events
SDL_assert(event->state == SDL_PRESSED);
return;
}
// Set modifier flags
modifiers = 0;
if (event->keysym.mod & KMOD_CTRL) {
modifiers |= MODIFIER_CTRL;
}
if (event->keysym.mod & KMOD_ALT) {
modifiers |= MODIFIER_ALT;
}
if (event->keysym.mod & KMOD_SHIFT) {
modifiers |= MODIFIER_SHIFT;
}
#ifdef ENABLE_META
if (event->keysym.mod & KMOD_GUI) {
modifiers |= MODIFIER_META;
}
#endif
// Set keycode. We explicitly use scancode here because GFE will try to correct
// for AZERTY layouts on the host but it depends on receiving VK_ values matching
// a QWERTY layout to work.
if (event->keysym.scancode >= SDL_SCANCODE_1 && event->keysym.scancode <= SDL_SCANCODE_9) {
// SDL defines SDL_SCANCODE_0 > SDL_SCANCODE_9, so we need to handle that manually
keyCode = (event->keysym.scancode - SDL_SCANCODE_1) + VK_0 + 1;
}
else if (event->keysym.scancode >= SDL_SCANCODE_A && event->keysym.scancode <= SDL_SCANCODE_Z) {
keyCode = (event->keysym.scancode - SDL_SCANCODE_A) + VK_A;
}
else if (event->keysym.scancode >= SDL_SCANCODE_F1 && event->keysym.scancode <= SDL_SCANCODE_F12) {
keyCode = (event->keysym.scancode - SDL_SCANCODE_F1) + VK_F1;
}
else if (event->keysym.scancode >= SDL_SCANCODE_F13 && event->keysym.scancode <= SDL_SCANCODE_F24) {
keyCode = (event->keysym.scancode - SDL_SCANCODE_F13) + VK_F13;
}
else if (event->keysym.scancode >= SDL_SCANCODE_KP_1 && event->keysym.scancode <= SDL_SCANCODE_KP_9) {
// SDL defines SDL_SCANCODE_KP_0 > SDL_SCANCODE_KP_9, so we need to handle that manually
keyCode = (event->keysym.scancode - SDL_SCANCODE_KP_1) + VK_NUMPAD0 + 1;
}
else {
switch (event->keysym.scancode) {
case SDL_SCANCODE_BACKSPACE:
keyCode = 0x08;
break;
case SDL_SCANCODE_TAB:
keyCode = 0x09;
break;
case SDL_SCANCODE_CLEAR:
keyCode = 0x0C;
break;
case SDL_SCANCODE_KP_ENTER: // FIXME: Is this correct?
case SDL_SCANCODE_RETURN:
keyCode = 0x0D;
break;
case SDL_SCANCODE_PAUSE:
keyCode = 0x13;
break;
case SDL_SCANCODE_CAPSLOCK:
keyCode = 0x14;
break;
case SDL_SCANCODE_ESCAPE:
keyCode = 0x1B;
break;
case SDL_SCANCODE_SPACE:
keyCode = 0x20;
break;
case SDL_SCANCODE_PAGEUP:
keyCode = 0x21;
break;
case SDL_SCANCODE_PAGEDOWN:
keyCode = 0x22;
break;
case SDL_SCANCODE_END:
keyCode = 0x23;
break;
case SDL_SCANCODE_HOME:
keyCode = 0x24;
break;
case SDL_SCANCODE_LEFT:
keyCode = 0x25;
break;
case SDL_SCANCODE_UP:
keyCode = 0x26;
break;
case SDL_SCANCODE_RIGHT:
keyCode = 0x27;
break;
case SDL_SCANCODE_DOWN:
keyCode = 0x28;
break;
case SDL_SCANCODE_SELECT:
keyCode = 0x29;
break;
case SDL_SCANCODE_EXECUTE:
keyCode = 0x2B;
break;
case SDL_SCANCODE_PRINTSCREEN:
keyCode = 0x2C;
break;
case SDL_SCANCODE_INSERT:
keyCode = 0x2D;
break;
case SDL_SCANCODE_DELETE:
keyCode = 0x2E;
break;
case SDL_SCANCODE_HELP:
keyCode = 0x2F;
break;
case SDL_SCANCODE_KP_0:
// See comment above about why we only handle SDL_SCANCODE_KP_0 here
keyCode = VK_NUMPAD0;
break;
case SDL_SCANCODE_0:
// See comment above about why we only handle SDL_SCANCODE_0 here
keyCode = VK_0;
break;
case SDL_SCANCODE_KP_MULTIPLY:
keyCode = 0x6A;
break;
case SDL_SCANCODE_KP_PLUS:
keyCode = 0x6B;
break;
case SDL_SCANCODE_KP_COMMA:
keyCode = 0x6C;
break;
case SDL_SCANCODE_KP_MINUS:
keyCode = 0x6D;
break;
case SDL_SCANCODE_KP_PERIOD:
keyCode = 0x6E;
break;
case SDL_SCANCODE_KP_DIVIDE:
keyCode = 0x6F;
break;
case SDL_SCANCODE_NUMLOCKCLEAR:
keyCode = 0x90;
break;
case SDL_SCANCODE_SCROLLLOCK:
keyCode = 0x91;
break;
case SDL_SCANCODE_LSHIFT:
keyCode = 0xA0;
break;
case SDL_SCANCODE_RSHIFT:
keyCode = 0xA1;
break;
case SDL_SCANCODE_LCTRL:
keyCode = 0xA2;
break;
case SDL_SCANCODE_RCTRL:
keyCode = 0xA3;
break;
case SDL_SCANCODE_LALT:
keyCode = 0xA4;
break;
case SDL_SCANCODE_RALT:
keyCode = 0xA5;
break;
#ifdef ENABLE_META
case SDL_SCANCODE_LGUI:
keyCode = 0x5B;
break;
case SDL_SCANCODE_RGUI:
keyCode = 0x5C;
break;
#endif
case SDL_SCANCODE_AC_BACK:
keyCode = 0xA6;
break;
case SDL_SCANCODE_AC_FORWARD:
keyCode = 0xA7;
break;
case SDL_SCANCODE_AC_REFRESH:
keyCode = 0xA8;
break;
case SDL_SCANCODE_AC_STOP:
keyCode = 0xA9;
break;
case SDL_SCANCODE_AC_SEARCH:
keyCode = 0xAA;
break;
case SDL_SCANCODE_AC_BOOKMARKS:
keyCode = 0xAB;
break;
case SDL_SCANCODE_AC_HOME:
keyCode = 0xAC;
break;
case SDL_SCANCODE_SEMICOLON:
keyCode = 0xBA;
break;
case SDL_SCANCODE_EQUALS:
keyCode = 0xBB;
break;
case SDL_SCANCODE_COMMA:
keyCode = 0xBC;
break;
case SDL_SCANCODE_MINUS:
keyCode = 0xBD;
break;
case SDL_SCANCODE_PERIOD:
keyCode = 0xBE;
break;
case SDL_SCANCODE_SLASH:
keyCode = 0xBF;
break;
case SDL_SCANCODE_GRAVE:
keyCode = 0xC0;
break;
case SDL_SCANCODE_LEFTBRACKET:
keyCode = 0xDB;
break;
case SDL_SCANCODE_BACKSLASH:
keyCode = 0xDC;
break;
case SDL_SCANCODE_RIGHTBRACKET:
keyCode = 0xDD;
break;
case SDL_SCANCODE_APOSTROPHE:
keyCode = 0xDE;
break;
case SDL_SCANCODE_NONUSBACKSLASH:
keyCode = 0xE2;
break;
default:
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION,
"Unhandled button event: %d",
event->keysym.scancode);
return;
}
}
// Track the key state so we always know which keys are down
if (event->state == SDL_PRESSED) {
m_KeysDown.insert(keyCode);
}
else {
m_KeysDown.remove(keyCode);
}
LiSendKeyboardEvent(keyCode,
event->state == SDL_PRESSED ?
KEY_ACTION_DOWN : KEY_ACTION_UP,
modifiers);
}
+277
View File
@@ -0,0 +1,277 @@
#include "input.h"
#include <Limelight.h>
#include <SDL.h>
#include "streaming/streamutils.h"
void SdlInputHandler::handleMouseButtonEvent(SDL_MouseButtonEvent* event)
{
int button;
if (event->which == SDL_TOUCH_MOUSEID) {
// Ignore synthetic mouse events
return;
}
else if (!isCaptureActive()) {
if (event->button == SDL_BUTTON_LEFT && event->state == SDL_RELEASED &&
isMouseInVideoRegion(event->x, event->y)) {
// Capture the mouse again if clicked when unbound.
// We start capture on left button released instead of
// pressed to avoid sending an errant mouse button released
// event to the host when clicking into our window (since
// the pressed event was consumed by this code).
setCaptureActive(true);
}
// Not capturing
return;
}
else if (m_AbsoluteMouseMode && !isMouseInVideoRegion(event->x, event->y) && event->state == SDL_PRESSED) {
// Ignore button presses outside the video region, but allow button releases
return;
}
switch (event->button)
{
case SDL_BUTTON_LEFT:
button = BUTTON_LEFT;
break;
case SDL_BUTTON_MIDDLE:
button = BUTTON_MIDDLE;
break;
case SDL_BUTTON_RIGHT:
button = BUTTON_RIGHT;
break;
case SDL_BUTTON_X1:
button = BUTTON_X1;
break;
case SDL_BUTTON_X2:
button = BUTTON_X2;
break;
default:
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION,
"Unhandled button event: %d",
event->button);
return;
}
if (m_SwapMouseButtons) {
if (button == BUTTON_RIGHT)
button = BUTTON_LEFT;
else if (button == BUTTON_LEFT)
button = BUTTON_RIGHT;
}
// Ensure any pending mouse position update has been sent before we send
// our button event. This ensures that the cursor is in the correct location
// when the button event is issued.
//
// On platforms like macOS, the mouse doesn't track when the window isn't
// focused. When we gain focus via mouse click, we immediately get a mouse
// move event and a mouse button event. If we don't flush here, the button
// will probably arrive before the mouse timer issues the position update.
flushMousePositionUpdate();
LiSendMouseButtonEvent(event->state == SDL_PRESSED ?
BUTTON_ACTION_PRESS :
BUTTON_ACTION_RELEASE,
button);
}
void SdlInputHandler::updateMousePositionReport(int mouseX, int mouseY)
{
int windowWidth, windowHeight;
// Call SDL_GetWindowSize() before entering the spinlock
SDL_GetWindowSize(m_Window, &windowWidth, &windowHeight);
SDL_AtomicLock(&m_MousePositionLock);
m_MousePositionReport.x = mouseX;
m_MousePositionReport.y = mouseY;
m_MousePositionReport.windowWidth = windowWidth;
m_MousePositionReport.windowHeight = windowHeight;
SDL_AtomicUnlock(&m_MousePositionLock);
SDL_AtomicSet(&m_MousePositionUpdated, 1);
}
void SdlInputHandler::flushMousePositionUpdate()
{
bool hasNewPosition = SDL_AtomicSet(&m_MousePositionUpdated, 0) != 0;
if (hasNewPosition) {
// If the lock is held now, the main thread is trying to update
// the mouse position. We'll pick up the new position next time.
if (SDL_AtomicTryLock(&m_MousePositionLock)) {
SDL_Rect src, dst;
bool mouseInVideoRegion;
src.x = src.y = 0;
src.w = m_StreamWidth;
src.h = m_StreamHeight;
dst.x = dst.y = 0;
dst.w = m_MousePositionReport.windowWidth;
dst.h = m_MousePositionReport.windowHeight;
// Use the stream and window sizes to determine the video region
StreamUtils::scaleSourceToDestinationSurface(&src, &dst);
mouseInVideoRegion = isMouseInVideoRegion(m_MousePositionReport.x,
m_MousePositionReport.y,
m_MousePositionReport.windowWidth,
m_MousePositionReport.windowHeight);
// Clamp motion to the video region
short x = qMin(qMax(m_MousePositionReport.x - dst.x, 0), dst.w);
short y = qMin(qMax(m_MousePositionReport.y - dst.y, 0), dst.h);
// Release the spinlock to unblock the main thread
SDL_AtomicUnlock(&m_MousePositionLock);
// Send the mouse position update if one of the following is true:
// a) it is in the video region now
// b) it just left the video region (to ensure the mouse is clamped to the video boundary)
// c) a mouse button is still down from before the cursor left the video region (to allow smooth dragging)
Uint32 buttonState = SDL_GetMouseState(nullptr, nullptr);
if (buttonState == 0) {
m_PendingMouseButtonsAllUpOnVideoRegionLeave = false;
}
if (mouseInVideoRegion || m_MouseWasInVideoRegion || m_PendingMouseButtonsAllUpOnVideoRegionLeave) {
LiSendMousePositionEvent(x, y, dst.w, dst.h);
}
// Adjust the cursor visibility if applicable
if (mouseInVideoRegion ^ m_MouseWasInVideoRegion) {
// We must push an event for the main thread to process, because it's not safe
// to directly can SDL_ShowCursor() on the arbitrary thread on which this timer
// executes.
SDL_Event event;
event.type = SDL_USEREVENT;
event.user.code = mouseInVideoRegion ? SDL_CODE_HIDE_CURSOR : SDL_CODE_SHOW_CURSOR;
SDL_PushEvent(&event);
if (!mouseInVideoRegion && buttonState != 0) {
// If we still have a button pressed on leave, wait for that to come up
// before we stop sending mouse position events.
m_PendingMouseButtonsAllUpOnVideoRegionLeave = true;
}
}
m_MouseWasInVideoRegion = mouseInVideoRegion;
}
}
}
void SdlInputHandler::handleMouseMotionEvent(SDL_MouseMotionEvent* event)
{
if (!isCaptureActive()) {
// Not capturing
return;
}
else if (event->which == SDL_TOUCH_MOUSEID) {
// Ignore synthetic mouse events
return;
}
// Batch until the next mouse polling window or we'll get awful
// input lag everything except GFE 3.14 and 3.15.
if (m_AbsoluteMouseMode) {
updateMousePositionReport(event->x, event->y);
}
else {
SDL_AtomicAdd(&m_MouseDeltaX, event->xrel);
SDL_AtomicAdd(&m_MouseDeltaY, event->yrel);
}
}
void SdlInputHandler::handleMouseWheelEvent(SDL_MouseWheelEvent* event)
{
if (!isCaptureActive()) {
// Not capturing
return;
}
else if (event->which == SDL_TOUCH_MOUSEID) {
// Ignore synthetic mouse events
return;
}
if (m_AbsoluteMouseMode) {
int mouseX, mouseY;
SDL_GetMouseState(&mouseX, &mouseY);
if (!isMouseInVideoRegion(mouseX, mouseY)) {
// Ignore scroll events outside the video region
return;
}
}
if (event->y != 0) {
LiSendScrollEvent((signed char)event->y);
}
}
bool SdlInputHandler::isMouseInVideoRegion(int mouseX, int mouseY, int windowWidth, int windowHeight)
{
SDL_Rect src, dst;
if (windowWidth < 0 || windowHeight < 0) {
SDL_GetWindowSize(m_Window, &windowWidth, &windowHeight);
}
src.x = src.y = 0;
src.w = m_StreamWidth;
src.h = m_StreamHeight;
dst.x = dst.y = 0;
dst.w = windowWidth;
dst.h = windowHeight;
// Use the stream and window sizes to determine the video region
StreamUtils::scaleSourceToDestinationSurface(&src, &dst);
return (mouseX >= dst.x && mouseX <= dst.x + dst.w) &&
(mouseY >= dst.y && mouseY <= dst.y + dst.h);
}
Uint32 SdlInputHandler::mouseMoveTimerCallback(Uint32 interval, void *param)
{
auto me = reinterpret_cast<SdlInputHandler*>(param);
short deltaX = (short)SDL_AtomicSet(&me->m_MouseDeltaX, 0);
short deltaY = (short)SDL_AtomicSet(&me->m_MouseDeltaY, 0);
if (deltaX != 0 || deltaY != 0) {
LiSendMouseMoveEvent(deltaX, deltaY);
}
// Send mouse position updates if applicable
me->flushMousePositionUpdate();
#ifdef Q_OS_WIN32
// See comment in SdlInputHandler::notifyMouseLeave()
if (me->m_AbsoluteMouseMode && me->m_PendingMouseLeaveButtonUp != 0 && me->isCaptureActive()) {
int mouseX, mouseY;
int windowX, windowY;
Uint32 mouseState = SDL_GetGlobalMouseState(&mouseX, &mouseY);
SDL_GetWindowPosition(me->m_Window, &windowX, &windowY);
// If the button is now up, send the synthetic mouse up event
if ((mouseState & SDL_BUTTON(me->m_PendingMouseLeaveButtonUp)) == 0) {
SDL_Event event;
event.button.type = SDL_MOUSEBUTTONUP;
event.button.timestamp = SDL_GetTicks();
event.button.windowID = SDL_GetWindowID(me->m_Window);
event.button.which = 0;
event.button.button = me->m_PendingMouseLeaveButtonUp;
event.button.state = SDL_RELEASED;
event.button.clicks = 1;
event.button.x = mouseX - windowX;
event.button.y = mouseY - windowY;
SDL_PushEvent(&event);
me->m_PendingMouseLeaveButtonUp = 0;
}
}
#endif
return interval;
}
+175
View File
@@ -0,0 +1,175 @@
#include "input.h"
#include <Limelight.h>
#include <SDL.h>
#include <QtMath>
// How long the mouse button will be pressed for a tap to click gesture
#define TAP_BUTTON_RELEASE_DELAY 100
// How long the fingers must be stationary to start a drag
#define DRAG_ACTIVATION_DELAY 650
// How far the finger can move before it cancels a drag or tap
#define DEAD_ZONE_DELTA 0.01f
Uint32 SdlInputHandler::releaseLeftButtonTimerCallback(Uint32, void*)
{
LiSendMouseButtonEvent(BUTTON_ACTION_RELEASE, BUTTON_LEFT);
return 0;
}
Uint32 SdlInputHandler::releaseRightButtonTimerCallback(Uint32, void*)
{
LiSendMouseButtonEvent(BUTTON_ACTION_RELEASE, BUTTON_RIGHT);
return 0;
}
Uint32 SdlInputHandler::dragTimerCallback(Uint32, void *param)
{
auto me = reinterpret_cast<SdlInputHandler*>(param);
// Check how many fingers are down now to decide
// which button to hold down
if (me->m_NumFingersDown == 2) {
me->m_DragButton = BUTTON_RIGHT;
}
else if (me->m_NumFingersDown == 1) {
me->m_DragButton = BUTTON_LEFT;
}
LiSendMouseButtonEvent(BUTTON_ACTION_PRESS, me->m_DragButton);
return 0;
}
void SdlInputHandler::handleRelativeFingerEvent(SDL_TouchFingerEvent* event)
{
int fingerIndex = -1;
// Observations on Windows 10: x and y appear to be relative to 0,0 of the window client area.
// Although SDL documentation states they are 0.0 - 1.0 float values, they can actually be higher
// or lower than those values as touch events continue for touches started within the client area that
// leave the client area during a drag motion.
// dx and dy are deltas from the last touch event, not the first touch down.
// Determine the index of this finger using our list
// of fingers that are currently active on screen.
// This is also required to handle finger up which
// where the finger will not be in SDL_GetTouchFinger()
// anymore.
if (event->type != SDL_FINGERDOWN) {
for (int i = 0; i < MAX_FINGERS; i++) {
if (event->fingerId == m_TouchDownEvent[i].fingerId) {
fingerIndex = i;
break;
}
}
}
else {
// Resolve the new finger by determining the ID of each
// finger on the display.
int numTouchFingers = SDL_GetNumTouchFingers(event->touchId);
for (int i = 0; i < numTouchFingers; i++) {
SDL_Finger* finger = SDL_GetTouchFinger(event->touchId, i);
SDL_assert(finger != nullptr);
if (finger != nullptr) {
if (finger->id == event->fingerId) {
fingerIndex = i;
break;
}
}
}
}
if (fingerIndex < 0 || fingerIndex >= MAX_FINGERS) {
// Too many fingers
return;
}
// Handle cursor motion based on the position of the
// primary finger on screen
if (fingerIndex == 0) {
// The event x and y values are relative to our window width
// and height. However, we want to scale them to be relative
// to the host resolution. Fortunately this is easy since we
// already have normalized values. We'll just multiply them
// by the stream dimensions to get real X and Y values rather
// than the client window dimensions.
short deltaX = static_cast<short>(event->dx * m_StreamWidth);
short deltaY = static_cast<short>(event->dy * m_StreamHeight);
if (deltaX != 0 || deltaY != 0) {
LiSendMouseMoveEvent(deltaX, deltaY);
}
}
// Start a drag timer when primary or secondary
// fingers go down
if (event->type == SDL_FINGERDOWN &&
(fingerIndex == 0 || fingerIndex == 1)) {
SDL_RemoveTimer(m_DragTimer);
m_DragTimer = SDL_AddTimer(DRAG_ACTIVATION_DELAY,
dragTimerCallback,
this);
}
if (event->type == SDL_FINGERMOTION) {
// If it's outside the deadzone delta, cancel drags and taps
if (qSqrt(qPow(event->x - m_TouchDownEvent[fingerIndex].x, 2) +
qPow(event->y - m_TouchDownEvent[fingerIndex].y, 2)) > DEAD_ZONE_DELTA) {
SDL_RemoveTimer(m_DragTimer);
m_DragTimer = 0;
// This effectively cancels the tap logic below
m_TouchDownEvent[fingerIndex].timestamp = 0;
}
}
if (event->type == SDL_FINGERUP) {
// Cancel the drag timer on finger up
SDL_RemoveTimer(m_DragTimer);
m_DragTimer = 0;
// Release any drag
if (m_DragButton != 0) {
LiSendMouseButtonEvent(BUTTON_ACTION_RELEASE, m_DragButton);
m_DragButton = 0;
}
// 2 finger tap
else if (event->timestamp - m_TouchDownEvent[1].timestamp < 250) {
// Zero timestamp of the primary finger to ensure we won't
// generate a left click if the primary finger comes up soon.
m_TouchDownEvent[0].timestamp = 0;
// Press down the right mouse button
LiSendMouseButtonEvent(BUTTON_ACTION_PRESS, BUTTON_RIGHT);
// Queue a timer to release it in 100 ms
SDL_RemoveTimer(m_RightButtonReleaseTimer);
m_RightButtonReleaseTimer = SDL_AddTimer(TAP_BUTTON_RELEASE_DELAY,
releaseRightButtonTimerCallback,
nullptr);
}
// 1 finger tap
else if (event->timestamp - m_TouchDownEvent[0].timestamp < 250) {
// Press down the left mouse button
LiSendMouseButtonEvent(BUTTON_ACTION_PRESS, BUTTON_LEFT);
// Queue a timer to release it in 100 ms
SDL_RemoveTimer(m_LeftButtonReleaseTimer);
m_LeftButtonReleaseTimer = SDL_AddTimer(TAP_BUTTON_RELEASE_DELAY,
releaseLeftButtonTimerCallback,
nullptr);
}
}
m_NumFingersDown = SDL_GetNumTouchFingers(event->touchId);
if (event->type == SDL_FINGERDOWN) {
m_TouchDownEvent[fingerIndex] = *event;
}
else if (event->type == SDL_FINGERUP) {
m_TouchDownEvent[fingerIndex] = {};
}
}
+544 -260
View File
File diff suppressed because it is too large Load Diff
+52 -20
View File
@@ -4,11 +4,11 @@
#include <Limelight.h>
#include <opus_multistream.h>
#include "backend/computermanager.h"
#include "settings/streamingpreferences.h"
#include "input.h"
#include "input/input.h"
#include "video/decoder.h"
#include "audio/renderers/renderer.h"
#include "video/overlaymanager.h"
class Session : public QObject
{
@@ -16,6 +16,7 @@ class Session : public QObject
friend class SdlInputHandler;
friend class DeferredSessionCleanupTask;
friend class AsyncConnectionStartThread;
public:
explicit Session(NvComputer* computer, NvApp& app, StreamingPreferences *preferences = nullptr);
@@ -25,17 +26,23 @@ public:
Q_INVOKABLE void exec(int displayOriginX, int displayOriginY);
static
bool isHardwareDecodeAvailable(StreamingPreferences::VideoDecoderSelection vds,
int videoFormat, int width, int height, int frameRate);
void getDecoderInfo(SDL_Window* window,
bool& isHardwareAccelerated, bool& isFullScreenOnly, QSize& maxResolution);
static
int getDecoderCapabilities(StreamingPreferences::VideoDecoderSelection vds,
int videoFormat, int width, int height, int frameRate);
static Session* get()
{
return s_ActiveSession;
}
Overlay::OverlayManager& getOverlayManager()
{
return m_OverlayManager;
}
signals:
void stageStarting(QString stage);
void stageFailed(QString stage, long errorCode);
void stageFailed(QString stage, int errorCode);
void connectionStarted();
@@ -45,47 +52,64 @@ signals:
void quitStarting();
void sessionFinished();
void sessionFinished(int portTestResult);
private:
void initialize();
bool initialize();
bool validateLaunch();
bool startConnectionAsync();
bool validateLaunch(SDL_Window* testWindow);
void emitLaunchWarning(QString text);
int getDecoderCapabilities();
bool populateDecoderProperties(SDL_Window* window);
IAudioRenderer* createAudioRenderer();
int detectAudioConfiguration();
IAudioRenderer* createAudioRenderer(const POPUS_MULTISTREAM_CONFIGURATION opusConfig);
bool testAudio(int audioConfiguration);
int getAudioRendererCapabilities(int audioConfiguration);
void getWindowDimensions(int& x, int& y,
int& width, int& height);
void toggleFullscreen();
void notifyMouseEmulationMode(bool enabled);
void updateOptimalWindowDisplayMode();
static
bool isHardwareDecodeAvailable(SDL_Window* window,
StreamingPreferences::VideoDecoderSelection vds,
int videoFormat, int width, int height, int frameRate);
static
bool chooseDecoder(StreamingPreferences::VideoDecoderSelection vds,
SDL_Window* window, int videoFormat, int width, int height,
int frameRate, bool enableVsync, IVideoDecoder*& chosenDecoder);
int frameRate, bool enableVsync, bool enableFramePacing,
bool testOnly,
IVideoDecoder*& chosenDecoder);
static
void clStageStarting(int stage);
static
void clStageFailed(int stage, long errorCode);
void clStageFailed(int stage, int errorCode);
static
void clConnectionTerminated(long errorCode);
void clConnectionTerminated(int errorCode);
static
void clLogMessage(const char* format, ...);
static
void clRumble(unsigned short controllerNumber, unsigned short lowFreqMotor, unsigned short highFreqMotor);
static
void clConnectionStatusUpdate(int connectionStatus);
static
int arInit(int audioConfiguration,
const POPUS_MULTISTREAM_CONFIGURATION opusConfig,
@@ -109,6 +133,7 @@ private:
StreamingPreferences* m_Preferences;
STREAM_CONFIGURATION m_StreamConfig;
DECODER_RENDERER_CALLBACKS m_VideoCallbacks;
AUDIO_RENDERER_CALLBACKS m_AudioCallbacks;
NvComputer* m_Computer;
NvApp m_App;
SDL_Window* m_Window;
@@ -121,6 +146,12 @@ private:
int m_DisplayOriginY;
bool m_PendingWindowedTransition;
bool m_UnexpectedTermination;
SdlInputHandler* m_InputHandler;
SDL_SpinLock m_InputHandlerLock;
int m_MouseEmulationRefCount;
bool m_AsyncConnectionSuccess;
int m_PortTestResults;
int m_ActiveVideoFormat;
int m_ActiveVideoWidth;
@@ -128,12 +159,13 @@ private:
int m_ActiveVideoFrameRate;
OpusMSDecoder* m_OpusDecoder;
short m_OpusDecodeBuffer[MAX_CHANNELS * SAMPLES_PER_FRAME];
IAudioRenderer* m_AudioRenderer;
OPUS_MULTISTREAM_CONFIGURATION m_AudioConfig;
int m_AudioSampleCount;
Uint32 m_DropAudioEndTime;
Overlay::OverlayManager m_OverlayManager;
static AUDIO_RENDERER_CALLBACKS k_AudioCallbacks;
static CONNECTION_LISTENER_CALLBACKS k_ConnCallbacks;
static Session* s_ActiveSession;
static QSemaphore s_ActiveSessionSemaphore;

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