Compare commits

..
14 Commits
Author SHA1 Message Date
edde746 260681aa24 chore: bump version 2025-11-08 10:10:58 +01:00
edde746 6228eb2690 refactor: rewrite os media controls
# Conflicts:
#	lib/screens/video_player_screen.dart
#	lib/services/media_service_manager.dart
#	pubspec.yaml
2025-11-08 10:04:51 +01:00
edde746 0d4f7a9e9f refactor: remove duplicate audio sessions 2025-11-08 08:35:52 +01:00
edde746 fac7aed1e7 feat: shuffle settings 2025-11-07 20:50:09 +01:00
edde746 b6234120dd fix: android crash 2025-11-07 17:53:44 +01:00
edde746 2eb33eb234 fix: android icons 2025-11-07 17:44:50 +01:00
edde746 d744e783ac feat: pgs & truehd support 2025-11-07 17:24:30 +01:00
edde746 3e068b2bea chore: update lockfile 2025-11-07 02:21:23 +01:00
edde746andGitHub 36a843b43f Merge pull request #65 from ComicalHysteria/QR-code-sign-in
Add QR code generation for sign in
2025-11-07 02:19:08 +01:00
edde746 3f40007f03 feat: throttle seeking commands 2025-11-07 02:16:07 +01:00
ComicalHysteriaandGitHub 66941b06d4 Add QR code generation for sign in 2025-11-06 14:40:38 -06:00
edde746 47f5454f61 feat: os media controls 2025-11-06 15:14:40 +01:00
edde746 2a6098c3ba feat: load library in parts 2025-11-06 11:54:31 +01:00
edde746 60a84380a6 feat: external subtitle support 2025-11-06 10:36:26 +01:00
39 changed files with 1563 additions and 199 deletions
+22
View File
@@ -3,6 +3,11 @@
<!-- Internet access permissions -->
<uses-permission android:name="android.permission.INTERNET"/>
<!-- Audio service permissions -->
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK"/>
<!-- Explicitly remove media permissions that media_kit may add -->
<uses-permission android:name="android.permission.READ_MEDIA_AUDIO" tools:node="remove" />
<uses-permission android:name="android.permission.READ_MEDIA_VIDEO" tools:node="remove" />
@@ -40,6 +45,23 @@
<meta-data
android:name="flutterEmbedding"
android:value="2" />
<!-- Audio service -->
<service android:name="com.ryanheise.audioservice.AudioService"
android:foregroundServiceType="mediaPlayback"
android:exported="true" tools:ignore="Instantiatable">
<intent-filter>
<action android:name="android.media.browse.MediaBrowserService" />
</intent-filter>
</service>
<!-- Media button receiver -->
<receiver android:name="com.ryanheise.audioservice.MediaButtonReceiver"
android:exported="true" tools:ignore="Instantiatable">
<intent-filter>
<action android:name="android.intent.action.MEDIA_BUTTON" />
</intent-filter>
</receiver>
</application>
<!-- Required to query activities that can process text, see:
https://developer.android.com/training/package-visibility and
@@ -1,5 +1,5 @@
package com.edde746.plezy
import io.flutter.embedding.android.FlutterActivity
import com.ryanheise.audioservice.AudioServiceActivity
class MainActivity : FlutterActivity()
class MainActivity : AudioServiceActivity()
Binary file not shown.

Before

Width:  |  Height:  |  Size: 582 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 354 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 820 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 724 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

@@ -8,7 +8,7 @@
</foreground>
<monochrome>
<inset
android:drawable="@drawable/ic_launcher_monochrome"
android:drawable="@mipmap/ic_launcher_monochrome"
android:inset="16%" />
</monochrome>
</adaptive-icon>
Binary file not shown.

After

Width:  |  Height:  |  Size: 4.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

