Compare commits

..
33 Commits
Author SHA1 Message Date
github-actions[bot] 743f2bb9f2 chore: bump version to 1.12.0 2025-12-23 08:32:40 +00:00
edde746 5f4c5a012b remove privacy policy
as it's been moved to the site
2025-12-23 09:12:06 +01:00
edde746 dae1750d86 feat: volume boost
close #37
2025-12-23 07:58:58 +01:00
edde746 e9d1055c60 fix: missing playback restart event 2025-12-23 03:31:27 +01:00
edde746 c2933c0fdf fix: key serialization
close #186
2025-12-23 03:07:16 +01:00
edde746 e252532988 feat: better pre-video loading indicator 2025-12-22 20:12:26 +01:00
edde746 16087cf640 fix: windows stretch issue 2025-12-22 20:12:26 +01:00
edde746 4804a25c1e fix: playlist semantic labels without mediaType
close #185
2025-12-22 17:15:04 +01:00
edde746 a74838d914 feat: improve number input UX for Android TV
close #170
2025-12-22 08:02:45 +01:00
edde746 b396464f70 feat: progressive seek acceleration
close #173
2025-12-22 07:20:33 +01:00
edde746 f9198c7d7a fix: green issue 2025-12-21 17:05:12 +01:00
edde746 f4753e6b2e i18n: add korean translation 2025-12-21 15:44:34 +01:00
edde746 3c5739eefd fix: don't pause on partial focus loss
closes #183
2025-12-21 15:00:31 +01:00
edde746 d8d39cca86 refactor: change desktop hero size 2025-12-21 14:02:41 +01:00
edde746 84c255b917 refactor: deduplicate logic 2025-12-21 13:19:21 +01:00
edde746 44007e6564 feat: auto play next episode 2025-12-21 12:51:24 +01:00
edde746 2dfebf32b6 fix: respect Plex track selection preferences
close #181
2025-12-21 10:51:32 +01:00
edde746 b27aa9cbda fix: wakelock follows play state
close #180
2025-12-20 15:47:42 +01:00
edde746 1bce10a6a4 feat: custom mpv config 2025-12-20 15:43:14 +01:00
edde746 c018cfef03 feat: previous/next buttons on mobile controls
close #130
2025-12-20 15:07:41 +01:00
edde746 d340536578 fix: don't switch input mode on atv pointer events
close #169
2025-12-20 14:56:18 +01:00
edde746 1419f6e043 add nixos mention in readme
close #154
2025-12-20 13:27:19 +01:00
edde746 722b53c0b9 chore: update os_media_controls
close #175
2025-12-20 13:26:48 +01:00
edde746 c61b2301a6 update readme 2025-12-20 06:42:20 +01:00
edde746 14f0e95a3d fix: mpv logs to app logger 2025-12-20 05:02:20 +01:00
edde746 688ad291bd refactor: hero section design improvements 2025-12-20 04:59:03 +01:00
edde746 2644c3ca55 update screenshots 2025-12-19 14:01:37 +01:00
edde746 2f3774db3d fixes 2025-12-19 13:33:22 +01:00
edde746 e11ebca370 fix: missing subtitle characters
close #178
2025-12-19 13:19:57 +01:00
edde746 bed2c35d97 feat: prompt for reviews 2025-12-19 13:10:11 +01:00
edde746 8db30c1568 feat: performance overlay 2025-12-19 13:06:58 +01:00
edde746 c6727baf07 fix: iOS usage descriptions 2025-12-19 10:13:16 +01:00
edde746 d9350d704f fix: iOS build 2025-12-19 05:53:58 +01:00
67 changed files with 19660 additions and 8022 deletions
-98
View File
@@ -1,98 +0,0 @@
# Privacy Policy for Plezy
**Last Updated: October 22, 2025**
## Introduction
Plezy ("we", "our", or "the app") is a third-party Plex client that allows you to access and stream content from your Plex Media Server. This privacy policy explains how we handle your information when you use our app.
## Information We Collect
### Authentication Information
When you sign in to Plezy using your Plex account, we collect and process:
- Plex authentication tokens
- Plex account username
- Plex server connection information
### Local Network Information
To connect to your Plex Media Server on your local network, we may access:
- Local network device discovery information
- IP addresses of Plex servers on your network
### Usage Information
The app stores locally on your device:
- Your authentication session
- App preferences and settings
- Recently accessed content history
## How We Use Your Information
We use the collected information solely to:
- Authenticate you with your Plex account
- Connect to and communicate with your Plex Media Server
- Display your media library and stream content
- Maintain your session and app preferences
## Data Storage and Security
- **Authentication tokens** are stored securely on your device using platform-specific secure storage mechanisms
- **App preferences** are stored locally on your device
- **No data** is transmitted to our servers - all communication is directly between your device and your Plex Media Server or Plex's authentication services
## Third-Party Services
### Plex
Plezy uses Plex's authentication and media services. When you use this app:
- You authenticate directly with Plex's servers
- Your media streaming occurs between your device and your Plex Media Server
- Plex's own privacy policy applies to their services: https://www.plex.tv/about/privacy-legal/
We do not control and are not responsible for Plex's data practices.
## Data Sharing
We do not:
- Sell your personal information
- Share your information with third parties for marketing purposes
- Transmit your data to our own servers
- Track your viewing habits outside of local app functionality
Your data is only shared with:
- **Plex services** for authentication and media server communication (as required for the app to function)
## Your Rights and Choices
You can:
- **Sign out** at any time to remove your authentication session from the device
- **Uninstall the app** to remove all locally stored data
- **Manage your Plex account** directly through Plex's services
## Children's Privacy
Plezy does not knowingly collect personal information from children under 13. The app relies on Plex account authentication, and users must comply with Plex's terms of service and age requirements.
## Changes to This Privacy Policy
We may update this privacy policy from time to time. We will notify users of any material changes by updating the "Last Updated" date at the top of this policy.
## Data Retention
- Authentication tokens are retained on your device until you sign out or uninstall the app
- Local preferences and settings are retained until you uninstall the app
- No data is retained on our servers as we do not operate any backend services
## International Data Transfers
As we do not operate backend servers, there are no international data transfers from our side. Any data transfers occur directly between your device and Plex's services, subject to Plex's privacy policy.
## Legal Compliance
This app complies with:
- General Data Protection Regulation (GDPR)
- California Consumer Privacy Act (CCPA)
- Children's Online Privacy Protection Act (COPPA)
- Other applicable privacy laws
## Your Consent
By using Plezy, you consent to this privacy policy and the processing of your information as described herein.
+27 -38
View File
@@ -3,13 +3,13 @@
Plezy
</h1>
Plezy is a modern Plex media client that provides a seamless streaming experience across desktop and mobile platforms. Built with Flutter, it offers native performance and a clean, intuitive interface for browsing and playing your Plex media library.
A modern Plex client for desktop and mobile. Built with Flutter for native performance and a clean interface.
<p align="center">
<img src="assets/screenshots/macos-home.png" alt="Plezy macOS Home Screen" width="800" />
</p>
*See more screenshots in the [screenshots folder](assets/screenshots/#readme)*
*More screenshots in the [screenshots folder](assets/screenshots/#readme)*
## Download
@@ -21,64 +21,55 @@ Plezy is a modern Plex media client that provides a seamless streaming experienc
- [Windows (x64)](https://github.com/edde746/plezy/releases/latest/download/plezy-windows-installer.exe)
- [macOS (Universal)](https://github.com/edde746/plezy/releases/latest/download/plezy-macos.zip)
- [Linux (x64)](https://github.com/edde746/plezy/releases/latest/download/plezy-linux.tar.gz)
> Download the latest release from the [Releases page](https://github.com/edde746/plezy/releases)
- [NixOS/Nix](https://github.com/mio-19/nurpkgs/tree/main/pkgs/plezy) - Community package by [@mio-19](https://github.com/mio-19) via `nur.repos.mio.plezy`
## Features
### 🔐 Authentication & Server Management
### 🔐 Authentication
- Sign in with Plex
- Automatic server discovery with smart connection selection
- Automatic server discovery and smart connection selection
- Persistent sessions with auto-login
### 📚 Media Browsing
- Browse libraries with rich metadata
- Discover featured content
- Advanced search across all media
- Season and episode navigation
- Collections and playlists
### 🎬 Video Playback
- Wide codec support including HEVC, AV1, VP9, and more
- HDR and Dolby Vision support (iOS, macOS & Windows)
- Advanced subtitle rendering with full ASS/SSA support
- Audio and subtitle track selection with user profile preferences
- Playback progress sync and resume functionality
### 🎬 Playback
- Wide codec support (HEVC, AV1, VP9, and more)
- HDR and Dolby Vision (iOS, macOS, Windows)
- Full ASS/SSA subtitle support
- Audio and subtitle preferences synced with Plex profile
- Progress sync and resume
- Auto-play next episode
## Prerequisites
### 📥 Downloads
- Download media for offline viewing
- Background downloads with queue management
- Flutter SDK 3.8.1 or higher
- A Plex account
- Access to a Plex Media Server (local or remote)
### 👥 Watch Together
- Synchronized playback with friends
- Real-time play/pause and seek sync
## Installation
## Building from Source
### Prerequisites
- Flutter SDK 3.8.1+
- A Plex account with server access
### Setup
1. Clone the repository:
```bash
git clone https://github.com/edde746/plezy.git
cd plezy
```
2. Install dependencies:
```bash
flutter pub get
```
3. Generate required code:
```bash
dart run build_runner build
```
4. Run the application:
```bash
flutter run
```
## Development
### Code Generation
The project uses code generation for JSON serialization. After modifying model classes, run:
After modifying model classes:
```bash
dart run build_runner build --delete-conflicting-outputs
@@ -88,6 +79,4 @@ dart run build_runner build --delete-conflicting-outputs
- Built with [Flutter](https://flutter.dev)
- Designed for [Plex Media Server](https://www.plex.tv)
- Playback powered by [mpv](https://mpv.io)
- [MPVKit](https://github.com/mpvkit/MPVKit)
- [mpv-android](https://github.com/mpv-android/mpv-android)
- Playback powered by [mpv](https://mpv.io) via [MPVKit](https://github.com/mpvkit/MPVKit) and [libmpv-android](https://github.com/jarnedemeulemeester/libmpv-android)
@@ -19,7 +19,8 @@ interface MpvPlayerDelegate {
class MpvPlayerCore(private val activity: Activity) :
SurfaceHolder.Callback,
MPVLib.EventObserver {
MPVLib.EventObserver,
MPVLib.LogObserver {
companion object {
private const val TAG = "MpvPlayerCore"
@@ -143,8 +144,9 @@ class MpvPlayerCore(private val activity: Activity) :
// Initialize MPV
MPVLib.init()
// Register event observer
// Register event and log observers
MPVLib.addObserver(this)
MPVLib.addLogObserver(this)
isInitialized = true
Log.d(TAG, "Initialized successfully")
@@ -235,6 +237,28 @@ class MpvPlayerCore(private val activity: Activity) :
}
}
// MPVLib.LogObserver
override fun logMessage(prefix: String, level: Int, text: String) {
val levelStr = when (level) {
MPVLib.MPV_LOG_LEVEL_FATAL -> "fatal"
MPVLib.MPV_LOG_LEVEL_ERROR -> "error"
MPVLib.MPV_LOG_LEVEL_WARN -> "warn"
MPVLib.MPV_LOG_LEVEL_INFO -> "info"
MPVLib.MPV_LOG_LEVEL_V -> "v"
MPVLib.MPV_LOG_LEVEL_DEBUG -> "debug"
MPVLib.MPV_LOG_LEVEL_TRACE -> "trace"
else -> "info"
}
activity.runOnUiThread {
delegate?.onEvent("log-message", mapOf(
"prefix" to prefix,
"level" to levelStr,
"text" to text
))
}
}
// Public API
fun setProperty(name: String, value: String) {
@@ -282,6 +306,7 @@ class MpvPlayerCore(private val activity: Activity) :
Log.d(TAG, "Disposing")
MPVLib.removeObserver(this)
MPVLib.removeLogObserver(this)
surfaceView?.holder?.removeCallback(this)
overlayLayoutListener?.let { listener ->
@@ -2,6 +2,9 @@
<resources>
<!-- Theme applied to the Android Window while the process is starting when the OS's Dark Mode setting is on -->
<style name="LaunchTheme" parent="@android:style/Theme.Black.NoTitleBar">
<!-- Disable Android's default green focus highlight that appears during d-pad/keyboard navigation -->
<item name="android:defaultFocusHighlightEnabled">false</item>
<item name="android:colorControlHighlight">@android:color/transparent</item>
</style>
<!-- Theme applied to the Android Window as soon as the process has started.
This theme determines the color of the Android Window while your
@@ -11,5 +14,8 @@
This Theme is only used starting with V2 of Flutter's Android embedding. -->
<style name="NormalTheme" parent="@android:style/Theme.Black.NoTitleBar">
<item name="android:windowBackground">?android:colorBackground</item>
<!-- Disable Android's default green focus highlight that appears during d-pad/keyboard navigation -->
<item name="android:defaultFocusHighlightEnabled">false</item>
<item name="android:colorControlHighlight">@android:color/transparent</item>
</style>
</resources>
@@ -2,6 +2,9 @@
<resources>
<!-- Theme applied to the Android Window while the process is starting when the OS's Dark Mode setting is off -->
<style name="LaunchTheme" parent="@android:style/Theme.Light.NoTitleBar">
<!-- Disable Android's default green focus highlight that appears during d-pad/keyboard navigation -->
<item name="android:defaultFocusHighlightEnabled">false</item>
<item name="android:colorControlHighlight">@android:color/transparent</item>
</style>
<!-- Theme applied to the Android Window as soon as the process has started.
This theme determines the color of the Android Window while your
@@ -11,5 +14,8 @@
This Theme is only used starting with V2 of Flutter's Android embedding. -->
<style name="NormalTheme" parent="@android:style/Theme.Light.NoTitleBar">
<item name="android:windowBackground">?android:colorBackground</item>
<!-- Disable Android's default green focus highlight that appears during d-pad/keyboard navigation -->
<item name="android:defaultFocusHighlightEnabled">false</item>
<item name="android:colorControlHighlight">@android:color/transparent</item>
</style>
</resources>
+2 -2
View File
@@ -32,13 +32,13 @@ platform :android do
desc "Build release AAB"
lane :build do
# Navigate to Flutter project root and build
sh("cd #{ENV['PWD']}/.. && flutter build appbundle")
sh("cd #{ENV['PWD']}/.. && flutter build appbundle --dart-define=ENABLE_IN_APP_REVIEW=true")
end
desc "Build and deploy to Google Play Store"
lane :release do
# Build the Flutter app
sh("cd #{ENV['PWD']}/.. && flutter build appbundle")
sh("cd #{ENV['PWD']}/.. && flutter build appbundle --dart-define=ENABLE_IN_APP_REVIEW=true")
# Get version code from pubspec.yaml
pubspec_path = "#{ENV['PWD']}/../pubspec.yaml"
Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.7 MiB

After

Width:  |  Height:  |  Size: 3.8 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.8 MiB

After

Width:  |  Height:  |  Size: 2.4 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.7 MiB

After

Width:  |  Height:  |  Size: 2.6 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.9 MiB

After

Width:  |  Height:  |  Size: 1.7 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.4 MiB

After

Width:  |  Height:  |  Size: 4.4 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.5 MiB

After

Width:  |  Height:  |  Size: 3.4 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.5 MiB

After

Width:  |  Height:  |  Size: 3.0 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.5 MiB

After

Width:  |  Height:  |  Size: 1.2 MiB

+5 -1
View File
@@ -1,5 +1,5 @@
# Uncomment this line to define a global platform for your project
# platform :ios, '13.0'
platform :ios, '14.0'
# CocoaPods analytics sends network stats synchronously affecting flutter build latency.
ENV['COCOAPODS_DISABLE_STATS'] = 'true'
@@ -25,6 +25,10 @@ end
require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root)
# Disable file_picker's media picker on iOS - removes DKImagePickerController dependency
# This app only uses file_picker for directory selection on desktop
Pod.const_set(:PICKER_MEDIA, false) unless Pod.const_defined?(:PICKER_MEDIA)
flutter_ios_podfile_setup
target 'Runner' do
+13 -51
View File
@@ -3,46 +3,16 @@ PODS:
- Flutter
- device_info_plus (0.0.1):
- Flutter
- DKImagePickerController/Core (4.3.9):
- DKImagePickerController/ImageDataManager
- DKImagePickerController/Resource
- DKImagePickerController/ImageDataManager (4.3.9)
- DKImagePickerController/PhotoGallery (4.3.9):
- DKImagePickerController/Core
- DKPhotoGallery
- DKImagePickerController/Resource (4.3.9)
- DKPhotoGallery (0.0.19):
- DKPhotoGallery/Core (= 0.0.19)
- DKPhotoGallery/Model (= 0.0.19)
- DKPhotoGallery/Preview (= 0.0.19)
- DKPhotoGallery/Resource (= 0.0.19)
- SDWebImage
- SwiftyGif
- DKPhotoGallery/Core (0.0.19):
- DKPhotoGallery/Model
- DKPhotoGallery/Preview
- SDWebImage
- SwiftyGif
- DKPhotoGallery/Model (0.0.19):
- SDWebImage
- SwiftyGif
- DKPhotoGallery/Preview (0.0.19):
- DKPhotoGallery/Model
- DKPhotoGallery/Resource
- SDWebImage
- SwiftyGif
- DKPhotoGallery/Resource (0.0.19):
- SDWebImage
- SwiftyGif
- file_picker (0.0.1):
- DKImagePickerController/PhotoGallery
- Flutter
- Flutter (1.0.0)
- flutter_webrtc (0.11.3):
- flutter_webrtc (1.2.0):
- Flutter
- WebRTC-SDK (= 125.6422.04)
- WebRTC-SDK (= 137.7151.04)
- gamepads_ios (0.1.1):
- Flutter
- in_app_review (2.0.0):
- Flutter
- os_media_controls (0.0.1):
- Flutter
- package_info_plus (0.4.5):
@@ -50,9 +20,6 @@ PODS:
- path_provider_foundation (0.0.1):
- Flutter
- FlutterMacOS
- SDWebImage (5.21.3):
- SDWebImage/Core (= 5.21.3)
- SDWebImage/Core (5.21.3)
- share_plus (0.0.1):
- Flutter
- shared_preferences_foundation (0.0.1):
@@ -86,12 +53,11 @@ PODS:
- sqlite3/perf-threadsafe
- sqlite3/rtree
- sqlite3/session
- SwiftyGif (5.4.5)
- url_launcher_ios (0.0.1):
- Flutter
- wakelock_plus (0.0.1):
- Flutter
- WebRTC-SDK (125.6422.04)
- WebRTC-SDK (137.7151.04)
- workmanager_apple (0.0.1):
- Flutter
@@ -102,6 +68,7 @@ DEPENDENCIES:
- Flutter (from `Flutter`)
- flutter_webrtc (from `.symlinks/plugins/flutter_webrtc/ios`)
- gamepads_ios (from `.symlinks/plugins/gamepads_ios/ios`)
- in_app_review (from `.symlinks/plugins/in_app_review/ios`)
- os_media_controls (from `.symlinks/plugins/os_media_controls/ios`)
- package_info_plus (from `.symlinks/plugins/package_info_plus/ios`)
- path_provider_foundation (from `.symlinks/plugins/path_provider_foundation/darwin`)
@@ -115,11 +82,7 @@ DEPENDENCIES:
SPEC REPOS:
trunk:
- DKImagePickerController
- DKPhotoGallery
- SDWebImage
- sqlite3
- SwiftyGif
- WebRTC-SDK
EXTERNAL SOURCES:
@@ -135,6 +98,8 @@ EXTERNAL SOURCES:
:path: ".symlinks/plugins/flutter_webrtc/ios"
gamepads_ios:
:path: ".symlinks/plugins/gamepads_ios/ios"
in_app_review:
:path: ".symlinks/plugins/in_app_review/ios"
os_media_controls:
:path: ".symlinks/plugins/os_media_controls/ios"
package_info_plus:
@@ -159,27 +124,24 @@ EXTERNAL SOURCES:
SPEC CHECKSUMS:
connectivity_plus: cb623214f4e1f6ef8fe7403d580fdad517d2f7dd
device_info_plus: 21fcca2080fbcd348be798aa36c3e5ed849eefbe
DKImagePickerController: 946cec48c7873164274ecc4624d19e3da4c1ef3c
DKPhotoGallery: b3834fecb755ee09a593d7c9e389d8b5d6deed60
file_picker: a0560bc09d61de87f12d246fc47d2119e6ef37be
file_picker: 8fc6fe5e42585a217d44d22f79ec046cb8d81140
Flutter: cabc95a1d2626b1b06e7179b784ebcf0c0cde467
flutter_webrtc: 89f078a5050779eaa4a6a4f472954737bb91f39f
flutter_webrtc: c3e21fc0dcd9d8eb246ae4d5256fcbeb2f5ecd22
gamepads_ios: c75c6d31377d275b0effb9174c619e2705678c09
in_app_review: 7dd1ea365263f834b8464673f9df72c80c17c937
os_media_controls: 86dceab6245a5325af90fc0fdebe243c42d789b4
package_info_plus: af8e2ca6888548050f16fa2f1938db7b5a5df499
path_provider_foundation: bb55f6dbba17d0dccd6737fe6f7f34fbd0376880
SDWebImage: 16309af6d214ba3f77a7c6f6fdda888cb313a50a
share_plus: 50da8cb520a8f0f65671c6c6a99b3617ed10a58a
shared_preferences_foundation: 7036424c3d8ec98dfe75ff1667cb0cd531ec82bb
sqflite_darwin: 20b2a3a3b70e43edae938624ce550a3cbf66a3d0
sqlite3: 8d708bc63e9f4ce48f0ad9d6269e478c5ced1d9b
sqlite3_flutter_libs: d13b8b3003f18f596e542bcb9482d105577eff41
SwiftyGif: 706c60cf65fa2bc5ee0313beece843c8eb8194d4
url_launcher_ios: 7a95fa5b60cc718a708b8f2966718e93db0cef1b
wakelock_plus: e29112ab3ef0b318e58cfa5c32326458be66b556
WebRTC-SDK: c3d69a87e7185fad3568f6f3cff7c9ac5890acf3
WebRTC-SDK: 40d4f5ba05cadff14e4db5614aec402a633f007e
workmanager_apple: 904529ae31e97fc5be632cf628507652294a0778
PODFILE CHECKSUM: 3c63482e143d1b91d2d2560aee9fb04ecc74ac7e
PODFILE CHECKSUM: faeab82d8b6e3c9d039ddf62b7666988a3dea540
COCOAPODS: 1.16.2
+2
View File
@@ -39,6 +39,8 @@
</array>
<key>NSLocalNetworkUsageDescription</key>
<string>This app needs to connect to your Plex Media Server on your local network.</string>
<key>NSCameraUsageDescription</key>
<string>Camera access is included by the WebRTC library used for Watch Together, but is not actively used by this app.</string>
<key>UIApplicationSupportsIndirectInputEvents</key>
<true/>
<key>UIFileSharingEnabled</key>
+15 -4
View File
@@ -344,13 +344,24 @@ class MpvPlayerCore: NSObject {
case MPV_EVENT_SHUTDOWN:
print("[MpvPlayerCore] MPV shutdown event")
case MPV_EVENT_PLAYBACK_RESTART:
DispatchQueue.main.async {
self.delegate?.onEvent(name: "playback-restart", data: nil)
}
case MPV_EVENT_LOG_MESSAGE:
if let msgPtr = event.data?.assumingMemoryBound(to: mpv_event_log_message.self) {
let msg = msgPtr.pointee
if let prefix = msg.prefix, let level = msg.level, let text = msg.text {
print(
"[MPV:\(String(cString: prefix))] \(String(cString: level)): \(String(cString: text))",
terminator: "")
let prefix = msg.prefix.map { String(cString: $0) } ?? ""
let level = msg.level.map { String(cString: $0) } ?? ""
let text = msg.text.map { String(cString: $0) } ?? ""
DispatchQueue.main.async {
self.delegate?.onEvent(name: "log-message", data: [
"prefix": prefix,
"level": level,
"text": text
])
}
}
+3 -3
View File
@@ -19,13 +19,13 @@ platform :ios do
desc "Build release IPA"
lane :build do
# Navigate to Flutter project root and build
sh("cd #{ENV['PWD']}/.. && flutter build ipa")
sh("cd #{ENV['PWD']}/.. && flutter build ipa --dart-define=ENABLE_IN_APP_REVIEW=true")
end
desc "Build and deploy to TestFlight"
lane :deploy_testflight do
# Build the Flutter app
sh("cd #{ENV['PWD']}/.. && flutter build ipa")
sh("cd #{ENV['PWD']}/.. && flutter build ipa --dart-define=ENABLE_IN_APP_REVIEW=true")
# Upload to TestFlight
upload_to_testflight(
@@ -36,7 +36,7 @@ platform :ios do
desc "Build and deploy to App Store"
lane :deploy_appstore do
# Build the Flutter app
sh("cd #{ENV['PWD']}/.. && flutter build ipa")
sh("cd #{ENV['PWD']}/.. && flutter build ipa --dart-define=ENABLE_IN_APP_REVIEW=true")
# Upload to App Store
upload_to_app_store(
+7
View File
@@ -95,6 +95,13 @@ class _InputModeTrackerState extends State<InputModeTracker> {
@override
Widget build(BuildContext context) {
// On Android TV, don't switch to pointer mode from pointer events
// as D-pad can generate synthetic pointer events that would incorrectly
// trigger pointer mode and show a cursor instead of D-pad focus navigation
if (TvDetectionService.isTVSync()) {
return _InputModeProvider(mode: _mode, child: widget.child);
}
return Listener(
// Switch to pointer mode on mouse activity
onPointerDown: (_) => _setMode(InputMode.pointer),
+15588 -6686
View File
File diff suppressed because it is too large Load Diff
+32 -1
View File
@@ -39,6 +39,7 @@
"licenses": "Licenses",
"switchProfile": "Switch Profile",
"subtitleStyling": "Subtitle Styling",
"mpvConfig": "MPV Configuration",
"search": "Search",
"logs": "Logs"
},
@@ -141,7 +142,11 @@
"downloadLocationSelectError": "Failed to select folder",
"downloadOnWifiOnly": "Download on WiFi only",
"downloadOnWifiOnlyDescription": "Prevent downloads when on cellular data",
"cellularDownloadBlocked": "Downloads are disabled on cellular data. Connect to WiFi or change the setting."
"cellularDownloadBlocked": "Downloads are disabled on cellular data. Connect to WiFi or change the setting.",
"maxVolume": "Maximum Volume",
"maxVolumeDescription": "Allow volume boost above 100% for quiet media",
"maxVolumePercent": "${percent}%",
"maxVolumeHint": "Enter max volume (100-300)"
},
"search": {
"hint": "Search movies, shows, music...",
@@ -296,6 +301,32 @@
"backgroundOpacity": "Background Opacity",
"backgroundColor": "Background Color"
},
"mpvConfig": {
"title": "MPV Configuration",
"description": "Advanced video player settings",
"properties": "Properties",
"presets": "Presets",
"noProperties": "No properties configured",
"noPresets": "No saved presets",
"addProperty": "Add Property",
"editProperty": "Edit Property",
"deleteProperty": "Delete Property",
"propertyKey": "Property Key",
"propertyKeyHint": "e.g., hwdec, demuxer-max-bytes",
"propertyValue": "Property Value",
"propertyValueHint": "e.g., auto, 256000000",
"saveAsPreset": "Save as Preset...",
"presetName": "Preset Name",
"presetNameHint": "Enter a name for this preset",
"loadPreset": "Load",
"deletePreset": "Delete",
"presetSaved": "Preset saved",
"presetLoaded": "Preset loaded",
"presetDeleted": "Preset deleted",
"confirmDeletePreset": "Are you sure you want to delete this preset?",
"confirmDeleteProperty": "Are you sure you want to delete this property?",
"entriesCount": "${count} entries"
},
"dialog": {
"confirmAction": "Confirm Action",
"cancel": "Cancel",
+32 -1
View File
@@ -40,6 +40,7 @@
"selectServer": "Server auswählen",
"switchProfile": "Profil wechseln",
"subtitleStyling": "Untertitel-Stil",
"mpvConfig": "MPV-Konfiguration",
"search": "Suche",
"logs": "Protokolle"
},
@@ -142,7 +143,11 @@
"downloadLocationSelectError": "Ordnerauswahl fehlgeschlagen",
"downloadOnWifiOnly": "Nur über WLAN herunterladen",
"downloadOnWifiOnlyDescription": "Downloads über mobile Daten verhindern",
"cellularDownloadBlocked": "Downloads sind über mobile Daten deaktiviert. Verbinde dich mit einem WLAN oder ändere die Einstellung."
"cellularDownloadBlocked": "Downloads sind über mobile Daten deaktiviert. Verbinde dich mit einem WLAN oder ändere die Einstellung.",
"maxVolume": "Maximale Lautstärke",
"maxVolumeDescription": "Lautstärke über 100% für leise Medien erlauben",
"maxVolumePercent": "${percent}%",
"maxVolumeHint": "Maximale Lautstärke eingeben (100-300)"
},
"search": {
"hint": "Filme, Serien, Musik suchen...",
@@ -297,6 +302,32 @@
"backgroundOpacity": "Hintergrunddeckkraft",
"backgroundColor": "Hintergrundfarbe"
},
"mpvConfig": {
"title": "MPV-Konfiguration",
"description": "Erweiterte Videoplayer-Einstellungen",
"properties": "Eigenschaften",
"presets": "Voreinstellungen",
"noProperties": "Keine Eigenschaften konfiguriert",
"noPresets": "Keine gespeicherten Voreinstellungen",
"addProperty": "Eigenschaft hinzufügen",
"editProperty": "Eigenschaft bearbeiten",
"deleteProperty": "Eigenschaft löschen",
"propertyKey": "Eigenschaftsschlüssel",
"propertyKeyHint": "z.B. hwdec, demuxer-max-bytes",
"propertyValue": "Eigenschaftswert",
"propertyValueHint": "z.B. auto, 256000000",
"saveAsPreset": "Als Voreinstellung speichern...",
"presetName": "Name der Voreinstellung",
"presetNameHint": "Namen für diese Voreinstellung eingeben",
"loadPreset": "Laden",
"deletePreset": "Löschen",
"presetSaved": "Voreinstellung gespeichert",
"presetLoaded": "Voreinstellung geladen",
"presetDeleted": "Voreinstellung gelöscht",
"confirmDeletePreset": "Möchten Sie diese Voreinstellung wirklich löschen?",
"confirmDeleteProperty": "Möchten Sie diese Eigenschaft wirklich löschen?",
"entriesCount": "${count} Einträge"
},
"dialog": {
"confirmAction": "Aktion bestätigen",
"cancel": "Abbrechen",
+32 -1
View File
@@ -40,6 +40,7 @@
"selectServer": "Seleziona server",
"switchProfile": "Cambia profilo",
"subtitleStyling": "Stile sottotitoli",
"mpvConfig": "Configurazione MPV",
"search": "Cerca",
"logs": "Registro"
},
@@ -142,7 +143,11 @@
"downloadLocationSelectError": "Impossibile selezionare la cartella",
"downloadOnWifiOnly": "Scarica solo con WiFi",
"downloadOnWifiOnlyDescription": "Impedisci i download quando si utilizza la rete dati cellulare",
"cellularDownloadBlocked": "I download sono disabilitati sulla rete dati cellulare. Connettiti al WiFi o modifica l'impostazione."
"cellularDownloadBlocked": "I download sono disabilitati sulla rete dati cellulare. Connettiti al WiFi o modifica l'impostazione.",
"maxVolume": "Volume massimo",
"maxVolumeDescription": "Consenti volume superiore al 100% per contenuti audio bassi",
"maxVolumePercent": "${percent}%",
"maxVolumeHint": "Inserisci volume massimo (100-300)"
},
"search": {
"hint": "Cerca film. spettacoli, musica...",
@@ -297,6 +302,32 @@
"backgroundOpacity": "Opacità sfondo",
"backgroundColor": "Colore sfondo"
},
"mpvConfig": {
"title": "Configurazione MPV",
"description": "Impostazioni avanzate del lettore video",
"properties": "Proprietà",
"presets": "Preset",
"noProperties": "Nessuna proprietà configurata",
"noPresets": "Nessun preset salvato",
"addProperty": "Aggiungi proprietà",
"editProperty": "Modifica proprietà",
"deleteProperty": "Elimina proprietà",
"propertyKey": "Chiave proprietà",
"propertyKeyHint": "es. hwdec, demuxer-max-bytes",
"propertyValue": "Valore proprietà",
"propertyValueHint": "es. auto, 256000000",
"saveAsPreset": "Salva come preset...",
"presetName": "Nome preset",
"presetNameHint": "Inserisci un nome per questo preset",
"loadPreset": "Carica",
"deletePreset": "Elimina",
"presetSaved": "Preset salvato",
"presetLoaded": "Preset caricato",
"presetDeleted": "Preset eliminato",
"confirmDeletePreset": "Sei sicuro di voler eliminare questo preset?",
"confirmDeleteProperty": "Sei sicuro di voler eliminare questa proprietà?",
"entriesCount": "${count} voci"
},
"dialog": {
"confirmAction": "Conferma azione",
"cancel": "Cancella",
+575
View File
@@ -0,0 +1,575 @@
{
"app": {
"title": "Plezy",
"loading": "로딩 중..."
},
"auth": {
"signInWithPlex": "Plex 계정으로 로그인",
"showQRCode": "QR 코드",
"cancel": "취소",
"authenticate": "인증",
"retry": "재시도",
"debugEnterToken": "디버깅을 위해 Plex 토큰을 입력하세요.",
"plexTokenLabel": "Plex 인증 토큰",
"plexTokenHint": "Plex.tv 토큰을 입력하세요",
"authenticationTimeout": "인증 시간이 초과되었습니다. 다시 시도해 주세요.",
"scanQRCodeInstruction": "Plex 계정에 로그인된 기기에서 이 QR 코드를 스캔하여 본인 인증을 해주세요.",
"waitingForAuth": "인증 대기 중... 브라우저에서 로그인을 완료해 주세요."
},
"common": {
"cancel": "취소",
"save": "저장",
"close": "닫기",
"clear": "지우기",
"reset": "초기화",
"later": "나중에",
"submit": "보내기",
"confirm": "확인",
"retry": "재시도",
"logout": "로그아웃",
"unknown": "알 수 없는",
"refresh": "새로고침",
"yes": "예",
"no": "아니오",
"delete": "삭제",
"shuffle": "무작위 재생",
"addTo": "추가하기..."
},
"screens": {
"licenses": "라이선스",
"selectServer": "서버 선택",
"switchProfile": "프로필 전환",
"subtitleStyling": "자막 스타일 설정",
"mpvConfig": "MPV 설정",
"search": "검색",
"logs": "로그"
},
"update": {
"available": "사용 가능한 업데이트",
"versionAvailable": "버전 ${version} 출시됨",
"currentVersion": "현재 버전: ${version}",
"skipVersion": "이 버전 건너뛰기",
"viewRelease": "릴리스 정보 보기",
"latestVersion": "최신 버전을 사용 중입니다",
"checkFailed": "업데이트 확인 실패"
},
"settings": {
"title": "설정",
"language": "언어",
"theme": "테마",
"appearance": "외관",
"videoPlayback": "비디오 재생",
"advanced": "고급",
"useSeasonPostersDescription": "에피소드에 시리즈 포스터 대신 시즌 포스터 표시",
"showHeroSectionDescription": "홈 화면에 주요 콘텐츠 캐러셀(슬라이드) 표시",
"secondsLabel": "초",
"minutesLabel": "분",
"secondsShort": "초",
"minutesShort": "분",
"durationHint": "기간 입력 (${min}-${max})",
"systemTheme": "시스템 설정",
"systemThemeDescription": "시스템 설정에 따름",
"lightTheme": "라이트 모드",
"darkTheme": "다크 모드",
"libraryDensity": "라이브러리 표시 밀도",
"compact": "좁게",
"compactDescription": "카드를 작게 표시하여 더 많은 항목을 보여줍니다.",
"normal": "보통",
"normalDescription": "기본 크기",
"comfortable": "넓게",
"comfortableDescription": "카드를 크게 표시하여 더 적은 항목을 보여줍니다.",
"viewMode": "보기 모드",
"gridView": "그리드 보기",
"gridViewDescription": "항목을 그리드 레이아웃으로 표시합니다",
"listView": "목록 보기",
"listViewDescription": "항목을 목록 레이아웃으로 표시합니다",
"useSeasonPosters": "시즌 포스터 사용",
"showHeroSection": "주요 추천 영역 표시",
"hardwareDecoding": "하드웨어 디코딩",
"hardwareDecodingDescription": "가능한 경우 하드웨어 가속을 사용합니다",
"bufferSize": "버퍼 크기",
"bufferSizeMB": "${size}MB",
"subtitleStyling": "자막 스타일",
"subtitleStylingDescription": "자막의 외형을 사용자 설정",
"smallSkipDuration": "짧은 건너뛰기 시간",
"largeSkipDuration": "긴 건너뛰기 시간",
"secondsUnit": "${seconds}초",
"defaultSleepTimer": "기본 취침 타이머",
"minutesUnit": "${minutes}분",
"rememberTrackSelections": "에피소드/영화별 트랙 선택 기억",
"rememberTrackSelectionsDescription": "재생 중 트랙을 변경할 때 오디오 및 자막 언어 설정을 자동으로 저장합니다",
"videoPlayerControls": "비디오 플레이어 컨트롤",
"keyboardShortcuts": "키보드 단축키",
"keyboardShortcutsDescription": "사용자 정의 키보드 단축키",
"videoPlayerNavigation": "비디오 플레이어 탐색",
"videoPlayerNavigationDescription": "방향 키를 사용하여 비디오 플레이어 컨트롤 탐색",
"debugLogging": "디버그 로깅",
"debugLoggingDescription": "문제 해결을 위해 상세 로깅 활성화",
"viewLogs": "로그 보기",
"viewLogsDescription": "애플리케이션 로그 확인",
"clearCache": "캐시 삭제",
"clearCacheDescription": "모든 캐시된 이미지와 데이터를 지웁니다. 캐시를 지우면 애플리케이션 콘텐츠 로딩 속도가 느려질 수 있습니다.",
"clearCacheSuccess": "캐시 삭제 성공",
"resetSettings": "설정 재설정",
"resetSettingsDescription": "모든 설정을 기본값으로 재설정합니다. 이 작업은 되돌릴 수 없습니다.",
"resetSettingsSuccess": "설정 재설정 성공",
"shortcutsReset": "단축키가 기본값으로 재설정되었습니다",
"about": "정보",
"aboutDescription": "응용 프로그램 정보 및 라이선스",
"updates": "업데이트",
"updateAvailable": "사용 가능한 업데이트 있음",
"checkForUpdates": "업데이트 확인",
"validationErrorEnterNumber": "유효한 숫자를 입력하세요",
"validationErrorDuration": "기간은 ${min}과 ${max} ${unit} 사이여야 합니다",
"shortcutAlreadyAssigned": "단축키가 이미 ${action}에 할당 되었습니다",
"shortcutUpdated": "단축키가 ${action}에 대해 업데이트 되었습니다",
"autoSkip": "자동 건너뛰기",
"autoSkipIntro": "자동으로 오프닝 건너뛰기",
"autoSkipIntroDescription": "몇 초 후 오프닝을 자동으로 건너뛰기",
"autoSkipCredits": "자동으로 엔딩 건너뛰기",
"autoSkipCreditsDescription": "엔딩 크레딧 자동 건너뛰기 후 다음 에피소드 재생",
"autoSkipDelay": "자동 건너뛰기 지연",
"autoSkipDelayDescription": "자동 건너뛰기 전 ${seconds} 초 대기",
"downloads": "다운로드",
"downloadLocationDescription": "다운로드 콘텐츠 저장 위치 선택",
"downloadLocationDefault": "기본값 (앱 저장소)",
"downloadLocationCustom": "사용자 지정 위치",
"selectFolder": "폴더 선택",
"resetToDefault": "기본값으로 재설정",
"currentPath": "현재: ${path}",
"downloadLocationChanged": "다운로드 위치가 변경 되었습니다",
"downloadLocationReset": "다운로드 위치가 기본값으로 재설정 되었습니다",
"downloadLocationInvalid": "선택한 폴더에 쓰기 권한이 없습니다",
"downloadLocationSelectError": "폴더 선택 실패",
"downloadOnWifiOnly": "WiFi 연결 시에만 다운로드",
"downloadOnWifiOnlyDescription": "셀룰러 데이터 사용 시 다운로드 불가",
"cellularDownloadBlocked": "셀룰러 데이터에서 다운로드가 차단 되었습니다. WiFi에 연결하거나 설정을 변경하세요.",
"maxVolume": "최대 볼륨",
"maxVolumeDescription": "조용한 미디어를 위해 100% 이상의 볼륨 허용",
"maxVolumePercent": "${percent}%",
"maxVolumeHint": "최대 볼륨 입력 (100-300)"
},
"search": {
"hint": "영화, 시리즈, 음악 등을 검색하세요...",
"tryDifferentTerm": "다른 검색어를 시도해 보세요",
"searchYourMedia": "미디어 검색",
"enterTitleActorOrKeyword": "제목, 배우 또는 키워드를 입력하세요"
},
"hotkeys": {
"setShortcutFor": "${actionName}에 대한 단축키 설정",
"clearShortcut": "단축키 삭제"
},
"pinEntry": {
"enterPin": "PIN 입력",
"showPin": "PIN 표시",
"hidePin": "PIN 숨기기"
},
"fileInfo": {
"title": "파일 정보",
"video": "비디오",
"audio": "오디오",
"file": "파일",
"advanced": "고급",
"codec": "코덱",
"resolution": "해상도",
"bitrate": "비트레이트",
"frameRate": "프레임 속도",
"aspectRatio": "종횡비",
"profile": "프로파일",
"bitDepth": "비트 심도",
"colorSpace": "색 공간",
"colorRange": "색 범위",
"colorPrimaries": "색상 원색",
"chromaSubsampling": "채도 서브샘플링",
"channels": "채널",
"path": "경로",
"size": "크기",
"container": "컨테이너",
"duration": "재생 시간",
"optimizedForStreaming": "스트리밍 최적화",
"has64bitOffsets": "64비트 오프셋"
},
"mediaMenu": {
"markAsWatched": "시청 완료로 표시",
"markAsUnwatched": "시청 안 함으로 표시",
"removeFromContinueWatching": "계속 보기에서 제거",
"goToSeries": "시리즈로 이동",
"goToSeason": "시즌으로 이동",
"shufflePlay": "무작위 재생",
"fileInfo": "파일 정보"
},
"accessibility": {
"mediaCardMovie": "${title}, 영화",
"mediaCardShow": "${title}, TV 프로그램",
"mediaCardEpisode": "${title}, ${episodeInfo}",
"mediaCardSeason": "${title}, ${seasonInfo}",
"mediaCardWatched": "시청 완료",
"mediaCardPartiallyWatched": "${percent} 퍼센트 시청 완료",
"mediaCardUnwatched": "미시청",
"tapToPlay": "터치 하여 재생"
},
"tooltips": {
"shufflePlay": "무작위 재생",
"markAsWatched": "시청 완료로 표시",
"markAsUnwatched": "시청 안 함으로 표시"
},
"videoControls": {
"audioLabel": "오디오",
"subtitlesLabel": "자막",
"resetToZero": "0ms로 재설정",
"addTime": "+${amount}${unit}",
"minusTime": "-${amount}${unit}",
"playsLater": "${label} 나중에 재생됨",
"playsEarlier": "${label} 더 먼저 재생됨",
"noOffset": "오프셋 없음",
"letterbox": "레터박스 모드",
"fillScreen": "화면 채우기",
"stretch": "확장",
"lockRotation": "회전 잠금",
"unlockRotation": "회전 잠금 해제",
"sleepTimer": "수면 타이머",
"timerActive": "타이머 활성화됨",
"playbackWillPauseIn": "재생이 ${duration} 후에 일시 중지 됩니다",
"sleepTimerCompleted": "수면 타이머 완료됨 - 재생이 일시 중지되었습니다",
"playButton": "재생",
"pauseButton": "일시정지",
"seekBackwardButton": "${seconds} 초 뒤로",
"seekForwardButton": "${seconds} 초 앞으로",
"previousButton": "이전 에피소드",
"nextButton": "다음 에피소드",
"previousChapterButton": "이전 챕터",
"nextChapterButton": "다음 챕터",
"muteButton": "음소거",
"unmuteButton": "음소거 해제",
"settingsButton": "동영상 설정",
"audioTrackButton": "음원 트랙",
"subtitlesButton": "자막",
"chaptersButton": "챕터",
"versionsButton": "동영상 버전",
"aspectRatioButton": "화면비율",
"fullscreenButton": "전체화면",
"exitFullscreenButton": "전체화면 종료",
"alwaysOnTopButton": "창 최상위 고정",
"rotationLockButton": "회전 잠금",
"timelineSlider": "타임라인",
"volumeSlider": "볼륨 조절",
"backButton": "뒤로 가기"
},
"userStatus": {
"admin": "관리자",
"restricted": "제한됨",
"protected": "보호됨",
"current": "현재"
},
"messages": {
"markedAsWatched": "시청 완료로 표시됨",
"markedAsUnwatched": "시청 안 함으로 표시됨",
"markedAsWatchedOffline": "시청 완료로 표시됨 (연결 시 동기화됨)",
"markedAsUnwatchedOffline": "미시청으로 표시됨 (연결 시 동기화됨)",
"removedFromContinueWatching": "계속 시청 목록에서 제거됨",
"errorLoading": "오류: ${error}",
"fileInfoNotAvailable": "파일 정보가 없습니다",
"errorLoadingFileInfo": "파일 정보 로딩 중 오류: ${error}",
"errorLoadingSeries": "시리즈 로딩 중 오류",
"errorLoadingSeason": "시즌 로딩 중 오류",
"musicNotSupported": "음악 재생 미지원",
"logsCleared": "로그가 삭제 되었습니다",
"logsCopied": "로그가 클립보드에 복사 되었습니다",
"noLogsAvailable": "사용 가능한 로그가 없습니다",
"libraryScanning": "\"${title}\"을(를) 스캔 중입니다...",
"libraryScanStarted": "\"${title}\" 미디어 라이브러리 스캔 시작",
"libraryScanFailed": "미디어 라이브러리 스캔 실패: ${error}",
"metadataRefreshing": "\"${title}\" 메타데이터 새로고침 중...",
"metadataRefreshStarted": "\"${title}\" 메타데이터 새로고침 시작됨",
"metadataRefreshFailed": "메타데이터 새로고침 실패: ${error}",
"logoutConfirm": "로그아웃 하시겠습니까?",
"noSeasonsFound": "시즌을 찾을 수 없음",
"noEpisodesFound": "시즌 1에서 에피소드를 찾을 수 없습니다",
"noEpisodesFoundGeneral": "에피소드를 찾을 수 없습니다",
"noResultsFound": "결과를 찾을 수 없습니다",
"sleepTimerSet": "수면 타이머가 ${label}로 설정 되었습니다",
"noItemsAvailable": "사용 가능한 항목이 없습니다",
"failedToCreatePlayQueue": "재생 대기열 생성 실패",
"failedToCreatePlayQueueNoItems": "재생 대기열 생성 실패 - 항목 없음",
"failedPlayback": "${action}을(를) 수행할 수 없습니다: ${error}"
},
"subtitlingStyling": {
"stylingOptions": "스타일 옵션",
"fontSize": "글자 크기",
"textColor": "텍스트 색상",
"borderSize": "테두리 크기",
"borderColor": "테두리 색상",
"backgroundOpacity": "배경 불투명도",
"backgroundColor": "배경색"
},
"mpvConfig": {
"title": "MPV 설정",
"description": "고급 비디오 플레이어 설정",
"properties": "속성",
"presets": "사전 설정",
"noProperties": "설정된 속성이 없습니다",
"noPresets": "저장된 사전 설정이 없습니다",
"addProperty": "속성 추가",
"editProperty": "속성 편집",
"deleteProperty": "속성 삭제",
"propertyKey": "속성 키",
"propertyKeyHint": "예: hwdec, demuxer-max-bytes",
"propertyValue": "속성값",
"propertyValueHint": "예: auto, 256000000",
"saveAsPreset": "프리셋으로 저장...",
"presetName": "프리셋 이름",
"presetNameHint": "이 프리셋의 이름을 입력하세요",
"loadPreset": "로드",
"deletePreset": "삭제",
"presetSaved": "프리셋이 저장 되었습니다",
"presetLoaded": "프리셋이 로드 되었습니다",
"presetDeleted": "프리셋이 삭제 되었습니다",
"confirmDeletePreset": "이 프리셋을 삭제 하시겠습니까?",
"confirmDeleteProperty": "이 속성을 삭제 하시겠습니까?",
"entriesCount": "${count} 항목"
},
"dialog": {
"confirmAction": "확인",
"cancel": "취소",
"playNow": "지금 재생"
},
"discover": {
"title": "발견",
"switchProfile": "사용자 전환",
"switchServer": "서버 전환",
"logout": "로그아웃",
"noContentAvailable": "사용 가능한 콘텐츠가 없습니다",
"addMediaToLibraries": "미디어 라이브러리에 미디어를 추가해 주세요",
"continueWatching": "계속 시청",
"play": "재생",
"playEpisode": "S${season}E${episode}",
"pause": "일시정지",
"overview": "개요",
"cast": "출연진",
"seasons": "시즌 수",
"studio": "제작사",
"rating": "연령 등급",
"watched": "시청 완료",
"episodeCount": "${count} 편",
"watchedProgress": "${watched}/${total} 편 시청 완료",
"movie": "영화",
"tvShow": "TV 시리즈",
"minutesLeft": "${minutes}분 남음"
},
"errors": {
"searchFailed": "검색 실패: ${error}",
"connectionTimeout": "${context} 로드 중 연결 시간 초과",
"connectionFailed": "Plex 서버에 연결할 수 없음",
"failedToLoad": "${context} 로드 실패: ${error}",
"noClientAvailable": "사용 가능한 클라이언트가 없습니다",
"authenticationFailed": "인증 실패: ${error}",
"couldNotLaunchUrl": "인증 URL을 열 수 없습니다",
"pleaseEnterToken": "토큰을 입력해 주세요",
"invalidToken": "토큰이 유효하지 않습니다",
"failedToVerifyToken": "토큰을 확인할 수 없습니다: ${error}",
"failedToSwitchProfile": "${displayName}으로 전환할 수 없습니다"
},
"libraries": {
"title": "미디어 라이브러리",
"scanLibraryFiles": "미디어 라이브러리 파일 스캔",
"scanLibrary": "미디어 라이브러리 스캔",
"analyze": "분석",
"analyzeLibrary": "미디어 라이브러리 분석",
"refreshMetadata": "메타데이터 새로 고침",
"emptyTrash": "휴지통 비우기",
"emptyingTrash": "「${title}」의 휴지통을 비우고 있습니다...",
"trashEmptied": "「${title}」의 휴지통을 비웠습니다",
"failedToEmptyTrash": "휴지통 비우기 실패: ${error}",
"analyzing": "\"${title}\" 분석 중...",
"analysisStarted": "\"${title}\" 분석 시작됨",
"failedToAnalyze": "미디어 라이브러리 분석 실패: ${error}",
"noLibrariesFound": "미디어 라이브러리 없음",
"thisLibraryIsEmpty": "이 미디어 라이브러리는 비어 있습니다",
"all": "전체",
"clearAll": "모두 삭제",
"scanLibraryConfirm": "「${title}」를 스캔 하시겠습니까?",
"analyzeLibraryConfirm": "「${title}」를 분석 하시겠습니까?",
"refreshMetadataConfirm": "「${title}」의 메타데이터를 새로고침 하시겠습니까?",
"emptyTrashConfirm": "${title}의 휴지통을 비우시겠습니까?",
"manageLibraries": "미디어 라이브러리 관리",
"sort": "정렬",
"sortBy": "정렬 기준",
"filters": "필터",
"confirmActionMessage": "이 작업을 실행 하시겠습니까?",
"showLibrary": "미디어 라이브러리 표시",
"hideLibrary": "미디어 라이브러리 숨기기",
"libraryOptions": "미디어 라이브러리 옵션",
"content": "미디어 라이브러리 콘텐츠",
"selectLibrary": "미디어 라이브러리 선택",
"filtersWithCount": "필터 (${count})",
"noRecommendations": "추천 없음",
"noCollections": "이 미디어 라이브러리에는 컬렉션이 없습니다",
"noFoldersFound": "폴더를 찾을 수 없습니다",
"folders": "폴더",
"tabs": {
"recommended": "추천",
"browse": "찾아보기",
"collections": "컬렉션",
"playlists": "재생 목록"
},
"groupings": {
"all": "전체",
"movies": "영화",
"shows": "TV 프로그램",
"seasons": "시즌",
"episodes": "화",
"folders": "폴더"
}
},
"about": {
"title": "소개",
"openSourceLicenses": "오픈소스 라이선스",
"versionLabel": "버전 ${version}",
"appDescription": "아름다운 Flutter Plex 클라이언트",
"viewLicensesDescription": "타사 라이브러리 라이선스 보기"
},
"serverSelection": {
"allServerConnectionsFailed": "어떤 서버에도 연결할 수 없습니다. 네트워크를 확인하고 다시 시도하세요.",
"noServersFound": "서버를 찾을 수 없습니다.",
"noServersFoundForAccount": "${username} (${email})의 서버를 찾을 수 없습니다.",
"failedToLoadServers": "서버를 로드할 수 없습니다: ${error}"
},
"hubDetail": {
"title": "제목",
"releaseYear": "출시 연도",
"dateAdded": "추가 날짜",
"rating": "평점",
"noItemsFound": "항목이 없습니다"
},
"logs": {
"clearLogs": "로그 지우기",
"copyLogs": "로그 복사",
"error": "오류:",
"stackTrace": "스택 추적 (Stack Trace):"
},
"licenses": {
"relatedPackages": "관련 소프트웨어 패키지",
"license": "라이선스",
"licenseNumber": "라이선스 ${number}",
"licensesCount": "${count} 개의 라이선스"
},
"navigation": {
"home": "홈",
"search": "검색",
"libraries": "미디어 라이브러리",
"settings": "설정",
"downloads": "다운로드"
},
"collections": {
"title": "컬렉션",
"collection": "컬렉션",
"empty": "컬렉션이 비어 있습니다",
"unknownLibrarySection": "삭제할 수 없습니다: 알 수 없는 미디어 라이브러리 섹션입니다",
"deleteCollection": "컬렉션 삭제",
"deleteConfirm": "\"${title}\"을(를) 삭제 하시겠습니까? 이 작업은 되돌릴 수 없습니다.",
"deleted": "컬렉션 삭제됨",
"deleteFailed": "컬렉션 삭제 실패",
"deleteFailedWithError": "컬렉션 삭제 실패: ${error}",
"failedToLoadItems": "컬렉션 항목 로드 실패: ${error}",
"selectCollection": "컬렉션 선택",
"createNewCollection": "새 컬렉션 생성",
"collectionName": "컬렉션 이름",
"enterCollectionName": "컬렉션 이름 입력",
"addedToCollection": "컬렉션에 추가됨",
"errorAddingToCollection": "컬렉션에 추가 실패",
"created": "컬렉션 생성됨",
"removeFromCollection": "컬렉션에서 제거",
"removeFromCollectionConfirm": "${title}을/를 이 컬렉션에서 제거 하시겠습니까?",
"removedFromCollection": "컬렉션에서 제거됨",
"removeFromCollectionFailed": "컬렉션에서 제거 실패",
"removeFromCollectionError": "컬렉션에서 제거 중 오류 발생: ${error}"
},
"playlists": {
"title": "플레이리스트",
"playlist": "재생 목록",
"noPlaylists": "재생 목록을 찾을 수 없습니다",
"create": "재생 목록 생성",
"playlistName": "재생 목록 이름",
"enterPlaylistName": "재생 목록 이름 입력",
"delete": "재생 목록 삭제",
"removeItem": "재생 목록에서 항목 제거",
"smartPlaylist": "스마트 재생 목록",
"itemCount": "${count}개 항목",
"oneItem": "1개 항목",
"emptyPlaylist": "이 재생 목록은 비어 있습니다",
"deleteConfirm": "재생 목록을 삭제 하시겠습니까?",
"deleteMessage": "\"${name}\"을(를) 삭제 하시겠습니까?",
"created": "재생 목록이 생성 되었습니다",
"deleted": "재생 목록이 삭제 되었습니다",
"itemAdded": "재생 목록에 추가 되었습니다",
"itemRemoved": "재생 목록에서 제거됨",
"selectPlaylist": "재생 목록 선택",
"createNewPlaylist": "새 재생 목록 생성",
"errorCreating": "재생 목록 생성 실패",
"errorDeleting": "재생 목록 삭제 실패",
"errorLoading": "재생 목록 로드 실패",
"errorAdding": "재생 목록에 추가 실패",
"errorReordering": "재생 목록 항목 재정렬 실패",
"errorRemoving": "재생 목록에서 제거 실패"
},
"watchTogether": {
"title": "함께 보기",
"description": "친구 및 가족과 콘텐츠를 동시에 시청하세요",
"createSession": "세션 생성",
"creating": "생성 중...",
"joinSession": "세션 참여",
"joining": "참가 중...",
"controlMode": "제어 모드",
"controlModeQuestion": "누가 재생을 제어할 수 있나요?",
"hostOnly": "호스트만",
"anyone": "누구나",
"hostingSession": "세션 호스팅",
"inSession": "세션 중",
"sessionCode": "세션 코드",
"hostControlsPlayback": "호스트 재생 제어",
"anyoneCanControl": "누구나 재생 제어 가능",
"hostControls": "호스트 제어",
"anyoneControls": "누구나 제어",
"participants": "참가자",
"host": "호스트",
"hostBadge": "호스트",
"youAreHost": "당신은 호스트 입니다",
"watchingWithOthers": "다른 사람과 함께 시청 중",
"endSession": "세션 종료",
"leaveSession": "세션 탈퇴",
"endSessionQuestion": "세션을 종료 하시겠습니까?",
"leaveSessionQuestion": "세션을 탈퇴 하시겠습니까?",
"endSessionConfirm": "이 작업은 모든 참가자의 세션을 종료합니다.",
"leaveSessionConfirm": "당신은 세션에서 제거됩니다.",
"endSessionConfirmOverlay": "이것은 모든 참가자의 시청 세션을 종료합니다.",
"leaveSessionConfirmOverlay": "시청 세션 연결이 끊어집니다.",
"end": "종료",
"leave": "이탈",
"syncing": "동기화 중...",
"participant": "참여자",
"joinWatchSession": "시청 세션에 참여",
"enterCodeHint": "8자리 코드 입력",
"pasteFromClipboard": "클립보드에서 붙여넣기",
"pleaseEnterCode": "세션 코드를 입력하세요",
"codeMustBe8Chars": "세션 코드는 반드시 8자리여야 합니다",
"joinInstructions": "호스트가 공유한 세션 코드를 입력하여 시청 세션에 참여하세요.",
"failedToCreate": "세션 생성 실패",
"failedToJoin": "세션 참여 실패"
},
"downloads": {
"title": "다운로드",
"manage": "관리",
"tvShows": "TV 프로그램",
"movies": "영화",
"noDownloads": "다운로드 없음",
"noDownloadsDescription": "다운로드한 콘텐츠는 오프라인 시청을 위해 여기에 표시됩니다",
"downloadNow": "다운로드",
"deleteDownload": "다운로드 삭제",
"retryDownload": "다운로드 재시도",
"downloadQueued": "다운로드 대기 중",
"episodesQueued": "${count} 에피소드가 다운로드 대기열에 추가 되었습니다",
"downloadDeleted": "다운로드 삭제됨",
"deleteConfirm": "\"${title}\"를 삭제 하시겠습니까? 다운로드한 파일이 기기에서 삭제됩니다.",
"deletingWithProgress": "${title} 삭제 중... (${current}/${total})"
}
}
+32 -1
View File
@@ -40,6 +40,7 @@
"selectServer": "Selecteer server",
"switchProfile": "Wissel van profiel",
"subtitleStyling": "Ondertitel opmaak",
"mpvConfig": "MPV-configuratie",
"search": "Zoeken",
"logs": "Logbestanden"
},
@@ -142,7 +143,11 @@
"downloadLocationSelectError": "Kan map niet selecteren",
"downloadOnWifiOnly": "Alleen via WiFi downloaden",
"downloadOnWifiOnlyDescription": "Voorkom downloads bij gebruik van mobiele data",
"cellularDownloadBlocked": "Downloads zijn uitgeschakeld bij mobiele data. Maak verbinding met WiFi of wijzig de instelling."
"cellularDownloadBlocked": "Downloads zijn uitgeschakeld bij mobiele data. Maak verbinding met WiFi of wijzig de instelling.",
"maxVolume": "Maximaal volume",
"maxVolumeDescription": "Volume boven 100% toestaan voor stille media",
"maxVolumePercent": "${percent}%",
"maxVolumeHint": "Voer maximaal volume in (100-300)"
},
"search": {
"hint": "Zoek films, series, muziek...",
@@ -297,6 +302,32 @@
"backgroundOpacity": "Achtergrond transparantie",
"backgroundColor": "Achtergrondkleur"
},
"mpvConfig": {
"title": "MPV-configuratie",
"description": "Geavanceerde videospeler-instellingen",
"properties": "Eigenschappen",
"presets": "Voorinstellingen",
"noProperties": "Geen eigenschappen geconfigureerd",
"noPresets": "Geen opgeslagen voorinstellingen",
"addProperty": "Eigenschap toevoegen",
"editProperty": "Eigenschap bewerken",
"deleteProperty": "Eigenschap verwijderen",
"propertyKey": "Eigenschapssleutel",
"propertyKeyHint": "bijv. hwdec, demuxer-max-bytes",
"propertyValue": "Eigenschapswaarde",
"propertyValueHint": "bijv. auto, 256000000",
"saveAsPreset": "Opslaan als voorinstelling...",
"presetName": "Naam voorinstelling",
"presetNameHint": "Voer een naam in voor deze voorinstelling",
"loadPreset": "Laden",
"deletePreset": "Verwijderen",
"presetSaved": "Voorinstelling opgeslagen",
"presetLoaded": "Voorinstelling geladen",
"presetDeleted": "Voorinstelling verwijderd",
"confirmDeletePreset": "Weet je zeker dat je deze voorinstelling wilt verwijderen?",
"confirmDeleteProperty": "Weet je zeker dat je deze eigenschap wilt verwijderen?",
"entriesCount": "${count} items"
},
"dialog": {
"confirmAction": "Bevestig actie",
"cancel": "Annuleren",
+32 -1
View File
@@ -40,6 +40,7 @@
"selectServer": "Välj server",
"switchProfile": "Byt profil",
"subtitleStyling": "Undertext-styling",
"mpvConfig": "MPV-konfiguration",
"search": "Sök",
"logs": "Loggar"
},
@@ -142,7 +143,11 @@
"downloadLocationSelectError": "Kunde inte välja mapp",
"downloadOnWifiOnly": "Ladda ner endast på WiFi",
"downloadOnWifiOnlyDescription": "Förhindra nedladdningar vid användning av mobildata",
"cellularDownloadBlocked": "Nedladdningar är inaktiverade på mobildata. Anslut till WiFi eller ändra inställningen."
"cellularDownloadBlocked": "Nedladdningar är inaktiverade på mobildata. Anslut till WiFi eller ändra inställningen.",
"maxVolume": "Maximal volym",
"maxVolumeDescription": "Tillåt volym över 100% för tyst media",
"maxVolumePercent": "${percent}%",
"maxVolumeHint": "Ange maximal volym (100-300)"
},
"search": {
"hint": "Sök filmer, serier, musik...",
@@ -297,6 +302,32 @@
"backgroundOpacity": "Bakgrundsopacitet",
"backgroundColor": "Bakgrundsfärg"
},
"mpvConfig": {
"title": "MPV-konfiguration",
"description": "Avancerade videospelares inställningar",
"properties": "Egenskaper",
"presets": "Förval",
"noProperties": "Inga egenskaper konfigurerade",
"noPresets": "Inga sparade förval",
"addProperty": "Lägg till egenskap",
"editProperty": "Redigera egenskap",
"deleteProperty": "Ta bort egenskap",
"propertyKey": "Egenskapsnyckel",
"propertyKeyHint": "t.ex. hwdec, demuxer-max-bytes",
"propertyValue": "Egenskapsvärde",
"propertyValueHint": "t.ex. auto, 256000000",
"saveAsPreset": "Spara som förval...",
"presetName": "Förvalnamn",
"presetNameHint": "Ange ett namn för detta förval",
"loadPreset": "Ladda",
"deletePreset": "Ta bort",
"presetSaved": "Förval sparat",
"presetLoaded": "Förval laddat",
"presetDeleted": "Förval borttaget",
"confirmDeletePreset": "Är du säker på att du vill ta bort detta förval?",
"confirmDeleteProperty": "Är du säker på att du vill ta bort denna egenskap?",
"entriesCount": "${count} poster"
},
"dialog": {
"confirmAction": "Bekräfta åtgärd",
"cancel": "Avbryt",
+32 -1
View File
@@ -40,6 +40,7 @@
"selectServer": "选择服务器",
"switchProfile": "切换用户",
"subtitleStyling": "字幕样式",
"mpvConfig": "MPV 配置",
"search": "搜索",
"logs": "日志"
},
@@ -142,7 +143,11 @@
"downloadLocationSelectError": "选择文件夹失败",
"downloadOnWifiOnly": "仅在 WiFi 时下载",
"downloadOnWifiOnlyDescription": "使用蜂窝数据时禁止下载",
"cellularDownloadBlocked": "蜂窝数据下已禁用下载。请连接 WiFi 或更改设置。"
"cellularDownloadBlocked": "蜂窝数据下已禁用下载。请连接 WiFi 或更改设置。",
"maxVolume": "最大音量",
"maxVolumeDescription": "允许音量超过 100% 以适应安静的媒体",
"maxVolumePercent": "${percent}%",
"maxVolumeHint": "输入最大音量 (100-300)"
},
"search": {
"hint": "搜索电影、系列、音乐...",
@@ -297,6 +302,32 @@
"backgroundOpacity": "背景不透明度",
"backgroundColor": "背景颜色"
},
"mpvConfig": {
"title": "MPV 配置",
"description": "高级视频播放器设置",
"properties": "属性",
"presets": "预设",
"noProperties": "未配置任何属性",
"noPresets": "没有保存的预设",
"addProperty": "添加属性",
"editProperty": "编辑属性",
"deleteProperty": "删除属性",
"propertyKey": "属性键",
"propertyKeyHint": "例如 hwdec, demuxer-max-bytes",
"propertyValue": "属性值",
"propertyValueHint": "例如 auto, 256000000",
"saveAsPreset": "保存为预设...",
"presetName": "预设名称",
"presetNameHint": "输入此预设的名称",
"loadPreset": "加载",
"deletePreset": "删除",
"presetSaved": "预设已保存",
"presetLoaded": "预设已加载",
"presetDeleted": "预设已删除",
"confirmDeletePreset": "确定要删除此预设吗?",
"confirmDeleteProperty": "确定要删除此属性吗?",
"entriesCount": "${count} 条目"
},
"dialog": {
"confirmAction": "确认操作",
"cancel": "取消",
+17 -3
View File
@@ -27,6 +27,7 @@ import 'watch_together/watch_together.dart';
import 'services/multi_server_manager.dart';
import 'services/offline_watch_sync_service.dart';
import 'services/data_aggregation_service.dart';
import 'services/in_app_review_service.dart';
import 'services/server_registry.dart';
import 'services/download_manager_service.dart';
import 'services/download_storage_service.dart';
@@ -129,6 +130,9 @@ class _MainAppState extends State<MainApp> with WidgetsBindingObserver {
_downloadManager = DownloadManagerService(database: _appDatabase, storageService: DownloadStorageService.instance);
_offlineWatchSyncService = OfflineWatchSyncService(database: _appDatabase, serverManager: _serverManager);
// Start in-app review session tracking
InAppReviewService.instance.startSession();
}
@override
@@ -139,9 +143,19 @@ class _MainAppState extends State<MainApp> with WidgetsBindingObserver {
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
if (state == AppLifecycleState.resumed) {
// App came back to foreground - trigger sync check
_offlineWatchSyncService.onAppResumed();
switch (state) {
case AppLifecycleState.resumed:
// App came back to foreground - trigger sync check and start new session
_offlineWatchSyncService.onAppResumed();
InAppReviewService.instance.startSession();
case AppLifecycleState.paused:
case AppLifecycleState.detached:
// App went to background or is closing - end session
InAppReviewService.instance.endSession();
case AppLifecycleState.inactive:
case AppLifecycleState.hidden:
// Transitional states - don't trigger session events
break;
}
}
+45
View File
@@ -0,0 +1,45 @@
/// Represents a single MPV configuration entry
class MpvConfigEntry {
final String key;
final String value;
final bool isEnabled;
const MpvConfigEntry({required this.key, required this.value, this.isEnabled = true});
factory MpvConfigEntry.fromJson(Map<String, dynamic> json) {
return MpvConfigEntry(
key: json['key'] as String,
value: json['value'] as String,
isEnabled: json['isEnabled'] as bool? ?? true,
);
}
Map<String, dynamic> toJson() => {'key': key, 'value': value, 'isEnabled': isEnabled};
MpvConfigEntry copyWith({String? key, String? value, bool? isEnabled}) {
return MpvConfigEntry(key: key ?? this.key, value: value ?? this.value, isEnabled: isEnabled ?? this.isEnabled);
}
}
/// Represents a saved preset of MPV configurations
class MpvPreset {
final String name;
final List<MpvConfigEntry> entries;
final DateTime createdAt;
const MpvPreset({required this.name, required this.entries, required this.createdAt});
factory MpvPreset.fromJson(Map<String, dynamic> json) {
return MpvPreset(
name: json['name'] as String,
entries: (json['entries'] as List).map((e) => MpvConfigEntry.fromJson(e as Map<String, dynamic>)).toList(),
createdAt: DateTime.parse(json['createdAt'] as String),
);
}
Map<String, dynamic> toJson() => {
'name': name,
'entries': entries.map((e) => e.toJson()).toList(),
'createdAt': createdAt.toIso8601String(),
};
}
@@ -4,15 +4,15 @@ import 'package:flutter/services.dart';
import 'package:path/path.dart' as path;
import 'package:path_provider/path_provider.dart';
/// Utility class for loading font assets on Android for libass subtitle rendering.
/// Utility class for loading font assets for libass subtitle rendering.
///
/// On Android, libass cannot access system fonts through fontconfig, so we need
/// to extract font files from Flutter assets to the app's cache directory.
class AndroidFontLoader {
/// Extracts font files from Flutter assets to the app's cache directory to ensure
/// comprehensive Unicode coverage (including CJK characters) for subtitles.
class SubtitleFontLoader {
static const String _fontAssetPath = 'assets/go-noto-current-regular.ttf';
static const String _fontName = 'Go Noto Current-Regular';
/// Loads the subtitle font from assets to the Android cache directory.
/// Loads the subtitle font from assets to the cache directory.
/// Returns the directory path containing the font file.
static Future<String?> loadSubtitleFont() async {
try {
+61 -11
View File
@@ -4,7 +4,8 @@ import 'dart:io' show Platform;
import 'package:flutter/services.dart';
import '../android_font_loader.dart';
import '../../utils/app_logger.dart';
import '../font_loader.dart';
import '../models.dart';
import 'player.dart';
import 'player_state.dart';
@@ -44,6 +45,7 @@ class PlayerNative implements Player {
final _errorController = StreamController<String>.broadcast();
final _audioDeviceController = StreamController<AudioDevice>.broadcast();
final _audioDevicesController = StreamController<List<AudioDevice>>.broadcast();
final _playbackRestartController = StreamController<void>.broadcast();
StreamSubscription? _eventSubscription;
bool _disposed = false;
@@ -65,9 +67,45 @@ class PlayerNative implements Player {
error: _errorController.stream,
audioDevice: _audioDeviceController.stream,
audioDevices: _audioDevicesController.stream,
playbackRestart: _playbackRestartController.stream,
);
_setupEventListener();
// Forward MPV logs to app logger
_logController.stream.listen(_forwardToAppLogger);
}
void _forwardToAppLogger(PlayerLog log) {
final message = '[MPV:${log.prefix}] ${log.text}'.trimRight();
switch (log.level) {
case PlayerLogLevel.fatal:
case PlayerLogLevel.error:
appLogger.e(message);
case PlayerLogLevel.warn:
appLogger.w(message);
case PlayerLogLevel.info:
case PlayerLogLevel.verbose:
appLogger.i(message);
case PlayerLogLevel.debug:
case PlayerLogLevel.trace:
appLogger.d(message);
case PlayerLogLevel.none:
break;
}
}
PlayerLogLevel _parseLogLevel(String level) {
return switch (level) {
'fatal' => PlayerLogLevel.fatal,
'error' => PlayerLogLevel.error,
'warn' => PlayerLogLevel.warn,
'info' => PlayerLogLevel.info,
'v' || 'verbose' => PlayerLogLevel.verbose,
'debug' => PlayerLogLevel.debug,
'trace' => PlayerLogLevel.trace,
_ => PlayerLogLevel.info,
};
}
void _setupEventListener() {
@@ -203,6 +241,19 @@ class PlayerNative implements Player {
_state = _state.copyWith(completed: false);
_completedController.add(false);
break;
case 'playback-restart':
// Playback started/restarted - first frame is ready
_playbackRestartController.add(null);
break;
case 'log-message':
final prefix = data?['prefix'] as String? ?? '';
final levelStr = data?['level'] as String? ?? 'info';
final text = data?['text'] as String? ?? '';
final level = _parseLogLevel(levelStr);
_logController.add(PlayerLog(level: level, prefix: prefix, text: text));
break;
}
}
@@ -292,10 +343,8 @@ class PlayerNative implements Player {
throw Exception('Failed to initialize player');
}
// Configure subtitle fonts for Android libass support
if (Platform.isAndroid) {
await _configureAndroidSubtitleFonts();
}
// Configure subtitle fonts for libass support
await _configureSubtitleFonts();
// Subscribe to MPV properties
await _observeProperty('time-pos', 'double');
@@ -317,17 +366,17 @@ class PlayerNative implements Player {
await _methodChannel.invokeMethod('observeProperty', {'name': name, 'format': format});
}
/// Configures subtitle fonts for Android libass support.
/// On Android, libass cannot access system fonts, so we need to provide
/// a font file from assets.
Future<void> _configureAndroidSubtitleFonts() async {
/// Configures subtitle fonts for libass support.
/// Provides a comprehensive Unicode font (Go Noto) with CJK coverage to ensure
/// proper rendering of non-Latin characters in subtitles.
Future<void> _configureSubtitleFonts() async {
try {
final fontDir = await AndroidFontLoader.loadSubtitleFont();
final fontDir = await SubtitleFontLoader.loadSubtitleFont();
if (fontDir != null) {
// Configure MPV to use the extracted font for libass
await setProperty('config', 'yes');
await setProperty('sub-fonts-dir', fontDir);
await setProperty('sub-font', AndroidFontLoader.fontName);
await setProperty('sub-font', SubtitleFontLoader.fontName);
}
} catch (e) {
// Font configuration is not critical - continue without it
@@ -548,5 +597,6 @@ class PlayerNative implements Player {
await _errorController.close();
await _audioDeviceController.close();
await _audioDevicesController.close();
await _playbackRestartController.close();
}
}
+4
View File
@@ -47,6 +47,9 @@ class PlayerStreams {
/// Stream of available audio devices.
final Stream<List<AudioDevice>> audioDevices;
/// Stream that emits when playback restarts (first frame ready after load/seek).
final Stream<void> playbackRestart;
const PlayerStreams({
required this.playing,
required this.completed,
@@ -62,5 +65,6 @@ class PlayerStreams {
required this.error,
required this.audioDevice,
required this.audioDevices,
required this.playbackRestart,
});
}
+20 -18
View File
@@ -106,6 +106,22 @@ class OfflineWatchProvider extends ChangeNotifier {
return episodes;
}
/// Batch resolve watch statuses for a list of episodes.
///
/// Returns a map of globalKey -> isWatched for each episode.
Future<Map<String, bool>> _resolveEpisodeWatchStatuses(List<PlexMetadata> episodes) async {
if (episodes.isEmpty) return {};
final globalKeys = episodes.map((e) => e.globalKey).toSet();
final localStatuses = await _syncService.getLocalWatchStatusesBatched(globalKeys);
return {
for (final episode in episodes)
episode.globalKey:
localStatuses[episode.globalKey] ?? _downloadProvider.getMetadata(episode.globalKey)?.isWatched ?? false,
};
}
/// Find the next unwatched downloaded episode for a show.
///
/// This is the "offline OnDeck" calculation - finds the first
@@ -118,15 +134,11 @@ class OfflineWatchProvider extends ChangeNotifier {
final episodes = _getSortedEpisodes(showRatingKey);
if (episodes.isEmpty) return null;
// Batch fetch all watch statuses in a single query
final globalKeys = episodes.map((e) => e.globalKey).toSet();
final localStatuses = await _syncService.getLocalWatchStatusesBatched(globalKeys);
final watchStatuses = await _resolveEpisodeWatchStatuses(episodes);
// Find first unwatched episode
for (final episode in episodes) {
final localStatus = localStatuses[episode.globalKey];
final watched = localStatus ?? _downloadProvider.getMetadata(episode.globalKey)?.isWatched ?? false;
if (!watched) {
if (!watchStatuses[episode.globalKey]!) {
return episode;
}
}
@@ -176,21 +188,11 @@ class OfflineWatchProvider extends ChangeNotifier {
/// Uses batched database query for efficiency.
Future<List<(PlexMetadata episode, bool isWatched)>> getEpisodesWithWatchStatus(String showRatingKey) async {
final episodes = _downloadProvider.getDownloadedEpisodesForShow(showRatingKey);
if (episodes.isEmpty) return [];
// Batch fetch all watch statuses in a single query
final globalKeys = episodes.map((e) => e.globalKey).toSet();
final localStatuses = await _syncService.getLocalWatchStatusesBatched(globalKeys);
final watchStatuses = await _resolveEpisodeWatchStatuses(episodes);
final results = <(PlexMetadata, bool)>[];
for (final episode in episodes) {
final localStatus = localStatuses[episode.globalKey];
final watched = localStatus ?? _downloadProvider.getMetadata(episode.globalKey)?.isWatched ?? false;
results.add((episode, watched));
}
return results;
return [for (final episode in episodes) (episode, watchStatuses[episode.globalKey]!)];
}
/// Trigger a manual sync of pending items.
File diff suppressed because it is too large Load Diff
+376
View File
@@ -0,0 +1,376 @@
import 'package:flutter/material.dart';
import 'package:plezy/widgets/app_icon.dart';
import 'package:material_symbols_icons/symbols.dart';
import '../../i18n/strings.g.dart';
import '../../models/mpv_config_models.dart';
import '../../services/settings_service.dart';
import '../../widgets/desktop_app_bar.dart';
class MpvConfigScreen extends StatefulWidget {
const MpvConfigScreen({super.key});
@override
State<MpvConfigScreen> createState() => _MpvConfigScreenState();
}
class _MpvConfigScreenState extends State<MpvConfigScreen> {
late SettingsService _settingsService;
bool _isLoading = true;
List<MpvConfigEntry> _entries = [];
List<MpvPreset> _presets = [];
@override
void initState() {
super.initState();
_loadSettings();
}
Future<void> _loadSettings() async {
_settingsService = await SettingsService.getInstance();
setState(() {
_entries = _settingsService.getMpvConfigEntries();
_presets = _settingsService.getMpvPresets();
_isLoading = false;
});
}
Future<void> _saveEntries() async {
await _settingsService.setMpvConfigEntries(_entries);
}
void _toggleEntry(int index) {
setState(() {
_entries[index] = _entries[index].copyWith(isEnabled: !_entries[index].isEnabled);
});
_saveEntries();
}
void _deleteEntry(int index) {
setState(() {
_entries.removeAt(index);
});
_saveEntries();
}
void _addEntry(MpvConfigEntry entry) {
setState(() {
_entries.add(entry);
});
_saveEntries();
}
void _updateEntry(int index, MpvConfigEntry entry) {
setState(() {
_entries[index] = entry;
});
_saveEntries();
}
Future<void> _showEntryDialog({int? editIndex}) async {
final isEdit = editIndex != null;
final existingEntry = isEdit ? _entries[editIndex] : null;
final keyController = TextEditingController(text: existingEntry?.key ?? '');
final valueController = TextEditingController(text: existingEntry?.value ?? '');
final result = await showDialog<bool>(
context: context,
builder: (context) => AlertDialog(
title: Text(isEdit ? t.mpvConfig.editProperty : t.mpvConfig.addProperty),
content: Column(
mainAxisSize: MainAxisSize.min,
children: [
TextField(
controller: keyController,
decoration: InputDecoration(labelText: t.mpvConfig.propertyKey, hintText: t.mpvConfig.propertyKeyHint),
autofocus: true,
),
const SizedBox(height: 16),
TextField(
controller: valueController,
decoration: InputDecoration(
labelText: t.mpvConfig.propertyValue,
hintText: t.mpvConfig.propertyValueHint,
),
),
],
),
actions: [
TextButton(onPressed: () => Navigator.pop(context, false), child: Text(t.common.cancel)),
TextButton(
onPressed: () {
if (keyController.text.isNotEmpty && valueController.text.isNotEmpty) {
Navigator.pop(context, true);
}
},
child: Text(t.common.save),
),
],
),
);
if (result == true) {
final entry = MpvConfigEntry(
key: keyController.text.trim(),
value: valueController.text.trim(),
isEnabled: existingEntry?.isEnabled ?? true,
);
if (isEdit) {
_updateEntry(editIndex, entry);
} else {
_addEntry(entry);
}
}
keyController.dispose();
valueController.dispose();
}
Future<bool> _showConfirmDeleteDialog({required String title, required String content}) async {
final result = await showDialog<bool>(
context: context,
builder: (context) => AlertDialog(
title: Text(title),
content: Text(content),
actions: [
TextButton(onPressed: () => Navigator.pop(context, false), child: Text(t.common.cancel)),
TextButton(onPressed: () => Navigator.pop(context, true), child: Text(t.common.delete)),
],
),
);
return result == true;
}
Future<void> _showDeleteEntryDialog(int index) async {
final confirmed = await _showConfirmDeleteDialog(
title: t.mpvConfig.deleteProperty,
content: t.mpvConfig.confirmDeleteProperty,
);
if (confirmed) {
_deleteEntry(index);
}
}
Future<void> _showSavePresetDialog() async {
if (_entries.isEmpty) return;
final nameController = TextEditingController();
final result = await showDialog<bool>(
context: context,
builder: (context) => AlertDialog(
title: Text(t.mpvConfig.saveAsPreset),
content: TextField(
controller: nameController,
decoration: InputDecoration(labelText: t.mpvConfig.presetName, hintText: t.mpvConfig.presetNameHint),
autofocus: true,
),
actions: [
TextButton(onPressed: () => Navigator.pop(context, false), child: Text(t.common.cancel)),
TextButton(
onPressed: () {
if (nameController.text.isNotEmpty) {
Navigator.pop(context, true);
}
},
child: Text(t.common.save),
),
],
),
);
if (result == true) {
await _settingsService.saveMpvPreset(nameController.text.trim(), _entries);
setState(() {
_presets = _settingsService.getMpvPresets();
});
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(t.mpvConfig.presetSaved)));
}
}
nameController.dispose();
}
Future<void> _loadPreset(MpvPreset preset) async {
await _settingsService.loadMpvPreset(preset.name);
setState(() {
_entries = _settingsService.getMpvConfigEntries();
});
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(t.mpvConfig.presetLoaded)));
}
}
Future<void> _deletePreset(MpvPreset preset) async {
final confirmed = await _showConfirmDeleteDialog(
title: t.mpvConfig.deletePreset,
content: t.mpvConfig.confirmDeletePreset,
);
if (confirmed) {
await _settingsService.deleteMpvPreset(preset.name);
setState(() {
_presets = _settingsService.getMpvPresets();
});
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(t.mpvConfig.presetDeleted)));
}
}
}
@override
Widget build(BuildContext context) {
if (_isLoading) {
return const Scaffold(body: Center(child: CircularProgressIndicator()));
}
return Scaffold(
body: CustomScrollView(
slivers: [
CustomAppBar(title: Text(t.screens.mpvConfig), pinned: true),
SliverPadding(
padding: const EdgeInsets.all(16),
sliver: SliverList(
delegate: SliverChildListDelegate([
_buildPresetsCard(),
const SizedBox(height: 16),
_buildEntriesCard(),
const SizedBox(height: 24),
]),
),
),
],
),
);
}
Widget _buildPresetsCard() {
return Card(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.all(16),
child: Text(
t.mpvConfig.presets,
style: Theme.of(context).textTheme.titleMedium?.copyWith(fontWeight: FontWeight.bold),
),
),
ListTile(
leading: const AppIcon(Symbols.save_rounded, fill: 1),
title: Text(t.mpvConfig.saveAsPreset),
enabled: _entries.isNotEmpty,
onTap: _entries.isNotEmpty ? _showSavePresetDialog : null,
),
if (_presets.isNotEmpty) ...[
const Divider(),
..._presets.map(
(preset) => ListTile(
leading: const AppIcon(Symbols.folder_rounded, fill: 1),
title: Text(preset.name),
subtitle: Text(t.mpvConfig.entriesCount(count: preset.entries.length)),
trailing: PopupMenuButton<String>(
onSelected: (value) {
if (value == 'load') {
_loadPreset(preset);
} else if (value == 'delete') {
_deletePreset(preset);
}
},
itemBuilder: (context) => [
PopupMenuItem(value: 'load', child: Text(t.mpvConfig.loadPreset)),
PopupMenuItem(value: 'delete', child: Text(t.mpvConfig.deletePreset)),
],
),
onTap: () => _loadPreset(preset),
),
),
] else
Padding(
padding: const EdgeInsets.fromLTRB(16, 0, 16, 16),
child: Text(
t.mpvConfig.noPresets,
style: Theme.of(
context,
).textTheme.bodyMedium?.copyWith(color: Theme.of(context).colorScheme.onSurfaceVariant),
),
),
],
),
);
}
Widget _buildEntriesCard() {
return Card(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.all(16),
child: Row(
children: [
Expanded(
child: Text(
t.mpvConfig.properties,
style: Theme.of(context).textTheme.titleMedium?.copyWith(fontWeight: FontWeight.bold),
),
),
IconButton(
icon: const AppIcon(Symbols.add_rounded, fill: 1),
onPressed: () => _showEntryDialog(),
tooltip: t.mpvConfig.addProperty,
),
],
),
),
if (_entries.isNotEmpty) ...[
const Divider(height: 1),
...List.generate(_entries.length, (index) {
final entry = _entries[index];
return ListTile(
leading: Switch(value: entry.isEnabled, onChanged: (_) => _toggleEntry(index)),
title: Text(
entry.key,
style: TextStyle(color: entry.isEnabled ? null : Theme.of(context).colorScheme.onSurfaceVariant),
),
subtitle: Text(
entry.value,
style: TextStyle(color: entry.isEnabled ? null : Theme.of(context).colorScheme.onSurfaceVariant),
),
trailing: PopupMenuButton<String>(
onSelected: (value) {
if (value == 'edit') {
_showEntryDialog(editIndex: index);
} else if (value == 'delete') {
_showDeleteEntryDialog(index);
}
},
itemBuilder: (context) => [
PopupMenuItem(value: 'edit', child: Text(t.mpvConfig.editProperty)),
PopupMenuItem(value: 'delete', child: Text(t.mpvConfig.deleteProperty)),
],
),
);
}),
] else
Padding(
padding: const EdgeInsets.fromLTRB(16, 0, 16, 16),
child: Text(
t.mpvConfig.noProperties,
style: Theme.of(
context,
).textTheme.bodyMedium?.copyWith(color: Theme.of(context).colorScheme.onSurfaceVariant),
),
),
],
),
);
}
}
+147 -2
View File
@@ -17,10 +17,13 @@ import '../../services/keyboard_shortcuts_service.dart';
import '../../services/settings_service.dart' as settings;
import '../../services/update_service.dart';
import '../../utils/snackbar_helper.dart';
import '../../utils/platform_detector.dart';
import '../../widgets/desktop_app_bar.dart';
import '../../widgets/tv_number_spinner.dart';
import 'hotkey_recorder_widget.dart';
import 'about_screen.dart';
import 'logs_screen.dart';
import 'mpv_config_screen.dart';
import 'subtitle_styling_screen.dart';
/// Helper class for option selection dialog items
@@ -57,6 +60,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
int _autoSkipDelay = 5;
bool _downloadOnWifiOnly = false;
bool _videoPlayerNavigationEnabled = false;
int _maxVolume = 100;
// Update checking state
bool _isCheckingForUpdate = false;
@@ -87,6 +91,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
_autoSkipDelay = _settingsService.getAutoSkipDelay();
_downloadOnWifiOnly = _settingsService.getDownloadOnWifiOnly();
_videoPlayerNavigationEnabled = _settingsService.getVideoPlayerNavigationEnabled();
_maxVolume = _settingsService.getMaxVolume();
_isLoading = false;
});
}
@@ -250,6 +255,15 @@ class _SettingsScreenState extends State<SettingsScreen> {
Navigator.push(context, MaterialPageRoute(builder: (context) => const SubtitleStylingScreen()));
},
),
ListTile(
leading: const AppIcon(Symbols.tune_rounded, fill: 1),
title: Text(t.mpvConfig.title),
subtitle: Text(t.mpvConfig.description),
trailing: const AppIcon(Symbols.chevron_right_rounded, fill: 1),
onTap: () {
Navigator.push(context, MaterialPageRoute(builder: (context) => const MpvConfigScreen()));
},
),
ListTile(
leading: const AppIcon(Symbols.replay_10_rounded, fill: 1),
title: Text(t.settings.smallSkipDuration),
@@ -271,6 +285,13 @@ class _SettingsScreenState extends State<SettingsScreen> {
trailing: const AppIcon(Symbols.chevron_right_rounded, fill: 1),
onTap: () => _showSleepTimerDurationDialog(),
),
ListTile(
leading: const AppIcon(Symbols.volume_up_rounded, fill: 1),
title: Text(t.settings.maxVolume),
subtitle: Text(t.settings.maxVolumePercent(percent: _maxVolume.toString())),
trailing: const AppIcon(Symbols.chevron_right_rounded, fill: 1),
onTap: () => _showMaxVolumeDialog(),
),
SwitchListTile(
secondary: const AppIcon(Symbols.bookmark_rounded, fill: 1),
title: Text(t.settings.rememberTrackSelections),
@@ -716,7 +737,9 @@ class _SettingsScreenState extends State<SettingsScreen> {
);
}
/// Generic numeric input dialog to avoid duplication across settings
/// Generic numeric input dialog to avoid duplication across settings.
/// On TV, uses a spinner widget with +/- buttons for D-pad navigation.
/// On other platforms, uses a TextField with focus management.
void _showNumericInputDialog({
required String title,
required String labelText,
@@ -725,9 +748,105 @@ class _SettingsScreenState extends State<SettingsScreen> {
required int max,
required int currentValue,
required Future<void> Function(int value) onSave,
}) {
final isTV = PlatformDetector.isTV();
if (isTV) {
_showNumericInputDialogTV(
title: title,
suffixText: suffixText,
min: min,
max: max,
currentValue: currentValue,
onSave: onSave,
);
} else {
_showNumericInputDialogStandard(
title: title,
labelText: labelText,
suffixText: suffixText,
min: min,
max: max,
currentValue: currentValue,
onSave: onSave,
);
}
}
/// TV-specific numeric input dialog with spinner widget.
void _showNumericInputDialogTV({
required String title,
required String suffixText,
required int min,
required int max,
required int currentValue,
required Future<void> Function(int value) onSave,
}) {
int spinnerValue = currentValue;
showDialog(
context: context,
builder: (BuildContext dialogContext) {
return StatefulBuilder(
builder: (context, setDialogState) {
return AlertDialog(
title: Text(title),
content: Column(
mainAxisSize: MainAxisSize.min,
children: [
TvNumberSpinner(
value: spinnerValue,
min: min,
max: max,
suffix: suffixText,
autofocus: true,
onChanged: (value) {
setDialogState(() {
spinnerValue = value;
});
},
),
const SizedBox(height: 8),
Text(
t.settings.durationHint(min: min, max: max),
style: Theme.of(
context,
).textTheme.bodySmall?.copyWith(color: Theme.of(context).colorScheme.onSurfaceVariant),
),
],
),
actions: [
TextButton(onPressed: () => Navigator.pop(dialogContext), child: Text(t.common.cancel)),
TextButton(
onPressed: () async {
await onSave(spinnerValue);
if (dialogContext.mounted) {
Navigator.pop(dialogContext);
}
},
child: Text(t.common.save),
),
],
);
},
);
},
);
}
/// Standard numeric input dialog with TextField for non-TV platforms.
void _showNumericInputDialogStandard({
required String title,
required String labelText,
required String suffixText,
required int min,
required int max,
required int currentValue,
required Future<void> Function(int value) onSave,
}) {
final controller = TextEditingController(text: currentValue.toString());
String? errorText;
final saveFocusNode = FocusNode();
showDialog(
context: context,
@@ -746,6 +865,11 @@ class _SettingsScreenState extends State<SettingsScreen> {
suffixText: suffixText,
),
autofocus: true,
textInputAction: TextInputAction.done,
onEditingComplete: () {
// Move focus to Save button when keyboard checkmark is pressed
saveFocusNode.requestFocus();
},
onChanged: (value) {
final parsed = int.tryParse(value);
setDialogState(() {
@@ -762,6 +886,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
actions: [
TextButton(onPressed: () => Navigator.pop(dialogContext), child: Text(t.common.cancel)),
TextButton(
focusNode: saveFocusNode,
onPressed: () async {
final parsed = int.tryParse(controller.text);
if (parsed != null && parsed >= min && parsed <= max) {
@@ -778,7 +903,10 @@ class _SettingsScreenState extends State<SettingsScreen> {
},
);
},
);
).then((_) {
// Clean up focus node when dialog is dismissed
saveFocusNode.dispose();
});
}
void _showSeekTimeSmallDialog() {
@@ -847,6 +975,21 @@ class _SettingsScreenState extends State<SettingsScreen> {
);
}
void _showMaxVolumeDialog() {
_showNumericInputDialog(
title: t.settings.maxVolume,
labelText: t.settings.maxVolumeDescription,
suffixText: '%',
min: 100,
max: 300,
currentValue: _maxVolume,
onSave: (value) async {
setState(() => _maxVolume = value);
await _settingsService.setMaxVolume(value);
},
);
}
void _showKeyboardShortcutsDialog() {
if (_keyboardService == null) return;
@@ -927,6 +1070,8 @@ class _SettingsScreenState extends State<SettingsScreen> {
return 'Deutsch';
case AppLocale.zh:
return '中文';
case AppLocale.ko:
return '한국어';
}
}
+250 -92
View File
@@ -86,9 +86,16 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
StreamSubscription<dynamic>? _mediaControlSubscription;
StreamSubscription<bool>? _bufferingSubscription;
StreamSubscription<Tracks>? _trackLoadingSubscription;
StreamSubscription<Duration>? _positionSubscription;
StreamSubscription<void>? _playbackRestartSubscription;
bool _isReplacingWithVideo = false; // Flag to skip orientation restoration during video-to-video navigation
bool _isDisposingForNavigation = false;
// Auto-play next episode
Timer? _autoPlayTimer;
int _autoPlayCountdown = 5;
bool _completionTriggered = false;
// App lifecycle state tracking
bool _wasPlayingBeforeInactive = false;
@@ -107,6 +114,8 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
}
final ValueNotifier<bool> _isBuffering = ValueNotifier<bool>(false); // Track if video is currently buffering
final ValueNotifier<bool> _hasFirstFrame = ValueNotifier<bool>(false); // Track if first video frame has rendered
final ValueNotifier<bool> _isExiting = ValueNotifier<bool>(false); // Track if navigating away (for black overlay)
@override
void initState() {
@@ -179,17 +188,19 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
switch (state) {
case AppLifecycleState.inactive:
// App is inactive (Control Center, Notification Screen, etc.)
// Pause video but keep media controls for quick resume (mobile only)
// App is inactive (notification shade, split-screen, etc.)
// Don't pause - user may still be watching
break;
case AppLifecycleState.hidden:
// App is being hidden (user is switching away)
// Pause video since we don't support background playback (mobile only)
if (PlatformDetector.isMobile(context)) {
if (player != null && _isPlayerInitialized) {
_wasPlayingBeforeInactive = player!.state.playing;
if (_wasPlayingBeforeInactive) {
player!.pause();
appLogger.d('Video paused due to app becoming inactive (mobile)');
appLogger.d('Video paused due to app being hidden (mobile)');
}
// Keep media controls active on mobile for quick resume
_updateMediaControlsPlaybackState();
}
}
break;
@@ -229,8 +240,7 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
}
break;
case AppLifecycleState.detached:
case AppLifecycleState.hidden:
// No action needed for these states
// No action needed for this state
break;
}
}
@@ -313,8 +323,23 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
await player!.setProperty('sub-delay', offsetSeconds.toString());
}
// Apply saved volume
final savedVolume = settingsService.getVolume();
// Apply custom MPV config entries
final customMpvConfig = settingsService.getEnabledMpvConfigEntries();
for (final entry in customMpvConfig.entries) {
try {
await player!.setProperty(entry.key, entry.value);
appLogger.d('Applied custom MPV property: ${entry.key}=${entry.value}');
} catch (e) {
appLogger.w('Failed to set MPV property ${entry.key}', error: e);
}
}
// Set max volume limit for volume boost
final maxVolume = settingsService.getMaxVolume();
await player!.setProperty('volume-max', maxVolume.toString());
// Apply saved volume (clamped to max volume)
final savedVolume = settingsService.getVolume().clamp(0.0, maxVolume.toDouble());
player!.setVolume(savedVolume);
// Notify that player is ready
@@ -368,6 +393,25 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
_isBuffering.value = isBuffering;
});
// Listen to playback restart to detect first frame ready
_playbackRestartSubscription = player!.streams.playbackRestart.listen((_) {
if (!_hasFirstFrame.value) {
_hasFirstFrame.value = true;
}
});
// Listen to position for completion detection (fallback for unreliable MPV events)
_positionSubscription = player!.streams.position.listen((position) {
final duration = player!.state.duration;
if (duration.inMilliseconds > 0 &&
position.inMilliseconds >= duration.inMilliseconds - 1000 &&
!_showPlayNextDialog &&
!_completionTriggered &&
_nextEpisode != null) {
_onVideoCompleted(true);
}
});
// Initialize services
await _initializeServices();
@@ -638,6 +682,9 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
// Open video through Player
if (result.videoUrl != null) {
// Reset first frame flag for new video
_hasFirstFrame.value = false;
// Pass resume position if available
final resumePosition = widget.metadata.viewOffset != null
? Duration(milliseconds: widget.metadata.viewOffset!)
@@ -855,12 +902,16 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
if (confirmed == true && mounted) {
await _watchTogetherProvider!.leaveSession();
if (mounted) Navigator.of(context).pop(true);
if (mounted) {
_isExiting.value = true;
Navigator.of(context).pop(true);
}
}
return;
}
// Default behavior for hosts or non-session users
_isExiting.value = true;
Navigator.of(context).pop(true);
}
@@ -884,6 +935,8 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
// Dispose value notifiers
_isBuffering.dispose();
_hasFirstFrame.dispose();
_isExiting.dispose();
// Stop progress tracking and send final state
_progressTracker?.sendProgress('stopped');
@@ -901,6 +954,11 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
_mediaControlSubscription?.cancel();
_bufferingSubscription?.cancel();
_trackLoadingSubscription?.cancel();
_positionSubscription?.cancel();
_playbackRestartSubscription?.cancel();
// Cancel auto-play timer
_autoPlayTimer?.cancel();
// Clear media controls and dispose manager
_mediaControlsManager?.clear();
@@ -942,6 +1000,13 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
}
void _onPlayingStateChanged(bool isPlaying) {
// Toggle wakelock based on playback state
if (isPlaying) {
WakelockPlus.enable();
} else {
WakelockPlus.disable();
}
// Send timeline update when playback state changes
_progressTracker?.sendProgress(isPlaying ? 'playing' : 'paused');
@@ -950,10 +1015,19 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
}
void _onVideoCompleted(bool completed) {
if (completed && _nextEpisode != null && !_showPlayNextDialog) {
if (completed && _nextEpisode != null && !_showPlayNextDialog && !_completionTriggered) {
_completionTriggered = true;
// On Linux, show the Flutter layer so the overlay is visible
if (Platform.isLinux) {
player?.setControlsVisible(true);
}
setState(() {
_showPlayNextDialog = true;
_autoPlayCountdown = 5;
});
_startAutoPlayTimer();
}
}
@@ -1001,6 +1075,9 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
Future<void> _playNext() async {
if (_nextEpisode == null || _isLoadingNext) return;
// Cancel auto-play timer if running
_autoPlayTimer?.cancel();
// Notify Watch Together of episode change before navigating
_notifyWatchTogetherMediaChange(metadata: _nextEpisode);
@@ -1021,22 +1098,49 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
await _navigateToEpisode(_previousEpisode!);
}
void _startAutoPlayTimer() {
_autoPlayTimer?.cancel();
_autoPlayTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
if (!mounted) {
timer.cancel();
return;
}
setState(() {
_autoPlayCountdown--;
});
if (_autoPlayCountdown <= 0) {
timer.cancel();
_playNext();
}
});
}
void _cancelAutoPlay() {
_autoPlayTimer?.cancel();
_completionTriggered = false; // Reset so it can trigger again if user seeks near end
setState(() {
_showPlayNextDialog = false;
});
}
/// Apply track selection using the TrackSelectionService
Future<void> _applyTrackSelection() async {
if (!mounted || player == null) return;
final profileSettings = context.read<UserProfileProvider>().profileSettings;
final trackService = TrackSelectionService(
player: player!,
profileSettings: profileSettings,
metadata: widget.metadata,
plexMediaInfo: _currentMediaInfo,
);
await trackService.selectAndApplyTracks(
preferredAudioTrack: widget.preferredAudioTrack,
preferredSubtitleTrack: widget.preferredSubtitleTrack,
preferredPlaybackRate: widget.preferredPlaybackRate,
onAudioTrackChanged: _onAudioTrackChanged,
onSubtitleTrackChanged: _onSubtitleTrackChanged,
);
}
@@ -1294,6 +1398,7 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
Future<void> disposePlayerForNavigation() async {
if (_isDisposingForNavigation) return;
_isDisposingForNavigation = true;
_isExiting.value = true; // Show black overlay during transition
try {
_detachFromWatchTogetherSession();
@@ -1411,108 +1516,161 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
},
onBack: _handleBackButton,
canControl: canControl,
hasFirstFrame: _hasFirstFrame,
),
);
},
),
),
// Play Next Dialog
// Netflix-style auto-play overlay
if (_showPlayNextDialog && _nextEpisode != null)
Positioned.fill(
Positioned(
right: 24,
bottom: 100,
child: Container(
color: Colors.black.withValues(alpha: 0.8),
child: Center(
child: Container(
margin: const EdgeInsets.symmetric(horizontal: 32),
padding: const EdgeInsets.all(32),
decoration: BoxDecoration(color: Colors.grey[900], borderRadius: BorderRadius.circular(16)),
child: Column(
mainAxisSize: MainAxisSize.min,
width: 320,
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: Colors.black.withValues(alpha: 0.9),
borderRadius: BorderRadius.circular(12),
),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
const AppIcon(Symbols.play_circle_rounded, fill: 1, size: 64, color: Colors.white),
const SizedBox(height: 24),
Consumer<PlaybackStateProvider>(
builder: (context, playbackState, child) {
final isShuffleActive = playbackState.isShuffleActive;
return Row(
mainAxisSize: MainAxisSize.min,
children: [
const Text(
'Up Next',
style: TextStyle(color: Colors.white, fontSize: 24, fontWeight: FontWeight.bold),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Consumer<PlaybackStateProvider>(
builder: (context, playbackState, child) {
final isShuffleActive = playbackState.isShuffleActive;
return Row(
children: [
Text(
'Next Episode',
style: TextStyle(
color: Colors.white.withValues(alpha: 0.7),
fontSize: 12,
fontWeight: FontWeight.w500,
),
),
if (isShuffleActive) ...[
const SizedBox(width: 4),
AppIcon(
Symbols.shuffle_rounded,
fill: 1,
size: 12,
color: Colors.white.withValues(alpha: 0.7),
),
],
],
);
},
),
const SizedBox(height: 4),
if (_nextEpisode!.parentIndex != null && _nextEpisode!.index != null)
Text(
'S${_nextEpisode!.parentIndex} E${_nextEpisode!.index} · ${_nextEpisode!.title}',
style: const TextStyle(
color: Colors.white,
fontSize: 14,
fontWeight: FontWeight.w600,
),
maxLines: 2,
overflow: TextOverflow.ellipsis,
)
else
Text(
_nextEpisode!.title,
style: const TextStyle(
color: Colors.white,
fontSize: 14,
fontWeight: FontWeight.w600,
),
maxLines: 2,
overflow: TextOverflow.ellipsis,
),
if (isShuffleActive) ...[
const SizedBox(width: 8),
const AppIcon(Symbols.shuffle_rounded, fill: 1, size: 20, color: Colors.white70),
],
],
);
},
),
const SizedBox(height: 16),
Text(
_nextEpisode!.grandparentTitle ?? _nextEpisode!.title,
style: const TextStyle(color: Colors.white, fontSize: 18),
textAlign: TextAlign.center,
),
const SizedBox(height: 8),
if (_nextEpisode!.parentIndex != null && _nextEpisode!.index != null)
Text(
'S${_nextEpisode!.parentIndex} · E${_nextEpisode!.index} · ${_nextEpisode!.title}',
style: const TextStyle(color: Colors.white70, fontSize: 16),
textAlign: TextAlign.center,
],
),
const SizedBox(height: 32),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
OutlinedButton(
onPressed: () {
setState(() {
_showPlayNextDialog = false;
});
},
style: OutlinedButton.styleFrom(
foregroundColor: Colors.white,
side: const BorderSide(color: Colors.white),
padding: const EdgeInsets.symmetric(horizontal: 32, vertical: 16),
),
child: Text(t.dialog.cancel),
),
const SizedBox(width: 16),
FilledButton(
onPressed: _playNext,
style: FilledButton.styleFrom(
backgroundColor: Colors.white,
foregroundColor: Colors.black,
padding: const EdgeInsets.symmetric(horizontal: 32, vertical: 16),
),
child: Text(t.dialog.playNow),
),
],
),
],
),
),
const SizedBox(height: 12),
Row(
children: [
Expanded(
child: OutlinedButton(
onPressed: _cancelAutoPlay,
style: OutlinedButton.styleFrom(
foregroundColor: Colors.white,
side: BorderSide(color: Colors.white.withValues(alpha: 0.5)),
padding: const EdgeInsets.symmetric(vertical: 12),
),
child: Text(t.dialog.cancel),
),
),
const SizedBox(width: 8),
Expanded(
child: FilledButton(
onPressed: _playNext,
style: FilledButton.styleFrom(
backgroundColor: Colors.white,
foregroundColor: Colors.black,
padding: const EdgeInsets.symmetric(vertical: 12),
),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('$_autoPlayCountdown'),
const SizedBox(width: 4),
const AppIcon(Symbols.play_arrow_rounded, fill: 1, size: 18),
],
),
),
),
],
),
],
),
),
),
// Buffering indicator
// Buffering indicator (also shows during initial load, but not when exiting)
ValueListenableBuilder<bool>(
valueListenable: _isBuffering,
builder: (context, isBuffering, child) {
if (!isBuffering) return const SizedBox.shrink();
return Positioned.fill(
child: Center(
child: Container(
padding: const EdgeInsets.all(20),
decoration: BoxDecoration(color: Colors.black.withValues(alpha: 0.5), shape: BoxShape.circle),
child: const CircularProgressIndicator(color: Colors.white, strokeWidth: 3),
),
),
return ValueListenableBuilder<bool>(
valueListenable: _hasFirstFrame,
builder: (context, hasFrame, child) {
// Don't show spinner when exiting (just black overlay)
// Show spinner when (buffering OR loading) AND NOT exiting
if ((!isBuffering && hasFrame) || _isExiting.value) return const SizedBox.shrink();
return Positioned.fill(
child: Center(
child: Container(
padding: const EdgeInsets.all(20),
decoration: BoxDecoration(
color: Colors.black.withValues(alpha: 0.5),
shape: BoxShape.circle,
),
child: const CircularProgressIndicator(color: Colors.white, strokeWidth: 3),
),
),
);
},
);
},
),
// Black overlay during exit (no spinner - just covers transparency)
ValueListenableBuilder<bool>(
valueListenable: _isExiting,
builder: (context, isExiting, child) {
if (!isExiting) return const SizedBox.shrink();
return Positioned.fill(child: Container(color: Colors.black));
},
),
],
),
),
+29 -67
View File
@@ -247,15 +247,11 @@ class DataAggregationService {
// Private helper methods
/// Higher-order helper for per-server fan-out operations
/// Base helper for per-server fan-out operations
///
/// Iterates over all online clients, executes the operation for each server,
/// handles errors, updates server status, and aggregates results.
///
/// Type parameter `T` is the item type returned by the operation
/// [operationName] is used for logging (e.g., "fetching libraries")
/// [operation] is the async function to run per server, returning `List<T>`
Future<List<T>> _perServer<T>({
/// Returns raw results as (serverId, result) tuples.
/// Used by [_perServer] and [_perServerGrouped] for different aggregation strategies.
Future<List<(String serverId, List<T> result)>> _perServerRaw<T>({
required String operationName,
required Future<List<T>> Function(String serverId, PlexClient client, PlexServer? server) operation,
}) async {
@@ -268,61 +264,6 @@ class DataAggregationService {
appLogger.d('$operationName from ${clients.length} servers');
final allResults = <T>[];
// Execute operation on all servers in parallel
final Iterable<Future<List<T>>> futures = clients.entries.map((entry) async {
final serverId = entry.key;
final client = entry.value;
final server = _serverManager.getServer(serverId);
final sw = Stopwatch()..start();
try {
final result = await operation(serverId, client, server);
appLogger.d(
'$operationName for server $serverId completed in ${sw.elapsedMilliseconds}ms with ${result.length} items',
);
return result;
} catch (e, stackTrace) {
appLogger.e('Failed $operationName from server $serverId', error: e, stackTrace: stackTrace);
_serverManager.updateServerStatus(serverId, false);
appLogger.d('$operationName for server $serverId failed after ${sw.elapsedMilliseconds}ms');
return <T>[];
}
});
final List<List<T>> results = await Future.wait<List<T>>(futures);
// Flatten results
for (final items in results) {
allResults.addAll(items);
}
return allResults;
}
/// Higher-order helper for per-server fan-out operations that groups results by server
///
/// Similar to [_perServer] but returns a Map with results grouped by serverId
/// instead of flattening into a single list.
///
/// Type parameter `T` is the item type returned by the operation
/// [operationName] is used for logging (e.g., "fetching libraries")
/// [operation] is the async function to run per server, returning `List<T>`
Future<Map<String, List<T>>> _perServerGrouped<T>({
required String operationName,
required Future<List<T>> Function(String serverId, PlexClient client, PlexServer? server) operation,
}) async {
final clients = _serverManager.onlineClients;
if (clients.isEmpty) {
appLogger.w('No online servers available for $operationName');
return {};
}
appLogger.d('$operationName from ${clients.length} servers');
// Execute operation on all servers in parallel
final futures = clients.entries.map((entry) async {
final serverId = entry.key;
final client = entry.value;
@@ -334,17 +275,38 @@ class DataAggregationService {
appLogger.d(
'$operationName for server $serverId completed in ${sw.elapsedMilliseconds}ms with ${result.length} items',
);
return MapEntry(serverId, result);
return (serverId, result);
} catch (e, stackTrace) {
appLogger.e('Failed $operationName from server $serverId', error: e, stackTrace: stackTrace);
_serverManager.updateServerStatus(serverId, false);
appLogger.d('$operationName for server $serverId failed after ${sw.elapsedMilliseconds}ms');
return MapEntry(serverId, <T>[]);
return (serverId, <T>[]);
}
});
final results = await Future.wait(futures);
return await Future.wait(futures);
}
return Map.fromEntries(results);
/// Higher-order helper for per-server fan-out operations
///
/// Iterates over all online clients, executes the operation for each server,
/// handles errors, updates server status, and flattens results into a single list.
Future<List<T>> _perServer<T>({
required String operationName,
required Future<List<T>> Function(String serverId, PlexClient client, PlexServer? server) operation,
}) async {
final results = await _perServerRaw(operationName: operationName, operation: operation);
return [for (final (_, items) in results) ...items];
}
/// Higher-order helper for per-server fan-out operations that groups results by server
///
/// Similar to [_perServer] but returns a Map with results grouped by serverId.
Future<Map<String, List<T>>> _perServerGrouped<T>({
required String operationName,
required Future<List<T>> Function(String serverId, PlexClient client, PlexServer? server) operation,
}) async {
final results = await _perServerRaw(operationName: operationName, operation: operation);
return {for (final (id, items) in results) id: items};
}
}
+161
View File
@@ -0,0 +1,161 @@
import 'dart:io' show Platform;
import 'package:in_app_review/in_app_review.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../utils/app_logger.dart';
/// Service to manage in-app review prompts
/// Only enabled when ENABLE_IN_APP_REVIEW build flag is set
class InAppReviewService {
static final InAppReviewService _instance = InAppReviewService._();
static InAppReviewService get instance => _instance;
InAppReviewService._();
final InAppReview _inAppReview = InAppReview.instance;
// SharedPreferences keys
static const String _keyQualifyingSessionsCount = 'review_qualifying_sessions_count';
static const String _keyLastPromptTime = 'review_last_prompt_time';
// Configuration
static const int _requiredSessions = 6;
static const Duration _minimumSessionDuration = Duration(minutes: 5);
static const Duration _promptCooldown = Duration(days: 60);
// Session tracking
DateTime? _sessionStartTime;
/// Check if in-app review is enabled via build flag
/// Only enabled on mobile platforms (iOS and Android)
static bool get isEnabled {
if (!Platform.isIOS && !Platform.isAndroid) {
return false;
}
const enabled = bool.fromEnvironment('ENABLE_IN_APP_REVIEW', defaultValue: false);
return enabled;
}
/// Start tracking a new session
void startSession() {
if (!isEnabled) return;
_sessionStartTime = DateTime.now();
appLogger.d('In-app review: Session started');
}
/// End the current session and check if it qualifies
/// Call this when app goes to background or is closed
Future<void> endSession() async {
if (!isEnabled || _sessionStartTime == null) return;
final sessionDuration = DateTime.now().difference(_sessionStartTime!);
_sessionStartTime = null;
if (sessionDuration >= _minimumSessionDuration) {
await _incrementQualifyingSessions();
appLogger.d('In-app review: Qualifying session ended (${sessionDuration.inMinutes} minutes)');
await maybeRequestReview();
} else {
appLogger.d('In-app review: Session too short (${sessionDuration.inMinutes} minutes)');
}
}
/// Increment the qualifying sessions counter
Future<void> _incrementQualifyingSessions() async {
final prefs = await SharedPreferences.getInstance();
final currentCount = prefs.getInt(_keyQualifyingSessionsCount) ?? 0;
await prefs.setInt(_keyQualifyingSessionsCount, currentCount + 1);
}
/// Get the current qualifying sessions count
Future<int> _getQualifyingSessionsCount() async {
final prefs = await SharedPreferences.getInstance();
return prefs.getInt(_keyQualifyingSessionsCount) ?? 0;
}
/// Check if we should request a review based on session count and cooldown
Future<bool> _shouldRequestReview() async {
final prefs = await SharedPreferences.getInstance();
// Check session count
final sessionCount = await _getQualifyingSessionsCount();
if (sessionCount < _requiredSessions) {
appLogger.d('In-app review: Not enough sessions ($sessionCount/$_requiredSessions)');
return false;
}
// Check cooldown
final lastPromptString = prefs.getString(_keyLastPromptTime);
if (lastPromptString != null) {
final lastPrompt = DateTime.parse(lastPromptString);
final timeSinceLastPrompt = DateTime.now().difference(lastPrompt);
if (timeSinceLastPrompt < _promptCooldown) {
final daysRemaining = (_promptCooldown - timeSinceLastPrompt).inDays;
appLogger.d('In-app review: Cooldown active ($daysRemaining days remaining)');
return false;
}
}
return true;
}
/// Request a review if conditions are met
Future<void> maybeRequestReview() async {
if (!isEnabled) return;
final shouldRequest = await _shouldRequestReview();
if (!shouldRequest) return;
try {
// Check if in-app review is available on this device
final isAvailable = await _inAppReview.isAvailable();
if (!isAvailable) {
appLogger.d('In-app review: Not available on this device');
return;
}
// Request the review
await _inAppReview.requestReview();
appLogger.i('In-app review: Review prompt shown');
// Record that we showed the prompt and reset session count
await _recordPromptShown();
} catch (e) {
appLogger.e('In-app review: Error requesting review', error: e);
}
}
/// Record that the review prompt was shown
Future<void> _recordPromptShown() async {
final prefs = await SharedPreferences.getInstance();
await prefs.setString(_keyLastPromptTime, DateTime.now().toIso8601String());
// Reset session count so user needs to use app more before next prompt
await prefs.setInt(_keyQualifyingSessionsCount, 0);
}
/// Get debug info about the current state (for development/testing)
Future<Map<String, dynamic>> getDebugInfo() async {
final prefs = await SharedPreferences.getInstance();
final sessionCount = prefs.getInt(_keyQualifyingSessionsCount) ?? 0;
final lastPromptString = prefs.getString(_keyLastPromptTime);
final isAvailable = await _inAppReview.isAvailable();
return {
'isEnabled': isEnabled,
'isAvailable': isAvailable,
'qualifyingSessions': sessionCount,
'requiredSessions': _requiredSessions,
'lastPromptTime': lastPromptString,
'cooldownDays': _promptCooldown.inDays,
'currentSessionStartTime': _sessionStartTime?.toIso8601String(),
};
}
/// Reset all stored data (for testing purposes)
Future<void> reset() async {
final prefs = await SharedPreferences.getInstance();
await prefs.remove(_keyQualifyingSessionsCount);
await prefs.remove(_keyLastPromptTime);
_sessionStartTime = null;
appLogger.d('In-app review: State reset');
}
}
+4 -2
View File
@@ -14,6 +14,7 @@ class KeyboardShortcutsService {
Map<String, HotKey> _hotkeys = {}; // New HotKey objects
int _seekTimeSmall = 10; // Default, loaded from settings
int _seekTimeLarge = 30; // Default, loaded from settings
int _maxVolume = 100; // Default, loaded from settings (100-300%)
KeyboardShortcutsService._();
@@ -38,6 +39,7 @@ class KeyboardShortcutsService {
_hotkeys = await _settingsService.getKeyboardHotkeys(); // Primary method
_seekTimeSmall = _settingsService.getSeekTimeSmall();
_seekTimeLarge = _settingsService.getSeekTimeLarge();
_maxVolume = _settingsService.getMaxVolume();
}
Map<String, String> get shortcuts => Map.from(_shortcuts);
@@ -258,12 +260,12 @@ class KeyboardShortcutsService {
player.playOrPause();
break;
case 'volume_up':
final newVolume = (player.state.volume + 10).clamp(0.0, 100.0);
final newVolume = (player.state.volume + 10).clamp(0.0, _maxVolume.toDouble());
player.setVolume(newVolume);
_settingsService.setVolume(newVolume);
break;
case 'volume_down':
final newVolume = (player.state.volume - 10).clamp(0.0, 100.0);
final newVolume = (player.state.volume - 10).clamp(0.0, _maxVolume.toDouble());
player.setVolume(newVolume);
_settingsService.setVolume(newVolume);
break;
+2 -4
View File
@@ -533,7 +533,6 @@ class PlexClient {
final streamType = stream['streamType'] as int?;
if (streamType == PlexStreamType.audio) {
// Audio track
audioTracks.add(
PlexAudioTrack(
id: stream['id'] as int,
@@ -544,11 +543,10 @@ class PlexClient {
title: stream['title'] as String?,
displayTitle: stream['displayTitle'] as String?,
channels: stream['channels'] as int?,
selected: stream['selected'] == 1,
selected: stream['selected'] == 1 || stream['selected'] == true,
),
);
} else if (streamType == PlexStreamType.subtitle) {
// Subtitle track
subtitleTracks.add(
PlexSubtitleTrack(
id: stream['id'] as int,
@@ -558,7 +556,7 @@ class PlexClient {
languageCode: stream['languageCode'] as String?,
title: stream['title'] as String?,
displayTitle: stream['displayTitle'] as String?,
selected: stream['selected'] == 1,
selected: stream['selected'] == 1 || stream['selected'] == true,
forced: stream['forced'] == 1,
key: stream['key'] as String?,
),
+105 -2
View File
@@ -3,6 +3,7 @@ import 'package:flutter/services.dart';
import 'package:hotkey_manager/hotkey_manager.dart';
import 'package:plezy/utils/app_logger.dart';
import '../i18n/strings.g.dart';
import '../models/mpv_config_models.dart';
import 'base_shared_preferences_service.dart';
import '../utils/platform_detector.dart';
@@ -49,6 +50,10 @@ class SettingsService extends BaseSharedPreferencesService {
static const String _keyCustomDownloadPathType = 'custom_download_path_type';
static const String _keyDownloadOnWifiOnly = 'download_on_wifi_only';
static const String _keyVideoPlayerNavigationEnabled = 'video_player_navigation_enabled';
static const String _keyShowPerformanceOverlay = 'show_performance_overlay';
static const String _keyMpvConfigEntries = 'mpv_config_entries';
static const String _keyMpvConfigPresets = 'mpv_config_presets';
static const String _keyMaxVolume = 'max_volume';
SettingsService._();
@@ -218,6 +223,15 @@ class SettingsService extends BaseSharedPreferencesService {
return prefs.getDouble(_keyVolume) ?? 100.0; // Default: full volume
}
// Max Volume (100-300%, for volume boost)
Future<void> setMaxVolume(int percent) async {
await prefs.setInt(_keyMaxVolume, percent.clamp(100, 300));
}
int getMaxVolume() {
return prefs.getInt(_keyMaxVolume) ?? 100; // Default: 100% (no boost)
}
// Rotation Lock (mobile only)
Future<void> setRotationLocked(bool locked) async {
await prefs.setBool(_keyRotationLocked, locked);
@@ -431,6 +445,15 @@ class SettingsService extends BaseSharedPreferencesService {
return prefs.getBool(_keyVideoPlayerNavigationEnabled) ?? TvDetectionService.isTVSync();
}
// Performance Overlay (show debug stats on video player)
Future<void> setShowPerformanceOverlay(bool enabled) async {
await prefs.setBool(_keyShowPerformanceOverlay, enabled);
}
bool getShowPerformanceOverlay() {
return prefs.getBool(_keyShowPerformanceOverlay) ?? false; // Default: disabled
}
// Helper methods for HotKey serialization
static const _modifierMap = <String, HotKeyModifier>{
'alt': HotKeyModifier.alt,
@@ -442,7 +465,10 @@ class SettingsService extends BaseSharedPreferencesService {
};
Map<String, dynamic> _serializeHotKey(HotKey hotKey) {
return {'key': hotKey.key.toString(), 'modifiers': hotKey.modifiers?.map((m) => m.name).toList() ?? []};
// Use USB HID code for reliable serialization across debug/release modes
final physicalKey = hotKey.key as PhysicalKeyboardKey;
final usbHidCode = physicalKey.usbHidUsage.toRadixString(16).padLeft(8, '0');
return {'key': usbHidCode, 'modifiers': hotKey.modifiers?.map((m) => m.name).toList() ?? []};
}
HotKey? _deserializeHotKey(Map<String, dynamic> data) {
@@ -456,7 +482,8 @@ class SettingsService extends BaseSharedPreferencesService {
.cast<HotKeyModifier>()
.toList();
final key = _findKeyByString(keyString);
// Try direct USB HID lookup first (new format), fall back to string parsing (backwards compat)
final key = _usbHidKeyMap[keyString] ?? _findKeyByString(keyString);
if (key != null) {
return HotKey(key: key, modifiers: modifiers.isNotEmpty ? modifiers : null);
}
@@ -795,6 +822,78 @@ class SettingsService extends BaseSharedPreferencesService {
return prefs.getBool(_keyDownloadOnWifiOnly) ?? false;
}
// MPV Config Entries
/// Get all MPV config entries
List<MpvConfigEntry> getMpvConfigEntries() {
final jsonString = prefs.getString(_keyMpvConfigEntries);
if (jsonString == null) return [];
try {
final List<dynamic> decoded = json.decode(jsonString);
return decoded.map((e) => MpvConfigEntry.fromJson(e as Map<String, dynamic>)).toList();
} catch (e) {
return [];
}
}
/// Save all MPV config entries
Future<void> setMpvConfigEntries(List<MpvConfigEntry> entries) async {
final jsonString = json.encode(entries.map((e) => e.toJson()).toList());
await prefs.setString(_keyMpvConfigEntries, jsonString);
}
/// Get only enabled MPV config entries (for player initialization)
Map<String, String> getEnabledMpvConfigEntries() {
final entries = getMpvConfigEntries();
return Map.fromEntries(entries.where((e) => e.isEnabled).map((e) => MapEntry(e.key, e.value)));
}
// MPV Presets
/// Get all saved presets
List<MpvPreset> getMpvPresets() {
final jsonString = prefs.getString(_keyMpvConfigPresets);
if (jsonString == null) return [];
try {
final List<dynamic> decoded = json.decode(jsonString);
return decoded.map((e) => MpvPreset.fromJson(e as Map<String, dynamic>)).toList();
} catch (e) {
return [];
}
}
/// Save a new preset (overwrites existing with same name)
Future<void> saveMpvPreset(String name, List<MpvConfigEntry> entries) async {
final presets = getMpvPresets();
// Remove existing preset with same name
presets.removeWhere((p) => p.name == name);
presets.add(MpvPreset(name: name, entries: entries, createdAt: DateTime.now()));
final jsonString = json.encode(presets.map((p) => p.toJson()).toList());
await prefs.setString(_keyMpvConfigPresets, jsonString);
}
/// Delete a preset by name
Future<void> deleteMpvPreset(String name) async {
final presets = getMpvPresets();
presets.removeWhere((p) => p.name == name);
final jsonString = json.encode(presets.map((p) => p.toJson()).toList());
await prefs.setString(_keyMpvConfigPresets, jsonString);
}
/// Load a preset (replaces current entries)
Future<void> loadMpvPreset(String name) async {
final presets = getMpvPresets();
final preset = presets.firstWhere((p) => p.name == name, orElse: () => throw Exception('Preset not found: $name'));
await setMpvConfigEntries(preset.entries);
}
// Reset all settings to defaults
Future<void> resetAllSettings() async {
await Future.wait([
@@ -818,6 +917,7 @@ class SettingsService extends BaseSharedPreferencesService {
prefs.remove(_keyAudioSyncOffset),
prefs.remove(_keySubtitleSyncOffset),
prefs.remove(_keyVolume),
prefs.remove(_keyMaxVolume),
prefs.remove(_keySubtitleFontSize),
prefs.remove(_keySubtitleTextColor),
prefs.remove(_keySubtitleBorderSize),
@@ -830,6 +930,9 @@ class SettingsService extends BaseSharedPreferencesService {
prefs.remove(_keyCustomDownloadPathType),
prefs.remove(_keyDownloadOnWifiOnly),
prefs.remove(_keyVideoPlayerNavigationEnabled),
prefs.remove(_keyShowPerformanceOverlay),
prefs.remove(_keyMpvConfigEntries),
prefs.remove(_keyMpvConfigPresets),
]);
}
+105 -219
View File
@@ -1,18 +1,38 @@
import '../mpv/mpv.dart';
import '../models/plex_media_info.dart';
import '../models/plex_metadata.dart';
import '../models/plex_user_profile.dart';
import '../utils/app_logger.dart';
import '../utils/language_codes.dart';
/// Priority levels for track selection
enum TrackSelectionPriority {
navigation, // Priority 1: User's manual selection from previous episode
plexSelected, // Priority 2: Plex's selected track
perMedia, // Priority 3: Per-media language preference
profile, // Priority 4: User profile preferences
defaultTrack, // Priority 5: Default or first track
off, // Priority 6: Subtitles off (subtitle only)
}
/// Result of track selection including the selected track and which priority was used
class TrackSelectionResult<T> {
final T track;
final TrackSelectionPriority priority;
TrackSelectionResult(this.track, this.priority);
}
/// Service for selecting and applying audio and subtitle tracks based on
/// preferences, user profiles, and per-media settings.
class TrackSelectionService {
final Player player;
final PlexUserProfile? profileSettings;
final PlexMetadata metadata;
final PlexMediaInfo? plexMediaInfo;
TrackSelectionService({required this.player, this.profileSettings, required this.metadata});
TrackSelectionService({required this.player, this.profileSettings, required this.metadata, this.plexMediaInfo});
/// Build list of preferred languages from a user profile
List<String> _buildPreferredLanguages(PlexUserProfile profile, {required bool isAudio}) {
@@ -38,8 +58,6 @@ class TrackSelectionService {
String trackType,
) {
final languageVariations = LanguageCodes.getVariations(preferredLanguage);
appLogger.d('Checking language variations for "$preferredLanguage": ${languageVariations.join(", ")}');
return _findTrackByLanguageVariations<T>(
tracks,
preferredLanguage,
@@ -53,11 +71,7 @@ class TrackSelectionService {
/// Apply a filter to tracks, falling back to original if filter produces empty result
List<T> _applyFilterWithFallback<T>(List<T> tracks, List<T> Function(List<T>) filter, String filterDescription) {
final filtered = filter(tracks);
if (filtered.isNotEmpty) {
return filtered;
}
appLogger.d('No tracks match $filterDescription, using all tracks');
return tracks;
return filtered.isNotEmpty ? filtered : tracks;
}
/// Generic track matching for audio and subtitle tracks
@@ -111,28 +125,11 @@ class TrackSelectionService {
}
AudioTrack? findAudioTrackByProfile(List<AudioTrack> availableTracks, PlexUserProfile profile) {
appLogger.d('Audio track selection using user profile');
appLogger.d(
'Profile settings - autoSelectAudio: ${profile.autoSelectAudio}, defaultAudioLanguage: ${profile.defaultAudioLanguage}, defaultAudioLanguages: ${profile.defaultAudioLanguages}',
);
if (availableTracks.isEmpty || !profile.autoSelectAudio) {
appLogger.d(
'Cannot use profile: ${availableTracks.isEmpty ? "No tracks available" : "autoSelectAudio is false"}',
);
return null;
}
if (availableTracks.isEmpty || !profile.autoSelectAudio) return null;
final preferredLanguages = _buildPreferredLanguages(profile, isAudio: true);
if (preferredLanguages.isEmpty) return null;
if (preferredLanguages.isEmpty) {
appLogger.d('Cannot use profile: No defaultAudioLanguage(s) specified');
return null;
}
appLogger.d('Preferred languages: ${preferredLanguages.join(", ")}');
// Try to find track matching any preferred language
for (final preferredLanguage in preferredLanguages) {
final match = _findTrackByPreferredLanguage<AudioTrack>(
availableTracks,
@@ -144,7 +141,6 @@ class TrackSelectionService {
if (match != null) return match;
}
appLogger.d('No audio track found matching profile languages or their variations');
return null;
}
@@ -168,69 +164,35 @@ class TrackSelectionService {
PlexUserProfile profile, {
AudioTrack? selectedAudioTrack,
}) {
appLogger.d('Subtitle track selection using user profile');
appLogger.d(
'Profile settings - autoSelectSubtitle: ${profile.autoSelectSubtitle}, defaultSubtitleLanguage: ${profile.defaultSubtitleLanguage}, defaultSubtitleLanguages: ${profile.defaultSubtitleLanguages}, defaultSubtitleForced: ${profile.defaultSubtitleForced}, defaultSubtitleAccessibility: ${profile.defaultSubtitleAccessibility}',
);
if (availableTracks.isEmpty) {
appLogger.d('Cannot use profile: No subtitle tracks available');
return null;
}
if (availableTracks.isEmpty) return null;
// Mode 0: Manually selected - return OFF
if (profile.autoSelectSubtitle == 0) {
appLogger.d('Profile specifies manual mode (autoSelectSubtitle=0) - Subtitles OFF');
return SubtitleTrack.off;
}
if (profile.autoSelectSubtitle == 0) return SubtitleTrack.off;
// Mode 1: Shown with foreign audio
if (profile.autoSelectSubtitle == 1) {
appLogger.d('Profile specifies foreign audio mode (autoSelectSubtitle=1)');
// Check if audio language matches user's preferred subtitle language
if (selectedAudioTrack != null && profile.defaultSubtitleLanguage != null) {
final audioLang = selectedAudioTrack.language?.toLowerCase();
final prefLang = profile.defaultSubtitleLanguage!.toLowerCase();
final languageVariations = LanguageCodes.getVariations(prefLang);
appLogger.d('Checking if audio is foreign - audio: $audioLang, preferred subtitle lang: $prefLang');
// If audio matches preferred language, no subtitles needed
if (audioLang != null && languageVariations.contains(audioLang)) {
appLogger.d('Audio matches preferred language - Subtitles OFF');
return SubtitleTrack.off;
}
appLogger.d('Foreign audio detected - enabling subtitles');
}
// Foreign audio detected or cannot determine, enable subtitles
}
// Mode 2: Always enabled (or continuing from mode 1 with foreign audio)
appLogger.d('Selecting subtitle track based on preferences');
final preferredLanguages = _buildPreferredLanguages(profile, isAudio: false);
if (preferredLanguages.isEmpty) {
appLogger.d('Cannot use profile: No defaultSubtitleLanguage(s) specified');
return null;
}
appLogger.d('Preferred languages: ${preferredLanguages.join(", ")}');
if (preferredLanguages.isEmpty) return null;
// Apply filtering with fallback to original tracks if filter produces empty result
var candidateTracks = availableTracks;
// Filter by SDH (defaultSubtitleAccessibility: 0-3)
candidateTracks = filterSubtitlesBySDH(candidateTracks, profile.defaultSubtitleAccessibility);
// Filter by forced subtitle preference (defaultSubtitleForced: 0-3)
candidateTracks = filterSubtitlesByForced(candidateTracks, profile.defaultSubtitleForced);
// If no candidates after filtering, relax filters
candidateTracks = _applyFilterWithFallback(availableTracks, (_) => candidateTracks, 'strict filters');
// Try to find track matching any preferred language
for (final preferredLanguage in preferredLanguages) {
final match = _findTrackByPreferredLanguage<SubtitleTrack>(
candidateTracks,
@@ -242,7 +204,6 @@ class TrackSelectionService {
if (match != null) return match;
}
appLogger.d('No subtitle track found matching profile languages or their variations');
return null;
}
@@ -255,27 +216,13 @@ class TrackSelectionService {
/// - 3: Only show non-SDH subtitles
List<SubtitleTrack> filterSubtitlesBySDH(List<SubtitleTrack> tracks, int preference) {
if (preference == 0 || preference == 1) {
// Prefer but don't require
final preferSDH = preference == 1;
final preferred = tracks.where((t) => isSDH(t) == preferSDH).toList();
if (preferred.isNotEmpty) {
appLogger.d(
'Applying SDH preference: ${preferSDH ? "prefer SDH" : "prefer non-SDH"} (${preferred.length} tracks)',
);
return preferred;
}
appLogger.d('No tracks match SDH preference, using all tracks');
return tracks;
return preferred.isNotEmpty ? preferred : tracks;
} else if (preference == 2) {
// Only SDH
final filtered = tracks.where((t) => isSDH(t)).toList();
appLogger.d('Filtering to SDH only (${filtered.length} tracks)');
return filtered;
return tracks.where((t) => isSDH(t)).toList();
} else if (preference == 3) {
// Only non-SDH
final filtered = tracks.where((t) => !isSDH(t)).toList();
appLogger.d('Filtering to non-SDH only (${filtered.length} tracks)');
return filtered;
return tracks.where((t) => !isSDH(t)).toList();
}
return tracks;
}
@@ -289,27 +236,13 @@ class TrackSelectionService {
/// - 3: Only show non-forced subtitles
List<SubtitleTrack> filterSubtitlesByForced(List<SubtitleTrack> tracks, int preference) {
if (preference == 0 || preference == 1) {
// Prefer but don't require
final preferForced = preference == 1;
final preferred = tracks.where((t) => isForced(t) == preferForced).toList();
if (preferred.isNotEmpty) {
appLogger.d(
'Applying forced preference: ${preferForced ? "prefer forced" : "prefer non-forced"} (${preferred.length} tracks)',
);
return preferred;
}
appLogger.d('No tracks match forced preference, using all tracks');
return tracks;
return preferred.isNotEmpty ? preferred : tracks;
} else if (preference == 2) {
// Only forced
final filtered = tracks.where((t) => isForced(t)).toList();
appLogger.d('Filtering to forced only (${filtered.length} tracks)');
return filtered;
return tracks.where((t) => isForced(t)).toList();
} else if (preference == 3) {
// Only non-forced
final filtered = tracks.where((t) => !isForced(t)).toList();
appLogger.d('Filtering to non-forced only (${filtered.length} tracks)');
return filtered;
return tracks.where((t) => !isForced(t)).toList();
}
return tracks;
}
@@ -346,9 +279,6 @@ class TrackSelectionService {
for (var track in tracks) {
final trackLang = getLanguage(track)?.toLowerCase();
if (trackLang != null && languageVariations.any((lang) => trackLang.startsWith(lang))) {
appLogger.d(
'Found $trackType matching profile language "$preferredLanguage" (matched: "$trackLang"): ${getTrackDescription(track)}',
);
return track;
}
}
@@ -383,178 +313,133 @@ class TrackSelectionService {
return variations.contains(trackBase);
}
/// Log available tracks for debugging
void logAvailableTracks(List<AudioTrack> audioTracks, List<SubtitleTrack> subtitleTracks) {
appLogger.d('Available audio tracks: ${audioTracks.length}');
for (var track in audioTracks) {
appLogger.d(
' - ${track.title ?? "Track ${track.id}"} (${track.language ?? "unknown"}) ${track.isDefault == true ? "[DEFAULT]" : ""}',
);
}
appLogger.d('Available subtitle tracks: ${subtitleTracks.length}');
for (var track in subtitleTracks) {
appLogger.d(
' - ${track.title ?? "Track ${track.id}"} (${track.language ?? "unknown"}) ${track.isDefault == true ? "[DEFAULT]" : ""}',
);
}
}
/// Select the best audio track based on priority:
/// Priority 1: Preferred track from navigation
/// Priority 2: Per-media language preference
/// Priority 3: User profile preferences
/// Priority 4: Default or first track
AudioTrack? selectAudioTrack(List<AudioTrack> availableTracks, AudioTrack? preferredAudioTrack) {
/// Priority 2: Plex-selected track from media info
/// Priority 3: Per-media language preference
/// Priority 4: User profile preferences
/// Priority 5: Default or first track
TrackSelectionResult<AudioTrack>? selectAudioTrack(
List<AudioTrack> availableTracks,
AudioTrack? preferredAudioTrack,
) {
if (availableTracks.isEmpty) return null;
AudioTrack? trackToSelect;
// Priority 1: Try to match preferred track from navigation
if (preferredAudioTrack != null) {
appLogger.d('Priority 1: Checking preferred track from navigation');
appLogger.d(
' Preferred: ${preferredAudioTrack.title ?? "Track ${preferredAudioTrack.id}"} (${preferredAudioTrack.language ?? "unknown"})',
);
trackToSelect = findBestAudioMatch(availableTracks, preferredAudioTrack);
if (trackToSelect != null) {
appLogger.d(' Matched preferred track');
return trackToSelect;
return TrackSelectionResult(trackToSelect, TrackSelectionPriority.navigation);
}
appLogger.d(' No match found for preferred track');
} else {
appLogger.d('Priority 1: No preferred track from navigation');
}
// Priority 2: If no preferred track matched, try per-media language preference
if (metadata.audioLanguage != null) {
appLogger.d('Priority 2: Checking per-media audio language preference');
appLogger.d(' Per-media audio language: ${metadata.audioLanguage}');
// Priority 2: Check Plex-selected track from media info
if (plexMediaInfo != null) {
final plexAudioTracks = plexMediaInfo!.audioTracks;
final plexSelectedIndex = plexAudioTracks.indexWhere((t) => t.selected);
if (plexSelectedIndex >= 0 && plexSelectedIndex < availableTracks.length) {
return TrackSelectionResult(availableTracks[plexSelectedIndex], TrackSelectionPriority.plexSelected);
}
}
// Priority 3: Try per-media language preference
if (metadata.audioLanguage != null) {
final matchedTrack = availableTracks.firstWhere(
(track) => languageMatches(track.language, metadata.audioLanguage),
orElse: () => availableTracks.first,
);
if (languageMatches(matchedTrack.language, metadata.audioLanguage)) {
appLogger.d(' Matched per-media audio language preference');
return matchedTrack;
return TrackSelectionResult(matchedTrack, TrackSelectionPriority.perMedia);
}
appLogger.d(' No match found for per-media audio language');
} else {
appLogger.d('Priority 2: No per-media audio language preference');
}
// Priority 3: If no preferred track matched, try user profile preferences
// Priority 4: Try user profile preferences
if (profileSettings != null) {
appLogger.d('Priority 3: Checking user profile preferences');
trackToSelect = findAudioTrackByProfile(availableTracks, profileSettings!);
if (trackToSelect != null) {
return trackToSelect;
return TrackSelectionResult(trackToSelect, TrackSelectionPriority.profile);
}
} else {
appLogger.d('Priority 3: No user profile available');
}
// Priority 4: If no match, use default or first track
appLogger.d('Priority 4: Using default or first available track');
// Priority 5: Use default or first track
trackToSelect = availableTracks.firstWhere((t) => t.isDefault == true, orElse: () => availableTracks.first);
final isDefault = trackToSelect.isDefault == true;
appLogger.d(
' Selected ${isDefault ? "default" : "first"} track: ${trackToSelect.title ?? "Track ${trackToSelect.id}"} (${trackToSelect.language ?? "unknown"})',
);
return trackToSelect;
return TrackSelectionResult(trackToSelect, TrackSelectionPriority.defaultTrack);
}
/// Select the best subtitle track based on priority:
/// Priority 1: Preferred track from navigation
/// Priority 2: Per-media language preference
/// Priority 3: User profile preferences
/// Priority 4: Default track
/// Priority 5: Off
SubtitleTrack selectSubtitleTrack(
/// Priority 2: Plex-selected track from media info
/// Priority 3: Per-media language preference
/// Priority 4: User profile preferences
/// Priority 5: Default track
/// Priority 6: Off
TrackSelectionResult<SubtitleTrack> selectSubtitleTrack(
List<SubtitleTrack> availableTracks,
SubtitleTrack? preferredSubtitleTrack,
AudioTrack? selectedAudioTrack,
) {
SubtitleTrack? subtitleToSelect;
// Priority 1: Try preferred track from navigation (always wins)
// Priority 1: Try preferred track from navigation
if (preferredSubtitleTrack != null) {
appLogger.d('Priority 1: Checking preferred track from navigation');
if (preferredSubtitleTrack.id == 'no') {
appLogger.d(' Preferred: OFF');
return SubtitleTrack.off;
return TrackSelectionResult(SubtitleTrack.off, TrackSelectionPriority.navigation);
} else if (availableTracks.isNotEmpty) {
appLogger.d(
' Preferred: ${preferredSubtitleTrack.title ?? "Track ${preferredSubtitleTrack.id}"} (${preferredSubtitleTrack.language ?? "unknown"})',
);
subtitleToSelect = findBestSubtitleMatch(availableTracks, preferredSubtitleTrack);
if (subtitleToSelect != null) {
appLogger.d(' Matched preferred track');
return subtitleToSelect;
return TrackSelectionResult(subtitleToSelect, TrackSelectionPriority.navigation);
}
appLogger.d(' No match found for preferred track');
}
} else {
appLogger.d('Priority 1: No preferred track from navigation');
}
// Priority 2: If no preferred match, try per-media language preference
if (metadata.subtitleLanguage != null) {
appLogger.d('Priority 2: Checking per-media subtitle language preference');
appLogger.d(' Per-media subtitle language: ${metadata.subtitleLanguage}');
// Priority 2: Check Plex-selected track from media info
if (plexMediaInfo != null && availableTracks.isNotEmpty) {
final plexSubtitleTracks = plexMediaInfo!.subtitleTracks;
final plexSelectedIndex = plexSubtitleTracks.indexWhere((t) => t.selected);
if (plexSelectedIndex >= 0 && plexSelectedIndex < availableTracks.length) {
return TrackSelectionResult(availableTracks[plexSelectedIndex], TrackSelectionPriority.plexSelected);
}
}
// Check if subtitle should be disabled
// Priority 3: Try per-media language preference
if (metadata.subtitleLanguage != null) {
if (metadata.subtitleLanguage == 'none' || metadata.subtitleLanguage!.isEmpty) {
appLogger.d(' Per-media preference: Subtitles OFF');
return SubtitleTrack.off;
return TrackSelectionResult(SubtitleTrack.off, TrackSelectionPriority.perMedia);
} else if (availableTracks.isNotEmpty) {
final matchedTrack = availableTracks.firstWhere(
(track) => languageMatches(track.language, metadata.subtitleLanguage),
orElse: () => availableTracks.first,
);
if (languageMatches(matchedTrack.language, metadata.subtitleLanguage)) {
appLogger.d(' Matched per-media subtitle language preference');
return matchedTrack;
return TrackSelectionResult(matchedTrack, TrackSelectionPriority.perMedia);
}
appLogger.d(' No match found for per-media subtitle language');
}
} else {
appLogger.d('Priority 2: No per-media subtitle language preference');
}
// Priority 3: If no preferred match, apply user profile preferences
// Priority 4: Apply user profile preferences
if (profileSettings != null && availableTracks.isNotEmpty) {
appLogger.d('Priority 3: Checking user profile preferences');
subtitleToSelect = findSubtitleTrackByProfile(
availableTracks,
profileSettings!,
selectedAudioTrack: selectedAudioTrack,
);
if (subtitleToSelect != null) {
return subtitleToSelect;
return TrackSelectionResult(subtitleToSelect, TrackSelectionPriority.profile);
}
} else if (availableTracks.isNotEmpty) {
appLogger.d('Priority 3: No user profile available');
}
// Priority 4: If no profile match, check for default subtitle
// Priority 5: Check for default subtitle
if (availableTracks.isNotEmpty) {
appLogger.d('Priority 4: Checking for default subtitle track');
final defaultTrack = availableTracks.firstWhere((t) => t.isDefault == true, orElse: () => availableTracks.first);
if (defaultTrack.isDefault == true) {
appLogger.d(
' Found default track: ${defaultTrack.title ?? "Track ${defaultTrack.id}"} (${defaultTrack.language ?? "unknown"})',
);
return defaultTrack;
return TrackSelectionResult(defaultTrack, TrackSelectionPriority.defaultTrack);
}
appLogger.d(' No default subtitle track found');
}
// Priority 5: If still no subtitle selected, turn off
appLogger.d('Priority 5: No subtitle selected - Subtitles OFF');
return SubtitleTrack.off;
// Priority 6: Turn off subtitles
return TrackSelectionResult(SubtitleTrack.off, TrackSelectionPriority.off);
}
/// Select and apply audio and subtitle tracks based on preferences
@@ -572,42 +457,43 @@ class TrackSelectionService {
attempts++;
}
appLogger.d('Starting track selection process');
// Get real tracks (excluding auto and no)
final realAudioTracks = player.state.tracks.audio.where((t) => t.id != 'auto' && t.id != 'no').toList();
final realSubtitleTracks = player.state.tracks.subtitle.where((t) => t.id != 'auto' && t.id != 'no').toList();
// Log available tracks
logAvailableTracks(realAudioTracks, realSubtitleTracks);
// Select and apply audio track
appLogger.d('Audio track selection');
final selectedAudioTrack = selectAudioTrack(realAudioTracks, preferredAudioTrack);
if (selectedAudioTrack != null) {
appLogger.i(
'Final audio selection: ${selectedAudioTrack.title ?? "Track ${selectedAudioTrack.id}"} (${selectedAudioTrack.language ?? "unknown"})',
final audioResult = selectAudioTrack(realAudioTracks, preferredAudioTrack);
AudioTrack? selectedAudioTrack;
if (audioResult != null) {
selectedAudioTrack = audioResult.track;
appLogger.d(
'Audio: ${selectedAudioTrack.title ?? selectedAudioTrack.language ?? "Track ${selectedAudioTrack.id}"} [${audioResult.priority.name}]',
);
player.selectAudioTrack(selectedAudioTrack);
} else {
appLogger.d('No audio tracks available');
// Save to Plex if this was user's navigation preference (Priority 1)
if (audioResult.priority == TrackSelectionPriority.navigation && onAudioTrackChanged != null) {
onAudioTrackChanged(selectedAudioTrack);
}
}
// Select and apply subtitle track
appLogger.d('Subtitle track selection');
final selectedSubtitleTrack = selectSubtitleTrack(realSubtitleTracks, preferredSubtitleTrack, selectedAudioTrack);
final finalSubtitle = selectedSubtitleTrack.id == 'no'
final subtitleResult = selectSubtitleTrack(realSubtitleTracks, preferredSubtitleTrack, selectedAudioTrack);
final selectedSubtitleTrack = subtitleResult.track;
final subtitleName = selectedSubtitleTrack.id == 'no'
? 'OFF'
: '${selectedSubtitleTrack.title ?? "Track ${selectedSubtitleTrack.id}"} (${selectedSubtitleTrack.language ?? "unknown"})';
appLogger.i('Final subtitle selection: $finalSubtitle');
: (selectedSubtitleTrack.title ?? selectedSubtitleTrack.language ?? 'Track ${selectedSubtitleTrack.id}');
appLogger.d('Subtitle: $subtitleName [${subtitleResult.priority.name}]');
player.selectSubtitleTrack(selectedSubtitleTrack);
// Save to Plex if this was user's navigation preference (Priority 1)
if (subtitleResult.priority == TrackSelectionPriority.navigation && onSubtitleTrackChanged != null) {
onSubtitleTrackChanged(selectedSubtitleTrack);
}
// Set playback rate if preferred rate was provided
if (preferredPlaybackRate != null) {
appLogger.d('Setting preferred playback rate: ${preferredPlaybackRate}x');
player.setRate(preferredPlaybackRate);
}
appLogger.d('Track selection complete');
}
}
@@ -76,6 +76,14 @@ class WatchTogetherProvider with ChangeNotifier {
_displayName = name;
}
/// Wire up sync manager's state change callback to update provider state
void _wireSyncStateChanges() {
_syncManager!.onSyncStateChanged = (isSyncing) {
_isSyncing = isSyncing;
notifyListeners();
};
}
/// Create a new watch together session as host
Future<String> createSession({
required ControlMode controlMode,
@@ -113,10 +121,7 @@ class WatchTogetherProvider with ChangeNotifier {
displayName: _displayName,
);
_syncManager!.onSyncStateChanged = (isSyncing) {
_isSyncing = isSyncing;
notifyListeners();
};
_wireSyncStateChanges();
notifyListeners();
appLogger.d('WatchTogether: Session created: $sessionId');
@@ -164,10 +169,7 @@ class WatchTogetherProvider with ChangeNotifier {
notifyListeners();
};
_syncManager!.onSyncStateChanged = (isSyncing) {
_isSyncing = isSyncing;
notifyListeners();
};
_wireSyncStateChanges();
// Add self to participants
_participants.add(Participant(peerId: _peerService!.myPeerId!, displayName: _displayName, isHost: false));
@@ -83,6 +83,31 @@ class WatchTogetherPeerService {
return const Uuid().v4().substring(0, 8).toUpperCase();
}
/// Attach common peer event listeners for disconnected/close/error events
void _attachCommonPeerListeners({
required Completer completer,
required PeerErrorType errorType,
required String errorMessage,
}) {
_peer!.on('disconnected').listen((_) {
appLogger.w('WatchTogether: Peer disconnected from server');
_handleDisconnectedFromServer();
});
_peer!.on('close').listen((_) {
appLogger.d('WatchTogether: Peer closed');
_connectionStateController.add(false);
});
_peer!.on('error').listen((error) {
appLogger.e('WatchTogether: Peer error', error: error);
_errorController.add(PeerError(type: errorType, message: '$errorMessage: $error', originalError: error));
if (!completer.isCompleted) {
completer.completeError(error);
}
});
}
/// Create a new session as host
///
/// Returns the session ID that others can use to join
@@ -115,25 +140,11 @@ class WatchTogetherPeerService {
_handleNewConnection(dataConn);
});
_peer!.on('error').listen((error) {
appLogger.e('WatchTogether: Peer error', error: error);
_errorController.add(
PeerError(type: PeerErrorType.serverError, message: error.toString(), originalError: error),
);
if (!completer.isCompleted) {
completer.completeError(error);
}
});
_peer!.on('disconnected').listen((_) {
appLogger.w('WatchTogether: Peer disconnected from server');
_handleDisconnectedFromServer();
});
_peer!.on('close').listen((_) {
appLogger.d('WatchTogether: Peer closed');
_connectionStateController.add(false);
});
_attachCommonPeerListeners(
completer: completer,
errorType: PeerErrorType.serverError,
errorMessage: 'Server error',
);
} catch (e) {
appLogger.e('WatchTogether: Failed to create peer', error: e);
if (!completer.isCompleted) {
@@ -178,29 +189,11 @@ class WatchTogetherPeerService {
_handleNewConnection(conn, isOutgoing: true, completer: completer);
});
_peer!.on('error').listen((error) {
appLogger.e('WatchTogether: Peer error', error: error);
_errorController.add(
PeerError(
type: PeerErrorType.connectionFailed,
message: 'Failed to connect to session: $error',
originalError: error,
),
);
if (!completer.isCompleted) {
completer.completeError(error);
}
});
_peer!.on('disconnected').listen((_) {
appLogger.w('WatchTogether: Peer disconnected from server');
_handleDisconnectedFromServer();
});
_peer!.on('close').listen((_) {
appLogger.d('WatchTogether: Peer closed');
_connectionStateController.add(false);
});
_attachCommonPeerListeners(
completer: completer,
errorType: PeerErrorType.connectionFailed,
errorMessage: 'Failed to connect to session',
);
} catch (e) {
appLogger.e('WatchTogether: Failed to create peer for joining', error: e);
if (!completer.isCompleted) {
+12 -13
View File
@@ -241,19 +241,9 @@ class _DownloadTreeViewState extends State<DownloadTreeView> {
);
}
// Sort shows by status and title
shows.sort((a, b) {
final statusCompare = _compareByStatus(a.status, b.status);
if (statusCompare != 0) return statusCompare;
return a.title.compareTo(b.title);
});
// Sort movies by status and title
movies.sort((a, b) {
final statusCompare = _compareByStatus(a.status, b.status);
if (statusCompare != 0) return statusCompare;
return a.title.compareTo(b.title);
});
// Sort shows and movies by status and title
_sortNodesByStatusAndTitle(shows);
_sortNodesByStatusAndTitle(movies);
// Combine movies and shows
return [...movies, ...shows];
@@ -292,6 +282,15 @@ class _DownloadTreeViewState extends State<DownloadTreeView> {
return (statusOrder[a] ?? 99).compareTo(statusOrder[b] ?? 99);
}
/// Sort nodes by status (downloading first) then by title
void _sortNodesByStatusAndTitle(List<DownloadTreeNode> nodes) {
nodes.sort((a, b) {
final statusCompare = _compareByStatus(a.status, b.status);
if (statusCompare != 0) return statusCompare;
return a.title.compareTo(b.title);
});
}
/// Flatten the tree into a list of visible nodes with their depths
List<_FlatNode> _flattenTree(List<DownloadTreeNode> nodes, [int depth = 0]) {
final List<_FlatNode> result = [];
+5 -14
View File
@@ -61,25 +61,16 @@ class _HorizontalScrollWithArrowsState extends State<HorizontalScrollWithArrows>
});
}
void _scrollLeft() {
void _animateScroll(double direction) {
final position = _scrollController.position;
final targetScroll = (position.pixels - (position.viewportDimension * widget.scrollAmount)).clamp(
0.0,
position.maxScrollExtent,
);
final delta = direction * position.viewportDimension * widget.scrollAmount;
final targetScroll = (position.pixels + delta).clamp(0.0, position.maxScrollExtent);
_scrollController.animateTo(targetScroll, duration: tokens(context).slow, curve: Curves.easeInOut);
}
void _scrollRight() {
final position = _scrollController.position;
final targetScroll = (position.pixels + (position.viewportDimension * widget.scrollAmount)).clamp(
0.0,
position.maxScrollExtent,
);
void _scrollLeft() => _animateScroll(-1);
_scrollController.animateTo(targetScroll, duration: tokens(context).slow, curve: Curves.easeInOut);
}
void _scrollRight() => _animateScroll(1);
Widget _buildArrowButton({
required double position,
+12 -1
View File
@@ -69,7 +69,18 @@ class MediaCardState extends State<MediaCard> {
String _buildSemanticLabel() {
final item = widget.item;
// Build base label based on type
// Playlists don't expose mediaType, so build a simple localized label and exit early
if (item is PlexPlaylist) {
final count = item.leafCount;
final countText = count != null ? ', ${t.playlists.itemCount(count: count)}' : '';
return '${item.displayTitle}, ${t.playlists.playlist}$countText';
}
// Build base label based on PlexMetadata media type
if (item is! PlexMetadata) {
return '$item';
}
String baseLabel;
switch (item.mediaType) {
case PlexMediaType.episode:
+244
View File
@@ -0,0 +1,244 @@
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../focus/dpad_navigator.dart';
import '../focus/focus_theme.dart';
import '../focus/input_mode_tracker.dart';
import 'app_icon.dart';
import '../theme/mono_tokens.dart';
import 'package:material_symbols_icons/symbols.dart';
/// A TV-friendly number spinner with +/- buttons for D-pad navigation.
///
/// Displays a value with decrement/increment buttons on either side.
/// Supports keyboard repeat for faster value changes when holding arrows.
class TvNumberSpinner extends StatefulWidget {
/// Current value.
final int value;
/// Minimum allowed value.
final int min;
/// Maximum allowed value.
final int max;
/// Step size for each increment/decrement.
final int step;
/// Optional suffix text (e.g., "s" for seconds).
final String? suffix;
/// Called when the value changes.
final ValueChanged<int> onChanged;
/// Whether the spinner should request focus when built.
final bool autofocus;
const TvNumberSpinner({
super.key,
required this.value,
required this.min,
required this.max,
required this.onChanged,
this.step = 1,
this.suffix,
this.autofocus = false,
});
@override
State<TvNumberSpinner> createState() => _TvNumberSpinnerState();
}
class _TvNumberSpinnerState extends State<TvNumberSpinner> {
late FocusNode _focusNode;
Timer? _repeatTimer;
bool _isFocused = false;
@override
void initState() {
super.initState();
_focusNode = FocusNode(debugLabel: 'TvNumberSpinner');
}
@override
void dispose() {
_repeatTimer?.cancel();
_focusNode.dispose();
super.dispose();
}
void _increment() {
final newValue = widget.value + widget.step;
if (newValue <= widget.max) {
widget.onChanged(newValue);
}
}
void _decrement() {
final newValue = widget.value - widget.step;
if (newValue >= widget.min) {
widget.onChanged(newValue);
}
}
void _startRepeat(VoidCallback action) {
// Execute once immediately
action();
// Start repeat timer after initial delay
_repeatTimer?.cancel();
_repeatTimer = Timer(const Duration(milliseconds: 400), () {
_repeatTimer = Timer.periodic(const Duration(milliseconds: 100), (_) {
action();
});
});
}
void _stopRepeat() {
_repeatTimer?.cancel();
_repeatTimer = null;
}
KeyEventResult _handleKeyEvent(FocusNode node, KeyEvent event) {
final key = event.logicalKey;
if (event is KeyDownEvent) {
if (key.isUpKey || key.isRightKey) {
_startRepeat(_increment);
return KeyEventResult.handled;
} else if (key.isDownKey || key.isLeftKey) {
_startRepeat(_decrement);
return KeyEventResult.handled;
}
} else if (event is KeyUpEvent) {
if (key.isUpKey || key.isRightKey || key.isDownKey || key.isLeftKey) {
_stopRepeat();
return KeyEventResult.handled;
}
}
return KeyEventResult.ignored;
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final tokens = theme.extension<MonoTokens>();
final canDecrement = widget.value > widget.min;
final canIncrement = widget.value < widget.max;
final isKeyboardMode = InputModeTracker.isKeyboardMode(context);
return Focus(
focusNode: _focusNode,
autofocus: widget.autofocus,
onFocusChange: (hasFocus) {
setState(() => _isFocused = hasFocus);
if (!hasFocus) _stopRepeat();
},
onKeyEvent: _handleKeyEvent,
child: AnimatedContainer(
duration: tokens?.fast ?? const Duration(milliseconds: 150),
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(FocusTheme.defaultBorderRadius),
border: Border.all(
color: _isFocused && isKeyboardMode ? FocusTheme.getFocusBorderColor(context) : Colors.transparent,
width: FocusTheme.focusBorderWidth,
),
),
child: Row(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.center,
children: [
// Decrement button
_SpinnerButton(
icon: Symbols.remove_rounded,
onPressed: canDecrement ? _decrement : null,
onLongPressStart: canDecrement ? () => _startRepeat(_decrement) : null,
onLongPressEnd: _stopRepeat,
semanticLabel: 'Decrease',
),
const SizedBox(width: 16),
// Value display
Container(
constraints: const BoxConstraints(minWidth: 60),
alignment: Alignment.center,
child: Text(
widget.suffix != null ? '${widget.value}${widget.suffix}' : '${widget.value}',
style: theme.textTheme.headlineMedium?.copyWith(fontWeight: FontWeight.bold),
),
),
const SizedBox(width: 16),
// Increment button
_SpinnerButton(
icon: Symbols.add_rounded,
onPressed: canIncrement ? _increment : null,
onLongPressStart: canIncrement ? () => _startRepeat(_increment) : null,
onLongPressEnd: _stopRepeat,
semanticLabel: 'Increase',
),
],
),
),
);
}
}
/// Individual +/- button with long-press support.
class _SpinnerButton extends StatelessWidget {
final IconData icon;
final VoidCallback? onPressed;
final VoidCallback? onLongPressStart;
final VoidCallback? onLongPressEnd;
final String semanticLabel;
const _SpinnerButton({
required this.icon,
required this.onPressed,
this.onLongPressStart,
this.onLongPressEnd,
required this.semanticLabel,
});
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final isEnabled = onPressed != null;
return Semantics(
label: semanticLabel,
button: true,
enabled: isEnabled,
child: GestureDetector(
onLongPressStart: onLongPressStart != null ? (_) => onLongPressStart!() : null,
onLongPressEnd: onLongPressEnd != null ? (_) => onLongPressEnd!() : null,
child: Material(
color: Colors.transparent,
child: InkWell(
onTap: onPressed,
borderRadius: BorderRadius.circular(24),
child: Container(
width: 48,
height: 48,
decoration: BoxDecoration(
shape: BoxShape.circle,
color: isEnabled ? theme.colorScheme.primaryContainer : theme.colorScheme.surfaceContainerHighest,
),
child: Center(
child: AppIcon(
icon,
fill: 1,
color: isEnabled
? theme.colorScheme.onPrimaryContainer
: theme.colorScheme.onSurfaceVariant.withValues(alpha: 0.5),
),
),
),
),
),
),
);
}
}
@@ -67,6 +67,9 @@ class DesktopVideoControls extends StatefulWidget {
/// Whether the user can control playback (false in host-only mode for non-host).
final bool canControl;
/// Notifier for whether first video frame has rendered (shows loading state when false).
final ValueNotifier<bool>? hasFirstFrame;
const DesktopVideoControls({
super.key,
required this.player,
@@ -104,6 +107,7 @@ class DesktopVideoControls extends StatefulWidget {
this.serverId = '',
this.onBack,
this.canControl = true,
this.hasFirstFrame,
});
@override
@@ -128,6 +132,10 @@ class DesktopVideoControlsState extends State<DesktopVideoControls> {
// List of button focus nodes for horizontal navigation
late final List<FocusNode> _buttonFocusNodes;
// Progressive seek acceleration state
LogicalKeyboardKey? _seekDirection; // Current direction being held
int _seekRepeatCount = 0; // Consecutive key repeats for acceleration
@override
void initState() {
super.initState();
@@ -186,6 +194,9 @@ class DesktopVideoControlsState extends State<DesktopVideoControls> {
void _onFocusChange(bool hasFocus) {
if (hasFocus) {
widget.onFocusActivity?.call();
} else {
// Reset progressive seek state when timeline loses focus
_resetSeekState();
}
}
@@ -239,43 +250,84 @@ class DesktopVideoControlsState extends State<DesktopVideoControls> {
);
}
/// Reset progressive seek state
void _resetSeekState() {
_seekDirection = null;
_seekRepeatCount = 0;
}
/// Calculate seek multiplier based on repeat count (stepped tiers)
double _getSeekMultiplier() {
if (_seekRepeatCount <= 5) {
return 1.5;
} else if (_seekRepeatCount <= 15) {
return 3.0;
} else if (_seekRepeatCount <= 30) {
return 6.0;
} else {
return 10.0;
}
}
/// Handle key events for timeline navigation
KeyEventResult _handleTimelineKeyEvent(FocusNode node, KeyEvent event) {
final key = event.logicalKey;
// Handle key release to reset progressive seek state
if (event is KeyUpEvent) {
if (key == LogicalKeyboardKey.arrowLeft || key == LogicalKeyboardKey.arrowRight) {
_resetSeekState();
}
return KeyEventResult.ignored;
}
if (!event.isActionable) {
return KeyEventResult.ignored;
}
final key = event.logicalKey;
final duration = widget.player.state.duration;
final position = widget.player.state.position;
// UP arrow - hide controls
// UP arrow - hide controls and reset seek state
if (key == LogicalKeyboardKey.arrowUp) {
_resetSeekState();
widget.onHideControls?.call();
return KeyEventResult.handled;
}
// DOWN arrow - move focus to play/pause button
// DOWN arrow - move focus to play/pause button and reset seek state
if (key == LogicalKeyboardKey.arrowDown) {
_resetSeekState();
_playPauseFocusNode.requestFocus();
widget.onFocusActivity?.call();
return KeyEventResult.handled;
}
// LEFT/RIGHT for smooth scrubbing - only if user can control
// LEFT/RIGHT for smooth scrubbing with progressive acceleration
if (key == LogicalKeyboardKey.arrowLeft || key == LogicalKeyboardKey.arrowRight) {
// Ignore seeking if user cannot control
if (!widget.canControl) return KeyEventResult.handled;
if (duration.inMilliseconds <= 0) return KeyEventResult.handled;
// Base step: 0.5% of duration, minimum 500ms
final baseStep = Duration(milliseconds: (duration.inMilliseconds * 0.005).clamp(500, 15000).toInt());
// Track direction change - reset if direction changes
if (_seekDirection != key) {
_seekDirection = key;
_seekRepeatCount = 0;
}
// Accelerate on key repeat
final step = event is KeyRepeatEvent
? Duration(milliseconds: (baseStep.inMilliseconds * 2).clamp(500, 30000))
: baseStep;
// Increment repeat count on KeyRepeatEvent
if (event is KeyRepeatEvent) {
_seekRepeatCount++;
}
// Base step: 0.5% of duration, minimum 500ms, maximum 15s
final baseStepMs = (duration.inMilliseconds * 0.005).clamp(500, 15000).toInt();
// Apply progressive multiplier only on repeat events (initial press uses 1x)
final effectiveMultiplier = event is KeyRepeatEvent ? _getSeekMultiplier() : 1.0;
final stepMs = (baseStepMs * effectiveMultiplier).clamp(500, 60000).toInt();
final step = Duration(milliseconds: stepMs);
final isForward = key == LogicalKeyboardKey.arrowRight;
final newPosition = isForward ? position + step : position - step;
@@ -293,14 +345,24 @@ class DesktopVideoControlsState extends State<DesktopVideoControls> {
@override
Widget build(BuildContext context) {
return Column(
children: [
// Top bar with back button and title
_buildTopBar(context),
const Spacer(),
// Bottom controls
_buildBottomControls(context),
],
return ValueListenableBuilder<bool>(
valueListenable: widget.hasFirstFrame ?? ValueNotifier(true),
builder: (context, hasFrame, child) {
return Column(
children: [
// Top bar with back button and title (always visible)
_buildTopBar(context),
if (!hasFrame)
// Loading: empty space, spinner shown by video_player_screen
const Expanded(child: SizedBox.shrink())
else ...[
// Loaded: spacer + bottom controls
const Spacer(),
_buildBottomControlsContent(context, hasFrame: true),
],
],
);
},
);
}
@@ -334,7 +396,8 @@ class DesktopVideoControlsState extends State<DesktopVideoControls> {
return DesktopAppBarHelper.wrapWithGestureDetector(topBar, opaque: true);
}
Widget _buildBottomControls(BuildContext context) {
Widget _buildBottomControlsContent(BuildContext context, {required bool hasFrame}) {
final canInteract = widget.canControl && hasFrame;
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 16),
child: Column(
@@ -350,7 +413,7 @@ class DesktopVideoControlsState extends State<DesktopVideoControls> {
focusNode: _timelineFocusNode,
onKeyEvent: _handleTimelineKeyEvent,
onFocusChange: _onFocusChange,
enabled: widget.canControl,
enabled: canInteract,
),
const SizedBox(height: 4),
// Row 2: Playback controls and options
@@ -32,10 +32,15 @@ class MobileVideoControls extends StatelessWidget {
final VoidCallback? onCancelAutoHide;
final VoidCallback? onStartAutoHide;
final VoidCallback? onBack;
final VoidCallback? onNext;
final VoidCallback? onPrevious;
/// Whether the user can control playback (false in host-only mode for non-host).
final bool canControl;
/// Notifier for whether first video frame has rendered (shows loading state when false).
final ValueNotifier<bool>? hasFirstFrame;
const MobileVideoControls({
super.key,
required this.player,
@@ -51,7 +56,10 @@ class MobileVideoControls extends StatelessWidget {
this.onCancelAutoHide,
this.onStartAutoHide,
this.onBack,
this.onNext,
this.onPrevious,
this.canControl = true,
this.hasFirstFrame,
});
@override
@@ -94,6 +102,24 @@ class MobileVideoControls extends StatelessWidget {
return const SizedBox.shrink();
}
// Check if we're still loading first frame
final hasFirstFrameNotifier = hasFirstFrame;
if (hasFirstFrameNotifier != null) {
return ValueListenableBuilder<bool>(
valueListenable: hasFirstFrameNotifier,
builder: (context, hasFrame, child) {
if (!hasFrame) {
// Empty space, spinner shown by video_player_screen
return const SizedBox.shrink();
}
return _buildPlaybackControlsContent(context);
},
);
}
return _buildPlaybackControlsContent(context);
}
Widget _buildPlaybackControlsContent(BuildContext context) {
return StreamBuilder<bool>(
stream: player.streams.playing,
initialData: player.state.playing,
@@ -102,6 +128,16 @@ class MobileVideoControls extends StatelessWidget {
return Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
// Previous episode button (hidden when unavailable)
if (onPrevious != null) ...[
_buildCircularButton(
semanticLabel: t.videoControls.previousButton,
icon: Symbols.skip_previous_rounded,
iconSize: 48,
onPressed: onPrevious!,
),
const SizedBox(width: 16),
],
_buildCircularButton(
semanticLabel: t.videoControls.seekBackwardButton(seconds: seekTimeSmall),
icon: getReplayIcon(seekTimeSmall),
@@ -136,6 +172,16 @@ class MobileVideoControls extends StatelessWidget {
onSeekCompleted?.call(newPosition);
},
),
// Next episode button (hidden when unavailable)
if (onNext != null) ...[
const SizedBox(width: 16),
_buildCircularButton(
semanticLabel: t.videoControls.nextButton,
icon: Symbols.skip_next_rounded,
iconSize: 48,
onPressed: onNext!,
),
],
],
);
},
@@ -143,6 +189,24 @@ class MobileVideoControls extends StatelessWidget {
}
Widget _buildBottomBar(BuildContext context) {
// Check if we're still loading first frame
final hasFirstFrameNotifier = hasFirstFrame;
if (hasFirstFrameNotifier != null) {
return ValueListenableBuilder<bool>(
valueListenable: hasFirstFrameNotifier,
builder: (context, hasFrame, child) {
if (!hasFrame) {
// Hide timeline while loading
return const SizedBox.shrink();
}
return _buildBottomBarContent(context);
},
);
}
return _buildBottomBarContent(context);
}
Widget _buildBottomBarContent(BuildContext context) {
return _conditionalSafeArea(
context: context,
top: false, // Only respect bottom safe area when in portrait
@@ -111,6 +111,7 @@ class _VideoSettingsSheetState extends State<VideoSettingsSheet> {
late int _audioSyncOffset;
late int _subtitleSyncOffset;
bool _enableHDR = true;
bool _showPerformanceOverlay = false;
late final FocusNode _initialFocusNode;
@override
@@ -119,7 +120,7 @@ class _VideoSettingsSheetState extends State<VideoSettingsSheet> {
_audioSyncOffset = widget.audioSyncOffset;
_subtitleSyncOffset = widget.subtitleSyncOffset;
_initialFocusNode = FocusNode(debugLabel: 'VideoSettingsInitialFocus');
_loadHDRSetting();
_loadSettings();
}
@override
@@ -128,10 +129,11 @@ class _VideoSettingsSheetState extends State<VideoSettingsSheet> {
super.dispose();
}
Future<void> _loadHDRSetting() async {
Future<void> _loadSettings() async {
final settings = await SettingsService.getInstance();
setState(() {
_enableHDR = settings.getEnableHDR();
_showPerformanceOverlay = settings.getShowPerformanceOverlay();
});
}
@@ -146,6 +148,15 @@ class _VideoSettingsSheetState extends State<VideoSettingsSheet> {
await widget.player.setProperty('hdr-enabled', newValue ? 'yes' : 'no');
}
Future<void> _togglePerformanceOverlay() async {
final newValue = !_showPerformanceOverlay;
final settings = await SettingsService.getInstance();
await settings.setShowPerformanceOverlay(newValue);
setState(() {
_showPerformanceOverlay = newValue;
});
}
void _navigateTo(_SettingsView view) {
setState(() {
_currentView = view;
@@ -289,6 +300,22 @@ class _VideoSettingsSheetState extends State<VideoSettingsSheet> {
);
},
),
// Performance Overlay Toggle
ListTile(
leading: AppIcon(
Symbols.analytics_rounded,
fill: 1,
color: _showPerformanceOverlay ? Colors.amber : Colors.white70,
),
title: const Text('Performance Overlay', style: TextStyle(color: Colors.white)),
trailing: Switch(
value: _showPerformanceOverlay,
onChanged: (_) => _togglePerformanceOverlay(),
activeThumbColor: Colors.amber,
),
onTap: _togglePerformanceOverlay,
),
],
);
}
+63 -15
View File
@@ -39,6 +39,7 @@ import '../../utils/app_logger.dart';
import '../../i18n/strings.g.dart';
import '../../focus/input_mode_tracker.dart';
import 'widgets/track_chapter_controls.dart';
import 'widgets/performance_overlay/performance_overlay.dart';
import 'mobile_video_controls.dart';
import 'desktop_video_controls.dart';
@@ -57,6 +58,7 @@ Widget plexVideoControlsBuilder(
Function(Duration position)? onSeekCompleted,
VoidCallback? onBack,
bool canControl = true,
ValueNotifier<bool>? hasFirstFrame,
}) {
return PlexVideoControls(
player: player,
@@ -72,6 +74,7 @@ Widget plexVideoControlsBuilder(
onSeekCompleted: onSeekCompleted,
onBack: onBack,
canControl: canControl,
hasFirstFrame: hasFirstFrame,
);
}
@@ -96,6 +99,9 @@ class PlexVideoControls extends StatefulWidget {
/// Whether the user can control playback (false in host-only mode for non-host).
final bool canControl;
/// Notifier for whether first video frame has rendered (shows loading state when false).
final ValueNotifier<bool>? hasFirstFrame;
const PlexVideoControls({
super.key,
required this.player,
@@ -111,6 +117,7 @@ class PlexVideoControls extends StatefulWidget {
this.onSeekCompleted,
this.onBack,
this.canControl = true,
this.hasFirstFrame,
});
@override
@@ -166,6 +173,8 @@ class _PlexVideoControlsState extends State<PlexVideoControls> with WindowListen
double _autoSkipProgress = 0.0;
// Video player navigation (use arrow keys to navigate controls)
bool _videoPlayerNavigationEnabled = false;
// Performance overlay
bool _showPerformanceOverlay = false;
@override
void initState() {
@@ -197,6 +206,15 @@ class _PlexVideoControlsState extends State<PlexVideoControls> with WindowListen
});
// Register global key handler for focus-independent shortcuts (desktop only)
HardwareKeyboard.instance.addHandler(_handleGlobalKeyEvent);
// Listen for first frame to start auto-hide timer
widget.hasFirstFrame?.addListener(_onFirstFrameReady);
}
/// Called when hasFirstFrame changes - start auto-hide timer when first frame is ready
void _onFirstFrameReady() {
if (widget.hasFirstFrame?.value == true) {
_startHideTimer();
}
}
/// Focus play/pause button if we're in keyboard navigation mode (desktop only)
@@ -355,6 +373,7 @@ class _PlexVideoControlsState extends State<PlexVideoControls> with WindowListen
_autoSkipCredits = settingsService.getAutoSkipCredits();
_autoSkipDelay = settingsService.getAutoSkipDelay();
_videoPlayerNavigationEnabled = settingsService.getVideoPlayerNavigationEnabled();
_showPerformanceOverlay = settingsService.getShowPerformanceOverlay();
});
// Apply rotation lock setting
@@ -398,6 +417,7 @@ class _PlexVideoControlsState extends State<PlexVideoControls> with WindowListen
@override
void dispose() {
HardwareKeyboard.instance.removeHandler(_handleGlobalKeyEvent);
widget.hasFirstFrame?.removeListener(_onFirstFrameReady);
_hideTimer?.cancel();
_feedbackTimer?.cancel();
_resizeDebounceTimer?.cancel();
@@ -483,10 +503,17 @@ class _PlexVideoControlsState extends State<PlexVideoControls> with WindowListen
void _startHideTimer() {
_hideTimer?.cancel();
// Don't auto-hide while loading first frame (user needs to see spinner and back button)
final hasFrame = widget.hasFirstFrame?.value ?? true;
if (!hasFrame) return;
// Only auto-hide if playing
if (widget.player.state.playing) {
_hideTimer = Timer(const Duration(seconds: 3), () {
if (mounted && widget.player.state.playing) {
// Also check hasFirstFrame in callback (in case it changed)
final stillLoading = !(widget.hasFirstFrame?.value ?? true);
if (mounted && widget.player.state.playing && !stillLoading) {
setState(() {
_showControls = false;
});
@@ -1189,20 +1216,30 @@ class _PlexVideoControlsState extends State<PlexVideoControls> with WindowListen
child: GestureDetector(
onTap: _toggleControls,
behavior: HitTestBehavior.deferToChild,
child: Container(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [
Colors.black.withValues(alpha: 0.7),
Colors.transparent,
Colors.transparent,
Colors.black.withValues(alpha: 0.7),
],
stops: const [0.0, 0.2, 0.8, 1.0],
),
),
child: ValueListenableBuilder<bool>(
valueListenable: widget.hasFirstFrame ?? ValueNotifier(true),
builder: (context, hasFrame, child) {
return Container(
decoration: BoxDecoration(
// Use solid black when loading, gradient when loaded
color: hasFrame ? null : Colors.black,
gradient: hasFrame
? LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [
Colors.black.withValues(alpha: 0.7),
Colors.transparent,
Colors.transparent,
Colors.black.withValues(alpha: 0.7),
],
stops: const [0.0, 0.2, 0.8, 1.0],
)
: null,
),
child: child,
);
},
child: isMobile
? Listener(
behavior: HitTestBehavior.translucent,
@@ -1221,7 +1258,10 @@ class _PlexVideoControlsState extends State<PlexVideoControls> with WindowListen
onCancelAutoHide: () => _hideTimer?.cancel(),
onStartAutoHide: _startHideTimer,
onBack: widget.onBack,
onNext: widget.onNext,
onPrevious: widget.onPrevious,
canControl: widget.canControl,
hasFirstFrame: widget.hasFirstFrame,
),
)
: Listener(
@@ -1268,6 +1308,7 @@ class _PlexVideoControlsState extends State<PlexVideoControls> with WindowListen
serverId: widget.metadata.serverId ?? '',
onBack: widget.onBack,
canControl: widget.canControl,
hasFirstFrame: widget.hasFirstFrame,
),
),
),
@@ -1295,6 +1336,13 @@ class _PlexVideoControlsState extends State<PlexVideoControls> with WindowListen
bottom: isMobile ? 80 : 115,
child: AnimatedOpacity(opacity: 1.0, duration: tokens(context).slow, child: _buildSkipMarkerButton()),
),
// Performance overlay (top-left)
if (_showPerformanceOverlay)
Positioned(
top: isMobile ? 60 : 16,
left: 16,
child: IgnorePointer(child: PlayerPerformanceOverlay(player: widget.player)),
),
],
),
),
@@ -0,0 +1,188 @@
import 'package:flutter/material.dart';
import 'package:material_symbols_icons/symbols.dart';
import '../../../../mpv/mpv.dart';
import '../../../../widgets/app_icon.dart';
import 'performance_stats.dart';
import 'performance_stats_service.dart';
/// A toggleable overlay displaying real-time video player performance statistics.
///
/// Shows a single card with two columns of metrics organized by section.
/// Positioned in the top-left corner of the video player.
class PlayerPerformanceOverlay extends StatefulWidget {
final Player player;
const PlayerPerformanceOverlay({super.key, required this.player});
@override
State<PlayerPerformanceOverlay> createState() => _PlayerPerformanceOverlayState();
}
class _PlayerPerformanceOverlayState extends State<PlayerPerformanceOverlay> {
late final PerformanceStatsService _statsService;
PerformanceStats _stats = const PerformanceStats.empty();
@override
void initState() {
super.initState();
_statsService = PerformanceStatsService(widget.player);
_statsService.statsStream.listen((stats) {
if (mounted) {
setState(() {
_stats = stats;
});
}
});
_statsService.startPolling();
}
@override
void dispose() {
_statsService.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Container(
constraints: const BoxConstraints(maxWidth: 380),
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: Colors.black.withValues(alpha: 0.8),
borderRadius: BorderRadius.circular(8),
boxShadow: [BoxShadow(color: Colors.black.withValues(alpha: 0.3), blurRadius: 4)],
),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
// Left column
Flexible(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
_buildSection(Symbols.videocam_rounded, 'Video', [
_metric('Codec', _stats.videoCodec ?? 'N/A'),
_metric('Resolution', _stats.resolution),
_metric('FPS', _stats.videoFpsFormatted),
_metric('Bitrate', _stats.videoBitrateFormatted),
_metric('Decoder', _stats.hwdecFormatted),
if (_stats.aspectName != null && _stats.aspectName!.isNotEmpty) _metric('Aspect', _stats.aspectName!),
if (_stats.rotate != null && _stats.rotate != 0) _metric('Rotation', _stats.rotateFormatted),
]),
const SizedBox(height: 12),
_buildSection(Symbols.palette_rounded, 'Color', [
_metric('Pixel Fmt', _stats.pixelformat ?? 'N/A'),
if (_stats.hwPixelformat != null && _stats.hwPixelformat != _stats.pixelformat)
_metric('HW Fmt', _stats.hwPixelformat!),
_metric('Matrix', _stats.colormatrix ?? 'N/A'),
_metric('Primaries', _stats.primaries ?? 'N/A'),
_metric('Transfer', _stats.gamma ?? 'N/A'),
]),
if (_stats.hasHdrMetadata) ...[
const SizedBox(height: 12),
_buildSection(Symbols.hdr_on_rounded, 'HDR', [
if (_stats.maxLuma != null) _metric('Max Luma', _stats.maxLumaFormatted),
if (_stats.minLuma != null) _metric('Min Luma', _stats.minLumaFormatted),
if (_stats.maxCll != null) _metric('MaxCLL', _stats.maxCllFormatted),
if (_stats.maxFall != null) _metric('MaxFALL', _stats.maxFallFormatted),
]),
],
],
),
),
const SizedBox(width: 24),
// Right column
Flexible(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
_buildSection(Symbols.volume_up_rounded, 'Audio', [
_metric('Codec', _stats.audioCodec ?? 'N/A'),
_metric('Sample Rate', _stats.sampleRateFormatted),
_metric('Channels', _stats.audioChannels ?? 'N/A'),
_metric('Bitrate', _stats.audioBitrateFormatted),
]),
const SizedBox(height: 12),
_buildSection(Symbols.speed_rounded, 'Performance', [
_metric('Render FPS', _stats.actualFpsFormatted),
_metric('Display FPS', _stats.displayFpsFormatted),
_metric('A/V Sync', _stats.avsyncFormatted),
_metric('Dropped', _stats.droppedFramesFormatted),
]),
const SizedBox(height: 12),
_buildSection(Symbols.memory_rounded, 'Buffer', [
_metric('Duration', _stats.cacheDurationFormatted),
_metric('Cache Used', _stats.cacheUsedFormatted),
_metric('Speed', _stats.cacheSpeedFormatted),
]),
const SizedBox(height: 12),
_buildSection(Symbols.apps_rounded, 'App', [
_metric('Memory', _stats.appMemoryFormatted),
_metric('UI FPS', _stats.uiFpsFormatted),
]),
],
),
),
],
),
);
}
Widget _buildSection(IconData icon, String title, List<_Metric> metrics) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Row(
mainAxisSize: MainAxisSize.min,
children: [
AppIcon(icon, fill: 1, color: Colors.white70, size: 12),
const SizedBox(width: 4),
Text(
title,
style: const TextStyle(color: Colors.white, fontSize: 11, fontWeight: FontWeight.w600),
),
],
),
const SizedBox(height: 4),
...metrics.map(_buildMetricRow),
],
);
}
Widget _buildMetricRow(_Metric metric) {
return Padding(
padding: const EdgeInsets.only(bottom: 2),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Text('${metric.label}: ', style: const TextStyle(color: Colors.white60, fontSize: 10)),
Flexible(
child: Text(
metric.value,
style: const TextStyle(
color: Colors.white,
fontSize: 10,
fontWeight: FontWeight.w500,
fontFamily: 'monospace',
),
overflow: TextOverflow.ellipsis,
),
),
],
),
);
}
_Metric _metric(String label, String value) => _Metric(label, value);
}
class _Metric {
final String label;
final String value;
const _Metric(this.label, this.value);
}
@@ -0,0 +1,252 @@
/// Data model for video player performance statistics.
///
/// Contains metrics queried from libmpv including video/audio codec info,
/// playback performance, and buffer state.
class PerformanceStats {
// Video metrics
final String? videoCodec;
final int? videoWidth;
final int? videoHeight;
final double? videoFps;
final String? hwdecCurrent;
final int? videoBitrate;
final String? aspectName;
final int? rotate;
// Color/Format metrics
final String? pixelformat;
final String? hwPixelformat;
final String? colormatrix;
final String? primaries;
final String? gamma;
// HDR metadata
final double? maxLuma;
final double? minLuma;
final double? maxCll;
final double? maxFall;
// Audio metrics
final String? audioCodec;
final int? audioSamplerate;
final String? audioChannels;
final int? audioBitrate;
// Performance metrics
final double? actualFps;
final double? avsyncChange;
final double? displayFps;
final int? frameDropCount;
final int? decoderFrameDropCount;
// Buffer metrics
final int? cacheUsed;
final double? cacheSpeed;
final double? cacheDuration;
// App metrics
final int? appMemoryBytes;
final double? uiFps;
const PerformanceStats({
this.videoCodec,
this.videoWidth,
this.videoHeight,
this.videoFps,
this.hwdecCurrent,
this.videoBitrate,
this.aspectName,
this.rotate,
this.pixelformat,
this.hwPixelformat,
this.colormatrix,
this.primaries,
this.gamma,
this.maxLuma,
this.minLuma,
this.maxCll,
this.maxFall,
this.audioCodec,
this.audioSamplerate,
this.audioChannels,
this.audioBitrate,
this.actualFps,
this.avsyncChange,
this.displayFps,
this.frameDropCount,
this.decoderFrameDropCount,
this.cacheUsed,
this.cacheSpeed,
this.cacheDuration,
this.appMemoryBytes,
this.uiFps,
});
/// Creates an empty stats object (used as initial state).
const PerformanceStats.empty()
: videoCodec = null,
videoWidth = null,
videoHeight = null,
videoFps = null,
hwdecCurrent = null,
videoBitrate = null,
aspectName = null,
rotate = null,
pixelformat = null,
hwPixelformat = null,
colormatrix = null,
primaries = null,
gamma = null,
maxLuma = null,
minLuma = null,
maxCll = null,
maxFall = null,
audioCodec = null,
audioSamplerate = null,
audioChannels = null,
audioBitrate = null,
actualFps = null,
avsyncChange = null,
displayFps = null,
frameDropCount = null,
decoderFrameDropCount = null,
cacheUsed = null,
cacheSpeed = null,
cacheDuration = null,
appMemoryBytes = null,
uiFps = null;
/// Format video resolution as "WxH".
String get resolution {
if (videoWidth == null || videoHeight == null) return 'N/A';
return '${videoWidth}x$videoHeight';
}
/// Format video bitrate in Mbps.
String get videoBitrateFormatted {
if (videoBitrate == null || videoBitrate == 0) return 'N/A';
final mbps = videoBitrate! / 1000000;
return '${mbps.toStringAsFixed(1)} Mbps';
}
/// Format audio bitrate in kbps.
String get audioBitrateFormatted {
if (audioBitrate == null || audioBitrate == 0) return 'N/A';
final kbps = audioBitrate! / 1000;
return '${kbps.toStringAsFixed(0)} kbps';
}
/// Format audio sample rate in kHz.
String get sampleRateFormatted {
if (audioSamplerate == null) return 'N/A';
final khz = audioSamplerate! / 1000;
return '${khz.toStringAsFixed(1)} kHz';
}
/// Format FPS with 2 decimal places.
String get actualFpsFormatted {
if (actualFps == null) return 'N/A';
return actualFps!.toStringAsFixed(2);
}
/// Format source FPS with 2 decimal places.
String get videoFpsFormatted {
if (videoFps == null) return 'N/A';
return videoFps!.toStringAsFixed(2);
}
/// Format A/V sync in milliseconds.
String get avsyncFormatted {
if (avsyncChange == null) return 'N/A';
final ms = (avsyncChange! * 1000).round();
return '${ms > 0 ? '+' : ''}${ms}ms';
}
/// Format cache used in MB.
String get cacheUsedFormatted {
if (cacheUsed == null) return 'N/A';
final mb = cacheUsed! / (1024 * 1024);
return '${mb.toStringAsFixed(1)} MB';
}
/// Format cache speed in MB/s.
String get cacheSpeedFormatted {
if (cacheSpeed == null) return 'N/A';
final mbps = cacheSpeed! / (1024 * 1024);
return '${mbps.toStringAsFixed(1)} MB/s';
}
/// Format cache duration in seconds.
String get cacheDurationFormatted {
if (cacheDuration == null) return 'N/A';
return '${cacheDuration!.toStringAsFixed(1)}s';
}
/// Format display FPS.
String get displayFpsFormatted {
if (displayFps == null) return 'N/A';
return displayFps!.toStringAsFixed(0);
}
/// Format dropped frames count.
String get droppedFramesFormatted {
final total = (frameDropCount ?? 0) + (decoderFrameDropCount ?? 0);
return total.toString();
}
/// Format hardware decoding mode.
String get hwdecFormatted {
if (hwdecCurrent == null || hwdecCurrent!.isEmpty || hwdecCurrent == 'no') {
return 'Software';
}
return hwdecCurrent!;
}
/// Format app memory usage in MB.
String get appMemoryFormatted {
if (appMemoryBytes == null) return 'N/A';
final mb = appMemoryBytes! / (1024 * 1024);
return '${mb.toStringAsFixed(1)} MB';
}
/// Format UI FPS with 1 decimal place.
String get uiFpsFormatted {
if (uiFps == null) return 'N/A';
return uiFps!.toStringAsFixed(1);
}
/// Format rotation in degrees.
String get rotateFormatted {
if (rotate == null || rotate == 0) return 'N/A';
return '$rotate°';
}
/// Format luminance value in cd/m².
String get maxLumaFormatted {
if (maxLuma == null) return 'N/A';
return '${maxLuma!.toStringAsFixed(0)} cd/m²';
}
/// Format minimum luminance value in cd/m².
String get minLumaFormatted {
if (minLuma == null) return 'N/A';
return '${minLuma!.toStringAsFixed(4)} cd/m²';
}
/// Format MaxCLL value in cd/m².
String get maxCllFormatted {
if (maxCll == null) return 'N/A';
return '${maxCll!.toStringAsFixed(0)} cd/m²';
}
/// Format MaxFALL value in cd/m².
String get maxFallFormatted {
if (maxFall == null) return 'N/A';
return '${maxFall!.toStringAsFixed(0)} cd/m²';
}
/// Check if HDR metadata is available.
bool get hasHdrMetadata {
return maxLuma != null || maxCll != null;
}
}
@@ -0,0 +1,201 @@
import 'dart:async';
import 'dart:io' show ProcessInfo;
import 'package:flutter/scheduler.dart';
import '../../../../mpv/mpv.dart';
import '../../../../utils/app_logger.dart';
import 'performance_stats.dart';
/// Service that polls MPV properties and provides performance stats via a stream.
///
/// Usage:
/// ```dart
/// final service = PerformanceStatsService(player);
/// service.startPolling();
/// service.statsStream.listen((stats) => print(stats.resolution));
/// service.stopPolling();
/// service.dispose();
/// ```
class PerformanceStatsService {
final Player player;
Timer? _pollingTimer;
final _statsController = StreamController<PerformanceStats>.broadcast();
/// The interval between stats updates.
static const pollInterval = Duration(milliseconds: 500);
// FPS tracking
int _frameCount = 0;
DateTime _lastFpsUpdate = DateTime.now();
double? _currentUiFps;
PerformanceStatsService(this.player);
/// Stream of performance stats updates.
Stream<PerformanceStats> get statsStream => _statsController.stream;
/// Start polling for stats at regular intervals.
void startPolling() {
_pollingTimer?.cancel();
// Start FPS tracking
_startFpsTracking();
// Fetch immediately, then poll
_fetchStats();
_pollingTimer = Timer.periodic(pollInterval, (_) => _fetchStats());
}
/// Start tracking UI frame rate.
void _startFpsTracking() {
_frameCount = 0;
_lastFpsUpdate = DateTime.now();
SchedulerBinding.instance.addPersistentFrameCallback(_onFrame);
}
/// Called every frame to count FPS.
void _onFrame(Duration timestamp) {
_frameCount++;
final now = DateTime.now();
final elapsed = now.difference(_lastFpsUpdate);
if (elapsed.inMilliseconds >= 1000) {
_currentUiFps = _frameCount * 1000 / elapsed.inMilliseconds;
_frameCount = 0;
_lastFpsUpdate = now;
}
}
/// Stop polling for stats.
void stopPolling() {
_pollingTimer?.cancel();
_pollingTimer = null;
}
/// Fetch all performance stats from MPV.
Future<void> _fetchStats() async {
try {
// Fetch all properties in parallel for efficiency
final results = await Future.wait([
player.getProperty('video-codec'), // 0
player.getProperty('video-params/w'), // 1
player.getProperty('video-params/h'), // 2
player.getProperty('container-fps'), // 3
player.getProperty('estimated-vf-fps'), // 4
player.getProperty('video-bitrate'), // 5
player.getProperty('hwdec-current'), // 6
player.getProperty('audio-codec-name'), // 7
player.getProperty('audio-params/samplerate'), // 8
player.getProperty('audio-params/hr-channels'), // 9
player.getProperty('audio-bitrate'), // 10
player.getProperty('total-avsync-change'), // 11
player.getProperty('cache-used'), // 12
player.getProperty('cache-speed'), // 13
player.getProperty('display-fps'), // 14
player.getProperty('frame-drop-count'), // 15
player.getProperty('decoder-frame-drop-count'), // 16
player.getProperty('demuxer-cache-duration'), // 17
// Color/Format properties
player.getProperty('video-params/pixelformat'), // 18
player.getProperty('video-params/hw-pixelformat'), // 19
player.getProperty('video-params/colormatrix'), // 20
player.getProperty('video-params/primaries'), // 21
player.getProperty('video-params/gamma'), // 22
// HDR metadata
player.getProperty('video-params/max-luma'), // 23
player.getProperty('video-params/min-luma'), // 24
player.getProperty('video-params/max-cll'), // 25
player.getProperty('video-params/max-fall'), // 26
// Other
player.getProperty('video-params/aspect-name'), // 27
player.getProperty('video-params/rotate'), // 28
]);
// Get app memory usage
int? appMemory;
try {
appMemory = ProcessInfo.currentRss;
} catch (_) {
// ProcessInfo not available on all platforms
}
final stats = PerformanceStats(
videoCodec: _formatCodecName(results[0]),
videoWidth: _parseInt(results[1]),
videoHeight: _parseInt(results[2]),
videoFps: _parseDouble(results[3]),
actualFps: _parseDouble(results[4]),
videoBitrate: _parseInt(results[5]),
hwdecCurrent: results[6],
audioCodec: _formatCodecName(results[7]),
audioSamplerate: _parseInt(results[8]),
audioChannels: results[9],
audioBitrate: _parseInt(results[10]),
avsyncChange: _parseDouble(results[11]),
cacheUsed: _parseInt(results[12]),
cacheSpeed: _parseDouble(results[13]),
displayFps: _parseDouble(results[14]),
frameDropCount: _parseInt(results[15]),
decoderFrameDropCount: _parseInt(results[16]),
cacheDuration: _parseDouble(results[17]),
// Color/Format properties
pixelformat: results[18],
hwPixelformat: results[19],
colormatrix: results[20],
primaries: results[21],
gamma: results[22],
// HDR metadata
maxLuma: _parseDouble(results[23]),
minLuma: _parseDouble(results[24]),
maxCll: _parseDouble(results[25]),
maxFall: _parseDouble(results[26]),
// Other
aspectName: results[27],
rotate: _parseInt(results[28]),
appMemoryBytes: appMemory,
uiFps: _currentUiFps,
);
_statsController.add(stats);
} catch (e) {
appLogger.w('Failed to fetch performance stats', error: e);
}
}
/// Parse a string to int, returning null if parsing fails.
int? _parseInt(String? value) {
if (value == null || value.isEmpty) return null;
return int.tryParse(value);
}
/// Parse a string to double, returning null if parsing fails.
double? _parseDouble(String? value) {
if (value == null || value.isEmpty) return null;
return double.tryParse(value);
}
/// Format codec name for display (uppercase common codecs).
String? _formatCodecName(String? codec) {
if (codec == null || codec.isEmpty) return null;
// Common codec name mappings
final upper = codec.toUpperCase();
if (upper.contains('HEVC') || upper.contains('H265')) return 'HEVC';
if (upper.contains('H264') || upper.contains('AVC')) return 'H.264';
if (upper.contains('AV1')) return 'AV1';
if (upper.contains('VP9')) return 'VP9';
if (upper.contains('AAC')) return 'AAC';
if (upper.contains('AC3') || upper.contains('AC-3')) return 'AC3';
if (upper.contains('EAC3') || upper.contains('E-AC-3')) return 'EAC3';
if (upper.contains('DTS')) return 'DTS';
if (upper.contains('TRUEHD')) return 'TrueHD';
if (upper.contains('FLAC')) return 'FLAC';
if (upper.contains('OPUS')) return 'Opus';
if (upper.contains('VORBIS')) return 'Vorbis';
if (upper.contains('MP3')) return 'MP3';
return codec;
}
/// Dispose of the service and release resources.
void dispose() {
stopPolling();
_statsController.close();
}
}
@@ -52,6 +52,24 @@ class _VolumeControlState extends State<VolumeControl> {
/// Volume step size for keyboard adjustment.
static const double _volumeStep = 5.0;
/// Maximum volume from settings (100-300).
int _maxVolume = 100;
@override
void initState() {
super.initState();
_loadMaxVolume();
}
Future<void> _loadMaxVolume() async {
final settings = await SettingsService.getInstance();
if (mounted) {
setState(() {
_maxVolume = settings.getMaxVolume();
});
}
}
void _enterAdjustMode() {
setState(() {
_isAdjustMode = true;
@@ -66,7 +84,7 @@ class _VolumeControlState extends State<VolumeControl> {
Future<void> _adjustVolume(double delta) async {
final currentVolume = widget.player.state.volume;
final newVolume = (currentVolume + delta).clamp(0.0, 100.0);
final newVolume = (currentVolume + delta).clamp(0.0, _maxVolume.toDouble());
widget.player.setVolume(newVolume);
final settings = await SettingsService.getInstance();
await settings.setVolume(newVolume);
@@ -178,33 +196,58 @@ class _VolumeControlState extends State<VolumeControl> {
Widget _buildVolumeSlider(double volume, bool isKeyboardMode) {
// Show visual indicator when in adjust mode with keyboard
final showAdjustIndicator = _isAdjustMode && isKeyboardMode;
final maxVolumeDouble = _maxVolume.toDouble();
// Calculate 100% marker position as fraction of slider width
// Only show marker if max volume > 100
final showMarker = _maxVolume > 100;
final markerPosition = showMarker ? (100.0 / maxVolumeDouble) : 0.0;
return SizedBox(
width: 100,
child: SliderTheme(
data: SliderThemeData(
trackHeight: showAdjustIndicator ? 4 : 3,
thumbShape: RoundSliderThumbShape(enabledThumbRadius: showAdjustIndicator ? 8 : 6),
overlayShape: const RoundSliderOverlayShape(overlayRadius: 12),
),
child: Semantics(
label: t.videoControls.volumeSlider,
slider: true,
child: Slider(
value: volume,
min: 0.0,
max: 100.0,
onChanged: (value) {
widget.player.setVolume(value);
},
onChangeEnd: (value) async {
final settings = await SettingsService.getInstance();
await settings.setVolume(value);
},
activeColor: Colors.white,
inactiveColor: Colors.white.withValues(alpha: 0.3),
child: Stack(
alignment: Alignment.centerLeft,
children: [
// 100% marker (only shown if max > 100)
if (showMarker)
Positioned(
left: 100 * markerPosition - 1, // Adjust for marker width
child: Container(
width: 2,
height: 12,
decoration: BoxDecoration(
color: Colors.white.withValues(alpha: 0.6),
borderRadius: BorderRadius.circular(1),
),
),
),
// Volume slider
SliderTheme(
data: SliderThemeData(
trackHeight: showAdjustIndicator ? 4 : 3,
thumbShape: RoundSliderThumbShape(enabledThumbRadius: showAdjustIndicator ? 8 : 6),
overlayShape: const RoundSliderOverlayShape(overlayRadius: 12),
),
child: Semantics(
label: t.videoControls.volumeSlider,
slider: true,
child: Slider(
value: volume.clamp(0.0, maxVolumeDouble),
min: 0.0,
max: maxVolumeDouble,
onChanged: (value) {
widget.player.setVolume(value);
},
onChangeEnd: (value) async {
final settings = await SettingsService.getInstance();
await settings.setVolume(value);
},
activeColor: Colors.white,
inactiveColor: Colors.white.withValues(alpha: 0.3),
),
),
),
),
],
),
);
}
@@ -11,6 +11,7 @@ import file_picker
import flutter_webrtc
import gamepads_darwin
import hotkey_manager_macos
import in_app_review
import macos_window_utils
import os_media_controls
import package_info_plus
@@ -31,6 +32,7 @@ func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) {
FlutterWebRTCPlugin.register(with: registry.registrar(forPlugin: "FlutterWebRTCPlugin"))
GamepadsDarwinPlugin.register(with: registry.registrar(forPlugin: "GamepadsDarwinPlugin"))
HotkeyManagerMacosPlugin.register(with: registry.registrar(forPlugin: "HotkeyManagerMacosPlugin"))
InAppReviewPlugin.register(with: registry.registrar(forPlugin: "InAppReviewPlugin"))
MacOSWindowUtilsPlugin.register(with: registry.registrar(forPlugin: "MacOSWindowUtilsPlugin"))
OsMediaControlsPlugin.register(with: registry.registrar(forPlugin: "OsMediaControlsPlugin"))
FPPPackageInfoPlusPlugin.register(with: registry.registrar(forPlugin: "FPPPackageInfoPlusPlugin"))
+6
View File
@@ -15,6 +15,8 @@ PODS:
- hotkey_manager_macos (0.0.1):
- FlutterMacOS
- HotKey
- in_app_review (2.0.0):
- FlutterMacOS
- macos_window_utils (1.0.0):
- FlutterMacOS
- os_media_controls (0.0.1):
@@ -75,6 +77,7 @@ DEPENDENCIES:
- FlutterMacOS (from `Flutter/ephemeral`)
- gamepads_darwin (from `Flutter/ephemeral/.symlinks/plugins/gamepads_darwin/macos`)
- hotkey_manager_macos (from `Flutter/ephemeral/.symlinks/plugins/hotkey_manager_macos/macos`)
- in_app_review (from `Flutter/ephemeral/.symlinks/plugins/in_app_review/macos`)
- macos_window_utils (from `Flutter/ephemeral/.symlinks/plugins/macos_window_utils/macos`)
- os_media_controls (from `Flutter/ephemeral/.symlinks/plugins/os_media_controls/macos`)
- package_info_plus (from `Flutter/ephemeral/.symlinks/plugins/package_info_plus/macos`)
@@ -109,6 +112,8 @@ EXTERNAL SOURCES:
:path: Flutter/ephemeral/.symlinks/plugins/gamepads_darwin/macos
hotkey_manager_macos:
:path: Flutter/ephemeral/.symlinks/plugins/hotkey_manager_macos/macos
in_app_review:
:path: Flutter/ephemeral/.symlinks/plugins/in_app_review/macos
macos_window_utils:
:path: Flutter/ephemeral/.symlinks/plugins/macos_window_utils/macos
os_media_controls:
@@ -143,6 +148,7 @@ SPEC CHECKSUMS:
gamepads_darwin: 643b6a69e20ca678fae83781b7f7fc8f15f5d710
HotKey: 400beb7caa29054ea8d864c96f5ba7e5b4852277
hotkey_manager_macos: a4317849af96d2430fa89944d3c58977ca089fbe
in_app_review: 66e7680752b632d83f4f0e88b34d52ed303fbff4
macos_window_utils: 23f54331a0fd51eea9e0ed347253bf48fd379d1d
os_media_controls: c07c04c4afdf59dda0a3f398457a46823c4ce0ed
package_info_plus: f0052d280d17aa382b932f399edf32507174e870
+15 -2
View File
@@ -301,11 +301,24 @@ class MpvPlayerCore: NSObject {
case MPV_EVENT_SHUTDOWN:
print("[MpvPlayerCore] MPV shutdown event")
case MPV_EVENT_PLAYBACK_RESTART:
DispatchQueue.main.async {
self.delegate?.onEvent(name: "playback-restart", data: nil)
}
case MPV_EVENT_LOG_MESSAGE:
if let msgPtr = event.data?.assumingMemoryBound(to: mpv_event_log_message.self) {
let msg = msgPtr.pointee
if let prefix = msg.prefix, let level = msg.level, let text = msg.text {
print("[MPV:\(String(cString: prefix))] \(String(cString: level)): \(String(cString: text))", terminator: "")
let prefix = msg.prefix.map { String(cString: $0) } ?? ""
let level = msg.level.map { String(cString: $0) } ?? ""
let text = msg.text.map { String(cString: $0) } ?? ""
DispatchQueue.main.async {
self.delegate?.onEvent(name: "log-message", data: [
"prefix": prefix,
"level": level,
"text": text
])
}
}
+19 -3
View File
@@ -648,6 +648,22 @@ packages:
url: "https://pub.dev"
source: hosted
version: "4.5.4"
in_app_review:
dependency: "direct main"
description:
name: in_app_review
sha256: ab26ac54dbd802896af78c670b265eaeab7ecddd6af4d0751e9604b60574817f
url: "https://pub.dev"
source: hosted
version: "2.0.11"
in_app_review_platform_interface:
dependency: transitive
description:
name: in_app_review_platform_interface
sha256: fed2c755f2125caa9ae10495a3c163aa7fab5af3585a9c62ef4a6920c5b45f10
url: "https://pub.dev"
source: hosted
version: "2.0.5"
io:
dependency: transitive
description:
@@ -820,11 +836,11 @@ packages:
dependency: "direct main"
description:
path: "."
ref: "75dc5642cd148c54c03fe96976702b8d31c48599"
resolved-ref: "75dc5642cd148c54c03fe96976702b8d31c48599"
ref: "60b3bbbe16773d3862253c97df4b1e0a3b1cd0d4"
resolved-ref: "60b3bbbe16773d3862253c97df4b1e0a3b1cd0d4"
url: "https://github.com/edde746/os-media-controls"
source: git
version: "0.1.0"
version: "0.2.0"
package_config:
dependency: transitive
description:
+3 -2
View File
@@ -1,7 +1,7 @@
name: plezy
description: "A beautiful Plex client for Flutter"
publish_to: "none"
version: 1.11.0+25
version: 1.12.0+28
environment:
sdk: ^3.8.1
@@ -31,7 +31,7 @@ dependencies:
os_media_controls:
git:
url: https://github.com/edde746/os-media-controls
ref: 75dc5642cd148c54c03fe96976702b8d31c48599
ref: 60b3bbbe16773d3862253c97df4b1e0a3b1cd0d4
rate_limiter: ^1.0.0
wakelock_plus: ^1.2.10
path_provider: ^2.1.0
@@ -47,6 +47,7 @@ dependencies:
material_symbols_icons: ^4.2892.0
peerdart: ^0.5.6
share_plus: ^10.0.0
in_app_review: ^2.0.11
dev_dependencies:
flutter_test:
+15 -47
View File
@@ -1,33 +1,25 @@
#include "mpv_container.h"
#include <ShObjIdl.h>
#include <dwmapi.h>
#include <fstream>
#include "mpv_core.h"
#include "utils.h"
static void LogToFile(const char* message) {
std::ofstream log("C:\\Users\\admin\\mpv_debug.log", std::ios::app);
if (log.is_open()) {
log << message << std::endl;
log.close();
}
OutputDebugStringA(message);
OutputDebugStringA("\n");
}
namespace mpv {
MpvContainer* MpvContainer::GetInstance() { return instance_.get(); }
HWND MpvContainer::Create() {
LogToFile("MpvContainer::Create called");
MpvContainer::~MpvContainer() {
if (taskbar_) {
taskbar_->Release();
taskbar_ = nullptr;
}
}
HWND MpvContainer::Create() {
auto window_class = WNDCLASSEX{};
::SecureZeroMemory(&window_class, sizeof(window_class));
window_class.cbSize = sizeof(window_class);
// Don't use CS_DROPSHADOW, and avoid redraw styles that might cause issues
window_class.style = 0;
window_class.lpfnWndProc = WindowProc;
window_class.hInstance = GetModuleHandle(nullptr);
@@ -35,10 +27,7 @@ HWND MpvContainer::Create() {
window_class.hCursor = ::LoadCursorW(nullptr, IDC_ARROW);
window_class.hbrBackground = ::CreateSolidBrush(RGB(0, 0, 0));
ATOM atom = ::RegisterClassExW(&window_class);
char msg[256];
snprintf(msg, sizeof(msg), "MpvContainer::Create - RegisterClassExW returned: %d", atom);
LogToFile(msg);
::RegisterClassExW(&window_class);
// Use WS_POPUP for a borderless window without title bar.
// Use WS_EX_TOOLWINDOW | WS_EX_NOREDIRECTIONBITMAP to prevent shadow and DWM effects.
@@ -48,15 +37,6 @@ HWND MpvContainer::Create() {
0, 0, 100, 100, nullptr, nullptr,
GetModuleHandle(nullptr), nullptr);
if (!handle_) {
DWORD error = GetLastError();
snprintf(msg, sizeof(msg), "MpvContainer::Create - CreateWindow failed with error %lu", error);
LogToFile(msg);
} else {
snprintf(msg, sizeof(msg), "MpvContainer::Create - handle_: %p", handle_);
LogToFile(msg);
}
// Disable DWM animations on the container.
auto disable_window_transitions = TRUE;
DwmSetWindowAttribute(handle_, DWMWA_TRANSITIONS_FORCEDISABLED,
@@ -67,42 +47,30 @@ HWND MpvContainer::Create() {
}
HWND MpvContainer::Get(HWND flutter_window) {
LogToFile("MpvContainer::Get called");
char msg[256];
snprintf(msg, sizeof(msg), "MpvContainer::Get - flutter_window: %p, handle_: %p", flutter_window, handle_);
LogToFile(msg);
if (!handle_) {
LogToFile("MpvContainer::Get - handle_ is null, calling Create()");
Create();
}
RECT window_rect;
::GetWindowRect(flutter_window, &window_rect);
snprintf(msg, sizeof(msg), "MpvContainer::Get - window_rect: %ld,%ld,%ld,%ld",
window_rect.left, window_rect.top, window_rect.right, window_rect.bottom);
LogToFile(msg);
::SetWindowPos(handle_, flutter_window, window_rect.left, window_rect.top,
window_rect.right - window_rect.left,
window_rect.bottom - window_rect.top, SWP_NOACTIVATE);
::SetWindowLongPtr(handle_, GWLP_USERDATA,
reinterpret_cast<LONG_PTR>(flutter_window));
// Remove taskbar entry using ITaskbarList3.
ITaskbarList3* taskbar = nullptr;
HRESULT hr = ::CoCreateInstance(CLSID_TaskbarList, 0, CLSCTX_INPROC_SERVER,
IID_PPV_ARGS(&taskbar));
if (SUCCEEDED(hr) && taskbar) {
taskbar->DeleteTab(handle_);
taskbar->Release();
// Remove taskbar entry using cached ITaskbarList3.
if (!taskbar_) {
::CoCreateInstance(CLSID_TaskbarList, 0, CLSCTX_INPROC_SERVER,
IID_PPV_ARGS(&taskbar_));
}
if (taskbar_) {
taskbar_->DeleteTab(handle_);
}
::ShowWindow(handle_, SW_SHOWNOACTIVATE);
::SetFocus(flutter_window);
snprintf(msg, sizeof(msg), "MpvContainer::Get - returning handle_: %p", handle_);
LogToFile(msg);
return handle_;
}
+3
View File
@@ -1,6 +1,7 @@
#ifndef MPV_CONTAINER_H_
#define MPV_CONTAINER_H_
#include <ShObjIdl.h>
#include <Windows.h>
#include <memory>
@@ -17,6 +18,7 @@ class MpvContainer {
static MpvContainer* GetInstance();
MpvContainer() = default;
~MpvContainer();
// Creates the container window.
HWND Create();
@@ -32,6 +34,7 @@ class MpvContainer {
LPARAM lparam) noexcept;
HWND handle_ = nullptr;
ITaskbarList3* taskbar_ = nullptr;
static constexpr wchar_t kClassName[] = L"MPV_CONTAINER";
static constexpr wchar_t kWindowName[] = L"";
+58 -80
View File
@@ -1,20 +1,10 @@
#include "mpv_core.h"
#include <fstream>
#include <dwmapi.h>
#include "mpv_container.h"
#include "utils.h"
static void LogToFile(const char* message) {
std::ofstream log("C:\\Users\\admin\\mpv_debug.log", std::ios::app);
if (log.is_open()) {
log << message << std::endl;
log.close();
}
OutputDebugStringA(message);
OutputDebugStringA("\n");
}
namespace mpv {
MpvCore* MpvCore::GetInstance() { return instance_.get(); }
@@ -40,20 +30,8 @@ MpvCore::~MpvCore() {
}
void MpvCore::EnsureInitialized() {
LogToFile("MpvCore::EnsureInitialized called");
char msg[256];
snprintf(msg, sizeof(msg), "MpvCore::EnsureInitialized - flutter_window_: %p", flutter_window_);
LogToFile(msg);
// Enable per-pixel transparency on Flutter window.
LogToFile("MpvCore::EnsureInitialized - calling SetWindowComposition");
SetWindowComposition(flutter_window_, 6, 0);
LogToFile("MpvCore::EnsureInitialized - getting container");
// Get container - composition will be enabled in SetVisible() to batch DwmFlush calls
container_ = MpvContainer::GetInstance()->Get(flutter_window_);
snprintf(msg, sizeof(msg), "MpvCore::EnsureInitialized - container: %p", container_);
LogToFile(msg);
}
void MpvCore::CreateMpvView(HWND mpv_hwnd, RECT rect,
@@ -101,23 +79,34 @@ void MpvCore::SetHitTestBehavior(int32_t hittest_behavior) {
ex_style &= ~(WS_EX_TRANSPARENT | WS_EX_LAYERED);
}
::SetWindowLong(flutter_window_, GWL_EXSTYLE, ex_style);
// Force Windows to recalculate window frame after extended style changes.
// This ensures the render surface dimensions match the new window state.
::SetWindowPos(flutter_window_, nullptr, 0, 0, 0, 0,
SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE);
// Sync with DWM to ensure render target is updated
::DwmFlush();
}
void MpvCore::SetVisible(bool visible) {
char msg[256];
snprintf(msg, sizeof(msg), "MpvCore::SetVisible - visible: %d, container_: %p", visible, container_);
LogToFile(msg);
visible_ = visible;
if (container_) {
if (visible) {
SetWindowComposition(flutter_window_, 6, 0);
// Batch all window operations, single DwmFlush at end
::SetWindowPos(flutter_window_, nullptr, 0, 0, 0, 0,
SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE);
if (!composition_enabled_) {
SetWindowComposition(flutter_window_, 6, 0);
composition_enabled_ = true;
}
::ShowWindow(container_, SW_SHOWNOACTIVATE);
LogToFile("MpvCore::SetVisible - showed container, set composition to 6");
::DwmFlush(); // Single sync with DWM after all operations
} else {
SetWindowComposition(flutter_window_, 0, 0);
composition_enabled_ = false;
::ShowWindow(container_, SW_HIDE);
LogToFile("MpvCore::SetVisible - hid container, set composition to 0");
::DwmFlush(); // Sync with DWM after hiding
}
}
}
@@ -135,68 +124,55 @@ std::optional<HRESULT> MpvCore::WindowProc(HWND hwnd, UINT message,
break;
}
case WM_SIZE: {
char msg[256];
snprintf(msg, sizeof(msg), "WM_SIZE - wparam: %llu, last: %llu, visible_: %d, was_hidden: %d",
(unsigned long long)wparam, (unsigned long long)last_wm_size_wparam_,
visible_, was_window_hidden_due_to_minimize_);
LogToFile(msg);
// Handle Windows's minimize & maximize animations properly.
// During these transitions, we hide the container and make Flutter opaque,
// then restore after the animation completes.
// then restore after the animation completes using a Windows timer.
if (wparam != SIZE_RESTORED || last_wm_size_wparam_ == SIZE_MINIMIZED ||
last_wm_size_wparam_ == SIZE_MAXIMIZED ||
was_window_hidden_due_to_minimize_) {
was_window_hidden_due_to_minimize_ = false;
SetWindowComposition(flutter_window_, 0, 0);
composition_enabled_ = false;
::ShowWindow(container_, SW_HIDE);
LogToFile("WM_SIZE - hiding container, starting delay thread");
last_thread_time_ =
std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now().time_since_epoch())
.count();
std::thread(
[this](uint64_t time) {
std::this_thread::sleep_for(
std::chrono::milliseconds(kPositionAndShowDelay));
::DwmFlush(); // Single sync after hiding
// Check if this thread is still the latest (another WM_SIZE may have come in)
if (time != last_thread_time_) {
LogToFile("WM_SIZE thread - superseded by newer thread, skipping");
return;
}
char msg2[256];
snprintf(msg2, sizeof(msg2), "WM_SIZE thread - after delay, visible_: %d",
visible_);
LogToFile(msg2);
// Update container position to match current Flutter window bounds
RECT window_rect;
::GetWindowRect(flutter_window_, &window_rect);
snprintf(msg2, sizeof(msg2), "WM_SIZE thread - flutter rect: %ld,%ld,%ld,%ld",
window_rect.left, window_rect.top, window_rect.right, window_rect.bottom);
LogToFile(msg2);
::SetWindowPos(container_, flutter_window_, window_rect.left,
window_rect.top, window_rect.right - window_rect.left,
window_rect.bottom - window_rect.top, SWP_NOACTIVATE);
LogToFile("WM_SIZE thread - updated container position");
// Always restore transparency if video is visible
if (visible_) {
SetWindowComposition(flutter_window_, 6, 0);
LogToFile("WM_SIZE thread - restored composition to 6");
::ShowWindow(container_, SW_SHOWNOACTIVATE);
LogToFile("WM_SIZE thread - showed container");
}
},
last_thread_time_)
.detach();
// Cancel any pending timer and set a new one.
::KillTimer(flutter_window_, kCompositionRestoreTimerId);
::SetTimer(flutter_window_, kCompositionRestoreTimerId, kPositionAndShowDelay, nullptr);
}
last_wm_size_wparam_ = wparam;
break;
}
case WM_TIMER: {
if (wparam == kCompositionRestoreTimerId) {
::KillTimer(flutter_window_, kCompositionRestoreTimerId);
// Update container position to match current Flutter window bounds
RECT window_rect;
::GetWindowRect(flutter_window_, &window_rect);
::SetWindowPos(container_, flutter_window_, window_rect.left,
window_rect.top, window_rect.right - window_rect.left,
window_rect.bottom - window_rect.top, SWP_NOACTIVATE);
// Restore transparency if video is visible
if (visible_) {
// Batch all operations, single DwmFlush at end
::SetWindowPos(flutter_window_, nullptr, 0, 0, 0, 0,
SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE);
if (!composition_enabled_) {
SetWindowComposition(flutter_window_, 6, 0);
composition_enabled_ = true;
}
::ShowWindow(container_, SW_SHOWNOACTIVATE);
::DwmFlush(); // Single sync after all operations
// Force a redraw to ensure Flutter's render surface is correctly sized
::RedrawWindow(flutter_window_, nullptr, nullptr,
RDW_INVALIDATE | RDW_UPDATENOW | RDW_ALLCHILDREN);
}
}
break;
}
case WM_MOVE:
case WM_MOVING:
case WM_WINDOWPOSCHANGED: {
@@ -211,7 +187,9 @@ std::optional<HRESULT> MpvCore::WindowProc(HWND hwnd, UINT message,
if (window_rect.left < 0 && window_rect.top < 0 &&
window_rect.right < 0 && window_rect.bottom < 0) {
SetWindowComposition(flutter_window_, 0, 0);
composition_enabled_ = false;
::ShowWindow(container_, SW_HIDE);
::DwmFlush(); // Single sync after hiding
was_window_hidden_due_to_minimize_ = true;
}
}
+2 -3
View File
@@ -3,12 +3,10 @@
#include <Windows.h>
#include <chrono>
#include <cmath>
#include <map>
#include <memory>
#include <optional>
#include <thread>
namespace mpv {
@@ -17,6 +15,7 @@ namespace mpv {
class MpvCore {
public:
static constexpr auto kPositionAndShowDelay = 300;
static constexpr UINT_PTR kCompositionRestoreTimerId = 1001;
static MpvCore* GetInstance();
static void SetInstance(std::unique_ptr<MpvCore> instance);
@@ -57,10 +56,10 @@ class MpvCore {
HWND container_ = nullptr;
double device_pixel_ratio_ = 1.0;
std::map<HWND, RECT> mpv_views_;
uint64_t last_thread_time_ = 0;
WPARAM last_wm_size_wparam_ = SIZE_RESTORED;
bool was_window_hidden_due_to_minimize_ = false;
bool visible_ = true;
bool composition_enabled_ = false;
static std::unique_ptr<MpvCore> instance_;
static std::optional<int32_t> proc_id_;