+13
View File
@@ -1,4 +1,9 @@
PODS:
- audio_service (0.0.1):
- Flutter
- FlutterMacOS
- audio_session (0.0.1):
- Flutter
- Flutter (1.0.0)
- media_kit_libs_ios_video (1.0.4):
- Flutter
@@ -23,6 +28,8 @@ PODS:
- Flutter
DEPENDENCIES:
- audio_service (from `.symlinks/plugins/audio_service/darwin`)
- audio_session (from `.symlinks/plugins/audio_session/ios`)
- Flutter (from `Flutter`)
- media_kit_libs_ios_video (from `.symlinks/plugins/media_kit_libs_ios_video/ios`)
- media_kit_video (from `.symlinks/plugins/media_kit_video/ios`)
@@ -35,6 +42,10 @@ DEPENDENCIES:
- wakelock_plus (from `.symlinks/plugins/wakelock_plus/ios`)
EXTERNAL SOURCES:
audio_service:
:path: ".symlinks/plugins/audio_service/darwin"
audio_session:
:path: ".symlinks/plugins/audio_session/ios"
Flutter:
:path: Flutter
media_kit_libs_ios_video:
@@ -57,6 +68,8 @@ EXTERNAL SOURCES:
:path: ".symlinks/plugins/wakelock_plus/ios"
SPEC CHECKSUMS:
audio_service: aa99a6ba2ae7565996015322b0bb024e1d25c6fd
audio_session: 9bb7f6c970f21241b19f5a3658097ae459681ba0
Flutter: cabc95a1d2626b1b06e7179b784ebcf0c0cde467
media_kit_libs_ios_video: 5a18affdb97d1f5d466dc79988b13eff6c5e2854
media_kit_video: 1746e198cb697d1ffb734b1d05ec429d1fcd1474
+4
View File
@@ -39,6 +39,10 @@
<string>This app needs to connect to your Plex Media Server on your local network.</string>
<key>UIApplicationSupportsIndirectInputEvents</key>
<true/>
<key>UIBackgroundModes</key>
<array>
<string>audio</string>
</array>
<key>UILaunchStoryboardName</key>
<string>LaunchScreen</string>
<key>UIMainStoryboardFile</key>
+3 -1
View File
@@ -38,7 +38,7 @@ class PlexClient {
baseUrl: config.baseUrl,
headers: config.headers,
connectTimeout: const Duration(seconds: 10),
receiveTimeout: const Duration(seconds: 30),
receiveTimeout: const Duration(seconds: 120),
validateStatus: (status) => status != null && status < 500,
responseType: ResponseType.json,
contentType: 'application/json; charset=utf-8',
@@ -228,6 +228,7 @@ class PlexClient {
int? start,
int? size,
Map<String, String>? filters,
CancelToken? cancelToken,
}) async {
final queryParams = <String, dynamic>{};
if (start != null) queryParams['X-Plex-Container-Start'] = start;
@@ -241,6 +242,7 @@ class PlexClient {
final response = await _dio.get(
'/library/sections/$sectionId/all',
queryParameters: queryParams,
cancelToken: cancelToken,
);
return _extractMetadataList(response);
+44
View File
@@ -77,6 +77,50 @@ class PlexSubtitleTrack {
if (forced) parts.add('Forced');
return parts.isEmpty ? 'Track ${index ?? id}' : parts.join(' · ');
}
/// Returns true if this subtitle track is an external file (sidecar subtitle)
/// External subtitles have a key property that points to /library/streams/{id}
bool get isExternal => key != null && key!.isNotEmpty;
/// Constructs the full URL for fetching external subtitle files
/// Returns null if this is not an external subtitle
String? getSubtitleUrl(String baseUrl, String token) {
if (!isExternal) return null;
// Determine file extension based on codec
final ext = _getExtensionFromCodec(codec);
// Construct URL with authentication token
return '$baseUrl$key.$ext?X-Plex-Token=$token';
}
/// Maps Plex subtitle codec names to file extensions
String _getExtensionFromCodec(String? codec) {
if (codec == null) return 'srt';
switch (codec.toLowerCase()) {
case 'subrip':
case 'srt':
return 'srt';
case 'ass':
return 'ass';
case 'ssa':
return 'ssa';
case 'webvtt':
case 'vtt':
return 'vtt';
case 'mov_text':
return 'srt';
case 'pgs':
case 'hdmv_pgs_subtitle':
return 'sup';
case 'dvd_subtitle':
case 'dvdsub':
return 'sub';
default:
return 'srt'; // Default to SRT for unknown codecs
}
}
}
class PlexChapter {
+32 -1
View File
@@ -25,7 +25,8 @@ class PlaybackStateProvider with ChangeNotifier {
/// Gets the next episode in the shuffle queue.
/// Returns null if queue is exhausted or current episode is not in queue.
PlexMetadata? getNextEpisode(String currentEpisodeKey) {
/// [loopQueue] - If true, restart from beginning when queue is exhausted
PlexMetadata? getNextEpisode(String currentEpisodeKey, {bool loopQueue = false}) {
if (_shuffleQueue.isEmpty) return null;
// Find current episode in queue
@@ -42,6 +43,11 @@ class PlaybackStateProvider with ChangeNotifier {
// Check if there's a next episode
if (currentIndex + 1 >= _shuffleQueue.length) {
// Queue exhausted
if (loopQueue && _shuffleQueue.isNotEmpty) {
// Loop back to beginning
_currentIndex = 0;
return _shuffleQueue[_currentIndex];
}
return null;
}
@@ -49,6 +55,31 @@ class PlaybackStateProvider with ChangeNotifier {
return _shuffleQueue[_currentIndex];
}
/// Gets the previous episode in the shuffle queue.
/// Returns null if at the beginning of the queue or current episode is not in queue.
PlexMetadata? getPreviousEpisode(String currentEpisodeKey) {
if (_shuffleQueue.isEmpty) return null;
// Find current episode in queue
final currentIndex = _shuffleQueue.indexWhere(
(ep) => ep.ratingKey == currentEpisodeKey,
);
if (currentIndex == -1) {
// Current episode not in queue
return null;
}
// Check if there's a previous episode
if (currentIndex <= 0) {
// At the beginning of queue
return null;
}
_currentIndex = currentIndex - 1;
return _shuffleQueue[_currentIndex];
}
/// Clears the shuffle queue and exits shuffle mode
void clearShuffle() {
_shuffleQueue = [];
+33
View File
@@ -7,6 +7,9 @@ class SettingsProvider extends ChangeNotifier {
ViewMode _viewMode = ViewMode.grid;
bool _useSeasonPoster = false;
bool _showHeroSection = true;
bool _shuffleUnwatchedOnly = true;
bool _shuffleOrderNavigation = true;
bool _shuffleLoopQueue = false;
SettingsProvider() {
_initializeSettings();
@@ -18,6 +21,9 @@ class SettingsProvider extends ChangeNotifier {
_viewMode = _settingsService.getViewMode();
_useSeasonPoster = _settingsService.getUseSeasonPoster();
_showHeroSection = _settingsService.getShowHeroSection();
_shuffleUnwatchedOnly = _settingsService.getShuffleUnwatchedOnly();
_shuffleOrderNavigation = _settingsService.getShuffleOrderNavigation();
_shuffleLoopQueue = _settingsService.getShuffleLoopQueue();
notifyListeners();
}
@@ -25,6 +31,9 @@ class SettingsProvider extends ChangeNotifier {
ViewMode get viewMode => _viewMode;
bool get useSeasonPoster => _useSeasonPoster;
bool get showHeroSection => _showHeroSection;
bool get shuffleUnwatchedOnly => _shuffleUnwatchedOnly;
bool get shuffleOrderNavigation => _shuffleOrderNavigation;
bool get shuffleLoopQueue => _shuffleLoopQueue;
Future<void> setLibraryDensity(LibraryDensity density) async {
if (_libraryDensity != density) {
@@ -58,6 +67,30 @@ class SettingsProvider extends ChangeNotifier {
}
}
Future<void> setShuffleUnwatchedOnly(bool value) async {
if (_shuffleUnwatchedOnly != value) {
_shuffleUnwatchedOnly = value;
await _settingsService.setShuffleUnwatchedOnly(value);
notifyListeners();
}
}
Future<void> setShuffleOrderNavigation(bool value) async {
if (_shuffleOrderNavigation != value) {
_shuffleOrderNavigation = value;
await _settingsService.setShuffleOrderNavigation(value);
notifyListeners();
}
}
Future<void> setShuffleLoopQueue(bool value) async {
if (_shuffleLoopQueue != value) {
_shuffleLoopQueue = value;
await _settingsService.setShuffleLoopQueue(value);
notifyListeners();
}
}
String get libraryDensityDisplayName {
switch (_libraryDensity) {
case LibraryDensity.compact:
+67 -13
View File
@@ -2,6 +2,7 @@ import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:qr_flutter/qr_flutter.dart';
import '../services/plex_auth_service.dart';
import '../services/storage_service.dart';
import 'server_selection_screen.dart';
@@ -18,6 +19,8 @@ class _AuthScreenState extends State<AuthScreen> {
String? _errorMessage;
late PlexAuthService _authService;
bool _shouldCancelPolling = false;
bool _useQrFlow = false; // whether current auth attempt is QR based
String? _qrAuthUrl; // auth URL rendered as QR
@override
void initState() {
@@ -34,6 +37,10 @@ class _AuthScreenState extends State<AuthScreen> {
_isAuthenticating = true;
_errorMessage = null;
_shouldCancelPolling = false;
// preserve _useQrFlow as chosen prior to calling
if (!_useQrFlow) {
_qrAuthUrl = null; // ensure stale QR cleared for browser flow
}
});
try {
@@ -45,12 +52,19 @@ class _AuthScreenState extends State<AuthScreen> {
// Construct auth URL
final authUrl = _authService.getAuthUrl(pinCode);
// Open browser (in-app for mobile, external for desktop)
final uri = Uri.parse(authUrl);
if (await canLaunchUrl(uri)) {
await launchUrl(uri, mode: LaunchMode.inAppBrowserView);
if (_useQrFlow) {
// Display QR instead of launching browser
setState(() {
_qrAuthUrl = authUrl;
});
} else {
throw Exception('Could not launch auth URL');
// Open browser (in-app for mobile, external for desktop)
final uri = Uri.parse(authUrl);
if (await canLaunchUrl(uri)) {
await launchUrl(uri, mode: LaunchMode.inAppBrowserView);
} else {
throw Exception('Could not launch auth URL');
}
}
// Poll for authentication with cancellation support
@@ -73,10 +87,12 @@ class _AuthScreenState extends State<AuthScreen> {
}
// Auto-close the in-app browser on mobile (no-op on desktop)
try {
await closeInAppWebView();
} catch (e) {
// Ignore errors - browser might already be closed or on desktop
if (!_useQrFlow) {
try {
await closeInAppWebView();
} catch (e) {
// Ignore errors - browser might already be closed or on desktop
}
}
// Store the token
@@ -95,6 +111,11 @@ class _AuthScreenState extends State<AuthScreen> {
),
);
}
// Clear QR URL after successful auth
setState(() {
_qrAuthUrl = null;
_useQrFlow = false;
});
} catch (e) {
setState(() {
_isAuthenticating = false;
@@ -107,6 +128,7 @@ class _AuthScreenState extends State<AuthScreen> {
setState(() {
_shouldCancelPolling = true;
_isAuthenticating = false;
_qrAuthUrl = null;
});
// Start new authentication after a brief delay to ensure cleanup
Future.delayed(const Duration(milliseconds: 100), _startAuthentication);
@@ -226,11 +248,30 @@ class _AuthScreenState extends State<AuthScreen> {
if (_isAuthenticating) ...[
const Center(child: CircularProgressIndicator()),
const SizedBox(height: 16),
const Text(
'Waiting for authentication...\nPlease complete sign-in in your browser.',
Text(
_useQrFlow
? 'Scan this QR code with a device logged into Plex to authenticate.'
: 'Waiting for authentication...\nPlease complete sign-in in your browser.',
textAlign: TextAlign.center,
style: TextStyle(color: Colors.grey),
style: const TextStyle(color: Colors.grey),
),
if (_useQrFlow && _qrAuthUrl != null) ...[
const SizedBox(height: 24),
Center(
child: QrImageView(
data: _qrAuthUrl!,
size: 200,
version: QrVersions.auto,
backgroundColor: Colors.white,
),
),
const SizedBox(height: 16),
SelectableText(
_qrAuthUrl!,
textAlign: TextAlign.center,
style: const TextStyle(fontSize: 10, color: Colors.grey),
),
],
const SizedBox(height: 24),
OutlinedButton(
onPressed: _retryAuthentication,
@@ -242,7 +283,7 @@ class _AuthScreenState extends State<AuthScreen> {
),
child: const Text('Retry'),
),
] else ...[
] else ...[ // add QR button here
ElevatedButton(
onPressed: _startAuthentication,
style: ElevatedButton.styleFrom(
@@ -250,6 +291,19 @@ class _AuthScreenState extends State<AuthScreen> {
),
child: const Text('Sign in with Plex'),
),
const SizedBox(height: 12),
OutlinedButton(
onPressed: () {
setState(() {
_useQrFlow = true;
});
_startAuthentication();
},
style: OutlinedButton.styleFrom(
padding: const EdgeInsets.symmetric(vertical: 16),
),
child: const Text('Show QR Code'),
),
if (kDebugMode) ...[
const SizedBox(height: 12),
OutlinedButton(
+135 -32
View File
@@ -46,6 +46,13 @@ class _LibrariesScreenState extends State<LibrariesScreen>
bool _isSortDescending = false;
bool _isInitialLoad = true;
// Pagination state
int _currentPage = 0;
bool _hasMoreItems = true;
CancelToken? _cancelToken;
int _requestId = 0;
static const int _pageSize = 1000;
@override
void initState() {
super.initState();
@@ -201,7 +208,6 @@ class _LibrariesScreenState extends State<LibrariesScreen>
await storage.saveLibraryOrder(libraryKeys);
}
Future<void> _loadLibraryContent(String libraryKey) async {
// Compute visible libraries based on current provider state
final hiddenLibrariesProvider = Provider.of<HiddenLibrariesProvider>(
@@ -257,6 +263,18 @@ class _LibrariesScreenState extends State<LibrariesScreen>
await storage.saveLibraryFilters({});
}
// Cancel any existing requests
_cancelToken?.cancel();
_cancelToken = CancelToken();
final currentRequestId = ++_requestId;
// Reset pagination state
setState(() {
_currentPage = 0;
_hasMoreItems = true;
_items = [];
});
try {
// Load filters and sort options for the new library
_loadFilters(libraryKey);
@@ -270,16 +288,19 @@ class _LibrariesScreenState extends State<LibrariesScreen>
);
}
// Load content
final items = await client.getLibraryContent(
// Load pages sequentially
await _loadAllPagesSequentially(
libraryKey,
filters: filtersWithSort,
filtersWithSort,
currentRequestId,
client,
);
setState(() {
_items = items;
_isLoadingItems = false;
});
} catch (e) {
// Ignore cancellation errors
if (e is DioException && e.type == DioExceptionType.cancel) {
return;
}
setState(() {
_errorMessage = _getErrorMessage(e, 'library content');
_isLoadingItems = false;
@@ -287,6 +308,54 @@ class _LibrariesScreenState extends State<LibrariesScreen>
}
}
/// Load all pages sequentially until all items are fetched
Future<void> _loadAllPagesSequentially(
String libraryKey,
Map<String, String> filtersWithSort,
int requestId,
PlexClient client,
) async {
while (_hasMoreItems && requestId == _requestId) {
try {
final items = await client.getLibraryContent(
libraryKey,
start: _currentPage * _pageSize,
size: _pageSize,
filters: filtersWithSort,
cancelToken: _cancelToken,
);
// Check if request is still valid
if (requestId != _requestId) {
return; // Request was superseded
}
setState(() {
_items.addAll(items);
_currentPage++;
_hasMoreItems = items.length >= _pageSize;
// Mark as not loading if this is the last page
if (!_hasMoreItems) {
_isLoadingItems = false;
}
});
} catch (e) {
// Check if it's a cancellation
if (e is DioException && e.type == DioExceptionType.cancel) {
return;
}
// For other errors, update state and rethrow
setState(() {
_isLoadingItems = false;
_hasMoreItems = false;
});
rethrow;
}
}
}
Future<void> _loadFilters(String libraryKey) async {
try {
final clientProvider = Provider.of<PlexClientProvider>(
@@ -360,9 +429,17 @@ class _LibrariesScreenState extends State<LibrariesScreen>
}
Future<void> _applyFilters() async {
// Cancel any existing requests
_cancelToken?.cancel();
_cancelToken = CancelToken();
final currentRequestId = ++_requestId;
setState(() {
_isLoadingItems = true;
_errorMessage = null;
_currentPage = 0;
_hasMoreItems = true;
_items = [];
});
try {
@@ -383,15 +460,19 @@ class _LibrariesScreenState extends State<LibrariesScreen>
);
}
final items = await client.getLibraryContent(
// Load pages sequentially
await _loadAllPagesSequentially(
_selectedLibraryKey!,
filters: filtersWithSort,
filtersWithSort,
currentRequestId,
client,
);
setState(() {
_items = items;
_isLoadingItems = false;
});
} catch (e) {
// Ignore cancellation errors
if (e is DioException && e.type == DioExceptionType.cancel) {
return;
}
setState(() {
_errorMessage = 'Failed to load library content: $e';
_isLoadingItems = false;
@@ -912,7 +993,7 @@ class _LibrariesScreenState extends State<LibrariesScreen>
),
// Content grid
if (_isLoadingItems)
if (_isLoadingItems && _items.isEmpty)
const SliverFillRemaining(
child: Center(child: CircularProgressIndicator()),
)
@@ -952,24 +1033,21 @@ class _LibrariesScreenState extends State<LibrariesScreen>
),
),
)
else
else ...[
Consumer<SettingsProvider>(
builder: (context, settingsProvider, child) {
if (settingsProvider.viewMode == ViewMode.list) {
return SliverPadding(
padding: const EdgeInsets.fromLTRB(8, 0, 8, 8),
sliver: SliverList(
delegate: SliverChildBuilderDelegate(
(context, index) {
final item = _items[index];
return MediaCard(
key: Key(item.ratingKey),
item: item,
onRefresh: updateItem,
);
},
childCount: _items.length,
),
delegate: SliverChildBuilderDelegate((context, index) {
final item = _items[index];
return MediaCard(
key: Key(item.ratingKey),
item: item,
onRefresh: updateItem,
);
}, childCount: _items.length),
),
);
} else {
@@ -998,6 +1076,24 @@ class _LibrariesScreenState extends State<LibrariesScreen>
}
},
),
// Show loading indicator if there are more items to load
if (_hasMoreItems && _isLoadingItems)
SliverToBoxAdapter(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
children: [
const CircularProgressIndicator(),
const SizedBox(height: 8),
Text(
'Loading library... (${_items.length} items loaded)',
style: Theme.of(context).textTheme.bodySmall,
),
],
),
),
),
],
],
],
),
@@ -1450,7 +1546,9 @@ class _SortBottomSheetState extends State<_SortBottomSheet> {
child: RadioGroup<String>(
groupValue: _tempSelectedSort?.key,
onChanged: (value) {
final sort = widget.sortOptions.firstWhere((s) => s.key == value);
final sort = widget.sortOptions.firstWhere(
(s) => s.key == value,
);
setState(() {
_tempSelectedSort = sort;
// Use default direction for newly selected sort
@@ -1483,7 +1581,10 @@ class _SortBottomSheetState extends State<_SortBottomSheet> {
),
ButtonSegment(
value: true,
icon: Icon(Icons.arrow_downward, size: 16),
icon: Icon(
Icons.arrow_downward,
size: 16,
),
),
],
selected: {_tempDescending},
@@ -1717,9 +1818,11 @@ class _LibraryManagementSheetState extends State<_LibraryManagementSheet> {
padding: const EdgeInsets.only(right: 12),
child: Icon(
Icons.drag_indicator,
color: Theme.of(
context,
).textTheme.bodyMedium?.color?.withValues(alpha: 0.5),
color: Theme.of(context)
.textTheme
.bodyMedium
?.color
?.withValues(alpha: 0.5),
),
),
),
+66
View File
@@ -75,6 +75,8 @@ class _SettingsScreenState extends State<SettingsScreen> {
const SizedBox(height: 24),
_buildVideoPlaybackSection(),
const SizedBox(height: 24),
_buildShufflePlaySection(),
const SizedBox(height: 24),
_buildKeyboardShortcutsSection(),
const SizedBox(height: 24),
_buildAdvancedSection(),
@@ -248,6 +250,70 @@ class _SettingsScreenState extends State<SettingsScreen> {
);
}
Widget _buildShufflePlaySection() {
return Card(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.all(16),
child: Text(
'Shuffle Play',
style: Theme.of(
context,
).textTheme.titleMedium?.copyWith(fontWeight: FontWeight.bold),
),
),
Consumer<SettingsProvider>(
builder: (context, settingsProvider, child) {
return SwitchListTile(
secondary: const Icon(Icons.visibility_off),
title: const Text('Unwatched Only'),
subtitle: const Text(
'Only include unwatched episodes in shuffle queue',
),
value: settingsProvider.shuffleUnwatchedOnly,
onChanged: (value) async {
await settingsProvider.setShuffleUnwatchedOnly(value);
},
);
},
),
Consumer<SettingsProvider>(
builder: (context, settingsProvider, child) {
return SwitchListTile(
secondary: const Icon(Icons.shuffle),
title: const Text('Shuffle Order Navigation'),
subtitle: const Text(
'Next/previous buttons follow shuffled order',
),
value: settingsProvider.shuffleOrderNavigation,
onChanged: (value) async {
await settingsProvider.setShuffleOrderNavigation(value);
},
);
},
),
Consumer<SettingsProvider>(
builder: (context, settingsProvider, child) {
return SwitchListTile(
secondary: const Icon(Icons.loop),
title: const Text('Loop Shuffle Queue'),
subtitle: const Text(
'Restart queue when reaching the end',
),
value: settingsProvider.shuffleLoopQueue,
onChanged: (value) async {
await settingsProvider.setShuffleLoopQueue(value);
},
);
},
),
],
),
);
}
Widget _buildKeyboardShortcutsSection() {
return Card(
child: Column(
+173 -20
View File
@@ -8,11 +8,13 @@ import '../models/plex_metadata.dart';
import '../models/plex_user_profile.dart';
import '../providers/plex_client_provider.dart';
import '../providers/playback_state_provider.dart';
import '../providers/settings_provider.dart';
import '../utils/provider_extensions.dart';
import '../widgets/video_controls/video_controls.dart';
import '../utils/language_codes.dart';
import '../utils/app_logger.dart';
import '../services/settings_service.dart';
import '../services/audio_service_manager.dart';
import '../utils/orientation_helper.dart';
import '../utils/video_player_navigation.dart';
import '../utils/platform_detector.dart';
@@ -54,7 +56,8 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> {
StreamSubscription<String>? _errorSubscription;
StreamSubscription<bool>? _playingSubscription;
StreamSubscription<bool>? _completedSubscription;
bool _isReplacingWithVideo = false; // Flag to skip orientation restoration during video-to-video navigation
bool _isReplacingWithVideo =
false; // Flag to skip orientation restoration during video-to-video navigation
// BoxFit mode state: 0=contain (letterbox), 1=cover (fill screen), 2=fill (stretch)
int _boxFitMode = 0;
@@ -123,10 +126,13 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> {
mpvConfiguration: {
'sub-font-size': settingsService.getSubtitleFontSize().toString(),
'sub-color': settingsService.getSubtitleTextColor(),
'sub-border-size': settingsService.getSubtitleBorderSize().toString(),
'sub-border-size': settingsService
.getSubtitleBorderSize()
.toString(),
'sub-border-color': settingsService.getSubtitleBorderColor(),
'sub-back-color': '#${(settingsService.getSubtitleBackgroundOpacity() * 255 / 100).toInt().toRadixString(16).padLeft(2, '0').toUpperCase()}${settingsService.getSubtitleBackgroundColor().replaceFirst('#', '')}',
}
'sub-back-color':
'#${(settingsService.getSubtitleBackgroundOpacity() * 255 / 100).toInt().toRadixString(16).padLeft(2, '0').toUpperCase()}${settingsService.getSubtitleBackgroundColor().replaceFirst('#', '')}',
},
),
);
controller = VideoController(
@@ -194,10 +200,14 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> {
}
// Listen to playback state changes
_playingSubscription = player!.stream.playing.listen(_onPlayingStateChanged);
_playingSubscription = player!.stream.playing.listen(
_onPlayingStateChanged,
);
// Listen to completion
_completedSubscription = player!.stream.completed.listen(_onVideoCompleted);
_completedSubscription = player!.stream.completed.listen(
_onVideoCompleted,
);
// Listen to MPV logs
_logSubscription = player!.stream.log.listen(_onPlayerLog);
@@ -210,6 +220,9 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> {
// Load next/previous episodes
_loadAdjacentEpisodes();
// Initialize audio service for OS media controls
_initializeAudioService();
} catch (e) {
appLogger.e('Failed to initialize player', error: e);
if (mounted) {
@@ -220,6 +233,7 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> {
}
}
Future<void> _loadAdjacentEpisodes() async {
if (widget.metadata.type.toLowerCase() != 'episode') {
return;
@@ -231,16 +245,29 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> {
if (client == null) return;
final playbackState = context.read<PlaybackStateProvider>();
final settingsProvider = context.read<SettingsProvider>();
PlexMetadata? next;
PlexMetadata? previous;
// Check if shuffle mode is active
if (playbackState.isShuffleActive) {
// Get next episode from shuffle queue
next = playbackState.getNextEpisode(widget.metadata.ratingKey);
// No previous episode in shuffle mode
previous = null;
// Get settings
final shuffleOrderNavigation = settingsProvider.shuffleOrderNavigation;
final loopQueue = settingsProvider.shuffleLoopQueue;
if (shuffleOrderNavigation) {
// Use shuffled order for next/previous
next = playbackState.getNextEpisode(
widget.metadata.ratingKey,
loopQueue: loopQueue,
);
previous = playbackState.getPreviousEpisode(widget.metadata.ratingKey);
} else {
// Use chronological order even in shuffle mode
next = await client.findAdjacentEpisode(widget.metadata, 1);
previous = await client.findAdjacentEpisode(widget.metadata, -1);
}
} else {
// Use normal sequential episode loading
next = await client.findAdjacentEpisode(widget.metadata, 1);
@@ -252,12 +279,52 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> {
_nextEpisode = next;
_previousEpisode = previous;
});
// Update audio handler navigation availability
_updateAudioHandlerNavigation();
}
} catch (e) {
// Silently handle errors
}
}
Future<void> _initializeAudioService() async {
try {
if (player == null) return;
final clientProvider = context.plexClient;
final client = clientProvider.client;
if (client == null) return;
final audioManager = AudioServiceManager.instance;
// Initialize audio service (will only happen once)
await audioManager.initialize(
player: player!,
plexServerUrl: client.config.baseUrl,
authToken: client.config.token ?? '',
onSkipToNext: _nextEpisode != null ? _playNext : null,
onSkipToPrevious: _previousEpisode != null ? _playPrevious : null,
);
// Update media item with current content
audioManager.updateMediaItem(widget.metadata);
appLogger.d('Audio service initialized/updated successfully');
} catch (e) {
appLogger.e('Failed to initialize audio service', error: e);
// Continue playback even if audio service fails
}
}
void _updateAudioHandlerNavigation() {
final audioManager = AudioServiceManager.instance;
audioManager.updateNavigation(
onNext: _nextEpisode != null ? _playNext : null,
onPrevious: _previousEpisode != null ? _playPrevious : null,
);
}
Future<void> _startPlayback() async {
try {
final clientProvider = context.plexClient;
@@ -273,7 +340,63 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> {
);
if (videoUrl != null) {
// Open video without auto-playing
// Fetch media info to check for external subtitle tracks
final mediaInfo = await client.getMediaInfo(
widget.metadata.ratingKey,
mediaIndex: widget.selectedMediaIndex,
);
// Build list of external subtitle tracks for media_kit
final externalSubtitles = <SubtitleTrack>[];
if (mediaInfo != null) {
final externalTracks = mediaInfo.subtitleTracks
.where((track) => track.isExternal)
.toList();
if (externalTracks.isNotEmpty) {
appLogger.d(
'Found ${externalTracks.length} external subtitle track(s)',
);
}
for (final plexTrack in externalTracks) {
try {
// Skip if no auth token is available
final token = client.config.token;
if (token == null) {
appLogger.w('No auth token available for external subtitles');
continue;
}
final url = plexTrack.getSubtitleUrl(
client.config.baseUrl,
token,
);
// Skip if URL couldn't be constructed
if (url == null) continue;
externalSubtitles.add(
SubtitleTrack.uri(
url,
title:
plexTrack.displayTitle ??
plexTrack.language ??
'Track ${plexTrack.id}',
language: plexTrack.languageCode,
),
);
} catch (e) {
// Silent fallback - log error but continue with other subtitles
appLogger.w(
'Failed to add external subtitle track ${plexTrack.id}',
error: e,
);
}
}
}
// Open video (without external subtitles in Media constructor)
await player!.open(Media(videoUrl), play: false);
// Wait for media to be ready (duration > 0)
@@ -283,6 +406,33 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> {
attempts++;
}
// Add external subtitle tracks without auto-selecting them
if (externalSubtitles.isNotEmpty) {
appLogger.d(
'Adding ${externalSubtitles.length} external subtitle(s) to player',
);
final nativePlayer = player!.platform as dynamic;
for (final subtitleTrack in externalSubtitles) {
try {
// Use mpv's sub-add with 'auto' flag to avoid auto-selection
await nativePlayer.command([
'sub-add',
subtitleTrack.id,
'auto',
subtitleTrack.title ?? 'external',
subtitleTrack.language ?? 'auto',
]);
} catch (e) {
appLogger.w(
'Failed to add external subtitle: ${subtitleTrack.title}',
error: e,
);
}
}
}
// Set up playback position if resuming
if (widget.metadata.viewOffset != null &&
widget.metadata.viewOffset! > 0) {
@@ -336,21 +486,13 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> {
setState(() {
_boxFitMode = (_boxFitMode + 1) % 3;
});
final modes = [
'contain (letterbox)',
'cover (fill screen)',
'fill (stretch)',
];
appLogger.d('BoxFit mode: ${modes[_boxFitMode]}');
}
/// Toggle between contain and cover modes only (for pinch gesture)
void _toggleContainCover() {
setState(() {
_boxFitMode = _boxFitMode == 0 ? 1 : 0; // Toggle between 0 and 1
_boxFitMode = _boxFitMode == 0 ? 1 : 0;
});
final modes = ['contain (letterbox)', 'cover (fill screen)'];
appLogger.d('BoxFit mode toggled: ${modes[_boxFitMode]}');
}
/// Get current BoxFit based on mode
@@ -378,6 +520,17 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> {
_logSubscription?.cancel();
_errorSubscription?.cancel();
// Handle audio service based on navigation intent
if (_isReplacingWithVideo) {
// Switching to another episode: pause but keep notification visible
// The new VideoPlayerScreen will update the notification
AudioServiceManager.instance.pause();
} else {
// Truly exiting player: clear notification but keep singleton alive
// This allows controls to reappear when playing again
AudioServiceManager.instance.clearNotification();
}
// Send final stopped state
_sendProgress('stopped');
+186
View File
@@ -0,0 +1,186 @@
import 'package:audio_service/audio_service.dart';
import 'package:media_kit/media_kit.dart';
import '../models/plex_metadata.dart';
import '../utils/app_logger.dart';
import 'media_kit_audio_handler.dart';
/// Global singleton manager for audio service
/// Ensures AudioService.init() is only called once and the handler is reused
class AudioServiceManager {
static AudioServiceManager? _instance;
MediaKitAudioHandler? _handler;
bool _isInitialized = false;
bool _isInitializing = false;
AudioServiceManager._();
static AudioServiceManager get instance {
_instance ??= AudioServiceManager._();
return _instance!;
}
/// Initialize the audio service with the given player and configuration
/// This should only be called once - subsequent calls will reuse the existing handler
Future<void> initialize({
required Player player,
required String plexServerUrl,
required String authToken,
Future<void> Function()? onSkipToNext,
Future<void> Function()? onSkipToPrevious,
}) async {
// If already initialized, update the player reference and callbacks
if (_isInitialized && _handler != null) {
appLogger.d('Audio service already initialized, updating player reference and callbacks');
// Update the player reference (critical for episode switching)
await _handler!.updatePlayer(player);
// Update navigation callbacks
_handler!.onSkipToNext = onSkipToNext;
_handler!.onSkipToPrevious = onSkipToPrevious;
return;
}
// Prevent concurrent initialization
if (_isInitializing) {
appLogger.d('Audio service initialization already in progress, waiting...');
// Wait for initialization to complete
while (_isInitializing) {
await Future.delayed(const Duration(milliseconds: 100));
}
return;
}
try {
_isInitializing = true;
appLogger.d('Initializing audio service for the first time');
final handler = await AudioService.init(
builder: () => MediaKitAudioHandler(
player: player,
plexServerUrl: plexServerUrl,
authToken: authToken,
onSkipToNext: onSkipToNext,
onSkipToPrevious: onSkipToPrevious,
),
config: const AudioServiceConfig(
androidNotificationChannelId: 'com.edde746.plezy.audio',
androidNotificationChannelName: 'Plezy Playback',
androidNotificationOngoing: true,
androidShowNotificationBadge: true,
),
);
_handler = handler;
_isInitialized = true;
appLogger.d('Audio service initialized successfully');
} catch (e) {
appLogger.e('Failed to initialize audio service', error: e);
rethrow;
} finally {
_isInitializing = false;
}
}
/// Update the current media item being played
void updateMediaItem(PlexMetadata metadata) {
if (_handler == null) {
appLogger.w('Cannot update media item: audio handler not initialized');
return;
}
_handler!.updateCurrentMediaItem(metadata);
}
/// Update navigation callbacks for next/previous episode
void updateNavigation({
Future<void> Function()? onNext,
Future<void> Function()? onPrevious,
}) {
if (_handler == null) {
appLogger.w('Cannot update navigation: audio handler not initialized');
return;
}
_handler!.updateNavigationCallbacks(
onNext: onNext,
onPrevious: onPrevious,
);
}
/// Pause playback but keep the media session active
Future<void> pause() async {
if (_handler == null) {
appLogger.w('Cannot pause: audio handler not initialized');
return;
}
await _handler!.pause();
}
/// Clear the notification but keep the audio service singleton alive
/// This is used when exiting the video player but not closing the app
Future<void> clearNotification() async {
if (_handler == null) {
appLogger.w('Cannot clear notification: audio handler not initialized');
return;
}
appLogger.d('Clearing notification while keeping audio service alive');
// Broadcast idle state to remove notification
_handler!.playbackState.add(PlaybackState(
processingState: AudioProcessingState.idle,
playing: false,
controls: [],
systemActions: const {},
updatePosition: Duration.zero,
bufferedPosition: Duration.zero,
speed: 1.0,
));
// Clear media item
_handler!.mediaItem.add(null);
// IMPORTANT: DON'T reset _isInitialized or _handler
// Keep the singleton alive for next playback
appLogger.d('Notification cleared, audio service remains initialized');
}
/// Stop playback completely and remove the notification
/// This should only be called when the app is closing or user explicitly stops
Future<void> shutdown() async {
if (_handler == null) {
appLogger.w('Cannot shutdown: audio handler not initialized');
return;
}
appLogger.d('Shutting down audio service and removing notification');
// Broadcast idle state to remove notification
_handler!.playbackState.add(PlaybackState(
processingState: AudioProcessingState.idle,
playing: false,
controls: [],
systemActions: const {},
updatePosition: Duration.zero,
bufferedPosition: Duration.zero,
speed: 1.0,
));
// Clear media item
_handler!.mediaItem.add(null);
// Dispose the handler
await _handler!.dispose();
_handler = null;
_isInitialized = false;
appLogger.d('Audio service shutdown complete');
}
/// Check if the audio service is initialized
bool get isInitialized => _isInitialized;
/// Get the current handler (for advanced use cases)
MediaKitAudioHandler? get handler => _handler;
}
+314
View File
@@ -0,0 +1,314 @@
import 'dart:async';
import 'package:audio_service/audio_service.dart';
import 'package:media_kit/media_kit.dart';
import 'package:rxdart/rxdart.dart';
import '../models/plex_metadata.dart';
import '../utils/app_logger.dart';
/// Audio handler that bridges media_kit player with OS media controls
class MediaKitAudioHandler extends BaseAudioHandler with SeekHandler {
Player _player;
final String plexServerUrl;
final String authToken;
// Getter for player
Player get player => _player;
// Callback functions for episode navigation
Future<void> Function()? onSkipToNext;
Future<void> Function()? onSkipToPrevious;
// Stream subscriptions
StreamSubscription<bool>? _playingSubscription;
StreamSubscription<Duration>? _positionSubscription;
StreamSubscription<Duration>? _durationSubscription;
StreamSubscription<Duration>? _bufferSubscription;
// Queue management
final BehaviorSubject<List<MediaItem>> _queueSubject = BehaviorSubject.seeded([]);
MediaKitAudioHandler({
required Player player,
required this.plexServerUrl,
required this.authToken,
this.onSkipToNext,
this.onSkipToPrevious,
}) : _player = player {
_init();
}
void _init() {
// Map player state to playback state
_playingSubscription = _player.stream.playing.listen((isPlaying) {
_updatePlaybackState();
});
_positionSubscription = _player.stream.position.listen((_) {
_updatePlaybackState();
});
_durationSubscription = _player.stream.duration.listen((_) {
_updatePlaybackState();
});
_bufferSubscription = _player.stream.buffer.listen((_) {
_updatePlaybackState();
});
// Set initial state
_updatePlaybackState();
}
/// Update media item with current playing content
void updateCurrentMediaItem(PlexMetadata metadata) {
final artworkUrl = _getArtworkUrl(metadata);
final newMediaItem = MediaItem(
id: metadata.ratingKey,
title: metadata.title,
album: _getAlbumName(metadata),
artist: _getArtistName(metadata),
duration: metadata.duration != null
? Duration(milliseconds: metadata.duration!)
: null,
artUri: artworkUrl != null ? Uri.parse(artworkUrl) : null,
extras: {
'ratingKey': metadata.ratingKey,
'type': metadata.type,
},
);
mediaItem.add(newMediaItem);
appLogger.d('Updated media item: ${metadata.title}');
}
/// Update navigation callbacks
void updateNavigationCallbacks({
Future<void> Function()? onNext,
Future<void> Function()? onPrevious,
}) {
onSkipToNext = onNext;
onSkipToPrevious = onPrevious;
_updatePlaybackState();
}
/// Update the queue with episodes
void updateEpisodeQueue(List<PlexMetadata> episodes, int currentIndex) {
final items = episodes.map((episode) {
final artworkUrl = _getArtworkUrl(episode);
return MediaItem(
id: episode.ratingKey,
title: episode.title,
album: _getAlbumName(episode),
artist: _getArtistName(episode),
duration: episode.duration != null
? Duration(milliseconds: episode.duration!)
: null,
artUri: artworkUrl != null ? Uri.parse(artworkUrl) : null,
extras: {
'ratingKey': episode.ratingKey,
'type': episode.type,
},
);
}).toList();
_queueSubject.add(items);
queue.add(items);
if (currentIndex >= 0 && currentIndex < items.length) {
mediaItem.add(items[currentIndex]);
}
appLogger.d('Updated queue with ${items.length} episodes, current index: $currentIndex');
}
String? _getArtworkUrl(PlexMetadata metadata) {
String? thumbPath;
// For episodes, prefer show poster over episode thumbnail
if (metadata.type.toLowerCase() == 'episode') {
thumbPath = metadata.grandparentThumb ?? metadata.thumb;
} else {
thumbPath = metadata.thumb;
}
if (thumbPath == null) return null;
// Build full URL with authentication
return '$plexServerUrl$thumbPath?X-Plex-Token=$authToken';
}
String _getAlbumName(PlexMetadata metadata) {
// For episodes: "Show Name - Season X"
if (metadata.type.toLowerCase() == 'episode') {
final showName = metadata.grandparentTitle ?? '';
final seasonNum = metadata.parentIndex;
if (seasonNum != null) {
return '$showName - Season $seasonNum';
}
return showName;
}
// For movies: studio or year
return metadata.studio ?? metadata.year?.toString() ?? '';
}
String _getArtistName(PlexMetadata metadata) {
// For episodes: show episode info
if (metadata.type.toLowerCase() == 'episode') {
final seasonNum = metadata.parentIndex;
final episodeNum = metadata.index;
if (seasonNum != null && episodeNum != null) {
return 'S${seasonNum.toString().padLeft(2, '0')}E${episodeNum.toString().padLeft(2, '0')}';
}
}
return '';
}
void _updatePlaybackState() {
final isPlaying = _player.state.playing;
final position = _player.state.position;
final bufferedPosition = _player.state.buffer;
// Determine processing state
AudioProcessingState processingState;
if (_player.state.buffering) {
processingState = AudioProcessingState.buffering;
} else if (_player.state.completed) {
processingState = AudioProcessingState.completed;
} else {
processingState = AudioProcessingState.ready;
}
// Build controls based on state and available navigation
final controls = <MediaControl>[
if (onSkipToPrevious != null) MediaControl.skipToPrevious,
MediaControl.rewind,
if (isPlaying) MediaControl.pause else MediaControl.play,
MediaControl.fastForward,
if (onSkipToNext != null) MediaControl.skipToNext,
];
playbackState.add(PlaybackState(
controls: controls,
systemActions: const {
MediaAction.seek,
MediaAction.seekForward,
MediaAction.seekBackward,
},
androidCompactActionIndices: [
if (onSkipToPrevious != null) 0,
onSkipToPrevious != null ? 2 : 1, // Play/Pause button
if (onSkipToNext != null)
onSkipToPrevious != null ? 4 : 3,
].where((i) => i < controls.length).toList(),
processingState: processingState,
playing: isPlaying,
updatePosition: position,
bufferedPosition: bufferedPosition,
speed: 1.0,
queueIndex: 0, // TODO: Update based on actual queue position
));
}
@override
Future<void> play() async {
appLogger.d('Audio handler: play');
await _player.play();
}
@override
Future<void> pause() async {
appLogger.d('Audio handler: pause');
await _player.pause();
}
@override
Future<void> seek(Duration position) async {
appLogger.d('Audio handler: seek to ${position.inSeconds}s');
await _player.seek(position);
}
@override
Future<void> stop() async {
appLogger.d('Audio handler: stop');
await _player.stop();
}
@override
Future<void> fastForward() async {
appLogger.d('Audio handler: fast forward');
final newPosition = _player.state.position + const Duration(seconds: 10);
await _player.seek(newPosition);
}
@override
Future<void> rewind() async {
appLogger.d('Audio handler: rewind');
final newPosition = _player.state.position - const Duration(seconds: 10);
await _player.seek(newPosition > Duration.zero ? newPosition : Duration.zero);
}
@override
Future<void> skipToNext() async {
appLogger.d('Audio handler: skip to next');
if (onSkipToNext != null) {
await onSkipToNext!();
}
}
@override
Future<void> skipToPrevious() async {
appLogger.d('Audio handler: skip to previous');
if (onSkipToPrevious != null) {
await onSkipToPrevious!();
}
}
/// Update the player reference when switching episodes
/// This ensures the handler stays in sync with the current player instance
Future<void> updatePlayer(Player newPlayer) async {
appLogger.d('Audio handler: updating player reference');
// Cancel old subscriptions
await _playingSubscription?.cancel();
await _positionSubscription?.cancel();
await _durationSubscription?.cancel();
await _bufferSubscription?.cancel();
// Update player reference
_player = newPlayer;
// Create new subscriptions with the new player
_playingSubscription = _player.stream.playing.listen((isPlaying) {
_updatePlaybackState();
});
_positionSubscription = _player.stream.position.listen((_) {
_updatePlaybackState();
});
_durationSubscription = _player.stream.duration.listen((_) {
_updatePlaybackState();
});
_bufferSubscription = _player.stream.buffer.listen((_) {
_updatePlaybackState();
});
// Update playback state immediately
_updatePlaybackState();
appLogger.d('Audio handler: player reference updated successfully');
}
Future<void> dispose() async {
// Cancel subscriptions
await _playingSubscription?.cancel();
await _positionSubscription?.cancel();
await _durationSubscription?.cancel();
await _bufferSubscription?.cancel();
await _queueSubject.close();
}
}
+35
View File
@@ -37,6 +37,9 @@ class SettingsService {
static const String _keySubtitleBorderColor = 'subtitle_border_color';
static const String _keySubtitleBackgroundColor = 'subtitle_background_color';
static const String _keySubtitleBackgroundOpacity = 'subtitle_background_opacity';
static const String _keyShuffleUnwatchedOnly = 'shuffle_unwatched_only';
static const String _keyShuffleOrderNavigation = 'shuffle_order_navigation';
static const String _keyShuffleLoopQueue = 'shuffle_loop_queue';
static SettingsService? _instance;
late SharedPreferences _prefs;
@@ -777,6 +780,35 @@ class SettingsService {
}
}
// Shuffle Play Settings
/// Shuffle Unwatched Only - Filter shuffle queue to unwatched episodes only
Future<void> setShuffleUnwatchedOnly(bool enabled) async {
await _prefs.setBool(_keyShuffleUnwatchedOnly, enabled);
}
bool getShuffleUnwatchedOnly() {
return _prefs.getBool(_keyShuffleUnwatchedOnly) ?? true; // Default: true
}
/// Shuffle Order Navigation - Next/previous buttons follow shuffled order
Future<void> setShuffleOrderNavigation(bool enabled) async {
await _prefs.setBool(_keyShuffleOrderNavigation, enabled);
}
bool getShuffleOrderNavigation() {
return _prefs.getBool(_keyShuffleOrderNavigation) ?? true; // Default: true
}
/// Shuffle Loop Queue - Restart queue when reaching the end
Future<void> setShuffleLoopQueue(bool enabled) async {
await _prefs.setBool(_keyShuffleLoopQueue, enabled);
}
bool getShuffleLoopQueue() {
return _prefs.getBool(_keyShuffleLoopQueue) ?? false; // Default: false
}
// Reset all settings to defaults
Future<void> resetAllSettings() async {
await Future.wait([
@@ -805,6 +837,9 @@ class SettingsService {
_prefs.remove(_keySubtitleBorderColor),
_prefs.remove(_keySubtitleBackgroundColor),
_prefs.remove(_keySubtitleBackgroundOpacity),
_prefs.remove(_keyShuffleUnwatchedOnly),
_prefs.remove(_keyShuffleOrderNavigation),
_prefs.remove(_keyShuffleLoopQueue),
]);
}
+43 -11
View File
@@ -2,14 +2,15 @@ import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../models/plex_metadata.dart';
import '../providers/playback_state_provider.dart';
import '../providers/settings_provider.dart';
import '../utils/provider_extensions.dart';
import '../utils/video_player_navigation.dart';
/// Handle shuffle play action for shows and seasons
///
/// Fetches all unwatched episodes, shuffles them, and starts playback
/// from the first shuffled episode. The shuffle queue is stored in the
/// PlaybackStateProvider for continuous shuffle playback.
/// Fetches episodes based on user settings (unwatched only or including watched),
/// shuffles them, and starts playback from the first shuffled episode.
/// The shuffle queue is stored in the PlaybackStateProvider for continuous shuffle playback.
Future<void> handleShufflePlay(
BuildContext context,
PlexMetadata metadata,
@@ -18,8 +19,12 @@ Future<void> handleShufflePlay(
if (client == null) return;
final playbackState = context.read<PlaybackStateProvider>();
final settingsProvider = context.read<SettingsProvider>();
final itemType = metadata.type.toLowerCase();
// Get shuffle setting
final unwatchedOnly = settingsProvider.shuffleUnwatchedOnly;
try {
// Show loading indicator
if (context.mounted) {
@@ -31,17 +36,44 @@ Future<void> handleShufflePlay(
);
}
// Get unwatched episodes based on type
// Get episodes based on type and settings
List<PlexMetadata> episodes;
if (itemType == 'show') {
episodes = await client.getAllUnwatchedEpisodes(
metadata.ratingKey,
);
if (unwatchedOnly) {
// Get only unwatched episodes
episodes = await client.getAllUnwatchedEpisodes(
metadata.ratingKey,
);
} else {
// Get all episodes from all seasons
final allEpisodes = <PlexMetadata>[];
final seasons = await client.getChildren(metadata.ratingKey);
for (final season in seasons) {
if (season.type == 'season') {
final seasonEpisodes = await client.getChildren(season.ratingKey);
final episodesOnly = seasonEpisodes
.where((ep) => ep.type == 'episode')
.toList();
allEpisodes.addAll(episodesOnly);
}
}
episodes = allEpisodes;
}
} else {
// season
episodes = await client.getUnwatchedEpisodesInSeason(
metadata.ratingKey,
);
if (unwatchedOnly) {
// Get only unwatched episodes
episodes = await client.getUnwatchedEpisodesInSeason(
metadata.ratingKey,
);
} else {
// Get all episodes in season
final seasonEpisodes = await client.getChildren(metadata.ratingKey);
episodes = seasonEpisodes
.where((ep) => ep.type == 'episode')
.toList();
}
}
// Close loading indicator
@@ -52,7 +84,7 @@ Future<void> handleShufflePlay(
if (episodes.isEmpty) {
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('No unwatched episodes found')),
const SnackBar(content: Text('No episodes found')),
);
}
return;
@@ -40,7 +40,7 @@ class VideoControlButton extends StatelessWidget {
icon: Icon(icon, color: effectiveColor),
onPressed: onPressed,
tooltip: tooltip,
constraints: const BoxConstraints(minWidth: 40, minHeight: 56),
constraints: const BoxConstraints(minWidth: 40, minHeight: 40),
);
}
}
+130 -82
View File
@@ -92,6 +92,9 @@ class _PlexVideoControlsState extends State<PlexVideoControls>
double _doubleTapFeedbackOpacity = 0.0;
bool _lastDoubleTapWasForward = true;
Timer? _feedbackTimer;
// Seek throttle state
Timer? _seekThrottleTimer;
Duration? _pendingSeekPosition;
@override
void initState() {
@@ -168,6 +171,7 @@ class _PlexVideoControlsState extends State<PlexVideoControls>
void dispose() {
_hideTimer?.cancel();
_feedbackTimer?.cancel();
_seekThrottleTimer?.cancel();
_focusNode.dispose();
// Remove lifecycle observer
WidgetsBinding.instance.removeObserver(this);
@@ -358,11 +362,7 @@ class _PlexVideoControlsState extends State<PlexVideoControls>
// Only apply SafeArea in portrait mode
if (isPortrait) {
return SafeArea(
top: top,
bottom: bottom,
child: child,
);
return SafeArea(top: top, bottom: bottom, child: child);
}
// In landscape, return child without SafeArea
@@ -380,83 +380,90 @@ class _PlexVideoControlsState extends State<PlexVideoControls>
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
// Unified settings button (speed, sleep timer, audio sync, subtitle sync)
ListenableBuilder(
listenable: SleepTimerService(),
builder: (context, _) {
final sleepTimer = SleepTimerService();
final isActive =
sleepTimer.isActive ||
_audioSyncOffset != 0 ||
_subtitleSyncOffset != 0;
return VideoControlButton(
icon: Icons.tune,
isActive: isActive,
onPressed: () async {
await VideoSettingsSheet.show(
context,
widget.player,
_audioSyncOffset,
_subtitleSyncOffset,
);
// Sheet is now closed, reload immediately
if (mounted) {
await _loadSeekTimes();
}
},
);
},
),
if (_hasMultipleAudioTracks(tracks))
VideoControlButton(
icon: Icons.audiotrack,
onPressed: () => AudioTrackSheet.show(context, widget.player),
// Unified settings button (speed, sleep timer, audio sync, subtitle sync)
ListenableBuilder(
listenable: SleepTimerService(),
builder: (context, _) {
final sleepTimer = SleepTimerService();
final isActive =
sleepTimer.isActive ||
_audioSyncOffset != 0 ||
_subtitleSyncOffset != 0;
return VideoControlButton(
icon: Icons.tune,
isActive: isActive,
onPressed: () async {
await VideoSettingsSheet.show(
context,
widget.player,
_audioSyncOffset,
_subtitleSyncOffset,
);
// Sheet is now closed, reload immediately
if (mounted) {
await _loadSeekTimes();
}
},
);
},
),
if (_hasSubtitles(tracks))
VideoControlButton(
icon: Icons.subtitles,
onPressed: () => SubtitleTrackSheet.show(context, widget.player),
),
if (_chapters.isNotEmpty)
VideoControlButton(
icon: Icons.video_library,
onPressed: () => ChapterSheet.show(
context,
widget.player,
_chapters,
_chaptersLoaded,
if (_hasMultipleAudioTracks(tracks))
VideoControlButton(
icon: Icons.audiotrack,
onPressed: () => AudioTrackSheet.show(context, widget.player),
),
),
if (widget.availableVersions.length > 1)
VideoControlButton(
icon: Icons.video_file,
onPressed: () => VersionSheet.show(
context,
widget.availableVersions,
widget.selectedMediaIndex,
_switchMediaVersion,
if (_hasSubtitles(tracks))
VideoControlButton(
icon: Icons.subtitles,
onPressed: () =>
SubtitleTrackSheet.show(context, widget.player),
),
if (_chapters.isNotEmpty)
VideoControlButton(
icon: Icons.video_library,
onPressed: () => ChapterSheet.show(
context,
widget.player,
_chapters,
_chaptersLoaded,
),
),
if (widget.availableVersions.length > 1)
VideoControlButton(
icon: Icons.video_file,
onPressed: () => VersionSheet.show(
context,
widget.availableVersions,
widget.selectedMediaIndex,
_switchMediaVersion,
),
),
// BoxFit mode cycle button
if (widget.onCycleBoxFitMode != null)
VideoControlButton(
icon: _getBoxFitIcon(widget.boxFitMode),
tooltip: _getBoxFitTooltip(widget.boxFitMode),
onPressed: widget.onCycleBoxFitMode,
),
// Rotation lock toggle (mobile only)
if (PlatformDetector.isMobile(context))
VideoControlButton(
icon: _isRotationLocked
? Icons.screen_lock_rotation
: Icons.screen_rotation,
tooltip: _isRotationLocked
? 'Unlock rotation'
: 'Lock rotation',
onPressed: _toggleRotationLock,
),
// Fullscreen toggle (desktop only)
if (Platform.isWindows || Platform.isLinux || Platform.isMacOS)
VideoControlButton(
icon: _isFullscreen
? Icons.fullscreen_exit
: Icons.fullscreen,
onPressed: _toggleFullscreen,
),
),
// BoxFit mode cycle button
if (widget.onCycleBoxFitMode != null)
VideoControlButton(
icon: _getBoxFitIcon(widget.boxFitMode),
tooltip: _getBoxFitTooltip(widget.boxFitMode),
onPressed: widget.onCycleBoxFitMode,
),
// Rotation lock toggle (mobile only)
if (PlatformDetector.isMobile(context))
VideoControlButton(
icon: _isRotationLocked ? Icons.screen_lock_rotation : Icons.screen_rotation,
tooltip: _isRotationLocked ? 'Unlock rotation' : 'Lock rotation',
onPressed: _toggleRotationLock,
),
// Fullscreen toggle (desktop only)
if (Platform.isWindows || Platform.isLinux || Platform.isMacOS)
VideoControlButton(
icon: _isFullscreen ? Icons.fullscreen_exit : Icons.fullscreen,
onPressed: _toggleFullscreen,
),
],
),
);
@@ -521,6 +528,40 @@ class _PlexVideoControlsState extends State<PlexVideoControls>
widget.player.seek(clampedPosition);
}
/// Throttled seek for timeline slider - only sends seek events at most every 100ms
void _throttledSeek(Duration position) {
// Store the pending position
_pendingSeekPosition = position;
// If timer is already active, just update the pending position
if (_seekThrottleTimer?.isActive ?? false) {
return;
}
// Execute the seek immediately for the first call
widget.player.seek(position);
// Start a timer to throttle subsequent seeks
_seekThrottleTimer = Timer(const Duration(milliseconds: 200), () {
// If there's a pending position that's different, execute it
if (_pendingSeekPosition != null && _pendingSeekPosition != position) {
widget.player.seek(_pendingSeekPosition!);
}
_pendingSeekPosition = null;
});
}
/// Finalizes the seek when user stops scrubbing the timeline
void _finalizeSeek(Duration position) {
// Cancel any pending throttled seek
_seekThrottleTimer?.cancel();
_seekThrottleTimer = null;
// Execute the final position immediately to ensure accuracy
widget.player.seek(position);
_pendingSeekPosition = null;
}
/// Get the replay icon based on the duration
/// Returns numbered icons (replay_5, replay_10, replay_30) when available,
/// otherwise returns generic replay icon
@@ -878,7 +919,10 @@ class _PlexVideoControlsState extends State<PlexVideoControls>
widget.metadata.index != null)
Text(
'S${widget.metadata.parentIndex} · E${widget.metadata.index} · ${widget.metadata.title}',
style: const TextStyle(color: Colors.white70, fontSize: 14),
style: const TextStyle(
color: Colors.white70,
fontSize: 14,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
@@ -1310,7 +1354,10 @@ class _PlexVideoControlsState extends State<PlexVideoControls>
min: 0.0,
max: duration.inMilliseconds.toDouble(),
onChanged: (value) {
widget.player.seek(Duration(milliseconds: value.toInt()));
_throttledSeek(Duration(milliseconds: value.toInt()));
},
onChangeEnd: (value) {
_finalizeSeek(Duration(milliseconds: value.toInt()));
},
activeColor: Colors.white,
inactiveColor: Colors.white.withValues(alpha: 0.3),
@@ -1407,7 +1454,8 @@ class _PlexVideoControlsState extends State<PlexVideoControls>
final currentPosition = widget.player.state.position;
// Get state reference before async operations
final videoPlayerState = context.findAncestorStateOfType<VideoPlayerScreenState>();
final videoPlayerState = context
.findAncestorStateOfType<VideoPlayerScreenState>();
// Save the preference
final settingsService = await SettingsService.getInstance();
@@ -5,6 +5,8 @@
import FlutterMacOS
import Foundation
import audio_service
import audio_session
import hotkey_manager_macos
import macos_window_utils
import media_kit_libs_macos_video
@@ -20,6 +22,8 @@ import wakelock_plus
import window_manager
func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) {
AudioServicePlugin.register(with: registry.registrar(forPlugin: "AudioServicePlugin"))
AudioSessionPlugin.register(with: registry.registrar(forPlugin: "AudioSessionPlugin"))
HotkeyManagerMacosPlugin.register(with: registry.registrar(forPlugin: "HotkeyManagerMacosPlugin"))
MacOSWindowUtilsPlugin.register(with: registry.registrar(forPlugin: "MacOSWindowUtilsPlugin"))
MediaKitLibsMacosVideoPlugin.register(with: registry.registrar(forPlugin: "MediaKitLibsMacosVideoPlugin"))
+13
View File
@@ -1,4 +1,9 @@
PODS:
- audio_service (0.0.1):
- Flutter
- FlutterMacOS
- audio_session (0.0.1):
- FlutterMacOS
- FlutterMacOS (1.0.0)
- HotKey (0.2.1)
- hotkey_manager_macos (0.0.1):
@@ -33,6 +38,8 @@ PODS:
- FlutterMacOS
DEPENDENCIES:
- audio_service (from `Flutter/ephemeral/.symlinks/plugins/audio_service/darwin`)
- audio_session (from `Flutter/ephemeral/.symlinks/plugins/audio_session/macos`)
- FlutterMacOS (from `Flutter/ephemeral`)
- hotkey_manager_macos (from `Flutter/ephemeral/.symlinks/plugins/hotkey_manager_macos/macos`)
- macos_window_utils (from `Flutter/ephemeral/.symlinks/plugins/macos_window_utils/macos`)
@@ -53,6 +60,10 @@ SPEC REPOS:
- HotKey
EXTERNAL SOURCES:
audio_service:
:path: Flutter/ephemeral/.symlinks/plugins/audio_service/darwin
audio_session:
:path: Flutter/ephemeral/.symlinks/plugins/audio_session/macos
FlutterMacOS:
:path: Flutter/ephemeral
hotkey_manager_macos:
@@ -83,6 +94,8 @@ EXTERNAL SOURCES:
:path: Flutter/ephemeral/.symlinks/plugins/window_manager/macos
SPEC CHECKSUMS:
audio_service: aa99a6ba2ae7565996015322b0bb024e1d25c6fd
audio_session: eaca2512cf2b39212d724f35d11f46180ad3a33e
FlutterMacOS: d0db08ddef1a9af05a5ec4b724367152bb0500b1
HotKey: 400beb7caa29054ea8d864c96f5ba7e5b4852277
hotkey_manager_macos: a4317849af96d2430fa89944d3c58977ca089fbe
+96 -33
View File
@@ -41,6 +41,39 @@ packages:
url: "https://pub.dev"
source: hosted
version: "2.13.0"
audio_service:
dependency: "direct main"
description:
path: audio_service
ref: "4ca42f391183854095188a5a10fa6b59cd641e68"
resolved-ref: "4ca42f391183854095188a5a10fa6b59cd641e68"
url: "https://github.com/marckornberger/audio_service.git"
source: git
version: "0.18.18"
audio_service_platform_interface:
dependency: transitive
description:
name: audio_service_platform_interface
sha256: "6283782851f6c8b501b60904a32fc7199dc631172da0629d7301e66f672ab777"
url: "https://pub.dev"
source: hosted
version: "0.1.3"
audio_service_web:
dependency: transitive
description:
name: audio_service_web
sha256: b8ea9243201ee53383157fbccf13d5d2a866b5dda922ec19d866d1d5d70424df
url: "https://pub.dev"
source: hosted
version: "0.1.4"
audio_session:
dependency: "direct main"
description:
name: audio_session
sha256: "2b7fff16a552486d078bfc09a8cde19f426dc6d6329262b684182597bec5b1ac"
url: "https://pub.dev"
source: hosted
version: "0.1.25"
boolean_selector:
dependency: transitive
description:
@@ -400,6 +433,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.0.5"
js:
dependency: transitive
description:
name: js
sha256: "53385261521cc4a0c4658fd0ad07a7d14591cf8fc33abbceae306ddb974888dc"
url: "https://pub.dev"
source: hosted
version: "0.7.2"
json_annotation:
dependency: "direct main"
description:
@@ -492,59 +533,65 @@ packages:
dependency: "direct main"
description:
path: media_kit
ref: custom-mpv-config
resolved-ref: fd7bd79a9ba691306038c61791ea5754a5287d8a
ref: b6de7e44148043bd26f2569e8062dc8bce4f11b9
resolved-ref: b6de7e44148043bd26f2569e8062dc8bce4f11b9
url: "https://github.com/edde746/media-kit"
source: git
version: "1.2.1"
media_kit_libs_android_video:
dependency: transitive
description:
name: media_kit_libs_android_video
sha256: "3f6274e5ab2de512c286a25c327288601ee445ed8ac319e0ef0b66148bd8f76c"
url: "https://pub.dev"
source: hosted
version: "1.3.8"
path: "libs/android/media_kit_libs_android_video"
ref: b6de7e44148043bd26f2569e8062dc8bce4f11b9
resolved-ref: b6de7e44148043bd26f2569e8062dc8bce4f11b9
url: "https://github.com/edde746/media-kit"
source: git
version: "1.3.9"
media_kit_libs_ios_video:
dependency: transitive
description:
name: media_kit_libs_ios_video
sha256: b5382994eb37a4564c368386c154ad70ba0cc78dacdd3fb0cd9f30db6d837991
url: "https://pub.dev"
source: hosted
path: "libs/ios/media_kit_libs_ios_video"
ref: b6de7e44148043bd26f2569e8062dc8bce4f11b9
resolved-ref: b6de7e44148043bd26f2569e8062dc8bce4f11b9
url: "https://github.com/edde746/media-kit"
source: git
version: "1.1.4"
media_kit_libs_linux:
dependency: transitive
description:
name: media_kit_libs_linux
sha256: "2b473399a49ec94452c4d4ae51cfc0f6585074398d74216092bf3d54aac37ecf"
url: "https://pub.dev"
source: hosted
path: "libs/linux/media_kit_libs_linux"
ref: b6de7e44148043bd26f2569e8062dc8bce4f11b9
resolved-ref: b6de7e44148043bd26f2569e8062dc8bce4f11b9
url: "https://github.com/edde746/media-kit"
source: git
version: "1.2.1"
media_kit_libs_macos_video:
dependency: transitive
description:
name: media_kit_libs_macos_video
sha256: f26aa1452b665df288e360393758f84b911f70ffb3878032e1aabba23aa1032d
url: "https://pub.dev"
source: hosted
version: "1.1.4"
path: "libs/macos/media_kit_libs_macos_video"
ref: b6de7e44148043bd26f2569e8062dc8bce4f11b9
resolved-ref: b6de7e44148043bd26f2569e8062dc8bce4f11b9
url: "https://github.com/edde746/media-kit"
source: git
version: "1.1.5"
media_kit_libs_video:
dependency: "direct main"
description:
name: media_kit_libs_video
sha256: "2b235b5dac79c6020e01eef5022c6cc85fedc0df1738aadc6ea489daa12a92a9"
url: "https://pub.dev"
source: hosted
path: "libs/universal/media_kit_libs_video"
ref: b6de7e44148043bd26f2569e8062dc8bce4f11b9
resolved-ref: b6de7e44148043bd26f2569e8062dc8bce4f11b9
url: "https://github.com/edde746/media-kit"
source: git
version: "1.0.7"
media_kit_libs_windows_video:
dependency: transitive
description:
name: media_kit_libs_windows_video
sha256: dff76da2778729ab650229e6b4ec6ec111eb5151431002cbd7ea304ff1f112ab
url: "https://pub.dev"
source: hosted
version: "1.0.11"
path: "libs/windows/media_kit_libs_windows_video"
ref: b6de7e44148043bd26f2569e8062dc8bce4f11b9
resolved-ref: b6de7e44148043bd26f2569e8062dc8bce4f11b9
url: "https://github.com/edde746/media-kit"
source: git
version: "1.0.12"
media_kit_video:
dependency: "direct main"
description:
@@ -729,14 +776,30 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.5.0"
rxdart:
qr:
dependency: transitive
description:
name: rxdart
sha256: "5c3004a4a8dbb94bd4bf5412a4def4acdaa12e12f269737a5751369e12d1a962"
name: qr
sha256: "5a1d2586170e172b8a8c8470bbbffd5eb0cd38a66c0d77155ea138d3af3a4445"
url: "https://pub.dev"
source: hosted
version: "0.28.0"
version: "3.0.2"
qr_flutter:
dependency: "direct main"
description:
name: qr_flutter
sha256: "5095f0fc6e3f71d08adef8feccc8cea4f12eec18a2e31c2e8d82cb6019f4b097"
url: "https://pub.dev"
source: hosted
version: "4.1.0"
rxdart:
dependency: "direct main"
description:
name: rxdart
sha256: "0c7c0cedd93788d996e33041ffecda924cc54389199cde4e6a34b440f50044cb"
url: "https://pub.dev"
source: hosted
version: "0.27.7"
safe_local_storage:
dependency: transitive
description:
+15 -2
View File
@@ -1,7 +1,7 @@
name: plezy
description: "A beautiful Plex client for Flutter"
publish_to: "none"
version: 1.5.1+13
version: 1.6.0+14
environment:
sdk: ^3.8.1
@@ -25,13 +25,26 @@ dependencies:
provider: ^6.1.2
hotkey_manager: ^0.2.3
flex_color_picker: ^3.6.0
qr_flutter: ^4.1.0
audio_session: ^0.1.25
rxdart: ^0.27.2
audio_service:
git:
url: https://github.com/marckornberger/audio_service.git
ref: 4ca42f391183854095188a5a10fa6b59cd641e68
path: audio_service
dependency_overrides:
media_kit:
git:
url: https://github.com/edde746/media-kit
ref: custom-mpv-config
ref: b6de7e44148043bd26f2569e8062dc8bce4f11b9
path: media_kit
media_kit_libs_video:
git:
url: https://github.com/edde746/media-kit
ref: b6de7e44148043bd26f2569e8062dc8bce4f11b9
path: libs/universal/media_kit_libs_video
dev_dependencies:
flutter_test:
+131
View File
@@ -0,0 +1,131 @@
#!/usr/bin/env bash
# Android Icon Generator Script
# Generates notification icons and monochrome launcher icons from SVG source
# Usage: ./generate_android_icons.sh
set -e
# Configuration
SVG_SOURCE="assets/plezy.svg"
ANDROID_RES="android/app/src/main/res"
TEMP_DIR="/tmp/android_icons_$$"
# Check if source SVG exists
if [ ! -f "$SVG_SOURCE" ]; then
echo "Error: $SVG_SOURCE not found"
exit 1
fi
# Check for required tools
if ! command -v rsvg-convert &> /dev/null; then
echo "Error: rsvg-convert not found. Install with: brew install librsvg"
exit 1
fi
if ! command -v magick &> /dev/null && ! command -v convert &> /dev/null; then
echo "Error: ImageMagick not found. Install with: brew install imagemagick"
exit 1
fi
# Create temp directory
mkdir -p "$TEMP_DIR"
echo "🎨 Generating Android icons from $SVG_SOURCE..."
# Function to generate white silhouette icon
generate_white_icon() {
local size=$1
local output=$2
# Get SVG dimensions to detect if it's non-square
local svg_viewbox=$(grep -o 'viewBox="[^"]*"' "$SVG_SOURCE" | sed 's/viewBox="//;s/"//')
local svg_width=$(echo "$svg_viewbox" | awk '{print $3}')
local svg_height=$(echo "$svg_viewbox" | awk '{print $4}')
# Convert SVG to PNG, preserving aspect ratio
if (( $(echo "$svg_width != $svg_height" | bc -l) )); then
# Non-square SVG: render at size and add padding to center it
rsvg-convert --keep-aspect-ratio --background-color=transparent "$SVG_SOURCE" -o "$TEMP_DIR/temp_unpadded.png"
# Center the image in a square canvas with transparent padding
magick "$TEMP_DIR/temp_unpadded.png" \
-resize "${size}x${size}" \
-gravity center \
-background transparent \
-extent "${size}x${size}" \
"$TEMP_DIR/temp.png"
else
# Square SVG: convert directly
rsvg-convert -w "$size" -h "$size" --background-color=transparent "$SVG_SOURCE" -o "$TEMP_DIR/temp.png"
fi
# Convert to white silhouette: extract alpha, fill with white, apply alpha
magick "$TEMP_DIR/temp.png" \
-alpha extract \
"$TEMP_DIR/alpha_mask.png"
magick -size "${size}x${size}" xc:white \
"$TEMP_DIR/alpha_mask.png" \
-alpha off \
-compose copy-opacity \
-composite \
-define png:color-type=6 \
"$output"
echo " ✓ Generated $(basename $output) (${size}x${size}px)"
}
# Generate Notification Icons (24dp base)
echo ""
echo "📱 Generating notification icons (ic_stat_notification.png)..."
# Notification icon densities: 24dp base
# mdpi=1x, hdpi=1.5x, xhdpi=2x, xxhdpi=3x, xxxhdpi=4x
declare -A NOTIF_SIZES=(
["mdpi"]=24
["hdpi"]=36
["xhdpi"]=48
["xxhdpi"]=72
["xxxhdpi"]=96
)
for density in "${!NOTIF_SIZES[@]}"; do
size=${NOTIF_SIZES[$density]}
output_dir="$ANDROID_RES/drawable-$density"
mkdir -p "$output_dir"
generate_white_icon "$size" "$output_dir/ic_stat_notification.png"
done
# Generate Monochrome Launcher Icons (108dp base)
echo ""
echo "🚀 Generating monochrome launcher icons (ic_launcher_monochrome.png)..."
# Monochrome launcher icon densities: 108dp base
# mdpi=1x, hdpi=1.5x, xhdpi=2x, xxhdpi=3x, xxxhdpi=4x
declare -A MONO_SIZES=(
["mdpi"]=108
["hdpi"]=162
["xhdpi"]=216
["xxhdpi"]=324
["xxxhdpi"]=432
)
for density in "${!MONO_SIZES[@]}"; do
size=${MONO_SIZES[$density]}
output_dir="$ANDROID_RES/mipmap-$density"
mkdir -p "$output_dir"
generate_white_icon "$size" "$output_dir/ic_launcher_monochrome.png"
done
# Clean up
rm -rf "$TEMP_DIR"
echo ""
echo "✅ All icons generated successfully!"
echo ""
echo "Icon locations:"
echo " • Notification icons: $ANDROID_RES/drawable-*/ic_stat_notification.png"
echo " • Monochrome icons: $ANDROID_RES/mipmap-*/ic_launcher_monochrome.png"
echo ""
echo "To apply changes, rebuild the app: flutter clean && flutter build apk"