A cross platform Audiobookshelf client for Android and iOS
Dart
Keep Google Cast out of the iOS build now that its SDK wants iOS 16
Barnabas3b298a0f6d81
diff --git a/lib/widgets/ebook_reader_view.dart b/lib/widgets/ebook_reader_view.dartindex 8a690772..163e5d70 100644--- a/lib/widgets/ebook_reader_view.dart+++ b/lib/widgets/ebook_reader_view.dart@@ -5229,31 +5229,46 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObsitemId: widget.itemId, itemTitle: widget.title);},),- ListenableBuilder(- listenable: ChromecastService(),- builder: (_, __) {- final cast = ChromecastService();- final String label;- if (cast.isCasting && cast.castingItemId == widget.itemId) {- label = l.castingToDevice(cast.connectedDeviceName ?? 'device');- } else if (cast.isConnected) {- label = l.castToDeviceNamed(cast.connectedDeviceName ?? 'device');- } else {- label = l.castToDevice;- }- return MoreMenuItem(- icon: cast.isConnected- ? Icons.cast_connected_rounded- : Icons.cast_rounded,- label: label,- accent: accent,- onTap: () {- Navigator.pop(ctx);- _castFromReader();- },- );- },- ),+ // Cast is Android only; iPhones get the AirPlay route picker instead,+ // same split as the card.+ if (Platform.isIOS)+ MoreMenuItem(+ icon: Icons.airplay_rounded,+ label: 'AirPlay',+ accent: accent,+ onTap: () {+ Navigator.pop(ctx);+ const MethodChannel('com.absorb.audio_output')+ .invokeMethod('showRoutePicker')+ .catchError((_) => null);+ },+ )+ else+ ListenableBuilder(+ listenable: ChromecastService(),+ builder: (_, __) {+ final cast = ChromecastService();+ final String label;+ if (cast.isCasting && cast.castingItemId == widget.itemId) {+ label = l.castingToDevice(cast.connectedDeviceName ?? 'device');+ } else if (cast.isConnected) {+ label = l.castToDeviceNamed(cast.connectedDeviceName ?? 'device');+ } else {+ label = l.castToDevice;+ }+ return MoreMenuItem(+ icon: cast.isConnected+ ? Icons.cast_connected_rounded+ : Icons.cast_rounded,+ label: label,+ accent: accent,+ onTap: () {+ Navigator.pop(ctx);+ _castFromReader();+ },+ );+ },+ ),MoreMenuItem(icon: Icons.info_outline_rounded,label: l.bookDetailsLabel,diff --git a/packages/flutter_chrome_cast/CHANGELOG.md b/packages/flutter_chrome_cast/CHANGELOG.mdnew file mode 100644index 00000000..10c13197--- /dev/null+++ b/packages/flutter_chrome_cast/CHANGELOG.md@@ -0,0 +1,351 @@+## 1.4.1 - Stop Casting on App Terminated+### β¨ New Features+- **Stop Casting on App Kill**: Added `stopCastingOnAppTerminated` option to automatically stop casting and end the session when the app is killed/terminated+ - Available on both iOS and Android platforms+ - Configurable via `IOSGoogleCastOptions` and `GoogleCastOptionsAndroid`+ - When enabled, the Chromecast device stops playing when the user closes the app+ - Default is `false` (casting continues after app is closed, maintaining previous behavior)++### π§ Platform Improvements+- **iOS**: Added lifecycle observer to detect app termination and end cast session with `endSessionAndStopCasting(true)`+- **Android**: Implemented `ActivityLifecycleCallbacks` to monitor activity destruction and properly end cast sessions++### π Documentation+- Updated README with configuration options table+- Added code examples for both iOS and Android showing how to enable `stopCastingOnAppTerminated`+## 1.3.1 - Swift Package Manager Fixes+### π Bug Fixes+- **SPM Build Fixes**: Fixed Swift compiler errors when building with Swift Package Manager+ - Added missing `import Flutter` statements to all method channel Swift files+ - Added `@objc(GoogleCastPlugin)` attribute to expose Swift plugin class with correct name for Flutter's plugin registrant+ - Fixes "Cannot find type 'FlutterPlugin' in scope" and related compiler errors+ - Fixes "Unknown receiver 'GoogleCastPlugin'" error in GeneratedPluginRegistrant.m++### π§ Notes+- SPM support now fully functional for iOS builds+- No breaking API changes++## 1.3.0 - Swift Package Manager Support+### β¨ New Features+- **Swift Package Manager (SPM) Support**: Added full SPM support for iOS+ - Added `Package.swift` manifest with [SRGSSR/google-cast-sdk](https://github.com/SRGSSR/google-cast-sdk) dependency+ - Plugin now supports both CocoaPods and SPM for iOS dependency management+ - Resolves pub.dev scoring requirement for SPM support++### π§ Platform Changes+- **iOS Deployment Target**: Updated minimum iOS version from 14.0 to 15.0 (required by GoogleCast SPM package)++### π Documentation+- Updated README with SPM usage instructions+- Added SPM documentation to podspec++## 1.2.9 - iOS Cast contentURL fix+### π Fixes+- Use `GCKMediaInformationBuilder(contentURL:)` instead of deprecated `contentID` to align with current Google Cast SDK and fix media load failures (including HLS) on iOS.++## 1.2.8 - iOS HLS & Media Safety+### π Fixes+- Hardened iOS media parsing to avoid crashes from missing/invalid metadata; `fromMap` now bails out safely and treats infinite/NaN durations as zero.+- Improved HLS playback support by mapping segment formats, honoring `startAbsoluteTime`, and correctly propagating `playPosition`, `startTime`, and `preloadTime` values.+- Queue load options now respect fractional play positions, keeping live and buffered streams in sync.++### π§ UX+- Tweaked expanded player and mini controller behavior for live streams (slider, play/pause), improving control feedback during HLS playback.++**Full Changelog**: https://github.com/felnanuke2/flutter_google_cast/compare/v1.2.7...v1.2.8++## 1.2.7+## What's Changed+* Unknown track languages in m3u8 playlists cause player state events to be lost by @RabbitKabong in https://github.com/felnanuke2/flutter_google_cast/pull/46+* Bump version to 1.2.7 in pubspec.yaml by @felnanuke2 in https://github.com/felnanuke2/flutter_google_cast/pull/48++## New Contributors+* @RabbitKabong made their first contribution in https://github.com/felnanuke2/flutter_google_cast/pull/46++**Full Changelog**: https://github.com/felnanuke2/flutter_google_cast/compare/v1.2.6...v1.2.7++## 1.2.6 - iOS Simulator Build Compatibility Fix+### π Bug Fixes+- **iOS Simulator Module Resolution**: Fixed "Module 'flutter_chrome_cast' not found" parse error that occurred during iOS simulator builds+ - Issue affected only simulator builds; device builds and IPA generation worked correctly+ - Added `DEFINES_MODULE=YES` to podspec for proper Swift module header generation+ - Added `ENABLE_TESTING_SEARCH_PATHS=YES` to improve module resolution during simulator compilation+ - Updated Google Cast SDK to ~> 4.8+ - Maintains full compatibility with static framework linking for transitive Google Cast SDK dependencies++### π§ Notes+- No public API changes. This release focuses on build system compatibility for iOS simulator builds+- Resolves issue #XX where users encountered "Module not found" errors on some machines while others were unaffected++## 1.2.5 - iOS Apple Silicon Support & Enhanced Media Controls+### β¨ New Features+- **Missing Audio Control**: Added missing `stop` method for audio control in remote casting client+ - Implements the stop functionality that was previously missing from the Android remote media client+ - Fix contributed via PR #40 by @abdulmajedkhan++### π§ Platform Improvements+- **Apple Silicon Support**: Added full support for Apple Silicon (M1/M2/M3) Mac simulators+ - Updated Google Cast SDK dependency from `google-cast-sdk-no-bluetooth` to standard `google-cast-sdk` ~> 4.7+ - Removed arm64 simulator architecture exclusions that prevented builds on Apple Silicon+ - Fixes contributed via PR #39 by @SVyatoslavG and @nsikaktradearies+- **iOS Deployment Target**: Bumped minimum iOS deployment target to 13.0 to align with modern platform requirements+- **Enhanced Logging**: Improved debug logging capabilities with conditional debug print statements++### π Performance & Developer Experience+- **Faster Plugin Initialization**: Returns Flutter plugin result earlier during initialization for faster feedback+- **Conditional Logging**: Gated console logging behind debug flags to reduce noise in production builds+- **Better Discovery**: Enhanced device discovery initialization and lifecycle management++### π§ Technical Updates+- **CocoaPods Integration**: Updated CocoaPods and Xcode project metadata to reflect dependency changes+- **Build System**: Improved build phases and linker configuration for better compatibility++### π§ Notes+- No breaking API changes. This release focuses on platform compatibility and missing functionality+- Existing projects may need to update their iOS deployment target to 13.0 for optimal compatibility++## 1.2.4 - Misc fixes and Android method channel improvements+### π Bug Fixes+- **Android remote media client**: Fixes in `android_remote_media_client_method_channel.dart` to address method channel behavior when loading single media items.+- **Example fixes**: Minor example app updates to `example/lib/main.dart` and `example/android/app/build.gradle` to keep the sample project in sync with the plugin changes.+- **Pubspec tidy**: Updated `pubspec.yaml` to reflect dependency/metadata housekeeping.++### π§ Notes+- No public API breaking changes. This release contains internal fixes and example updates.++## 1.2.3 - iOS Teardown Crash Fix+### π Bug Fixes+- **iOS Teardown Safety**: Safely teardown Google Cast listeners on iOS to avoid a crash when the app terminates.+ - Fix merged via pull request #32: https://github.com/felnanuke2/flutter_google_cast/pull/32++### π§ Notes+- No public API changes. This is a small internal lifecycle fix for iOS listener teardown.++## 1.2.2 - Repeat Mode Bug Fix+### π Bug Fixes+### π Bug Fixes+- **Cross-Platform Repeat Mode Fix**: Fixed repeat mode handling across Android and iOS platforms+ - **Android**: Updated repeat mode parsing to use string-based values instead of integer mapping+ - **iOS**: Fixed GCKMediaQueueLoadOptions repeat mode enum parsing to handle string values+ - **Dart**: Enhanced GoogleCastMediaRepeatMode enum with proper string value mapping+ - **Consistency**: Ensured consistent repeat mode behavior across all platforms++### π§ Code Improvements+- **Removed Platform-Specific Code**: Eliminated Android-specific repeat mode extensions for cleaner architecture+- **Type Safety**: Improved type safety in repeat mode handling with proper string-to-enum conversion+- **Code Formatting**: Applied consistent code formatting and styling improvements+++## 1.2.1 - Documentation & Testing Improvements+### π Documentation Enhancements+- **Expanded API Documentation**: Added comprehensive documentation for public members across all Dart classes+- **Improved Public API Coverage**: Enhanced doc comments for better IDE support and developer experience+- **Coverage Badge**: Added test coverage badge to track and display code coverage metrics++### π§ͺ Testing Infrastructure+- **Test Suite Initialization**: Started implementing comprehensive test coverage for the application+- **Testing Foundation**: Established testing framework and initial test cases for core functionality+- **Quality Assurance**: Improved code reliability through systematic testing approach++### π§ Code Quality+- **Documentation Standards**: Ensured all public class members have proper documentation+- **Code Coverage Tracking**: Implemented coverage monitoring for better code quality insights+- **Developer Experience**: Enhanced IDE support with better API documentation++## 1.2.0 - API Documentation & Quality Release+### π Documentation & API Improvements+- **Extensive API Documentation**: Added or improved doc comments for nearly all public classes, methods, enums, and fields across the codebase.+- **Public API Coverage**: Significantly increased public API documentation coverage for better IDE support and pub.dev health.+- **README & Example Updates**: Improved usage examples, customization guides, and documentation for easier integration.+- **Linter Rule**: Enabled `public_member_api_docs` lint to enforce documentation for all public members.+- **No Breaking Changes**: This is a safe update with no breaking API changes.++### π οΈ Internal & Quality+- Improved code comments and structure for maintainability.+- All previous features and fixes from 1.1.1 included.++## 1.1.1 - Perfect Package Score Achievement+### π Quality Improvements+- **Perfect Pana Score**: Achieved 160/160 points in package analysis+ - β **File Conventions (30/30)**: Valid `pubspec.yaml`, `README.md`, `CHANGELOG.md`, and OSI-approved BSD-3-Clause license+ - β **Documentation (20/20)**: 31.5% of public API documented (above 20% requirement) with comprehensive example+ - β **Platform Support (20/20)**: Full iOS and Android support+ - β **Static Analysis (50/50)**: Zero errors, warnings, lints, or formatting issues+ - β **Dependencies (40/40)**: All dependencies up-to-date and compatible with constraint lower bounds++### π§ Technical Improvements+- **Code Formatting**: Applied `dart format` to ensure consistent code style across all files+- **Static Analysis**: Resolved all linting and formatting issues for perfect static analysis score+- **Dependency Compatibility**: Verified compatibility with latest stable Dart and Flutter SDKs+- **Package Health**: Optimized for pub.dev publication with excellent package health metrics++### π Package Metrics+- **API Documentation Coverage**: 234 out of 744 API elements documented (31.5%)+- **Platform Coverage**: iOS β Android β+- **License**: BSD-3-Clause (OSI-approved)+- **Dependencies**: All current and compatible+- **Static Analysis**: Perfect score with zero issues++## 1.1.0 - Modular Import System+### β¨ New Features+- **Modular Import System**: Introduced a new flexible import structure for better performance and cleaner code+ - Added `flutter_chrome_cast.dart` as the main entry point (imports everything)+ - Added selective imports: `cast_context.dart`, `discovery.dart`, `session.dart`, `media.dart`, `widgets.dart`, etc.+ - Each module exports only related functionality for optimized bundle size++### π¦ Import Options+- **Complete Import**: `import 'package:flutter_chrome_cast/flutter_chrome_cast.dart';` (recommended for getting started)+- **Selective Imports**: Import only what you need for production apps+ ```dart+ import 'package:flutter_chrome_cast/cast_context.dart'; // Core functionality+ import 'package:flutter_chrome_cast/media.dart'; // Media control+ import 'package:flutter_chrome_cast/widgets.dart'; // UI widgets+ ```++### π Benefits+- **Smaller Bundle Size**: Only include the functionality you actually use+- **Faster Compilation**: Less code to analyze and compile+- **Cleaner Namespace**: Avoid importing unused classes+- **Better IDE Support**: More precise auto-completion and error detection++### π Migration Guide+- **Old**: `import 'package:flutter_chrome_cast/lib.dart';` (still works but deprecated)+- **New**: Choose between complete import or selective imports based on your needs++### π Documentation+- Updated README with comprehensive import strategy guide+- Added import comparison table showing what each module includes+- Added migration examples and best practices++### β οΈ Deprecations+- `lib.dart` is now deprecated in favor of the new import system (still functional for backward compatibility)++## 1.0.4+### Bug Fixes+- **Code Quality**: Fixed Dart formatting issues across the entire codebase+- **Static Analysis**: Resolved formatting warnings to improve pub.dev package score+- **Formatted Files**: Applied Dart formatter to 115 files ensuring compliance with Dart style guidelines+ - Fixed formatting in `android_discovery_manager.dart`+ - Fixed formatting in `ios_cast_session_manager.dart`+ - Applied consistent formatting across all library files++## 1.0.3+### Breaking Changes+- **Enum Naming Convention Update**: All enums have been updated from UPPER_SNAKE_CASE to lowerCamelCase for better Dart conventions+ - `GoogleCastConnectState.ConnectionStateConnected` β `GoogleCastConnectState.connected`+ - `CastMediaStreamType.BUFFERED` β `CastMediaStreamType.buffered`+ - `TrackType.TEXT` β `TrackType.text`+ - `TextTrackType.SUBTITLES` β `TextTrackType.subtitles`+ - `RFC5646_LANGUAGE` β `Rfc5646Language`+ - And many more enum updates across the codebase++### Android Build System Modernization+- **Gradle Update**: Updated from 7.x to 8.4 for better compatibility+- **Android Gradle Plugin**: Updated from 7.x to 8.3.0+- **Kotlin**: Updated from 1.6.10 to 1.9.10+- **Java Compatibility**: Updated to Java 11+- **Android SDK**: Updated compile SDK to 35, target SDK to 34+- **Dependencies**: Updated Google Cast Framework (21.0.1 β 21.5.0), AndroidX libraries, and other Android dependencies++### Enhanced UI/UX+- **Completely Redesigned Mini Controller**:+ - Modern Material Design with floating card style+ - Marquee text scrolling for long titles and subtitles+ - Better visual hierarchy and improved touch targets+ - Theme-aware styling with customizable colors and typography+- **Enhanced Expanded Player**:+ - Drag-to-dismiss gesture support with smooth animations+ - Better media image handling with fallbacks+ - Improved controls layout with backdrop blur effects+ - Caption/subtitle track selection+ - Seek forward/backward 30 seconds functionality+ - Volume control integration+- **Theme Support**: Added comprehensive theming with `ExpandedGoogleCastPlayerTheme`+- **Internationalization**: Added `ExpandedGoogleCastPlayerTexts` for customizable text content++### Bug Fixes+- **Device Discovery**: Fixed duplicate device detection in Android discovery manager+- **Error Handling**: Improved error handling and removed debug print statements+- **Import Issues**: Fixed missing imports and dependency issues+- **Memory Leaks**: Better disposal of animation controllers and stream subscriptions+- **UI Stability**: Fixed various layout and rendering issues++### New Features+- **Marquee Text Support**: Added `marquee` package dependency for scrolling text+- **Customizable Texts**: Complete internationalization support with example+- **Advanced Theming**: Comprehensive theme customization options+- **Better Examples**: Added `customizable_texts_example.dart` and documentation+- **Enhanced Documentation**: Added `CUSTOMIZABLE_TEXTS.md` with usage examples++### Developer Experience+- **Improved Code Quality**: Better type safety, null safety compliance+- **Documentation**: Enhanced inline documentation and examples+- **File Organization**: Better separation of concerns and cleaner imports++### Migration Guide+If you're upgrading from previous versions, you'll need to update enum usage:+```dart+// Before+GoogleCastConnectState.ConnectionStateConnected+CastMediaStreamType.BUFFERED+TrackType.TEXT++// After+GoogleCastConnectState.connected+CastMediaStreamType.buffered+TrackType.text+```++## 1.0.2+- Improved README.md with better documentation and examples+- Enhanced setup instructions and usage guidelines+- Updated documentation formatting and clarity++## 0.0.1++* TODO: Describe initial release.+++## 0.0.3+allow change subtitle tracks and audio tracks++## 0.0.4+add license to pubspec.yaml++## 0.0.5+add repository to pubspec.yaml++## 0.0.6+generate dart doc with dartdoc++## 0.0.7+update package name in podpec++## 0.0.8+fix GoogleCastPlugin.m file++## 0.0.9+fix /android/app/src/main/AndroidManifest.xml and add+```xml+<meta-data+ android:name=+ "com.google.android.gms.cast.framework.OPTIONS_PROVIDER_CLASS_NAME"+ android:value="com.felnanuke.google_cast.GoogleCastOptionsProvider" />+```++## 0.0.10+- Now supports Flutter 3.22.0, thanks to contributions from fmsidoe.++## 0.0.11+- fix issue on that crash app when session is disconnected+- add to doc and example new properties required to work on android api 34+++## 1.0.0+- Update plugin to support Flutter v3.24.3.+- Bump version and update dependency versions in pubspec.yaml.+- Update SDK constraints in both main and example pubspec files for compatibility with latest Flutter.+- Add conditional namespace configuration in android/build.gradle for compatibility with the latest Gradle and Android Studio.++## 1.0.1+- Update README example to use fully qualified provider class name for Android manifest integration+- Clarify the android:value meta-data entry with complete package path to prevent ambiguity when registering the options providerdiff --git a/packages/flutter_chrome_cast/LICENSE b/packages/flutter_chrome_cast/LICENSEnew file mode 100644index 00000000..b69325f9--- /dev/null+++ b/packages/flutter_chrome_cast/LICENSE@@ -0,0 +1,11 @@+Copyright 2023 felnanuke2++Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:++1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.++2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.++3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.++THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS βAS ISβ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\ No newline at end of filediff --git a/packages/flutter_chrome_cast/README.md b/packages/flutter_chrome_cast/README.mdnew file mode 100644index 00000000..e85e24df--- /dev/null+++ b/packages/flutter_chrome_cast/README.md@@ -0,0 +1,934 @@+# Flutter Google Cast++[](https://codecov.io/gh/felnanuke2/flutter_google_cast)+[](https://github.com/felnanuke2/flutter_google_cast/actions)++**FlutterGoogleCast** is a comprehensive Flutter plugin that provides seamless integration with the Google Cast SDK for both iOS and Android platforms. This plugin enables your Flutter application to discover, connect to, and control Chromecast devices and other Google Cast-enabled receivers.++> **π± Alternative for Non-Cast Devices**: If you need to integrate with devices that don't have Google Cast built-in or are not Chromecast devices, you may be interested in https://github.com/felnanuke2/media_cast_dlna - take a look!++## Support the Project++<a href='https://ko-fi.com/Y8Y61HCG2P' target='_blank'><img height='36' style='border:0px;height:36px;' src='https://storage.ko-fi.com/cdn/kofi5.png?v=6' border='0' alt='Buy Me a Coffee at ko-fi.com' /></a>++## Demo Video++<video src="https://raw.githubusercontent.com/felnanuke2/flutter_google_cast/refs/heads/master/Screen_Recording_20250618_125333.mp4" controls width="600" poster="https://raw.githubusercontent.com/felnanuke2/flutter_google_cast/refs/heads/master/Screenshot_20250618_130514.jpg">+ Your browser does not support the video tag.+</video>++## Features++- π **Device Discovery**: Automatically discover Google Cast devices on your network+- π± **Cross-Platform**: Full support for both iOS and Android+- π₯ **Media Streaming**: Stream videos, audio, and other media content+- π **Queue Management**: Load and manage media queues with multiple items+- ποΈ **Media Controls**: Play, pause, seek, volume control, and more+- πΊ **Session Management**: Connect and disconnect from cast devices+- π **Real-time Updates**: Stream-based APIs for real-time status updates+- π± **Mini Controller**: Built-in mini controller widget for easy integration+- π οΈ **Robust Build System**: Optimized Android builds with automated troubleshooting tools++## Getting Started++### Installation++Add `flutter_chrome_cast` to your `pubspec.yaml` file:++```yaml+dependencies:+ flutter_chrome_cast: ^latest_version+```++Then run:+```bash+flutter pub get+```++## Import Strategy++This package provides flexible import options to optimize your app's performance:++### π― Modular Imports (Recommended)++Instead of importing everything, you can now import only what you need:++| Import | What it includes | When to use |+|--------|------------------|-------------|+| `flutter_chrome_cast.dart` | Everything | Getting started, prototyping |+| `cast_context.dart` | Google Cast initialization | Always needed |+| `discovery.dart` | Device discovery | When you need to find devices |+| `session.dart` | Session management | When managing cast sessions |+| `media.dart` | Media control | When controlling media playback |+| `widgets.dart` | UI components | When using built-in cast widgets |+| `entities.dart` | Data models | When working with cast data |+| `enums.dart` | Constants & enums | When you need specific constants |++### π Benefits++- **Smaller bundle size**: Only include what you use+- **Faster compilation**: Less code to analyze and compile+- **Cleaner namespace**: Avoid importing unused classes+- **Better IDE support**: More precise auto-completion++### π Migration Guide++**Before (v1.0.4 and earlier):**+```dart+import 'package:flutter_chrome_cast/lib.dart';+```++**After (v1.1.0+):**+```dart+// Option 1: Everything (same functionality)+import 'package:flutter_chrome_cast/flutter_chrome_cast.dart';++// Option 2: Only what you need (recommended)+import 'package:flutter_chrome_cast/cast_context.dart';+import 'package:flutter_chrome_cast/media.dart';+import 'package:flutter_chrome_cast/widgets.dart';+```++## Platform Setup++### iOS Configuration++This plugin supports both **CocoaPods** (default) and **Swift Package Manager (SPM)** for iOS dependency management.++#### Info.plist Configuration++Add the following configuration to your `ios/Runner/Info.plist` file:++```xml+<key>NSLocalNetworkUsageDescription</key>+<string>${PRODUCT_NAME} uses the local network to discover Cast-enabled devices on your WiFi network.</string>+<key>NSBonjourServices</key>+<array>+ <string>_CC1AD845._googlecast._tcp</string>+ <string>_googlecast._tcp</string>+</array>+```++> **Note**: Replace `_CC1AD845._googlecast._tcp` with your actual Google Cast application ID.++#### Using Swift Package Manager (SPM)++If you prefer to use SPM instead of CocoaPods, or if you're experiencing CocoaPods read-only issues, this plugin provides full SPM support.++The plugin uses the [SRGSSR/google-cast-sdk](https://github.com/SRGSSR/google-cast-sdk) community wrapper since Google does not officially provide an SPM-compatible distribution of the Cast SDK.++To use SPM:++1. Open your iOS project in Xcode+2. Navigate to File β Add Package Dependencies+3. Add the flutter_chrome_cast plugin's iOS package++Or add it to your project's `Package.swift`:++```swift+dependencies: [+ .package(url: "https://github.com/felnanuke2/flutter_google_cast.git", from: "1.2.6")+]+```++<details>+<summary>Complete iOS Info.plist example</summary>++```xml+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>NSLocalNetworkUsageDescription</key>+ <string>${PRODUCT_NAME} uses the local network to discover Cast-enabled devices on your WiFi network.</string>+ <key>NSBonjourServices</key>+ <array>+ <string>_CC1AD845._googlecast._tcp</string>+ <string>_googlecast._tcp</string>+ </array>+ <key>CFBundleDevelopmentRegion</key>+ <string>$(DEVELOPMENT_LANGUAGE)</string>+ <key>CFBundleDisplayName</key>+ <string>Google Cast</string>+ <key>CFBundleExecutable</key>+ <string>$(EXECUTABLE_NAME)</string>+ <key>CFBundleIdentifier</key>+ <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>+ <key>CFBundleInfoDictionaryVersion</key>+ <string>6.0</string>+ <key>CFBundleName</key>+ <string>google_cast_example</string>+ <key>CFBundlePackageType</key>+ <string>APPL</string>+ <key>CFBundleShortVersionString</key>+ <string>$(FLUTTER_BUILD_NAME)</string>+ <key>CFBundleSignature</key>+ <string>????</string>+ <key>CFBundleVersion</key>+ <string>$(FLUTTER_BUILD_NUMBER)</string>+ <key>LSRequiresIPhoneOS</key>+ <true/>+ <key>UILaunchStoryboardName</key>+ <string>LaunchScreen</string>+ <key>UIMainStoryboardFile</key>+ <string>Main</string>+ <key>UISupportedInterfaceOrientations</key>+ <array>+ <string>UIInterfaceOrientationPortrait</string>+ <string>UIInterfaceOrientationLandscapeLeft</string>+ <string>UIInterfaceOrientationLandscapeRight</string>+ </array>+ <key>UISupportedInterfaceOrientations~ipad</key>+ <array>+ <string>UIInterfaceOrientationPortrait</string>+ <string>UIInterfaceOrientationPortraitUpsideDown</string>+ <string>UIInterfaceOrientationLandscapeLeft</string>+ <string>UIInterfaceOrientationLandscapeRight</string>+ </array>+ <key>UIViewControllerBasedStatusBarAppearance</key>+ <false/>+ <key>CADisableMinimumFrameDurationOnPhone</key>+ <true/>+</dict>+</plist>+```+</details>++### Android Configuration++Add the following to your `android/app/src/main/AndroidManifest.xml` file inside the `<application>` tag:++```xml+<!-- Required permission for media playback in foreground service -->+<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK" />++<!-- Google Cast framework configuration -->+<meta-data+ android:name="com.google.android.gms.cast.framework.OPTIONS_PROVIDER_CLASS_NAME"+ android:value="com.felnanuke.google_cast.GoogleCastOptionsProvider" />++<!-- Media notification service for cast controls -->+<service+ android:name="com.google.android.gms.cast.framework.media.MediaNotificationService"+ android:exported="false"+ android:foregroundServiceType="mediaPlayback" />+```++<details>+<summary>Complete Android AndroidManifest.xml example</summary>++```xml+<manifest xmlns:android="http://schemas.android.com/apk/res/android"+ package="com.felnanuke.google_cast_example">++ <uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK" />++ <application+ android:label="google_cast_example"+ android:name="${applicationName}"+ android:icon="@mipmap/ic_launcher">++ <activity+ android:name=".MainActivity"+ android:exported="true"+ android:launchMode="singleTop"+ android:theme="@style/LaunchTheme"+ android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"+ android:hardwareAccelerated="true"+ android:windowSoftInputMode="adjustResize">++ <meta-data+ android:name="io.flutter.embedding.android.NormalTheme"+ android:resource="@style/NormalTheme" />++ <intent-filter>+ <action android:name="android.intent.action.MAIN" />+ <category android:name="android.intent.category.LAUNCHER" />+ </intent-filter>+ </activity>++ <meta-data+ android:name="flutterEmbedding"+ android:value="2" />++ <meta-data+ android:name="com.google.android.gms.cast.framework.OPTIONS_PROVIDER_CLASS_NAME"+ android:value="com.felnanuke.google_cast.GoogleCastOptionsProvider" />++ <service+ android:name="com.google.android.gms.cast.framework.media.MediaNotificationService"+ android:exported="false"+ android:foregroundServiceType="mediaPlayback" />++ </application>+</manifest>+```+</details>++## Usage++### 1. Import the Library++You have several options for importing the Flutter Chrome Cast library:++#### Option A: Complete Import (Recommended for getting started)+```dart+import 'dart:io';+import 'package:flutter/material.dart';+import 'package:flutter_chrome_cast/flutter_chrome_cast.dart';+```++#### Option B: Selective Imports (Recommended for production)+For better performance and cleaner code, import only what you need:++```dart+import 'dart:io';+import 'package:flutter/material.dart';++// Core functionality+import 'package:flutter_chrome_cast/cast_context.dart'; // Google Cast initialization+import 'package:flutter_chrome_cast/discovery.dart'; // Device discovery+import 'package:flutter_chrome_cast/session.dart'; // Session management+import 'package:flutter_chrome_cast/media.dart'; // Media control++// UI widgets (if needed)+import 'package:flutter_chrome_cast/widgets.dart'; // Cast UI widgets++// Data models (if needed)+import 'package:flutter_chrome_cast/entities.dart'; // Cast entities+import 'package:flutter_chrome_cast/enums.dart'; // Enums and constants+```++#### Option C: Legacy Import (Deprecated)+```dart+import 'dart:io';+import 'package:flutter/material.dart';+import 'package:flutter_chrome_cast/lib.dart'; // β οΈ Deprecated - use option A or B+```++> **π‘ Pro Tip**: Use selective imports (Option B) in production apps to reduce bundle size and improve compile times. You only import the functionality you actually use.++### 2. Initialize the Google Cast Context++Initialize the Google Cast context in your app's `initState()` or main function:++```dart+Future<void> initPlatformState() async {+ // Use the default Cast application ID or your custom one+ const appId = GoogleCastDiscoveryCriteria.kDefaultApplicationId;+ GoogleCastOptions? options;++ if (Platform.isIOS) {+ options = IOSGoogleCastOptions(+ GoogleCastDiscoveryCriteriaInitialize.initWithApplicationID(appId),+ // Optional: Stop casting when app is killed (default: false)+ stopCastingOnAppTerminated: true,+ );+ } else if (Platform.isAndroid) {+ options = GoogleCastOptionsAndroid(+ appId: appId,+ // Optional: Stop casting when app is killed (default: false)+ stopCastingOnAppTerminated: true,+ );+ }++ // Initialize the Google Cast context+ GoogleCastContext.instance.setSharedInstanceWithOptions(options!);+}+```++### Configuration Options++The `GoogleCastOptions` class and its platform-specific subclasses support the following configuration options:++| Option | Type | Default | Description |+|--------|------|---------|-------------|+| `stopCastingOnAppTerminated` | `bool` | `false` | When `true`, automatically stops casting and ends the session when the app is killed/terminated. Useful when you want casting to stop when users close the app. |+| `physicalVolumeButtonsWillControlDeviceVolume` | `bool` | `true` | Whether hardware volume buttons control the Cast device volume. |+| `suspendSessionsWhenBackgrounded` | `bool` | `true` | Whether to suspend sessions when the app goes to background. |+| `stopReceiverApplicationWhenEndingSession` | `bool` | `false` | Whether to stop the receiver application when ending a session. |++#### Stop Casting on App Terminated++By default, when you close/kill your app, casting continues on the Chromecast device. If you want the casting to stop when the app is killed, set `stopCastingOnAppTerminated: true`:++```dart+// iOS+options = IOSGoogleCastOptions(+ GoogleCastDiscoveryCriteriaInitialize.initWithApplicationID(appId),+ stopCastingOnAppTerminated: true, // Stop casting when app is killed+);++// Android+options = GoogleCastOptionsAndroid(+ appId: appId,+ stopCastingOnAppTerminated: true, // Stop casting when app is killed+);+```++> **Note:** This works for normal app closures and most system-initiated kills. Force-kills (swiping away from recent apps) may not always trigger this behavior depending on the platform and circumstances.++### 3. Device Discovery++The plugin automatically discovers Cast devices when initialized. You can also manually start/stop discovery:++```dart+// Start discovery (usually automatic when app is in foreground)+GoogleCastDiscoveryManager.instance.startDiscovery();++// Stop discovery to save battery+GoogleCastDiscoveryManager.instance.stopDiscovery();+```++### 4. Display Available Devices++Create a UI to show discovered Cast devices:++```dart+StreamBuilder<List<GoogleCastDevice>>(+ stream: GoogleCastDiscoveryManager.instance.devicesStream,+ builder: (context, snapshot) {+ final devices = snapshot.data ?? [];++ if (devices.isEmpty) {+ return const Center(+ child: Text('No Cast devices found'),+ );+ }++ return ListView.builder(+ itemCount: devices.length,+ itemBuilder: (context, index) {+ final device = devices[index];+ return ListTile(+ leading: const Icon(Icons.cast),+ title: Text(device.friendlyName),+ subtitle: Text(device.modelName ?? 'Unknown model'),+ onTap: () => _connectToDevice(device),+ );+ },+ );+ },+)+```++### 5. Connect to a Cast Device++```dart+Future<void> _connectToDevice(GoogleCastDevice device) async {+ try {+ await GoogleCastSessionManager.instance.startSessionWithDevice(device);+ print('Connected to ${device.friendlyName}');+ } catch (e) {+ print('Failed to connect: $e');+ }+}+```++### 6. Monitor Connection Status++Listen to connection state changes:++```dart+StreamBuilder<GoogleCastSession?>(+ stream: GoogleCastSessionManager.instance.currentSessionStream,+ builder: (context, snapshot) {+ final isConnected = GoogleCastSessionManager.instance.connectionState ==+ GoogleCastConnectState.ConnectionStateConnected;++ return IconButton(+ onPressed: isConnected+ ? GoogleCastSessionManager.instance.endSessionAndStopCasting+ : null,+ icon: Icon(+ isConnected ? Icons.cast_connected : Icons.cast,+ color: isConnected ? Colors.blue : Colors.grey,+ ),+ );+ },+)+```++### 7. Load and Play Media++#### Single Media Item++```dart+Future<void> _loadSingleMedia(GoogleCastDevice device) async {+ await GoogleCastSessionManager.instance.startSessionWithDevice(device);++ await GoogleCastRemoteMediaClient.instance.loadMedia(+ GoogleCastMediaInformationIOS(+ contentId: 'elephants_dream',+ streamType: CastMediaStreamType.BUFFERED,+ contentUrl: Uri.parse(+ 'http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ElephantsDream.mp4'+ ),+ contentType: 'video/mp4',+ metadata: GoogleCastTvShowMediaMetadata(+ episode: 1,+ season: 1,+ seriesTitle: 'Elephants Dream',+ originalAirDate: DateTime.now(),+ images: [+ GoogleCastImage(+ url: Uri.parse(+ 'https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/images/ElephantsDream.jpg'+ ),+ height: 480,+ width: 854,+ ),+ ],+ ),+ tracks: [+ GoogleCastMediaTrack(+ trackId: 0,+ type: TrackType.TEXT,+ trackContentId: Uri.parse(+ 'https://raw.githubusercontent.com/felnanuke2/flutter_cast/master/example/assets/VEED-subtitles_Blender_Foundation_-_Elephants_Dream_1024.vtt'+ ).toString(),+ trackContentType: 'text/vtt',+ name: 'English Subtitles',+ language: RFC5646_LANGUAGE.ENGLISH_UNITED_STATES,+ subtype: TextTrackType.SUBTITLES,+ ),+ ],+ ),+ autoPlay: true,+ playPosition: const Duration(seconds: 0),+ playbackRate: 1.0,+ activeTrackIds: [0],+ );+}+```++#### Media Queue (Playlist)++```dart+Future<void> _loadMediaQueue(GoogleCastDevice device) async {+ await GoogleCastSessionManager.instance.startSessionWithDevice(device);++ await GoogleCastRemoteMediaClient.instance.queueLoadItems(+ [+ GoogleCastQueueItem(+ activeTrackIds: [0],+ mediaInformation: GoogleCastMediaInformationIOS(+ contentId: 'elephants_dream',+ streamType: CastMediaStreamType.BUFFERED,+ contentUrl: Uri.parse(+ 'http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ElephantsDream.mp4'+ ),+ contentType: 'video/mp4',+ metadata: GoogleCastMovieMediaMetadata(+ title: 'Elephants Dream',+ studio: 'Blender Foundation',+ releaseDate: DateTime(2006),+ images: [+ GoogleCastImage(+ url: Uri.parse(+ 'https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/images/ElephantsDream.jpg'+ ),+ height: 480,+ width: 854,+ ),+ ],+ ),+ tracks: [+ GoogleCastMediaTrack(+ trackId: 0,+ type: TrackType.TEXT,+ trackContentId: Uri.parse(+ 'https://raw.githubusercontent.com/felnanuke2/flutter_cast/master/example/assets/VEED-subtitles_Blender_Foundation_-_Elephants_Dream_1024.vtt'+ ).toString(),+ trackContentType: 'text/vtt',+ name: 'English',+ language: RFC5646_LANGUAGE.ENGLISH_UNITED_STATES,+ subtype: TextTrackType.SUBTITLES,+ ),+ ],+ ),+ ),+ GoogleCastQueueItem(+ preLoadTime: const Duration(seconds: 15),+ mediaInformation: GoogleCastMediaInformationIOS(+ contentId: 'big_buck_bunny',+ streamType: CastMediaStreamType.BUFFERED,+ contentUrl: Uri.parse(+ 'http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4'+ ),+ contentType: 'video/mp4',+ metadata: GoogleCastMovieMediaMetadata(+ title: 'Big Buck Bunny',+ studio: 'Blender Foundation',+ releaseDate: DateTime(2008),+ images: [+ GoogleCastImage(+ url: Uri.parse(+ 'https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/images/BigBuckBunny.jpg'+ ),+ height: 480,+ width: 854,+ ),+ ],+ ),+ ),+ ),+ ],+ options: GoogleCastQueueLoadOptions(+ startIndex: 0,+ playPosition: const Duration(seconds: 0),+ ),+ );+}+```++### 8. Media Playback Controls++#### Basic Controls++```dart+// Play/Pause toggle+void _togglePlayPause() {+ final isPlaying = GoogleCastRemoteMediaClient.instance.mediaStatus?.playerState ==+ CastMediaPlayerState.playing;++ if (isPlaying) {+ GoogleCastRemoteMediaClient.instance.pause();+ } else {+ GoogleCastRemoteMediaClient.instance.play();+ }+}++// Stop playback+void _stop() {+ GoogleCastRemoteMediaClient.instance.stop();+}++// Seek to specific position+void _seekTo(Duration position) {+ GoogleCastRemoteMediaClient.instance.seek(+ GoogleCastMediaSeekOption(position: position)+ );+}+```++#### Queue Controls++```dart+// Skip to next item in queue+void _skipToNext() {+ GoogleCastRemoteMediaClient.instance.queueNextItem();+}++// Skip to previous item in queue+void _skipToPrevious() {+ GoogleCastRemoteMediaClient.instance.queuePrevItem();+}++// Insert item into queue+void _insertQueueItem() {+ GoogleCastRemoteMediaClient.instance.queueInsertItems(+ [+ GoogleCastQueueItem(+ mediaInformation: GoogleCastMediaInformationIOS(+ contentId: 'new_video',+ streamType: CastMediaStreamType.BUFFERED,+ contentUrl: Uri.parse('your_video_url_here'),+ contentType: 'video/mp4',+ metadata: GoogleCastMovieMediaMetadata(+ title: 'New Video',+ studio: 'Your Studio',+ releaseDate: DateTime.now(),+ ),+ ),+ )+ ],+ beforeItemWithId: 2, // Insert before item with ID 2+ );+}+```++### 9. Monitor Media Status++```dart+StreamBuilder<GoggleCastMediaStatus?>(+ stream: GoogleCastRemoteMediaClient.instance.mediaStatusStream,+ builder: (context, snapshot) {+ final mediaStatus = snapshot.data;++ if (mediaStatus == null) {+ return const Text('No media loaded');+ }++ final isPlaying = mediaStatus.playerState == CastMediaPlayerState.playing;+ final duration = mediaStatus.mediaInformation?.duration ?? Duration.zero;+ final position = GoogleCastRemoteMediaClient.instance.playerPosition;++ return Column(+ children: [+ Text('Status: ${isPlaying ? "Playing" : "Paused"}'),+ Text('Title: ${mediaStatus.mediaInformation?.metadata?.title ?? "Unknown"}'),+ LinearProgressIndicator(+ value: duration.inSeconds > 0 ? position.inSeconds / duration.inSeconds : 0,+ ),+ Text('${_formatDuration(position)} / ${_formatDuration(duration)}'),+ ],+ );+ },+)+```++### 10. Add Mini Controller++The plugin provides a convenient mini controller widget:++```dart+@override+Widget build(BuildContext context) {+ return Scaffold(+ body: Stack(+ children: [+ // Your main app content+ YourMainContent(),++ // Mini controller (appears when casting)+ const GoogleCastMiniController(),+ ],+ ),+ );+}+```++## Customization: Themes & Texts++You can customize the look and feel of the player and localize its texts using the `GoogleCastPlayerTheme` and `GoogleCastPlayerTexts` classes.++### Customizing the Player Theme++```dart+final darkTheme = GoogleCastPlayerTheme(+ backgroundColor: Colors.black,+ titleTextStyle: const TextStyle(+ fontSize: 18,+ fontWeight: FontWeight.bold,+ color: Colors.white,+ ),+ deviceTextStyle: TextStyle(+ fontSize: 14,+ color: Colors.grey[400],+ fontWeight: FontWeight.w400,+ ),+ iconColor: Colors.white,+ iconSize: 32,+ imageBorderRadius: BorderRadius.circular(8),+ imageShadow: [+ BoxShadow(+ color: Colors.white.withOpacity(0.2),+ blurRadius: 6,+ offset: const Offset(0, 2),+ ),+ ],+);++// Use with the player widget:+ExpandedGoogleCastPlayerController(+ theme: darkTheme,+)+```++### Customizing Player Texts (Localization)++```dart+const spanishTexts = GoogleCastPlayerTexts(+ unknownTitle: 'TΓtulo desconocido',+ castingToDevice: (deviceName) => 'Transmitiendo a $deviceName',+ noCaptionsAvailable: 'Sin subtΓtulos disponibles',+ captionsOff: 'Desactivar',+ trackFallback: (trackId) => 'Pista $trackId',+);++// Use with the player widget:+ExpandedGoogleCastPlayerController(+ texts: spanishTexts,+)+```++You can combine both theme and texts for full customization:++```dart+ExpandedGoogleCastPlayerController(+ theme: darkTheme,+ texts: spanishTexts,+)+```++For more advanced examples, see the example app in [`example/lib/main.dart`](example/lib/main.dart).++## Complete Example++A full working example is available in [`example/lib/main.dart`](example/lib/main.dart) in this repository.++The usage snippets above cover the most common integration patterns. For advanced usage, custom UI, and more, see the example app source code.++## API Reference++### Core Classes++#### GoogleCastContext+Main entry point for Google Cast functionality.+- `setSharedInstanceWithOptions(GoogleCastOptions options)`: Initialize Cast context++#### GoogleCastDiscoveryManager+Manages device discovery.+- `startDiscovery()`: Start discovering Cast devices+- `stopDiscovery()`: Stop device discovery+- `devicesStream`: Stream of discovered devices++#### GoogleCastSessionManager+Manages Cast sessions.+- `startSessionWithDevice(GoogleCastDevice device)`: Connect to a device+- `endSessionAndStopCasting()`: Disconnect from current device+- `currentSessionStream`: Stream of session changes+- `connectionState`: Current connection state++#### GoogleCastRemoteMediaClient+Controls media playback.+- `loadMedia()`: Load a single media item+- `queueLoadItems()`: Load a media queue+- `play()`: Start playback+- `pause()`: Pause playback+- `stop()`: Stop playback+- `seek()`: Seek to position+- `queueNextItem()`: Skip to next item+- `queuePrevItem()`: Skip to previous item+- `mediaStatusStream`: Stream of media status updates++### Widgets++#### GoogleCastMiniController+A pre-built widget that provides basic media controls when casting.++## Troubleshooting++### Common Issues++1. **No devices found**: Ensure your mobile device and Cast receiver are on the same WiFi network.++2. **iOS: Local network permission**: Make sure you've added the `NSLocalNetworkUsageDescription` to your Info.plist.++3. **Android: Service not found**: Verify that the required meta-data and service entries are in your AndroidManifest.xml.++4. **Media not loading**: Check that your media URLs are accessible and in supported formats (MP4, WebM, etc.).++### Supported Media Formats++- **Video**: MP4, WebM, MOV+- **Audio**: MP3, AAC, FLAC, WAV+- **Streaming**: HLS (m3u8), DASH++## π Documentation++### User Guides+- **[Import Guide](IMPORT_GUIDE.md)** - Optimize your Flutter imports for better performance+- **[Main README](README.md)** - This file - complete plugin usage and setup++### Developer Documentation+- **[Native Development Guide](NATIVE_GUIDE.md)** - Overview of native implementation architecture+- **[iOS Native Guide](NATIVE_IOS_GUIDE.md)** - Swift implementation details, debugging, and contribution guide+- **[Android Native Guide](NATIVE_ANDROID_GUIDE.md)** - Kotlin implementation details, debugging, and contribution guide++### Quick Links+- π― **New to the plugin?** Start with this README and the [Import Guide](IMPORT_GUIDE.md)+- π§ **Want to contribute to native code?** Check out the [Native Development Guide](NATIVE_GUIDE.md)+- π **iOS development?** See the [iOS Native Guide](NATIVE_IOS_GUIDE.md)+- π€ **Android development?** See the [Android Native Guide](NATIVE_ANDROID_GUIDE.md)+- π‘ **Optimizing imports?** Use the [Import Guide](IMPORT_GUIDE.md)++## Development & Testing++### Running Tests++This project maintains high test coverage to ensure reliability. Tests are automatically run on every PR to master.++```bash+# Run all tests+flutter test++# Run tests with coverage+flutter test --coverage++# Quick coverage report (opens in browser on macOS/Linux)+./scripts/quick_coverage.sh+```++### Coverage Reports++Coverage is automatically generated and reported on every PR. Reports are uploaded to Codecov and the workflow produces HTML artifacts for each run.++Coverage badges at the top of this README show the current coverage status. Detailed coverage reports are available:+- As artifacts in GitHub Actions workflow runs+- On [Codecov](https://codecov.io/gh/felnanuke2/flutter_google_cast)++### Coverage Scripts++The project includes several coverage scripts:++- `scripts/run_coverage.sh` - Comprehensive coverage analysis with detailed reporting+- `scripts/quick_coverage.sh` - Quick coverage check for development+- `scripts/test_enforcement.sh` - Enforces test requirements++## Troubleshooting++### Android Build Issues++If you encounter Android build issues, the plugin includes several solutions:++#### Quick Fix Script++Run the automated fix script:++```bash+./scripts/fix_android_build.sh+```++#### Common Issues++1. **Java heap space errors during build**:+ - The plugin now includes optimized Gradle settings+ - Heap size is automatically increased to 3GB++2. **Android x86 target deprecation warnings**:+ - x86 targets are excluded by default+ - Use: `flutter build apk --target-platform android-arm64,android-arm`++3. **AndroidX migration conflicts**:+ - Jetifier is optimized with blacklisted problematic dependencies+ - AndroidX is enabled by default++4. **Dependency resolution issues**:+ ```bash+ flutter clean+ flutter pub get+ cd android && ./gradlew clean+ flutter build apk --target-platform android-arm64,android-arm+ ```++For detailed troubleshooting, see [ANDROID_BUILD_TROUBLESHOOTING.md](ANDROID_BUILD_TROUBLESHOOTING.md).++### Dependency Updates++Check for outdated dependencies:++```bash+flutter pub outdated+```++The CI automatically checks and reports outdated dependencies, but they won't fail the build if they're incompatible with current constraints.++## Contributing++Contributions are welcome! Please submit pull requests to our GitHub repository.++## License++This plugin is released under the BSD-3-Clause License. See the LICENSE file for details.diff --git a/packages/flutter_chrome_cast/analysis_options.yaml b/packages/flutter_chrome_cast/analysis_options.yamlnew file mode 100644index 00000000..10c3576d--- /dev/null+++ b/packages/flutter_chrome_cast/analysis_options.yaml@@ -0,0 +1,59 @@+include: package:flutter_lints/flutter.yaml++# Additional information about this file can be found at+# https://dart.dev/guides/language/analysis-options++analyzer:+ # Exclude generated files and build artifacts+ exclude:+ - "**/*.g.dart"+ - "**/*.freezed.dart"+ - "**/build/**"+ - "**/.dart_tool/**"++ # Enable more strict analysis+ language:+ # strict-casts: true+ # strict-inference: true+ # strict-raw-types: true++linter:+ rules:+ # Documentation rules+ public_member_api_docs: true++ # Testing-related rules+ # These rules help encourage good testing practices++ # Code quality rules that make testing easier+ # avoid_catches_without_on_clauses: true+ # avoid_catching_errors: true+ # avoid_empty_else: true+ # avoid_returning_null_for_future: true+ # avoid_slow_async_io: true+ # cancel_subscriptions: true+ # close_sinks: true++ # Test-specific rules (these apply to test files)+ # Note: These only work when you have test files+ # avoid_redundant_argument_values: true # Helps in test assertions+ # prefer_const_constructors_in_immutables: true # Better test objects++ # Rules that make code more testable+ # prefer_final_locals: true+ # prefer_final_in_for_each: true+ # prefer_single_quotes: true+ # avoid_function_literals_in_foreach_calls: true+ # avoid_positional_boolean_parameters: true++ # # Error handling (important for testing)+ # use_build_context_synchronously: true++ # # Performance rules (help with test performance)+ # avoid_unnecessary_containers: true+ # sized_box_for_whitespace: true++ # # Code organization (makes tests cleaner)+ # directives_ordering: true+ # sort_constructors_first: true+ # sort_unnamed_constructors_first: truediff --git a/packages/flutter_chrome_cast/android/build.gradle b/packages/flutter_chrome_cast/android/build.gradlenew file mode 100644index 00000000..42ceb901--- /dev/null+++ b/packages/flutter_chrome_cast/android/build.gradle@@ -0,0 +1,58 @@+group 'com.felnanuke.google_cast'+version '1.0-SNAPSHOT'++buildscript {+ ext.kotlin_version = '1.9.10'+ repositories {+ google()+ mavenCentral()+ }++ dependencies {+ classpath 'com.android.tools.build:gradle:8.3.0'+ classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"+ }+}++rootProject.allprojects {+ repositories {+ google()+ mavenCentral()+ }+}++apply plugin: 'com.android.library'+apply plugin: 'kotlin-android'+++android {+ namespace = "com.felnanuke.google_cast"+ compileSdk = 35++ compileOptions {+ sourceCompatibility JavaVersion.VERSION_11+ targetCompatibility JavaVersion.VERSION_11+ }++ kotlinOptions {+ jvmTarget = '11'+ }++ sourceSets {+ main.java.srcDirs += 'src/main/kotlin'+ }++ defaultConfig {+ minSdkVersion 21+ }+}++dependencies {+ implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"+ implementation 'androidx.appcompat:appcompat:1.6.1'+ implementation 'androidx.mediarouter:mediarouter:1.4.0'+ implementation 'com.google.android.gms:play-services-cast-framework:21.5.0'+ api 'com.google.code.gson:gson:2.10.1'+++}diff --git a/packages/flutter_chrome_cast/android/gradle.properties b/packages/flutter_chrome_cast/android/gradle.propertiesnew file mode 100644index 00000000..bc93b96e--- /dev/null+++ b/packages/flutter_chrome_cast/android/gradle.properties@@ -0,0 +1,8 @@+org.gradle.jvmargs=-Xmx4096M -XX:MaxMetaspaceSize=1024m -XX:+HeapDumpOnOutOfMemoryError+android.useAndroidX=true+android.enableJetifier=true+# Optimize Jetifier for better performance+android.jetifier.ignorelist=bcprov-jdk15on+# Gradle performance optimizations+org.gradle.parallel=true+org.gradle.caching=truediff --git a/packages/flutter_chrome_cast/android/gradle/wrapper/gradle-wrapper.jar b/packages/flutter_chrome_cast/android/gradle/wrapper/gradle-wrapper.jarnew file mode 100644index 00000000..41d9927aBinary files /dev/null and b/packages/flutter_chrome_cast/android/gradle/wrapper/gradle-wrapper.jar differdiff --git a/packages/flutter_chrome_cast/android/gradle/wrapper/gradle-wrapper.properties b/packages/flutter_chrome_cast/android/gradle/wrapper/gradle-wrapper.propertiesnew file mode 100644index 00000000..e411586a--- /dev/null+++ b/packages/flutter_chrome_cast/android/gradle/wrapper/gradle-wrapper.properties@@ -0,0 +1,5 @@+distributionBase=GRADLE_USER_HOME+distributionPath=wrapper/dists+distributionUrl=https\://services.gradle.org/distributions/gradle-8.4-bin.zip+zipStoreBase=GRADLE_USER_HOME+zipStorePath=wrapper/distsdiff --git a/packages/flutter_chrome_cast/android/gradlew b/packages/flutter_chrome_cast/android/gradlewnew file mode 100644index 00000000..1b6c7873--- /dev/null+++ b/packages/flutter_chrome_cast/android/gradlew@@ -0,0 +1,234 @@+#!/bin/sh++#+# Copyright Β© 2015-2021 the original authors.+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# https://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+#++##############################################################################+#+# Gradle start up script for POSIX generated by Gradle.+#+# Important for running:+#+# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is+# noncompliant, but you have some other compliant shell such as ksh or+# bash, then to run this script, type that shell name before the whole+# command line, like:+#+# ksh Gradle+#+# Busybox and similar reduced shells will NOT work, because this script+# requires all of these POSIX shell features:+# * functions;+# * expansions Β«$varΒ», Β«${var}Β», Β«${var:-default}Β», Β«${var+SET}Β»,+# Β«${var#prefix}Β», Β«${var%suffix}Β», and Β«$( cmd )Β»;+# * compound commands having a testable exit status, especially Β«caseΒ»;+# * various built-in commands including Β«commandΒ», Β«setΒ», and Β«ulimitΒ».+#+# Important for patching:+#+# (2) This script targets any POSIX shell, so it avoids extensions provided+# by Bash, Ksh, etc; in particular arrays are avoided.+#+# The "traditional" practice of packing multiple parameters into a+# space-separated string is a well documented source of bugs and security+# problems, so this is (mostly) avoided, by progressively accumulating+# options in "$@", and eventually passing that to Java.+#+# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,+# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;+# see the in-line comments for details.+#+# There are tweaks for specific operating systems such as AIX, CygWin,+# Darwin, MinGW, and NonStop.+#+# (3) This script is generated from the Groovy template+# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt+# within the Gradle project.+#+# You can find Gradle at https://github.com/gradle/gradle/.+#+##############################################################################++# Attempt to set APP_HOME++# Resolve links: $0 may be a link+app_path=$0++# Need this for daisy-chained symlinks.+while+ APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path+ [ -h "$app_path" ]+do+ ls=$( ls -ld "$app_path" )+ link=${ls#*' -> '}+ case $link in #(+ /*) app_path=$link ;; #(+ *) app_path=$APP_HOME$link ;;+ esac+done++APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit++APP_NAME="Gradle"+APP_BASE_NAME=${0##*/}++# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.+DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'++# Use the maximum available, or set MAX_FD != -1 to use that value.+MAX_FD=maximum++warn () {+ echo "$*"+} >&2++die () {+ echo+ echo "$*"+ echo+ exit 1+} >&2++# OS specific support (must be 'true' or 'false').+cygwin=false+msys=false+darwin=false+nonstop=false+case "$( uname )" in #(+ CYGWIN* ) cygwin=true ;; #(+ Darwin* ) darwin=true ;; #(+ MSYS* | MINGW* ) msys=true ;; #(+ NONSTOP* ) nonstop=true ;;+esac++CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar+++# Determine the Java command to use to start the JVM.+if [ -n "$JAVA_HOME" ] ; then+ if [ -x "$JAVA_HOME/jre/sh/java" ] ; then+ # IBM's JDK on AIX uses strange locations for the executables+ JAVACMD=$JAVA_HOME/jre/sh/java+ else+ JAVACMD=$JAVA_HOME/bin/java+ fi+ if [ ! -x "$JAVACMD" ] ; then+ die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME++Please set the JAVA_HOME variable in your environment to match the+location of your Java installation."+ fi+else+ JAVACMD=java+ which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.++Please set the JAVA_HOME variable in your environment to match the+location of your Java installation."+fi++# Increase the maximum file descriptors if we can.+if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then+ case $MAX_FD in #(+ max*)+ MAX_FD=$( ulimit -H -n ) ||+ warn "Could not query maximum file descriptor limit"+ esac+ case $MAX_FD in #(+ '' | soft) :;; #(+ *)+ ulimit -n "$MAX_FD" ||+ warn "Could not set maximum file descriptor limit to $MAX_FD"+ esac+fi++# Collect all arguments for the java command, stacking in reverse order:+# * args from the command line+# * the main class name+# * -classpath+# * -D...appname settings+# * --module-path (only if needed)+# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.++# For Cygwin or MSYS, switch paths to Windows format before running java+if "$cygwin" || "$msys" ; then+ APP_HOME=$( cygpath --path --mixed "$APP_HOME" )+ CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )++ JAVACMD=$( cygpath --unix "$JAVACMD" )++ # Now convert the arguments - kludge to limit ourselves to /bin/sh+ for arg do+ if+ case $arg in #(+ -*) false ;; # don't mess with options #(+ /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath+ [ -e "$t" ] ;; #(+ *) false ;;+ esac+ then+ arg=$( cygpath --path --ignore --mixed "$arg" )+ fi+ # Roll the args list around exactly as many times as the number of+ # args, so each arg winds up back in the position where it started, but+ # possibly modified.+ #+ # NB: a `for` loop captures its iteration list before it begins, so+ # changing the positional parameters here affects neither the number of+ # iterations, nor the values presented in `arg`.+ shift # remove old arg+ set -- "$@" "$arg" # push replacement arg+ done+fi++# Collect all arguments for the java command;+# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of+# shell script including quotes and variable substitutions, so put them in+# double quotes to make sure that they get re-expanded; and+# * put everything else in single quotes, so that it's not re-expanded.++set -- \+ "-Dorg.gradle.appname=$APP_BASE_NAME" \+ -classpath "$CLASSPATH" \+ org.gradle.wrapper.GradleWrapperMain \+ "$@"++# Use "xargs" to parse quoted args.+#+# With -n1 it outputs one arg per line, with the quotes and backslashes removed.+#+# In Bash we could simply go:+#+# readarray ARGS < <( xargs -n1 <<<"$var" ) &&+# set -- "${ARGS[@]}" "$@"+#+# but POSIX shell has neither arrays nor command substitution, so instead we+# post-process each arg (as a line of input to sed) to backslash-escape any+# character that might be a shell metacharacter, then use eval to reverse+# that process (while maintaining the separation between arguments), and wrap+# the whole thing up as a single "set" statement.+#+# This will of course break if any of these variables contains a newline or+# an unmatched quote.+#++eval "set -- $(+ printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |+ xargs -n1 |+ sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |+ tr '\n' ' '+ )" '"$@"'++exec "$JAVACMD" "$@"diff --git a/packages/flutter_chrome_cast/android/gradlew.bat b/packages/flutter_chrome_cast/android/gradlew.batnew file mode 100644index 00000000..107acd32--- /dev/null+++ b/packages/flutter_chrome_cast/android/gradlew.bat@@ -0,0 +1,89 @@+@rem+@rem Copyright 2015 the original author or authors.+@rem+@rem Licensed under the Apache License, Version 2.0 (the "License");+@rem you may not use this file except in compliance with the License.+@rem You may obtain a copy of the License at+@rem+@rem https://www.apache.org/licenses/LICENSE-2.0+@rem+@rem Unless required by applicable law or agreed to in writing, software+@rem distributed under the License is distributed on an "AS IS" BASIS,+@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+@rem See the License for the specific language governing permissions and+@rem limitations under the License.+@rem++@if "%DEBUG%" == "" @echo off+@rem ##########################################################################+@rem+@rem Gradle startup script for Windows+@rem+@rem ##########################################################################++@rem Set local scope for the variables with windows NT shell+if "%OS%"=="Windows_NT" setlocal++set DIRNAME=%~dp0+if "%DIRNAME%" == "" set DIRNAME=.+set APP_BASE_NAME=%~n0+set APP_HOME=%DIRNAME%++@rem Resolve any "." and ".." in APP_HOME to make it shorter.+for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi++@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.+set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"++@rem Find java.exe+if defined JAVA_HOME goto findJavaFromJavaHome++set JAVA_EXE=java.exe+%JAVA_EXE% -version >NUL 2>&1+if "%ERRORLEVEL%" == "0" goto execute++echo.+echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.+echo.+echo Please set the JAVA_HOME variable in your environment to match the+echo location of your Java installation.++goto fail++:findJavaFromJavaHome+set JAVA_HOME=%JAVA_HOME:"=%+set JAVA_EXE=%JAVA_HOME%/bin/java.exe++if exist "%JAVA_EXE%" goto execute++echo.+echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%+echo.+echo Please set the JAVA_HOME variable in your environment to match the+echo location of your Java installation.++goto fail++:execute+@rem Setup the command line++set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar+++@rem Execute Gradle+"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*++:end+@rem End local scope for the variables with windows NT shell+if "%ERRORLEVEL%"=="0" goto mainEnd++:fail+rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of+rem the _cmd.exe /c_ return code!+if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1+exit /b 1++:mainEnd+if "%OS%"=="Windows_NT" endlocal++:omegadiff --git a/packages/flutter_chrome_cast/android/proguard-rules.pro b/packages/flutter_chrome_cast/android/proguard-rules.pronew file mode 100644index 00000000..dff8ee6f--- /dev/null+++ b/packages/flutter_chrome_cast/android/proguard-rules.pro@@ -0,0 +1,31 @@+-keep public class com.google.android.gms.common.internal.safeparcel.SafeParcelable {+ public static final *** NULL;+}++-keepnames class * implements android.os.Parcelable+-keepclassmembers class * implements android.os.Parcelable {+ public static final *** CREATOR;+}++-keep @interface android.support.annotation.Keep+-keep @android.support.annotation.Keep class *+-keepclasseswithmembers class * {+ @android.support.annotation.Keep <fields>;+}+-keepclasseswithmembers class * {+ @android.support.annotation.Keep <methods>;+}++-keep @interface com.google.android.gms.common.annotation.KeepName+-keepnames @com.google.android.gms.common.annotation.KeepName class *+-keepclassmembernames class * {+ @com.google.android.gms.common.annotation.KeepName *;+}++-keep @interface com.google.android.gms.common.util.DynamiteApi+-keep public @com.google.android.gms.common.util.DynamiteApi class * {+ public <fields>;+ public <methods>;+}++-dontwarn android.security.NetworkSecurityPolicydiff --git a/packages/flutter_chrome_cast/android/settings.gradle b/packages/flutter_chrome_cast/android/settings.gradlenew file mode 100644index 00000000..74245639--- /dev/null+++ b/packages/flutter_chrome_cast/android/settings.gradle@@ -0,0 +1 @@+rootProject.name = 'google_cast'diff --git a/packages/flutter_chrome_cast/android/src/main/AndroidManifest.xml b/packages/flutter_chrome_cast/android/src/main/AndroidManifest.xmlnew file mode 100644index 00000000..1240f805--- /dev/null+++ b/packages/flutter_chrome_cast/android/src/main/AndroidManifest.xml@@ -0,0 +1,4 @@+<manifest xmlns:android="http://schemas.android.com/apk/res/android"+ package="com.felnanuke.google_cast">++</manifest>diff --git a/packages/flutter_chrome_cast/android/src/main/kotlin/com/felnanuke/google_cast/CastContextMethodChannel.kt b/packages/flutter_chrome_cast/android/src/main/kotlin/com/felnanuke/google_cast/CastContextMethodChannel.ktnew file mode 100644index 00000000..9c5cc49b--- /dev/null+++ b/packages/flutter_chrome_cast/android/src/main/kotlin/com/felnanuke/google_cast/CastContextMethodChannel.kt@@ -0,0 +1,191 @@+package com.felnanuke.google_cast++import android.annotation.SuppressLint+import android.content.Context+import android.os.Build+import android.util.Log+import androidx.activity.ComponentActivity+import androidx.activity.result.ActivityResultLauncher+import androidx.activity.result.contract.ActivityResultContracts+import com.google.android.gms.cast.framework.CastContext+import com.google.android.gms.cast.framework.CastOptions+import io.flutter.embedding.engine.plugins.FlutterPlugin+import io.flutter.plugin.common.MethodCall+import io.flutter.plugin.common.MethodChannel+import io.flutter.embedding.engine.plugins.activity.ActivityAware+import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding+import com.google.android.gms.cast.LaunchOptions+import java.util.concurrent.Executors++/**+ * Tag for logging Cast context operations+ */+private const val TAG = "CastContext"++/**+ * Flutter method channel for Google Cast context management+ *+ * This class handles all Google Cast context-related operations, including SDK initialization,+ * configuration management, and Cast framework setup. It serves as the primary interface+ * between Flutter and the Google Cast SDK for Android context operations.+ *+ * Key responsibilities:+ * - Google Cast SDK initialization and configuration+ * - Cast context lifecycle management+ * - Permission handling for device discovery (Android 13+)+ * - Integration with other Cast method channels+ * - Activity lifecycle awareness for proper context management+ *+ * Architecture:+ * The class coordinates multiple Cast SDK components:+ * - DiscoveryManagerMethodChannel: Handles device discovery operations+ * - SessionManagerMethodChannel: Manages Cast session lifecycle+ * - CastContext: Core Google Cast SDK context for all operations+ *+ * The class implements ActivityAware to properly handle Android activity lifecycle+ * events and ensure Cast SDK operations work correctly with the host application.+ *+ * @author LUIZ FELIPE ALVES LIMA+ * @since Android API 21 (Android 5.0)+ */+class CastContextMethodChannel : FlutterPlugin, MethodChannel.MethodCallHandler {++ /**+ * Flutter method channel for Cast context communication+ *+ * This channel handles method calls related to Cast context operations,+ * including initialization, configuration, and state management.+ * Channel name: "com.felnanuke.google_cast.context"+ */+ private lateinit var channel: MethodChannel++ /**+ * Android application context for Cast SDK operations+ *+ * Required for Google Cast SDK initialization and provides access+ * to system services and application-level resources needed for+ * Cast functionality.+ */+ private lateinit var appContext: Context++ /**+ * Discovery manager method channel for device discovery operations+ *+ * Handles all Cast device discovery functionality including starting/stopping+ * discovery, managing discovered devices, and notifying Flutter of device changes.+ */+ private val discoveryManager = DiscoveryManagerMethodChannel()++ /**+ * Session manager method channel for Cast session management+ *+ * Manages Cast session lifecycle including session creation, connection,+ * disconnection, and session state monitoring. Initialized with discovery manager+ * reference for device selection during session creation.+ */+ private lateinit var sessionManagerMethodChannel: SessionManagerMethodChannel++ /**+ * Permission launcher for nearby WiFi devices (Android 13+)+ *+ * Handles runtime permission requests for accessing nearby WiFi devices,+ * which is required for Cast device discovery on Android 13 and higher.+ * Uses the new runtime permission system for enhanced privacy.+ */+ private lateinit var nearbyWifiDevicesPermissionLauncher: ActivityResultLauncher<String>++ /**+ * Executor for Cast context operations+ *+ * Single-threaded executor used for Cast SDK operations that need to be+ * performed off the main thread to avoid blocking the UI.+ */+ private val executor = Executors.newSingleThreadExecutor()++ // MARK: - Flutter Plugin Lifecycle+++ /**+ * Called when the Flutter plugin is attached to the Flutter engine+ *+ * Initializes the Cast context method channel and sets up all necessary+ * components for Cast SDK operations. This method prepares the plugin+ * for Cast functionality by establishing communication channels and+ * initializing dependent components.+ *+ * Setup operations:+ * - Stores application context for Cast SDK operations+ * - Creates and configures the Cast context method channel+ * - Initializes the discovery manager for device discovery+ * - Sets up the session manager with discovery manager reference+ * - Prepares all components for Cast operations+ *+ * @param binding Flutter plugin binding providing access to engine resources+ */+ override fun onAttachedToEngine(binding: FlutterPlugin.FlutterPluginBinding) {++ appContext = binding.applicationContext+ channel = MethodChannel(binding.binaryMessenger, "com.felnanuke.google_cast.context")+ channel.setMethodCallHandler(this)+ discoveryManager.onAttachedToEngine(binding)+ sessionManagerMethodChannel = SessionManagerMethodChannel(discoveryManager)+ sessionManagerMethodChannel.onAttachedToEngine(binding)++ }++ override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {+ channel.setMethodCallHandler(null)+ // Clean up session manager listener to prevent memory leaks+ try {+ CastContext.getSharedInstance(appContext)?.sessionManager?.removeSessionManagerListener(sessionManagerMethodChannel)+ } catch (e: Exception) {+ Log.w(TAG, "Failed to remove session manager listener", e)+ }+ }+++ // MethodCallHandler+ override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {+ when (call.method) {+ "setSharedInstance" -> setSharedInstance(call.arguments, result)+ else -> result.notImplemented()+ }+ }++ private fun setupActivityResult(activity: ComponentActivity) {+ nearbyWifiDevicesPermissionLauncher =+ activity.registerForActivityResult(ActivityResultContracts.RequestPermission()) { isGranted: Boolean ->+ if (isGranted) {+ Log.d(TAG, "Nearby WiFi devices permission granted")+ } else {+ Log.w(TAG, "Nearby WiFi devices permission denied")+ }+ }+ }+++ private fun setSharedInstance(arguments: Any?, result: MethodChannel.Result) {+ try {+ val map = arguments as HashMap<*, *>+ val optionsBuilder = CastOptions.Builder()+ optionsBuilder.setReceiverApplicationId(map["appId"] as String)+ val launcherOptions = LaunchOptions.Builder().setAndroidReceiverCompatible(true).build()+ optionsBuilder.setLaunchOptions(launcherOptions)+ optionsBuilder.setResumeSavedSession(true)+ optionsBuilder.setEnableReconnectionService(true)+ GoogleCastOptionsProvider.options = optionsBuilder.build()++ // Store the stopCastingOnAppTerminated option+ val stopCastingOnAppTerminated = map["stopCastingOnAppTerminated"] as? Boolean ?: false+ GoogleCastOptionsProvider.stopCastingOnAppTerminated = stopCastingOnAppTerminated+ Log.d(TAG, "stopCastingOnAppTerminated set to: $stopCastingOnAppTerminated")++ CastContext.getSharedInstance(appContext).sessionManager.addSessionManagerListener(sessionManagerMethodChannel)+ result.success(true)+ } catch (e: Exception) {+ Log.e(TAG, "Failed to set shared instance", e)+ result.error("CAST_ERROR", "Failed to initialize Cast context: ${e.message}", null)+ }+ }++}\ No newline at end of filediff --git a/packages/flutter_chrome_cast/android/src/main/kotlin/com/felnanuke/google_cast/DiscoveryManagerMethodChannel.kt b/packages/flutter_chrome_cast/android/src/main/kotlin/com/felnanuke/google_cast/DiscoveryManagerMethodChannel.ktnew file mode 100644index 00000000..c425ebea--- /dev/null+++ b/packages/flutter_chrome_cast/android/src/main/kotlin/com/felnanuke/google_cast/DiscoveryManagerMethodChannel.kt@@ -0,0 +1,274 @@+package com.felnanuke.google_cast++import android.content.Context+import android.util.Log+import androidx.mediarouter.media.MediaControlIntent+import androidx.mediarouter.media.MediaRouteSelector+import androidx.mediarouter.media.MediaRouter+import com.felnanuke.google_cast.extensions.toMap+import com.google.android.gms.cast.CastDevice+import com.google.android.gms.cast.CastMediaControlIntent+import io.flutter.embedding.engine.plugins.FlutterPlugin+import io.flutter.plugin.common.MethodCall+import io.flutter.plugin.common.MethodChannel+import com.google.gson.Gson++/**+ * Tag for logging discovery manager operations+ */+private const val TAG = "DiscoveryManager"++/**+ * Flutter method channel for Google Cast device discovery operations+ *+ * This class manages the discovery of Google Cast devices on the local network using+ * Android's MediaRouter framework. It handles device discovery lifecycle, maintains+ * discovered device state, and communicates device availability changes to Flutter.+ *+ * Key responsibilities:+ * - Cast device discovery management (start/stop)+ * - Real-time device availability monitoring+ * - Device state synchronization with Flutter+ * - Integration with Android MediaRouter framework+ * - Device selection and routing preparation+ *+ * Architecture:+ * The class uses Android's MediaRouter system to discover Cast devices:+ * - MediaRouter: Core Android component for device discovery+ * - MediaRouteSelector: Defines criteria for Cast device discovery+ * - DiscoveryRouterCallback: Handles device discovery events+ * - Device state management for Flutter communication+ *+ * Discovery Process:+ * 1. Creates MediaRouteSelector for Cast devices+ * 2. Registers callback with MediaRouter for device events+ * 3. Monitors device availability changes in real-time+ * 4. Notifies Flutter of discovered/removed devices+ * 5. Maintains device list for session creation+ *+ * @author LUIZ FELIPE ALVES LIMA+ * @since Android API 21 (Android 5.0)+ */+class DiscoveryManagerMethodChannel : FlutterPlugin, MethodChannel.MethodCallHandler {++ /**+ * Flutter method channel for discovery communication+ *+ * Handles method calls related to device discovery operations and sends+ * device availability updates to Flutter. Channel name:+ * "com.felnanuke.google_cast.discovery_manager"+ */+ lateinit var channel: MethodChannel++ /**+ * Media router callback for device discovery events+ *+ * Receives callbacks from Android's MediaRouter when Cast devices are+ * discovered, updated, or removed from the network. Implements the+ * callback interface to handle real-time device state changes.+ */+ val routerCallBack: DiscoveryRouterCallback = DiscoveryRouterCallback()++ /**+ * Android MediaRouter instance for device discovery+ *+ * Core Android component that handles media device discovery and routing.+ * Provides access to available Cast devices on the local network and+ * manages the discovery process lifecycle.+ */+ val router: MediaRouter+ get() = MediaRouter.getInstance(context)++ /**+ * Android application context for system services+ *+ * Required for accessing MediaRouter instance and other system services+ * needed for Cast device discovery operations.+ */+ private lateinit var context: Context++ // MARK: - Flutter Plugin Lifecycle+++ /**+ * Called when the Flutter plugin is attached to the Flutter engine+ *+ * Initializes the discovery manager method channel and prepares the+ * component for Cast device discovery operations.+ *+ * Setup operations:+ * - Creates the discovery manager method channel+ * - Registers this class as the method call handler+ * - Stores application context for MediaRouter access+ * - Prepares discovery infrastructure+ *+ * @param binding Flutter plugin binding providing access to engine resources+ */+ override fun onAttachedToEngine(binding: FlutterPlugin.FlutterPluginBinding) {+ channel =+ MethodChannel(binding.binaryMessenger, "com.felnanuke.google_cast.discovery_manager")+ channel.setMethodCallHandler(this)+ context = binding.applicationContext+ }++ /**+ * Called when the Flutter plugin is detached from the Flutter engine+ *+ * Performs cleanup of discovery manager resources to prevent memory leaks.+ *+ * Cleanup operations:+ * - Removes method call handler from the channel+ * - Stops any active discovery operations+ * - Releases discovery-related resources+ *+ * @param binding Flutter plugin binding being detached+ */+ override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {+ channel.setMethodCallHandler(null)+ }++ /**+ * Handles method calls from the Flutter side+ *+ * Processes incoming method calls for device discovery operations.+ * Manages the discovery lifecycle and device state synchronization.+ *+ * Supported methods:+ * - `startDiscovery`: Begins Cast device discovery on the local network+ * - `stopDiscovery`: Stops Cast device discovery and clears device list+ *+ * @param call The method call from Flutter containing method name and arguments+ * @param result The result callback to return responses to Flutter+ */+ override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {+ when (call.method) {+ "startDiscovery" -> {+ startDiscovery()+ result.success(true)+ }+ "stopDiscovery" -> {+ stopDiscovery()+ result.success(true)+ }+ else -> result.notImplemented()+ }+ }++ private fun stopDiscovery() {++ router.removeCallback(routerCallBack)+ }++ private fun startDiscovery() {+ router.removeCallback(routerCallBack)+ val selector = MediaRouteSelector.Builder()+ .addControlCategories(listOf(CastMediaControlIntent.categoryForRemotePlayback()))+ .build()+ router.addCallback(+ selector, routerCallBack, MediaRouter.CALLBACK_FLAG_REQUEST_DISCOVERY+ )++ routerCallBack.getCastDevicesMap()+ }++ inner class DiscoveryRouterCallback : MediaRouter.Callback() {++ override fun onRouteUnselected(+ router: MediaRouter, route: MediaRouter.RouteInfo, reason: Int+ ) {+ super.onRouteUnselected(router, route, reason)+ Log.d(TAG, "Route unselected, total routes: ${router.routes.size}")+ }++ override fun onRouteAdded(router: MediaRouter, route: MediaRouter.RouteInfo) {+ super.onRouteAdded(router, route)+ getCastDevicesMap()+ }++ override fun onRouteRemoved(router: MediaRouter, route: MediaRouter.RouteInfo) {+ super.onRouteRemoved(router, route)+ getCastDevicesMap()+ }++ override fun onRouteChanged(router: MediaRouter, route: MediaRouter.RouteInfo) {+ super.onRouteChanged(router, route)+ getCastDevicesMap()+ }++ override fun onRouteVolumeChanged(router: MediaRouter, route: MediaRouter.RouteInfo) {+ super.onRouteVolumeChanged(router, route)+ getCastDevicesMap()+ }+++ override fun onProviderAdded(router: MediaRouter, provider: MediaRouter.ProviderInfo) {+ super.onProviderAdded(router, provider)+ Log.d(TAG, "Provider added, total routes: ${router.routes.size}")+ }++ override fun onProviderRemoved(router: MediaRouter, provider: MediaRouter.ProviderInfo) {+ super.onProviderRemoved(router, provider)+ Log.d(TAG, "Provider removed, total routes: ${router.routes.size}")+ }++ override fun onProviderChanged(router: MediaRouter, provider: MediaRouter.ProviderInfo) {+ super.onProviderChanged(router, provider)+ Log.d(TAG, "Provider changed, total routes: ${router.routes.size}")+ }++ private fun getCastDevice(routeInfo: MediaRouter.RouteInfo): Map<*, *>? {+ val device = CastDevice.getFromBundle(routeInfo.extras)+ return device?.let {+ device.toMap()+ }+++ }++ fun getCastDevicesMap() {+ val devices = mutableListOf<kotlin.collections.Map<*, *>>()+ val seenDeviceIds = mutableSetOf<String>()+ val seenDeviceSignatures = mutableSetOf<String>()++ for (route in router.routes) {+ val device = getCastDevice(route)+ if (device != null) {+ val deviceId = device["id"] as? String+ val deviceName = device["name"] as? String+ val deviceModel = device["model_name"] as? String+ val deviceSignature = "${deviceName}_${deviceModel}"++ Log.d(TAG, "Found route with device ID: $deviceId, name: $deviceName, model: $deviceModel")++ // Skip devices we've already seen by ID or by name+model combination+ if (deviceId != null &&+ !seenDeviceIds.contains(deviceId) &&+ !seenDeviceSignatures.contains(deviceSignature)) {+ seenDeviceIds.add(deviceId)+ seenDeviceSignatures.add(deviceSignature)+ devices.add(device)+ Log.d(TAG, "Added unique device: $deviceId ($deviceSignature)")+ } else {+ Log.w(TAG, "Skipping duplicate device - ID: $deviceId, signature: $deviceSignature")+ }+ }+ }+ val json = Gson().toJson(devices)+ [email protected]("onDevicesChanged", json)+ Log.w(TAG, "onDevicesChanged $json")+ }+ }++ fun selectRoute(id: String) {+ val routes = router?.routes+ val selectedRoute = routes?.find {+ val device = CastDevice.getFromBundle(it.extras)+ device?.deviceId == id+ }+ if (selectedRoute != null) {+ this.router?.selectRoute(selectedRoute)+ }+ }+++}\ No newline at end of filediff --git a/packages/flutter_chrome_cast/android/src/main/kotlin/com/felnanuke/google_cast/GoogleCastOptionsProvider.kt b/packages/flutter_chrome_cast/android/src/main/kotlin/com/felnanuke/google_cast/GoogleCastOptionsProvider.ktnew file mode 100644index 00000000..21e53ab4--- /dev/null+++ b/packages/flutter_chrome_cast/android/src/main/kotlin/com/felnanuke/google_cast/GoogleCastOptionsProvider.kt@@ -0,0 +1,65 @@+package com.felnanuke.google_cast++import android.content.Context+import com.google.android.gms.cast.framework.CastOptions+import com.google.android.gms.cast.framework.OptionsProvider+import com.google.android.gms.cast.framework.SessionProvider++/**+ * Google Cast options provider for Flutter Google Cast plugin+ *+ * This class provides Cast framework configuration options that are set up+ * during plugin initialization. It implements the OptionsProvider interface+ * required by the Google Cast SDK for Android.+ *+ * The options are configured dynamically through the Flutter plugin and+ * stored in the companion object for access by the Cast framework.+ *+ * @author LUIZ FELIPE ALVES LIMA+ * @since Android API 21 (Android 5.0)+ */+class GoogleCastOptionsProvider : OptionsProvider {++ companion object {+ /**+ * Cast options configured by the Flutter plugin+ *+ * These options are set by the CastContextMethodChannel during+ * Cast context initialization and include receiver application ID,+ * launch options, and other Cast framework configuration.+ */+ lateinit var options: CastOptions++ /**+ * Whether to stop casting when the app is terminated+ *+ * When true, the plugin will automatically end the cast session+ * and stop casting on the receiver when the app is killed.+ * Default is false (casting continues after app is closed).+ */+ var stopCastingOnAppTerminated: Boolean = false+ }++ /**+ * Provides Cast options to the Google Cast framework+ *+ * @param context Android application context+ * @return Configured Cast options for the framework+ */+ override fun getCastOptions(context: Context): CastOptions {+ return options+ }++ /**+ * Provides additional session providers for custom Cast functionality+ *+ * Currently returns null as no additional session providers are needed+ * for basic Cast functionality.+ *+ * @param context Android application context+ * @return List of additional session providers, or null if none needed+ */+ override fun getAdditionalSessionProviders(context: Context): MutableList<SessionProvider>? {+ return null+ }+}\ No newline at end of filediff --git a/packages/flutter_chrome_cast/android/src/main/kotlin/com/felnanuke/google_cast/GoogleCastPlugin.kt b/packages/flutter_chrome_cast/android/src/main/kotlin/com/felnanuke/google_cast/GoogleCastPlugin.ktnew file mode 100644index 00000000..387f0d5b--- /dev/null+++ b/packages/flutter_chrome_cast/android/src/main/kotlin/com/felnanuke/google_cast/GoogleCastPlugin.kt@@ -0,0 +1,217 @@+package com.felnanuke.google_cast++import android.app.Activity+import android.app.Application+import android.os.Bundle+import android.util.Log+import androidx.annotation.NonNull+import com.google.android.gms.cast.framework.CastContext++import io.flutter.embedding.engine.plugins.FlutterPlugin+import io.flutter.embedding.engine.plugins.activity.ActivityAware+import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding+import io.flutter.plugin.common.MethodCall+import io.flutter.plugin.common.MethodChannel+import io.flutter.plugin.common.MethodChannel.MethodCallHandler+import io.flutter.plugin.common.MethodChannel.Result++/**+ * Main Google Cast plugin for Android implementation+ *+ * This class serves as the primary entry point for the Flutter Google Cast plugin on Android.+ * It implements the FlutterPlugin interface to integrate with the Flutter framework and+ * coordinates the initialization of all Cast-related method channels.+ *+ * The plugin manages:+ * - Flutter plugin lifecycle (attachment/detachment)+ * - Registration of specialized method channels for Cast features+ * - Integration with the Google Cast SDK for Android+ * - Coordination between different Cast functionality components+ * - Automatic cast session termination when the app is killed+ *+ * Architecture:+ * The main plugin acts as a coordinator, delegating specific Cast operations to+ * specialized method channels:+ * - CastContextMethodChannel: Handles Cast context initialization and configuration+ * - DiscoveryManagerMethodChannel: Manages device discovery operations+ * - SessionManagerMethodChannel: Controls Cast session lifecycle+ * - RemoteMediaClientMethodChannel: Handles media playback operations+ *+ * The plugin follows Android's component lifecycle patterns and ensures proper+ * resource management when the Flutter engine is attached or detached.+ *+ * @author LUIZ FELIPE ALVES LIMA+ * @since Android API 21 (Android 5.0)+ */+class GoogleCastPlugin : FlutterPlugin, MethodCallHandler, ActivityAware, Application.ActivityLifecycleCallbacks {++ companion object {+ private const val TAG = "GoogleCastPlugin"+ }++ /**+ * Flutter method channel for basic plugin communication+ *+ * This channel handles general plugin operations and serves as the main+ * communication bridge between Flutter and the native Android implementation.+ * It's primarily used for plugin lifecycle management and basic queries.+ */+ private lateinit var channel: MethodChannel++ /**+ * Cast context method channel for Google Cast SDK operations+ *+ * This specialized channel handles all Cast context-related operations,+ * including SDK initialization, configuration, and context management.+ * It's automatically initialized and managed by this main plugin class.+ */+ private val castContextMethodChannel = CastContextMethodChannel()++ /**+ * Reference to the current activity for lifecycle management+ */+ private var activity: Activity? = null++ /**+ * Application context for Cast SDK operations+ */+ private var applicationContext: android.content.Context? = null++ /**+ * Called when the Flutter plugin is attached to the Flutter engine+ *+ * This method is invoked by the Flutter framework when the plugin is being+ * initialized. It sets up all necessary method channels and prepares the+ * plugin for communication with the Flutter side.+ *+ * Setup operations performed:+ * - Creates the main method channel for plugin communication+ * - Registers this class as the method call handler+ * - Initializes and attaches the Cast context method channel+ * - Prepares all Cast SDK integration components+ *+ * @param flutterPluginBinding The binding that provides access to Flutter engine resources+ */+ override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {+ channel = MethodChannel(flutterPluginBinding.binaryMessenger, "google_cast")+ channel.setMethodCallHandler(this)+ applicationContext = flutterPluginBinding.applicationContext+ castContextMethodChannel.onAttachedToEngine(flutterPluginBinding)+ }++ /**+ * Handles method calls from the Flutter side+ *+ * Processes incoming method calls from Flutter and routes them to appropriate+ * handlers. The main plugin currently handles basic platform queries, while+ * Cast-specific operations are delegated to specialized method channels.+ *+ * Supported methods:+ * - `getPlatformVersion`: Returns the current Android version information+ *+ * @param call The method call from Flutter containing method name and arguments+ * @param result The result callback to return responses or errors to Flutter+ */+ override fun onMethodCall(@NonNull call: MethodCall, @NonNull result: Result) {+ when (call.method) {+ "getPlatformVersion" -> {+ result.success("Android ${android.os.Build.VERSION.RELEASE}")+ }+ else -> {+ result.notImplemented()+ }+ }+ }++ /**+ * Called when the Flutter plugin is detached from the Flutter engine+ *+ * This method is invoked by the Flutter framework when the plugin is being+ * cleaned up. It ensures proper resource cleanup and prevents memory leaks+ * by removing method call handlers and releasing resources.+ *+ * Cleanup operations performed:+ * - Removes the method call handler from the main channel+ * - Allows garbage collection of plugin resources+ * - Ensures no lingering references that could cause memory leaks+ *+ * @param binding The Flutter plugin binding being detached+ */+ override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) {+ channel.setMethodCallHandler(null)+ }++ // MARK: - ActivityAware Implementation++ /**+ * Called when the plugin is attached to an Activity+ *+ * Registers this plugin as an Activity lifecycle callback to monitor+ * when the activity is destroyed and end the cast session accordingly.+ *+ * @param binding The activity plugin binding+ */+ override fun onAttachedToActivity(binding: ActivityPluginBinding) {+ activity = binding.activity+ activity?.application?.registerActivityLifecycleCallbacks(this)+ }++ override fun onDetachedFromActivityForConfigChanges() {+ // Don't unregister on config changes (e.g., rotation)+ }++ override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) {+ activity = binding.activity+ }++ override fun onDetachedFromActivity() {+ activity?.application?.unregisterActivityLifecycleCallbacks(this)+ activity = null+ }++ // MARK: - Application.ActivityLifecycleCallbacks Implementation++ override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {}++ override fun onActivityStarted(activity: Activity) {}++ override fun onActivityResumed(activity: Activity) {}++ override fun onActivityPaused(activity: Activity) {}++ override fun onActivityStopped(activity: Activity) {}++ override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {}++ /**+ * Called when the activity is destroyed+ *+ * When the activity is destroyed (app killed) and stopCastingOnAppTerminated is enabled,+ * this method ends the cast session and stops casting on the receiver device.+ * This ensures that casting stops when the user closes or kills the app.+ *+ * @param activity The activity being destroyed+ */+ override fun onActivityDestroyed(activity: Activity) {+ if (activity == this.activity && activity.isFinishing) {+ // Only end the cast session if stopCastingOnAppTerminated option is enabled+ if (!GoogleCastOptionsProvider.stopCastingOnAppTerminated) {+ Log.d(TAG, "App destroyed - stopCastingOnAppTerminated is false, keeping cast session alive")+ return+ }++ // End the cast session and stop casting when app is killed+ try {+ val context = applicationContext ?: return+ val castContext = CastContext.getSharedInstance(context)+ val sessionManager = castContext?.sessionManager+ if (sessionManager?.currentCastSession != null) {+ Log.d(TAG, "App destroyed - ending cast session and stopping casting (stopCastingOnAppTerminated=true)")+ sessionManager.endCurrentSession(true)+ }+ } catch (e: Exception) {+ Log.w(TAG, "Failed to end cast session on app destroy", e)+ }+ }+ }+}diff --git a/packages/flutter_chrome_cast/android/src/main/kotlin/com/felnanuke/google_cast/RemoteMediaClientMethodChannel.kt b/packages/flutter_chrome_cast/android/src/main/kotlin/com/felnanuke/google_cast/RemoteMediaClientMethodChannel.ktnew file mode 100644index 00000000..c9713cf2--- /dev/null+++ b/packages/flutter_chrome_cast/android/src/main/kotlin/com/felnanuke/google_cast/RemoteMediaClientMethodChannel.kt@@ -0,0 +1,402 @@+package com.felnanuke.google_cast++import android.media.session.MediaSession+import android.util.Log+import com.felnanuke.google_cast.extensions.*+import com.google.android.gms.cast.MediaStatus.REPEAT_MODE_REPEAT_ALL+import com.google.android.gms.cast.MediaStatus.REPEAT_MODE_REPEAT_ALL_AND_SHUFFLE+import com.google.android.gms.cast.MediaStatus.REPEAT_MODE_REPEAT_OFF+import com.google.android.gms.cast.MediaStatus.REPEAT_MODE_REPEAT_SINGLE+import com.google.android.gms.cast.framework.CastContext+import com.google.android.gms.cast.framework.media.RemoteMediaClient+import com.google.gson.Gson+import io.flutter.embedding.engine.plugins.FlutterPlugin+import io.flutter.plugin.common.MethodCall+import io.flutter.plugin.common.MethodChannel+import org.json.JSONObject++/**+ * Tag for logging remote media client operations+ */+private const val TAG = "RemoteMediaClient"++/**+ * Flutter method channel for Google Cast remote media client operations+ *+ * This class manages all media-related operations for Google Cast sessions, providing+ * comprehensive control over media playback, queue management, and media status monitoring.+ * It implements Google Cast remote media client callback interfaces to receive media+ * events and progress updates, communicating these changes to Flutter in real-time.+ *+ * Key responsibilities:+ * - Media loading and queue management operations+ * - Playback controls (play, pause, stop, seek)+ * - Volume and audio track management+ * - Media progress and status monitoring+ * - Queue operations (insert, remove, reorder items)+ * - Text track and subtitle controls+ * - Real-time media updates to Flutter+ *+ * Architecture:+ * The class integrates with Google Cast SDK media components:+ * - RemoteMediaClient: Core Cast SDK media control interface+ * - RemoteMediaClient.Callback: Receives media status change events+ * - RemoteMediaClient.ProgressListener: Monitors media playback progress+ * - Media queue management for playlist functionality+ * - Automatic progress tracking during media playback+ *+ * Media Operations:+ * 1. Media loading with metadata and options+ * 2. Queue management for playlist functionality+ * 3. Playback control and seeking operations+ * 4. Track selection and subtitle management+ * 5. Progress monitoring and status updates+ * 6. Event propagation to Flutter for UI updates+ *+ * @author LUIZ FELIPE ALVES LIMA+ * @since Android API 21 (Android 5.0)+ */+class RemoteMediaClientMethodChannel : FlutterPlugin, MethodChannel.MethodCallHandler,+ RemoteMediaClient.Callback(), RemoteMediaClient.ProgressListener {++ /**+ * Flutter method channel for remote media client communication+ *+ * Handles method calls related to media control operations and sends+ * media status and progress updates to Flutter. Channel name:+ * "com.felnanuke.google_cast.remote_media_client"+ */+ private lateinit var channel: MethodChannel++ /**+ * Current remote media client instance for the active Cast session+ *+ * Provides access to the media client for the current Cast session.+ * Returns null if no Cast session is active or no media client is available.+ *+ * @return The current remote media client, or null if not available+ */+ private val currentRemoteMediaClient: RemoteMediaClient?+ get() =+ CastContext.getSharedInstance()?.sessionManager?.currentCastSession?.remoteMediaClient++ // MARK: - Flutter Plugin Lifecycle+++ /**+ * Called when the Flutter plugin is attached to the Flutter engine+ *+ * Initializes the remote media client method channel for media operations.+ *+ * Setup operations:+ * - Creates the remote media client method channel+ * - Registers this class as the method call handler+ * - Prepares media control infrastructure+ *+ * @param binding Flutter plugin binding providing access to engine resources+ */+ override fun onAttachedToEngine(binding: FlutterPlugin.FlutterPluginBinding) {+ channel =+ MethodChannel(binding.binaryMessenger, "com.felnanuke.google_cast.remote_media_client")+ channel.setMethodCallHandler(this)+ }++ /**+ * Called when the Flutter plugin is detached from the Flutter engine+ *+ * Performs cleanup of remote media client resources to prevent memory leaks.+ *+ * Cleanup operations:+ * - Removes method call handler from the channel+ * - Stops media monitoring+ * - Releases media-related resources+ *+ * @param binding Flutter plugin binding being detached+ */+ override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {+ channel.setMethodCallHandler(null)+ // Clean up media client listeners to prevent memory leaks+ endListen()+ }++ // MARK: - Flutter Method Call Handling++ /**+ * Handles method calls from the Flutter side+ *+ * Processes incoming method calls for media control operations. Supports+ * comprehensive media management including loading, playback control,+ * queue management, and track selection.+ *+ * Supported methods:+ * - `loadMedia`: Load a single media item with options+ * - `queueLoadItems`: Load multiple items into a media queue+ * - `queueInsertItems`: Insert items into existing queue+ * - `queueInsertItemAndPlay`: Insert item and start playback+ * - `queueNextItem`: Skip to next item in queue+ * - `queuePrevItem`: Skip to previous item in queue+ * - `queueJumpToItemWithId`: Jump to specific queue item+ * - `queueRemoveItemsWithIds`: Remove items from queue+ * - `queueReorderItems`: Reorder queue items+ * - `seek`: Seek to specific position in media+ * - `setActiveTrackIds`: Select audio/subtitle tracks+ * - `setPlaybackRate`: Adjust playback speed+ * - `setTextTrackStyle`: Configure subtitle appearance+ * - `play`: Start or resume media playback+ * - `pause`: Pause media playback+ * - And many more media control operations...+ *+ * @param call The method call from Flutter containing method name and arguments+ * @param result The result callback to return responses to Flutter+ */+ override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {+ when (call.method) {+ "loadMedia" -> {+ loadMedia(call.arguments as Map<String, Any?>)+ result.success(true)+ }++ "queueLoadItems" -> {+ queueLoadItems(call.arguments as Map<String, Any?>)+ result.success(true)+ }++ "queueInsertItems" -> {+ queueInsertItems(call.arguments as Map<String, Any?>)+ result.success(true)+ }++ "queueInsertItemAndPlay" -> {+ queueInsertItemAndPlay(call.arguments as Map<String, Any?>)+ result.success(true)+ }++ "queueNextItem" -> {+ queueNextItem()+ result.success(true)+ }++ "queuePrevItem" -> {+ queuePrevItem()+ result.success(true)+ }++ "queueJumpToItemWithId" -> {+ queueJumpToItemWithId(call.arguments)+ result.success(true)+ }++ "queueRemoveItemsWithIds" -> {+ queueRemoveItemsWithIds(call.arguments)+ result.success(true)+ }++ "queueReorderItems" -> {+ queueReorderItems(call.arguments)+ result.success(true)+ }++ "seek" -> {+ seek(call.arguments)+ result.success(true)+ }++ "setActiveTrackIds" -> {+ setActiveTrackIds(call.arguments)+ result.success(true)+ }++ "setPlaybackRate" -> {+ setPlaybackRate(call.arguments)+ result.success(true)+ }++ "setTextTrackStyle" -> {+ setTextTrackStyle(call.arguments)+ result.success(true)+ }++ "play" -> {+ play()+ result.success(true)+ }++ "pause" -> {+ pause()+ result.success(true)+ }+ "stop" -> {+ stop()+ result.success(true)+ }++ else -> result.notImplemented()+ }+ }++ private fun setTextTrackStyle(arguments: Any?) {++ }++ private fun setPlaybackRate(arguments: Any?) {+ val playbackRate = arguments as Double+ currentRemoteMediaClient?.setPlaybackRate(playbackRate)+ }++ private fun setActiveTrackIds(arguments: Any?) {+ arguments as ArrayList<Long>+ val longArray = arguments.map {+ it.toLong()+ }+ currentRemoteMediaClient?.setActiveMediaTracks(longArray.toLongArray())+ ?.addStatusListener { status ->+ if (status.isSuccess) {++ Log.w(TAG, "setActiveTrackIds success $longArray")+ } else {+ Log.w(TAG, "setActiveTrackIds failed $longArray")+ }++ }+++ }++ private fun seek(arguments: Any?) {+ arguments as Map<String, Any?>+ val options = GoogleCastSeekOptionsBuilder.fromMap(arguments)+ currentRemoteMediaClient?.seek(options)+ }++ private fun queueReorderItems(arguments: Any?) {+ arguments as Map<String, Any?>+ val itemIds = arguments["itemsIds"] as IntArray+ val beforeItemWithId =+ (arguments["beforeItemWithId"] as Int?) ?: MediaSession.QueueItem.UNKNOWN_ID+ currentRemoteMediaClient?.queueReorderItems(itemIds, beforeItemWithId, JSONObject())+ }++ private fun queueRemoveItemsWithIds(arguments: Any?) {+ arguments as IntArray+ currentRemoteMediaClient?.queueRemoveItems(arguments, JSONObject())+ }++ private fun queueJumpToItemWithId(arguments: Any?) {+ val itemId = arguments as Int+ currentRemoteMediaClient?.queueJumpToItem(itemId, JSONObject())++ }++ private fun queuePrevItem() {+ currentRemoteMediaClient?.queuePrev(JSONObject())+ }++ private fun queueNextItem() {+ currentRemoteMediaClient?.queueNext(JSONObject())+ }++ private fun queueInsertItemAndPlay(arguments: Map<String, Any?>) {+ val item =+ GoogleCastQueueItemBuilder.fromMap(arguments["item"] as Map<String, Any?>) ?: return+ val beforeItemWithId = arguments["beforeItemWithId"] as Int+ var jsonObject = JSONObject()+ currentRemoteMediaClient?.queueInsertAndPlayItem(item, beforeItemWithId, jsonObject)++ }++ private fun queueInsertItems(arguments: Map<String, Any?>) {+ val items =+ GoogleCastQueueItemBuilder.listFromMap(arguments["items"] as List<Map<String, Any?>>)+ val beforeItemWithId =+ (arguments["beforeItemWithId"] as Int?) ?: MediaSession.QueueItem.UNKNOWN_ID+ var jsonObject = JSONObject()+ currentRemoteMediaClient?.queueInsertItems(+ items.toTypedArray(),+ beforeItemWithId,+ jsonObject+ )++ }++ private fun pause() {+ currentRemoteMediaClient?.pause()+ }++ private fun play() {+ currentRemoteMediaClient?.play()++ }++ private fun stop() {+ currentRemoteMediaClient?.stop()+ }++ private fun queueLoadItems(arguments: Map<String, Any?>) {+ val queueItemsData = arguments["queueItems"] as List<Map<String, Any?>>+ val optionsData = arguments["options"] as Map<String, Any?>+ val startIndex = optionsData["startIndex"] as Int+ val repeatMode = optionsData["repeatMode"] as String?+ val playPosition = optionsData["playPosition"] as Int+ val queueItems = GoogleCastQueueItemBuilder.listFromMap(queueItemsData)+ currentRemoteMediaClient?.queueLoad(+ queueItems.toTypedArray(),+ startIndex,+ when (repeatMode) {+ "OFF" -> REPEAT_MODE_REPEAT_OFF+ "ALL" -> REPEAT_MODE_REPEAT_ALL+ "SINGLE" -> REPEAT_MODE_REPEAT_SINGLE+ "ALL_AND_SHUFFLE" -> REPEAT_MODE_REPEAT_ALL_AND_SHUFFLE+ else -> REPEAT_MODE_REPEAT_OFF+ },+ playPosition.toLong() * 1000,+ JSONObject()+ )+ }++ private fun loadMedia(arguments: Map<String, Any?>) {+ val mediaInfo =+ GoogleCastMediaInfo.fromMap(arguments["mediaInfo"] as Map<String, Any?>) ?: return+ val options = GoogleCastMediaLoadOptions.fromMap(arguments)+ currentRemoteMediaClient?.load(mediaInfo, options)+ }++ fun startListen() {+ currentRemoteMediaClient?.registerCallback(this)+ currentRemoteMediaClient?.addProgressListener(this, 500)+ }++ fun endListen() {+ currentRemoteMediaClient?.removeProgressListener(this)+ currentRemoteMediaClient?.unregisterCallback(this)+ }++ // ProgressListener+ override fun onProgressUpdated(progress: Long, duration: Long) {+ var data = mapOf<String, Any?>(+ "progress" to progress,+ "duration" to duration,+ )+ channel.invokeMethod("onPlayerPositionChanged", data)+ }+ // RemoteMediaCallBack++ override fun onStatusUpdated() {+ super.onStatusUpdated()+ val mediaStatus = currentRemoteMediaClient?.mediaStatus+ val jsonObject = currentRemoteMediaClient?.mediaStatus?.toJson()+ jsonObject?.put("activeTrackIds", Gson().toJson(mediaStatus?.activeTrackIds))+ Log.w(TAG, "onStatusUpdated $jsonObject")+ val json = jsonObject?.toString()+ channel.invokeMethod("onMediaStatusChanged", json)+ }++ override fun onQueueStatusUpdated() {+ super.onQueueStatusUpdated()+ val list = currentRemoteMediaClient?.mediaStatus?.queueItems?.map {+ it.toJson().toString()+ }+ channel.invokeMethod("onQueueStatusChanged", list)+++ }+}diff --git a/packages/flutter_chrome_cast/android/src/main/kotlin/com/felnanuke/google_cast/SessionManagerMethodChannel.kt b/packages/flutter_chrome_cast/android/src/main/kotlin/com/felnanuke/google_cast/SessionManagerMethodChannel.ktnew file mode 100644index 00000000..6a2a3811--- /dev/null+++ b/packages/flutter_chrome_cast/android/src/main/kotlin/com/felnanuke/google_cast/SessionManagerMethodChannel.kt@@ -0,0 +1,220 @@+package com.felnanuke.google_cast++import com.felnanuke.google_cast.extensions.toMap+import com.google.android.gms.cast.framework.*+import io.flutter.embedding.engine.plugins.FlutterPlugin+import io.flutter.plugin.common.MethodCall+import io.flutter.plugin.common.MethodChannel++/**+ * Tag for logging session manager operations+ */+private const val TAG = "SessionManager"++/**+ * Flutter method channel for Google Cast session management+ *+ * This class manages the complete lifecycle of Google Cast sessions, including session+ * creation, connection, monitoring, and termination. It implements the Google Cast+ * SessionManagerListener to receive session events and communicates session state+ * changes to Flutter in real-time.+ *+ * Key responsibilities:+ * - Cast session lifecycle management (creation, connection, termination)+ * - Session state monitoring and event handling+ * - Device volume control during active sessions+ * - Integration with discovery manager for device selection+ * - Coordination with remote media client for media operations+ * - Real-time session updates to Flutter+ *+ * Architecture:+ * The class integrates with multiple Cast SDK components:+ * - SessionManager: Core Google Cast SDK session management+ * - DiscoveryManagerMethodChannel: For device selection during session creation+ * - RemoteMediaClientMethodChannel: For media operations during active sessions+ * - Session events are propagated to Flutter for UI updates+ *+ * Session Lifecycle:+ * 1. Session creation request from Flutter with device ID+ * 2. Device selection via discovery manager+ * 3. Session connection and status monitoring+ * 4. Session state synchronization with Flutter+ * 5. Session termination and cleanup+ *+ * @param discoveryManager Reference to discovery manager for device operations+ * @author LUIZ FELIPE ALVES LIMA+ * @since Android API 21 (Android 5.0)+ */+class SessionManagerMethodChannel(discoveryManager: DiscoveryManagerMethodChannel) : FlutterPlugin,+ MethodChannel.MethodCallHandler, SessionManagerListener<Session> {++ /**+ * Flutter method channel for session management communication+ *+ * Handles method calls related to Cast session operations and sends+ * session state updates to Flutter. Channel name:+ * "com.felnanuke.google_cast.session_manager"+ */+ private lateinit var channel: MethodChannel++ /**+ * Reference to discovery manager for device selection+ *+ * Used during session creation to select and connect to specific Cast+ * devices identified by their device ID. Provides the bridge between+ * device discovery and session establishment.+ */+ private val discoveryManagerMethodChannel: DiscoveryManagerMethodChannel = discoveryManager++ /**+ * Remote media client method channel for media operations+ *+ * Handles all media-related operations during active Cast sessions,+ * including media loading, playback control, and media state monitoring.+ * Automatically initialized and managed by the session manager.+ */+ private val remoteMediaClientMethodChannel = RemoteMediaClientMethodChannel()++ /**+ * Google Cast session manager instance+ *+ * Provides access to the current Cast session manager from the Google Cast+ * SDK. Used for all session lifecycle operations and state queries.+ *+ * @return The current session manager instance, or null if Cast context not initialized+ */+ private val sessionManager: SessionManager?+ get() {+ return CastContext.getSharedInstance()?.sessionManager+ }++ // MARK: - Flutter Plugin Lifecycle++ /**+ * Called when the Flutter plugin is attached to the Flutter engine+ *+ * Initializes the session manager method channel and sets up the remote+ * media client for media operations during Cast sessions.+ *+ * Setup operations:+ * - Creates the session manager method channel+ * - Registers this class as the method call handler+ * - Initializes the remote media client method channel+ * - Prepares session management infrastructure+ *+ * @param binding Flutter plugin binding providing access to engine resources+ */+ override fun onAttachedToEngine(binding: FlutterPlugin.FlutterPluginBinding) {+ channel =+ MethodChannel(binding.binaryMessenger, "com.felnanuke.google_cast.session_manager")+ channel.setMethodCallHandler(this)+ remoteMediaClientMethodChannel.onAttachedToEngine(binding)+ }++ /**+ * Called when the Flutter plugin is detached from the Flutter engine+ *+ * Performs cleanup of session manager resources to prevent memory leaks.+ *+ * Cleanup operations:+ * - Removes method call handler from the channel+ * - Stops session monitoring+ * - Releases session-related resources+ *+ * @param binding Flutter plugin binding being detached+ */+ override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {+ channel.setMethodCallHandler(null)+ }++ /**+ * Handles method calls from the Flutter side+ *+ * Processes incoming method calls for Cast session management operations.+ * Manages session lifecycle and device control during active sessions.+ *+ * Supported methods:+ * - `startSessionWithDeviceId`: Initiates a Cast session with specified device+ * - `endSessionAndStopCasting`: Terminates session and stops casting on receiver+ * - `endSession`: Ends the current session gracefully+ * - `setStreamVolume`: Adjusts the volume of the Cast device+ *+ * @param call The method call from Flutter containing method name and arguments+ * @param result The result callback to return responses to Flutter+ */+ override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {+ when (call.method) {+ "startSessionWithDeviceId" -> startSession(call.arguments, result)+ "endSessionAndStopCasting" -> sessionManager?.endCurrentSession(true)+ "endSession" -> sessionManager?.endCurrentSession(false)+ "setStreamVolume" -> sessionManager?.currentCastSession?.volume = call.arguments as Double+ }+ }++ /**+ * Initiates a Cast session with the specified device+ *+ * Starts a new Cast session by selecting the target device through the+ * discovery manager and initiating the connection process. The actual+ * session connection status is reported through session manager listener+ * callbacks.+ *+ * @param arguments The device ID as a String for the target Cast device+ * @param result Flutter result callback to indicate session initiation status+ */+ private fun startSession(arguments: Any?, result: MethodChannel.Result) {+ val deviceId = arguments as String+ discoveryManagerMethodChannel.selectRoute(deviceId)+ result.success(true)+ }+++ //SessionManagerLister+ override fun onSessionEnded(session: Session, p1: Int) {+ onSessionChanged()+ }++ override fun onSessionEnding(p0: Session) {+ onSessionChanged()+ }++ override fun onSessionResumeFailed(p0: Session, p1: Int) {++ onSessionChanged()+ }++ override fun onSessionResumed(p0: Session, p1: Boolean) {+ remoteMediaClientMethodChannel.startListen()+ onSessionChanged()+ }++ override fun onSessionResuming(p0: Session, p1: String) {+ onSessionChanged()+ }++ override fun onSessionStartFailed(p0: Session, p1: Int) {+ onSessionChanged()+ }++ override fun onSessionStarted(session: Session, p1: String) {+ remoteMediaClientMethodChannel.startListen()+ onSessionChanged()+ }++ override fun onSessionStarting(p0: Session) {+ onSessionChanged()+ }++ override fun onSessionSuspended(p0: Session, p1: Int) {+ onSessionChanged()+ }+++ private fun onSessionChanged() {+ val session = sessionManager?.currentCastSession+ val map = session?.toMap()+ channel.invokeMethod("onSessionChanged", map)+ }+++}\ No newline at end of filediff --git a/packages/flutter_chrome_cast/android/src/main/kotlin/com/felnanuke/google_cast/extensions/CastDeviceExtensions.kt b/packages/flutter_chrome_cast/android/src/main/kotlin/com/felnanuke/google_cast/extensions/CastDeviceExtensions.ktnew file mode 100644index 00000000..d8d54f3f--- /dev/null+++ b/packages/flutter_chrome_cast/android/src/main/kotlin/com/felnanuke/google_cast/extensions/CastDeviceExtensions.kt@@ -0,0 +1,54 @@+package com.felnanuke.google_cast.extensions++import com.google.android.gms.cast.CastDevice++/**+ * Extension functions for Google Cast CastDevice to provide Flutter-compatible data conversion+ *+ * This extension adds functionality to convert Google Cast SDK device objects into+ * Map format suitable for transmission to Flutter. It ensures all relevant device+ * information is properly serialized and accessible from the Flutter side.+ *+ * The extension provides a standardized way to represent Cast device information+ * across the Flutter-Android bridge, maintaining consistency in device data+ * representation and ensuring compatibility with Flutter's type system.+ *+ * @author LUIZ FELIPE ALVES LIMA+ * @since Android API 21 (Android 5.0)+ */++/**+ * Converts the CastDevice object to a Flutter-compatible Map+ *+ * This extension function serializes all relevant Cast device properties into a+ * Map format that can be transmitted to Flutter via method channels. The resulting+ * Map contains all essential device information needed for device identification+ * and display in the Flutter UI.+ *+ * Map keys and their corresponding values:+ * - `id`: Device unique identifier (String)+ * - `name`: User-friendly device name for display (String)+ * - `model_name`: Device model name (e.g., "Chromecast", "Google Nest Hub") (String)+ * - `device_version`: Device firmware/software version (String)+ * - `is_on_local_network`: Boolean indicating if device is on local network (Boolean)+ *+ * @return Map containing all device properties for Flutter consumption+ * @receiver CastDevice The Cast device to convert+ * @since Android API 21 (Android 5.0)+ *+ * Example usage:+ * ```kotlin+ * val device: CastDevice = getDiscoveredDevice()+ * val deviceMap = device.toMap()+ * channel.invokeMethod("onDeviceDiscovered", deviceMap)+ * ```+ */+fun CastDevice.toMap(): Map<*, *> {+ return mapOf(+ "id" to this.deviceId,+ "name" to this.friendlyName,+ "model_name" to this.modelName,+ "device_version" to this.deviceVersion,+ "is_on_local_network" to this.isOnLocalNetwork,+ )+}\ No newline at end of filediff --git a/packages/flutter_chrome_cast/android/src/main/kotlin/com/felnanuke/google_cast/extensions/MediaInfoExtensions.kt b/packages/flutter_chrome_cast/android/src/main/kotlin/com/felnanuke/google_cast/extensions/MediaInfoExtensions.ktnew file mode 100644index 00000000..5a6ec328--- /dev/null+++ b/packages/flutter_chrome_cast/android/src/main/kotlin/com/felnanuke/google_cast/extensions/MediaInfoExtensions.kt@@ -0,0 +1,77 @@+package com.felnanuke.google_cast.extensions++import com.google.android.gms.cast.MediaInfo+import com.google.android.gms.cast.MediaMetadata+import com.google.gson.JsonElement+import com.google.gson.JsonObject+import org.json.JSONObject++/**+ * Utility class for building [MediaInfo] objects for Google Cast from map representations.+ */+class GoogleCastMediaInfo {+ companion object {+ /**+ * Creates a [MediaInfo] instance from a [Map] representation.+ *+ * @param map A [Map] containing media information. Expected keys:+ * - "contentID": [String] (required) - The unique content ID.+ * - "contentURL": [String]? - The URL of the content.+ * - "contentType": [String]? - The MIME type of the content.+ * - "tracks": [List]<[Map]<[String], Any?>>? - List of media track maps.+ * - "metadata": [Map]<[String], Any?>? - Metadata map.+ * - "customData": [Map]<[String], Any?>? - Custom data map.+ * @return A [MediaInfo] object if the required fields are present, otherwise null.+ */+ fun fromMap(map: Map<String, Any?>): MediaInfo? {+ val contentId = map["contentID"] as String+ val contentUrl = map["contentURL"] as String?+ val contentType = map["contentType"] as String?+ val streamType = map["streamType"] as String?+ val tracks = GoogleCastMediaTrackBuilder.listFromMap(+ map["tracks"] as List<Map<String, Any?>>? ?: listOf()+ )+ val metaData =+ GoogleCastMetadataBuilder.fromMap(map["metadata"] as Map<String, Any?>? ?: mapOf())+ val builder = MediaInfo.Builder(contentId)+ if (contentUrl != null)+ builder.setContentUrl(contentUrl)+ if (streamType != null)+ builder.setStreamType(when (streamType) {+ "BUFFERED" -> MediaInfo.STREAM_TYPE_BUFFERED+ "LIVE" -> MediaInfo.STREAM_TYPE_LIVE+ "NONE" -> MediaInfo.STREAM_TYPE_NONE+ else -> MediaInfo.STREAM_TYPE_INVALID+ })+ if (contentType != null)+ builder.setContentType(contentType)+ if (tracks.isNotEmpty())+ builder.setMediaTracks(tracks)++ if (metaData != null)+ builder.setMetadata(metaData)+ var customData = map["customData"] as Map<String, Any?>?++ if (customData != null) {+ builder.setCustomData(JSONObject(customData))+ }++ return builder.build()+ }+ }+}++//fun MediaInfo.toMap(): Map<String, Any?> {+// var map = mutableMapOf<String, Any?>()+// map["contentID"] = contentId+// map["contentURL"] = contentUrl+// map["contentType"] = contentType+// map["streamType"] = streamType+// map["streamDuration"] = streamDuration+// map["tracks"] = mediaTracks?.map {+// it.toMap()+// }+// map["metadata"] = null+// return map+//+//}\ No newline at end of filediff --git a/packages/flutter_chrome_cast/android/src/main/kotlin/com/felnanuke/google_cast/extensions/MediaLoadOptionsExtensions.kt b/packages/flutter_chrome_cast/android/src/main/kotlin/com/felnanuke/google_cast/extensions/MediaLoadOptionsExtensions.ktnew file mode 100644index 00000000..e34ec1c1--- /dev/null+++ b/packages/flutter_chrome_cast/android/src/main/kotlin/com/felnanuke/google_cast/extensions/MediaLoadOptionsExtensions.kt@@ -0,0 +1,61 @@+package com.felnanuke.google_cast.extensions++import com.google.android.gms.cast.MediaLoadOptions++/**+ * Extension class for converting Flutter/Dart map data to Google Cast MediaLoadOptions.+ *+ * This class provides utility methods to create MediaLoadOptions objects from Flutter's+ * map representation, facilitating the bridge between Flutter and native Android Google Cast API.+ */+class GoogleCastMediaLoadOptions {+ companion object {+ /**+ * Converts a Flutter map to a MediaLoadOptions object for Google Cast.+ *+ * This method takes a map containing media load configuration parameters+ * and creates a properly configured MediaLoadOptions instance that can be+ * used with the Google Cast SDK.+ *+ * @param map A map containing the following keys:+ * - autoPlay (Boolean): Whether the media should start playing automatically+ * - playPosition (Int): The starting position in seconds (will be converted to milliseconds)+ * - activeTrackIds (ArrayList<Long>?): Optional list of track IDs to activate (e.g., subtitles, audio tracks)+ * - credentials (String?): Optional credentials for authentication+ * - credentialsType (String?): Optional type of credentials being used+ * - playbackRate (Double): The playback rate (1.0 = normal speed)+ *+ * @return MediaLoadOptions A configured MediaLoadOptions object ready for use with Google Cast+ *+ * @throws ClassCastException if any of the map values are not of the expected type+ */+ fun fromMap(map: Map<String, Any?>): MediaLoadOptions {+ // Extract configuration values from the Flutter map+ val autoPlay = map["autoPlay"] as Boolean+ val playPosition = map["playPosition"] as Int+ val activeTrackIds = map["activeTrackIds"] as ArrayList<Long>?+ val credentials = map["credentials"] as String?+ val credentialsType = map["credentialsType"] as String?+ val playbackRate = map["playbackRate"] as Double++ // Build MediaLoadOptions using the builder pattern+ val builder = MediaLoadOptions.Builder()+ builder.setAutoplay(autoPlay)+ // Convert play position from seconds to milliseconds as required by the Google Cast API+ builder.setPlayPosition((playPosition * 1000).toLong())++ // Set active track IDs if provided (for subtitles, audio tracks, etc.)+ if (activeTrackIds != null)+ builder.setActiveTrackIds(activeTrackIds.toLongArray())++ // Set authentication credentials if provided+ builder.setCredentials(credentials)+ builder.setCredentialsType(credentialsType)++ // Set playback rate (1.0 = normal speed, 2.0 = double speed, etc.)+ builder.setPlaybackRate(playbackRate)++ return builder.build()+ }+ }+}\ No newline at end of filediff --git a/packages/flutter_chrome_cast/android/src/main/kotlin/com/felnanuke/google_cast/extensions/MediaStatusExtensions.kt b/packages/flutter_chrome_cast/android/src/main/kotlin/com/felnanuke/google_cast/extensions/MediaStatusExtensions.ktnew file mode 100644index 00000000..2bc31ac0--- /dev/null+++ b/packages/flutter_chrome_cast/android/src/main/kotlin/com/felnanuke/google_cast/extensions/MediaStatusExtensions.kt@@ -0,0 +1,77 @@+package com.felnanuke.google_cast.extensions++import com.google.android.gms.cast.MediaStatus+import com.google.gson.Gson++/**+ * Extension class for Google Cast MediaStatus operations.+ *+ * This class provides utilities for working with MediaStatus objects in the context+ * of the Flutter Google Cast plugin, facilitating data conversion between native+ * Android and Flutter/Dart representations.+ */+class GoogleCastMediaStatusExtensions {+ // This class serves as a container for MediaStatus-related extension functions+ // and utilities that may be added in the future.+}++/**+ * Converts a MediaStatus object to a Map representation suitable for Flutter.+ *+ * This extension function transforms a Google Cast MediaStatus object into a map+ * that can be easily serialized and passed to the Flutter layer. It extracts+ * all relevant media playback state information.+ *+ * @return Map<String, Any?> A map containing the following keys:+ * - activeTrackIds: Array of currently active track IDs (subtitles, audio tracks, etc.)+ * - currentItemId: ID of the currently playing queue item+ * - idleReason: Reason why the player is idle (if applicable)+ * - isMute: Boolean indicating if the player is muted+ * - isPlayingAd: Boolean indicating if an advertisement is currently playing+ * - loadingItemId: ID of the item currently being loaded+ * - mediaInfo: String representation of the current media information+ * - playbackRate: Current playback rate (1.0 = normal speed)+ * - playerState: Current state of the media player+ * - preloadedItemId: ID of the preloaded queue item+ * - queueItemCount: Total number of items in the queue+ * - queueRepeatMode: Current repeat mode for the queue+ * - streamVolume: Current volume level of the stream+ */+fun MediaStatus.toMap(): Map<String, Any?> {+ val map = mutableMapOf<String, Any?>()++ // Track information+ map["activeTrackIds"] = activeTrackIds++ // Queue and item management+ map["currentItemId"] = this.currentItemId+ map["loadingItemId"] = this.loadingItemId+ map["preloadedItemId"] = this.preloadedItemId+ map["queueItemCount"] = this.queueItemCount+ map["queueRepeatMode"] = this.queueRepeatMode++ // Player state information+ map["playerState"] = this.playerState+ map["idleReason"] = this.idleReason+ map["playbackRate"] = this.playbackRate++ // Audio and media information+ map["isMute"] = this.isMute+ map["streamVolume"] = this.streamVolume+ map["mediaInfo"] = this.mediaInfo?.toString()++ // Advertisement state+ map["isPlayingAd"] = this.isPlayingAd++ // Live seekable range+ map["liveSeekableRange"] = this.liveSeekableRange?.let { range ->+ mapOf(+ "start" to range.startTime,+ "end" to range.endTime,+ "isMovingWindow" to range.isMovingWindow,+ "isLiveDone" to range.isLiveDone+ )+ }++ return map+}\ No newline at end of filediff --git a/packages/flutter_chrome_cast/android/src/main/kotlin/com/felnanuke/google_cast/extensions/MediaTrackExtensions.kt b/packages/flutter_chrome_cast/android/src/main/kotlin/com/felnanuke/google_cast/extensions/MediaTrackExtensions.ktnew file mode 100644index 00000000..99202f88--- /dev/null+++ b/packages/flutter_chrome_cast/android/src/main/kotlin/com/felnanuke/google_cast/extensions/MediaTrackExtensions.kt@@ -0,0 +1,55 @@+package com.felnanuke.google_cast.extensions++import com.google.android.gms.cast.MediaTrack+import com.google.gson.JsonElement+import com.google.gson.JsonObject+import org.json.JSONObject++class GoogleCastMediaTrackBuilder {+ companion object {++ fun fromMap(map: Map<String, Any?>): MediaTrack {+ val trackId = map["trackId"] as Int+ val trackType = map["type"] as Int+ val contentId = map["trackContentId"] as String+ val contentType = map["trackContentType"] as String?+ val subType = map["subtype"] as Int?+ val name = map["name"] as String?+ val language = map["language"] as String?+ val customDataData = map["customData"] as Map<String, Any?>?+ val builder = MediaTrack.Builder(trackId.toLong(), trackType)+ builder.setContentId(contentId)+ if (contentType != null)+ builder.setContentType(contentType)+ if (customDataData != null) {+ val customData = JSONObject(customDataData)+ builder.setCustomData(customData)+ }++ if (subType != null)+ builder.setSubtype(subType)+ builder.setName(name)+ builder.setLanguage(language)+ return builder.build()+ }++ fun listFromMap(items: List<Map<String, Any?>>): List<MediaTrack> {+ val list = items.map {+ fromMap(it)+ }+ return list+ }+ }+}++fun MediaTrack.toMap(): Map<String, Any?> {+ val map = mutableMapOf<String, Any?>()+ map["trackId"] = id+ map["type"] = type+ map["trackContentId"] = contentId+ map["trackContentType"] = contentType+ map["subtype"] = subtype+ map["name"] = name+ map["language"] = language+ return map+}\ No newline at end of filediff --git a/packages/flutter_chrome_cast/android/src/main/kotlin/com/felnanuke/google_cast/extensions/MetadataExtensions.kt b/packages/flutter_chrome_cast/android/src/main/kotlin/com/felnanuke/google_cast/extensions/MetadataExtensions.ktnew file mode 100644index 00000000..111b5e5c--- /dev/null+++ b/packages/flutter_chrome_cast/android/src/main/kotlin/com/felnanuke/google_cast/extensions/MetadataExtensions.kt@@ -0,0 +1,84 @@+package com.felnanuke.google_cast.extensions+++import android.net.Uri+import com.google.android.gms.cast.MediaMetadata+import com.google.android.gms.common.images.WebImage+import java.util.*++class GoogleCastMetadataBuilder {+ companion object {+ fun fromMap(args: Map<String, Any?>): MediaMetadata? {++ var map = args.toMutableMap()+ if (map.isEmpty()) return null+ val type = args["metadataType"] as Int+ val metadata = MediaMetadata(type)+++ for (item in map) {+ val datesKey = listOf(+ "releaseDate",+ "broadcastDate",+ "creationDateTime",+ "creationDate"+ )+ if (item.key in datesKey) {+ val calendar = Calendar.getInstance()+ calendar.timeInMillis = item.value as Long+ when (item.key) {+ "releaseDate" -> metadata.putDate(MediaMetadata.KEY_RELEASE_DATE, calendar)+ "broadcastDate" -> metadata.putDate(+ MediaMetadata.KEY_BROADCAST_DATE, calendar+ )+ "creationDateTime" -> metadata.putDate(+ MediaMetadata.KEY_CREATION_DATE, calendar+ )+ "creationDate" -> metadata.putDate(+ MediaMetadata.KEY_CREATION_DATE, calendar+ )+ }+++ } else {+ when (item.value) {+ is String -> metadata.putString(item.key, item.value as String)+ is Int -> metadata.putInt(+ item.key, item.value as Int+ )+ is Double -> metadata.putDouble(item.key, item.value as Double)++ }+ }++ }+ val imagesData = map["images"] as List<Map<String, Any?>>?+ if (imagesData != null) {+ val images = imagesData.map {+ imageFromMap(it)+ }+ for (image in images) {+ metadata.addImage(image)+ }+ }+ return metadata+ }++ private fun imageFromMap(args: Map<String, Any?>): WebImage {+ val url = args["url"] as String+ val width = args["width"] as Int?+ val height = args["height"] as Int?+ return WebImage(Uri.parse(url), width ?: 250, height ?: 250)+ }+++ }+}++fun MediaMetadata.toMap(): Map<String, Any?> {+ val map = mutableMapOf<String, Any?>()+ for ( key in this.keySet() ){+ MediaMetadata.getTypeForKey(key)+ }+ return map+}\ No newline at end of filediff --git a/packages/flutter_chrome_cast/android/src/main/kotlin/com/felnanuke/google_cast/extensions/QueueItemsExtensions.kt b/packages/flutter_chrome_cast/android/src/main/kotlin/com/felnanuke/google_cast/extensions/QueueItemsExtensions.ktnew file mode 100644index 00000000..80e335cb--- /dev/null+++ b/packages/flutter_chrome_cast/android/src/main/kotlin/com/felnanuke/google_cast/extensions/QueueItemsExtensions.kt@@ -0,0 +1,51 @@+package com.felnanuke.google_cast.extensions++import com.google.android.gms.cast.MediaInfo+import com.google.android.gms.cast.MediaQueueItem+import org.json.JSONObject++object GoogleCastQueueItemBuilder {++ fun fromMap(map: Map<String, Any?>): MediaQueueItem? {+ val activeTrackIds = (map["activeTrackIds"] as ArrayList<Number>? ?: arrayListOf())+ val activeTrackIdsLongArray = activeTrackIds.map { it.toLong() }.toLongArray()+ val startTime = map["startTime"] as Int?+ val id = map["itemId"] as Int?+ val preloadTime = map["preloadTime"] as Int?+ val playbackDuration = map["playbackDuration"] as Int?+ val customD = map["customData"] as Map<String, Any?>?+ val autoPlay = map["autoPlay"] as Boolean? ?: true+ var mediaInfo: MediaInfo? =+ GoogleCastMediaInfo.fromMap(map["media"] as Map<String, Any?>) ?: return null+ var builder = MediaQueueItem.Builder(mediaInfo!!)+ if (activeTrackIds != null)+ builder.setActiveTrackIds(activeTrackIdsLongArray)+ if (id != null)+ builder.setItemId(id)+ if (preloadTime != null)+ builder.setPreloadTime(preloadTime.toDouble())+ if (startTime != null)+ builder.setPreloadTime(startTime.toDouble())+ if (playbackDuration != null)+ builder.setPlaybackDuration(playbackDuration.toDouble())+ if (customD != null) {+ val customData = JSONObject(customD)+ builder.setCustomData(customData)+ }+ builder.setAutoplay(autoPlay)+ return builder.build()++ }++ fun listFromMap(items: List<Map<String, Any?>>): List<MediaQueueItem> {+ val list = mutableListOf<MediaQueueItem>()+ for (item in items) {+ val queueItem = GoogleCastQueueItemBuilder.fromMap(item)+ if (queueItem != null)+ list.add(queueItem)+ }+ return list++ }++}\ No newline at end of filediff --git a/packages/flutter_chrome_cast/android/src/main/kotlin/com/felnanuke/google_cast/extensions/SeekOptionsExtensions.kt b/packages/flutter_chrome_cast/android/src/main/kotlin/com/felnanuke/google_cast/extensions/SeekOptionsExtensions.ktnew file mode 100644index 00000000..00a3029c--- /dev/null+++ b/packages/flutter_chrome_cast/android/src/main/kotlin/com/felnanuke/google_cast/extensions/SeekOptionsExtensions.kt@@ -0,0 +1,18 @@+package com.felnanuke.google_cast.extensions++import com.google.android.gms.cast.MediaSeekOptions++class GoogleCastSeekOptionsBuilder {+ companion object {+ fun fromMap(arguments: Map<String, Any?>): MediaSeekOptions {+ val position = arguments["position"] as Int+ val resumeState = arguments["resumeState"] as Int+ val seekToInfinity = arguments["seekToInfinity"] as Boolean+ val builder = MediaSeekOptions.Builder()+ builder.setPosition((position * 1000).toLong())+ builder.setResumeState(resumeState)+ builder.setIsSeekToInfinite(seekToInfinity)+ return builder.build()+ }+ }+}\ No newline at end of filediff --git a/packages/flutter_chrome_cast/android/src/main/kotlin/com/felnanuke/google_cast/extensions/SessionExtensions.kt b/packages/flutter_chrome_cast/android/src/main/kotlin/com/felnanuke/google_cast/extensions/SessionExtensions.ktnew file mode 100644index 00000000..2b10194f--- /dev/null+++ b/packages/flutter_chrome_cast/android/src/main/kotlin/com/felnanuke/google_cast/extensions/SessionExtensions.kt@@ -0,0 +1,27 @@+package com.felnanuke.google_cast.extensions++import com.google.android.gms.cast.CastDevice+import com.google.android.gms.cast.framework.CastSession+import com.google.gson.Gson++fun CastSession.toMap(): Map<String, Any?> {+ val map = mutableMapOf<String, Any?>()+ map["device"] = this.castDevice?.toMap()+ map["sessionID"] = this.sessionId+ map["connectionState"] = this.connectState()+ map["isMute"] = this.isMute+ map["statusMessage"] = this.applicationStatus+ map["volume"] = this.volume+ return map+}++fun CastSession.connectState(): Int {+ return when (true) {+ this.isDisconnected -> 0+ this.isConnecting -> 1+ this.isConnected -> 2+ this.isDisconnecting -> 3+ else -> 0+ }+}+diff --git a/packages/flutter_chrome_cast/android/src/main/res/values/strings.xml b/packages/flutter_chrome_cast/android/src/main/res/values/strings.xmlnew file mode 100644index 00000000..04e4478c--- /dev/null+++ b/packages/flutter_chrome_cast/android/src/main/res/values/strings.xml@@ -0,0 +1,4 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+ <string name="app_id">ED7DABE1</string>+</resources>\ No newline at end of filediff --git a/packages/flutter_chrome_cast/lib/_discovery_manager/_discovery_manager.dart b/packages/flutter_chrome_cast/lib/_discovery_manager/_discovery_manager.dartnew file mode 100644index 00000000..e67ccc5c--- /dev/null+++ b/packages/flutter_chrome_cast/lib/_discovery_manager/_discovery_manager.dart@@ -0,0 +1,4 @@+export 'android_discovery_manager.dart';+export 'discovery_manager.dart';+export 'discovery_manager_platform_interface.dart';+export 'ios_discovery_manager.dart';diff --git a/packages/flutter_chrome_cast/lib/_discovery_manager/android_discovery_manager.dart b/packages/flutter_chrome_cast/lib/_discovery_manager/android_discovery_manager.dartnew file mode 100644index 00000000..40e53ae7--- /dev/null+++ b/packages/flutter_chrome_cast/lib/_discovery_manager/android_discovery_manager.dart@@ -0,0 +1,101 @@+import 'dart:convert';+import 'package:flutter/foundation.dart';+import 'package:flutter/services.dart';+import 'package:flutter_chrome_cast/_discovery_manager/discovery_manager_platform_interface.dart';+import 'package:flutter_chrome_cast/entities/cast_device.dart';+import 'package:flutter_chrome_cast/models/android/cast_device.dart';+import 'package:rxdart/subjects.dart';++/// Android-specific implementation of the Google Cast discovery manager.+///+/// This class handles the discovery of Google Cast devices on Android platform+/// using method channels to communicate with the native Android implementation.+class GoogleCastDiscoveryManagerMethodChannelAndroid+ implements GoogleCastDiscoveryManagerPlatformInterface {+ /// Creates a new instance of the Android discovery manager.+ ///+ /// Sets up the method call handler to receive updates from the native side.+ GoogleCastDiscoveryManagerMethodChannelAndroid() {+ _channel.setMethodCallHandler(_onMethodCallHandler);+ }++ final _channel =+ const MethodChannel('com.felnanuke.google_cast.discovery_manager');++ final _devicesStreamController = BehaviorSubject<List<GoogleCastDevice>>()+ ..add([]);++ @override+ List<GoogleCastDevice> get devices => _devicesStreamController.value;++ @override+ Stream<List<GoogleCastDevice>> get devicesStream =>+ _devicesStreamController.stream;++ @override+ Future<bool> isDiscoveryActiveForDeviceCategory(String deviceCategory) {+ throw UnimplementedError('IOS Only');+ }++ @override+ Future<void> startDiscovery() async {+ _channel.invokeMethod('startDiscovery');+ return;+ }++ @override+ Future<void> stopDiscovery() async {+ _channel.invokeMethod('stopDiscovery');+ return;+ }++ Future _onMethodCallHandler(MethodCall call) async {+ switch (call.method) {+ case 'onDevicesChanged':+ return _onDevicesChanged(call.arguments);++ default:+ }+ }++ void _onDevicesChanged(dynamic arguments) {+ try {+ arguments as String;+ final list = jsonDecode(arguments);+ final listMap = List.from(list);+ final devices = GoogleCastAndroidDevices.fromMap(listMap);++ if (kDebugMode) {+ print('Received ${devices.length} devices from native');+ for (final device in devices) {+ print(+ 'Device: ${device.deviceID} - ${device.friendlyName} (${device.modelName})');+ }+ }++ // Enhanced deduplication: remove devices with same name and model+ final Map<String, GoogleCastDevice> uniqueDevices = {};+ for (final device in devices) {+ final key = '${device.friendlyName}_${device.modelName}';+ if (!uniqueDevices.containsKey(key)) {+ uniqueDevices[key] = device;+ if (kDebugMode) {+ print('Added unique device with key: $key');+ }+ } else {+ if (kDebugMode) {+ print('Skipped duplicate device with key: $key');+ }+ }+ }++ if (kDebugMode) {+ print(+ 'Final device count after deduplication: ${uniqueDevices.length}');+ }+ _devicesStreamController.add(uniqueDevices.values.toList());+ } catch (e) {+ rethrow;+ }+ }+}diff --git a/packages/flutter_chrome_cast/lib/_discovery_manager/discovery_manager.dart b/packages/flutter_chrome_cast/lib/_discovery_manager/discovery_manager.dartnew file mode 100644index 00000000..26e721a7--- /dev/null+++ b/packages/flutter_chrome_cast/lib/_discovery_manager/discovery_manager.dart@@ -0,0 +1,26 @@+import 'dart:io';+import 'package:flutter_chrome_cast/_discovery_manager/android_discovery_manager.dart';+import 'package:flutter_chrome_cast/_discovery_manager/discovery_manager_platform_interface.dart';+import 'package:flutter_chrome_cast/_discovery_manager/ios_discovery_manager.dart';++/// Main entry point for Google Cast device discovery functionality.+///+/// This class provides a platform-agnostic interface for discovering Google Cast+/// devices on the network. It automatically selects the appropriate platform-specific+/// implementation based on the current operating system.+class GoogleCastDiscoveryManager {+ static GoogleCastDiscoveryManagerPlatformInterface? _instance;++ /// Gets the singleton instance of the discovery manager.+ ///+ /// Returns the appropriate platform-specific implementation+ /// (Android or iOS) based on the current platform.+ static GoogleCastDiscoveryManagerPlatformInterface get instance {+ return _instance ??= Platform.isAndroid+ ? GoogleCastDiscoveryManagerMethodChannelAndroid()+ : GoogleCastDiscoveryManagerMethodChannelIOS();+ }++ /// Private constructor to enforce singleton pattern.+ GoogleCastDiscoveryManager._();+}diff --git a/packages/flutter_chrome_cast/lib/_discovery_manager/discovery_manager_platform_interface.dart b/packages/flutter_chrome_cast/lib/_discovery_manager/discovery_manager_platform_interface.dartnew file mode 100644index 00000000..ac257cb1--- /dev/null+++ b/packages/flutter_chrome_cast/lib/_discovery_manager/discovery_manager_platform_interface.dart@@ -0,0 +1,36 @@+import 'package:flutter_chrome_cast/entities/cast_device.dart';+import 'package:plugin_platform_interface/plugin_platform_interface.dart';++/// Platform interface for Google Cast device discovery functionality.+///+/// This abstract class defines the contract that platform-specific implementations+/// must follow. It manages the device discovery process and maintains a collection+/// of currently discovered Google Cast devices.+///+/// The framework automatically starts the discovery process when the application+/// moves to the foreground and suspends it when the application moves to the background.+/// It is generally not necessary for the application to manually start and stop discovery,+/// except as an optimization measure to reduce network traffic and CPU utilization.+///+/// Based on the Google Cast iOS SDK's GCKDiscoveryManager class.+abstract class GoogleCastDiscoveryManagerPlatformInterface+ implements PlatformInterface {+ /// Returns the list of currently discovered devices.+ List<GoogleCastDevice> get devices;++ /// Returns a stream of the currently discovered devices.+ Stream<List<GoogleCastDevice>> get devicesStream;++ /// Starts the discovery process.+ /// strongly recommended to call this method when the application is show cast devices dialog+ /// because the battery consumption is high when the discovery process is running.+ Future<void> startDiscovery();++ ///Stops the discovery process.+ /// strongly recommended to call this method when the application close the show cast devices dialog+ /// for reduce battery consumption.+ Future<void> stopDiscovery();++ ///Tests whether discovery is currently active for the given device category.+ Future<bool> isDiscoveryActiveForDeviceCategory(String deviceCategory);+}diff --git a/packages/flutter_chrome_cast/lib/_discovery_manager/ios_discovery_manager.dart b/packages/flutter_chrome_cast/lib/_discovery_manager/ios_discovery_manager.dartnew file mode 100644index 00000000..a290f9c8--- /dev/null+++ b/packages/flutter_chrome_cast/lib/_discovery_manager/ios_discovery_manager.dart@@ -0,0 +1,85 @@+import 'package:flutter/foundation.dart';+import 'package:flutter/services.dart';+import 'package:flutter_chrome_cast/entities/cast_device.dart';+import 'package:flutter_chrome_cast/models/ios/ios_cast_device.dart';+import 'package:rxdart/subjects.dart';+import 'discovery_manager_platform_interface.dart';++/// iOS-specific implementation of the Google Cast discovery manager.+///+/// This class handles the discovery of Google Cast devices on iOS platform+/// using method channels to communicate with the native iOS implementation.+class GoogleCastDiscoveryManagerMethodChannelIOS+ implements GoogleCastDiscoveryManagerPlatformInterface {+ /// Creates a new instance of the iOS discovery manager.+ ///+ /// Sets up the method call handler to receive updates from the native side.+ GoogleCastDiscoveryManagerMethodChannelIOS() {+ _channel.setMethodCallHandler(_handleMethodCall);+ }++ final _channel = const MethodChannel('google_cast.discovery_manager');++ final _devicesStreamController = BehaviorSubject<List<GoogleCastDevice>>()+ ..add([]);++ @override+ List<GoogleCastDevice> get devices => _devicesStreamController.value;++ @override+ Stream<List<GoogleCastDevice>> get devicesStream =>+ _devicesStreamController.stream;++ @override+ Future<bool> isDiscoveryActiveForDeviceCategory(String deviceCategory) async {+ return await _channel.invokeMethod('isDiscoveryActiveForDeviceCategory', {+ 'deviceCategory': deviceCategory,+ });+ }++ @override+ Future<void> startDiscovery() {+ return _channel.invokeMethod('startDiscovery');+ }++ @override+ Future<void> stopDiscovery() {+ return _channel.invokeMethod('stopDiscovery');+ }++ /// Handles device changes for testing purposes.+ /// This method is visible for testing and allows simulating device changes+ /// in unit tests by calling the internal [_onDevicesChanged] method.+ @visibleForTesting+ void onDevicesChanged(List arguments) {+ _onDevicesChanged(arguments);+ }++ /// Handles method calls from the platform channel for testing purposes.+ /// This method is visible for testing and allows simulating platform+ /// method calls in unit tests.+ @visibleForTesting+ Future<void> handleMethodCall(MethodCall call) {+ return _handleMethodCall(call);+ }++ void _onDevicesChanged(List arguments) {+ final devices = List.from(arguments)+ .map((device) => GoogleCastIosDevice.fromMap(Map.from(device)))+ .toList();++ _devicesStreamController.add(devices);+ }++ Future _handleMethodCall(MethodCall call) async {+ switch (call.method) {+ case 'onDevicesChanged':+ _onDevicesChanged(call.arguments);+ break;+ default:+ if (kDebugMode) {+ print('No Handler for method ${call.method}');+ }+ }+ }+}diff --git a/packages/flutter_chrome_cast/lib/_google_cast_context/_google_cast_context.dart b/packages/flutter_chrome_cast/lib/_google_cast_context/_google_cast_context.dartnew file mode 100644index 00000000..c1b46875--- /dev/null+++ b/packages/flutter_chrome_cast/lib/_google_cast_context/_google_cast_context.dart@@ -0,0 +1,4 @@+export 'android_google_cast_context_method_channel.dart';+export 'google_cast_context.dart';+export 'google_cast_context_platform_interface.dart';+export 'ios_google_cast_context_method_channel.dart';diff --git a/packages/flutter_chrome_cast/lib/_google_cast_context/android_google_cast_context_method_channel.dart b/packages/flutter_chrome_cast/lib/_google_cast_context/android_google_cast_context_method_channel.dartnew file mode 100644index 00000000..f99b456a--- /dev/null+++ b/packages/flutter_chrome_cast/lib/_google_cast_context/android_google_cast_context_method_channel.dart@@ -0,0 +1,25 @@+import 'package:flutter/services.dart';+import 'package:flutter_chrome_cast/entities/cast_options.dart';++import 'google_cast_context_platform_interface.dart';++/// Android-specific implementation of Google Cast context functionality.+///+/// This class provides the Android platform implementation for initializing+/// and managing the Google Cast context using method channels.+class GoogleCastContextAndroidMethodChannel+ implements GoogleCastContextPlatformInterface {+ final _channel = const MethodChannel('com.felnanuke.google_cast.context');++ @override+ Future<bool> setSharedInstanceWithOptions(+ GoogleCastOptions castOptions) async {+ try {+ final result =+ await _channel.invokeMethod('setSharedInstance', castOptions.toMap());+ return result == true;+ } catch (e) {+ rethrow;+ }+ }+}diff --git a/packages/flutter_chrome_cast/lib/_google_cast_context/google_cast_context.dart b/packages/flutter_chrome_cast/lib/_google_cast_context/google_cast_context.dartnew file mode 100644index 00000000..096ca774--- /dev/null+++ b/packages/flutter_chrome_cast/lib/_google_cast_context/google_cast_context.dart@@ -0,0 +1,26 @@+import 'dart:io';++import 'package:flutter_chrome_cast/_google_cast_context/android_google_cast_context_method_channel.dart';+import 'package:flutter_chrome_cast/_google_cast_context/google_cast_context_platform_interface.dart';++import 'ios_google_cast_context_method_channel.dart';++/// Main entry point for Google Cast context functionality.+///+/// This class provides a platform-agnostic interface for initializing and+/// managing the Google Cast context. It automatically selects the appropriate+/// platform-specific implementation based on the current operating system.+class GoogleCastContext {+ static final GoogleCastContextPlatformInterface _instance = Platform.isAndroid+ ? GoogleCastContextAndroidMethodChannel()+ : FlutterIOSGoogleCastContextMethodChannel();++ /// Gets the singleton instance of the Google Cast context.+ ///+ /// Returns the appropriate platform-specific implementation+ /// (Android or iOS) based on the current platform.+ static GoogleCastContextPlatformInterface instance = _instance;++ /// Private constructor to enforce singleton pattern.+ GoogleCastContext._();+}diff --git a/packages/flutter_chrome_cast/lib/_google_cast_context/google_cast_context_platform_interface.dart b/packages/flutter_chrome_cast/lib/_google_cast_context/google_cast_context_platform_interface.dartnew file mode 100644index 00000000..bcaa2f6b--- /dev/null+++ b/packages/flutter_chrome_cast/lib/_google_cast_context/google_cast_context_platform_interface.dart@@ -0,0 +1,18 @@+import 'package:flutter_chrome_cast/entities/cast_options.dart';+import 'package:plugin_platform_interface/plugin_platform_interface.dart';++/// Platform interface for Google Cast context functionality.+///+/// This abstract class defines the contract that platform-specific implementations+/// must follow for initializing and managing the Google Cast context.+abstract class GoogleCastContextPlatformInterface extends PlatformInterface {+ /// Creates a new instance of the platform interface.+ GoogleCastContextPlatformInterface() : super(token: Object());++//MARK: - CONTEXT+ /// Initializes the shared Google Cast context with the provided options.+ ///+ /// [castOptions] contains the configuration options for the Cast context.+ /// Returns true if the initialization was successful, false otherwise.+ Future<bool> setSharedInstanceWithOptions(GoogleCastOptions castOptions);+}diff --git a/packages/flutter_chrome_cast/lib/_google_cast_context/ios_google_cast_context_method_channel.dart b/packages/flutter_chrome_cast/lib/_google_cast_context/ios_google_cast_context_method_channel.dartnew file mode 100644index 00000000..ce49d161--- /dev/null+++ b/packages/flutter_chrome_cast/lib/_google_cast_context/ios_google_cast_context_method_channel.dart@@ -0,0 +1,26 @@+import 'package:flutter/services.dart';+import 'package:flutter_chrome_cast/entities/cast_options.dart';+import 'google_cast_context_platform_interface.dart';++/// iOS-specific implementation of Google Cast context functionality.+///+/// This class provides the iOS platform implementation for initializing+/// and managing the Google Cast context using method channels.+class FlutterIOSGoogleCastContextMethodChannel+ extends GoogleCastContextPlatformInterface {+ static const _methodChannel = MethodChannel('google_cast.context');++ @override+ Future<bool> setSharedInstanceWithOptions(+ GoogleCastOptions castOptions) async {+ try {+ final result = await _methodChannel.invokeMethod(+ 'setSharedInstanceWithOptions',+ castOptions.toMap(),+ );+ return result == true;+ } catch (e) {+ rethrow;+ }+ }+}diff --git a/packages/flutter_chrome_cast/lib/_remote_media_client/_remote_media_client.dart b/packages/flutter_chrome_cast/lib/_remote_media_client/_remote_media_client.dartnew file mode 100644index 00000000..5c930789--- /dev/null+++ b/packages/flutter_chrome_cast/lib/_remote_media_client/_remote_media_client.dart@@ -0,0 +1,4 @@+export 'android_remote_media_client_method_channel.dart';+export 'ios_remote_media_client_method_channel.dart';+export 'remote_media_client.dart';+export 'remote_media_client_platform.dart';diff --git a/packages/flutter_chrome_cast/lib/_remote_media_client/android_remote_media_client_method_channel.dart b/packages/flutter_chrome_cast/lib/_remote_media_client/android_remote_media_client_method_channel.dartnew file mode 100644index 00000000..8308bbdf--- /dev/null+++ b/packages/flutter_chrome_cast/lib/_remote_media_client/android_remote_media_client_method_channel.dart@@ -0,0 +1,256 @@+import 'dart:convert';+import 'package:flutter/services.dart';+import 'package:flutter_chrome_cast/_remote_media_client/remote_media_client_platform.dart';+import 'package:flutter_chrome_cast/entities/cast_media_status.dart';+import 'package:flutter_chrome_cast/entities/load_options.dart';+import 'package:flutter_chrome_cast/entities/media_information.dart';+import 'package:flutter_chrome_cast/entities/media_seek_option.dart';+import 'package:flutter_chrome_cast/entities/queue_item.dart';+import 'package:flutter_chrome_cast/models/android/android_media_status.dart';+import 'package:flutter_chrome_cast/models/android/android_queue_item.dart';+import 'package:rxdart/subjects.dart';++/// Android-specific implementation of Google Cast remote media client functionality.+class GoogleCastRemoteMediaClientAndroidMethodChannel+ implements GoogleCastRemoteMediaClientPlatformInterface {+ /// Creates a new Android remote media client method channel.+ GoogleCastRemoteMediaClientAndroidMethodChannel() {+ _channel.setMethodCallHandler(_onMethodCallHandler);+ }++ final _channel = const MethodChannel(+ 'com.felnanuke.google_cast.remote_media_client',+ );++ // Media Status+ final _mediaStatusStreamController = BehaviorSubject<GoggleCastMediaStatus?>()+ ..add(null);++ @override+ GoggleCastMediaStatus? get mediaStatus => _mediaStatusStreamController.value;++ @override+ Stream<GoggleCastMediaStatus?> get mediaStatusStream =>+ _mediaStatusStreamController.stream;++ // QueueItems+ final _queueItemsStreamController =+ BehaviorSubject<List<GoogleCastQueueItem>>()..add([]);++ @override+ List<GoogleCastQueueItem> get queueItems => _queueItemsStreamController.value;++ @override+ Stream<List<GoogleCastQueueItem>> get queueItemsStream =>+ _queueItemsStreamController.stream;++ // PlayerPosition+ final _playerPositionStreamController = BehaviorSubject<Duration>()+ ..add(Duration.zero);+ @override+ Duration get playerPosition => _playerPositionStreamController.value;++ @override+ Stream<Duration> get playerPositionStream =>+ _playerPositionStreamController.stream;++ // Queue has Next or revious item+ @override+ bool get queueHasNextItem {+ final currentQueueItemId = mediaStatus?.currentItemId;+ final currentItemIndex = queueItems+ .map((e) => e.itemId)+ .toList()+ .lastIndexOf(currentQueueItemId);+ return (queueItems.length - 1) > currentItemIndex;+ }++ @override+ bool get queueHasPreviousItem => true;++ @override+ Future<void> loadMedia(+ GoogleCastMediaInformation mediaInfo, {+ bool autoPlay = true,+ Duration playPosition = Duration.zero,+ double playbackRate = 1.0,+ List<int>? activeTrackIds,+ String? credentials,+ String? credentialsType,+ }) async {+ await _channel.invokeMethod('loadMedia', {+ 'mediaInfo': mediaInfo.toMap(),+ 'autoPlay': autoPlay,+ 'playPosition': playPosition.inSeconds,+ 'playbackRate': playbackRate,+ 'activeTrackIds': activeTrackIds,+ 'credentials': credentials,+ 'credentialsType': credentialsType,+ });+ }++ @override+ Future<void> pause() async {+ await _channel.invokeMethod('pause');+ }++ @override+ Future<void> play() async {+ await _channel.invokeMethod('play');+ }++ @override+ Future<void> queueLoadItems(+ List<GoogleCastQueueItem> queueItems, {+ GoogleCastQueueLoadOptions? options,+ }) async {+ await _channel.invokeMethod('queueLoadItems', {+ 'queueItems': queueItems.map((item) => item.toMap()).toList(),+ 'options': options?.toMap(android: true),+ });+ }++ @override+ Future<void> queueNextItem() async {+ await _channel.invokeMethod('queueNextItem');+ }++ @override+ Future<void> queuePrevItem() async {+ await _channel.invokeMethod('queuePrevItem');+ }++ @override+ Future<void> seek(GoogleCastMediaSeekOption option) async {+ await _channel.invokeMethod('seek', option.toMap());+ }++ @override+ Future<void> setActiveTrackIDs(List<int> activeTrackIDs) async {+ await _channel.invokeMethod(+ 'setActiveTrackIds',+ activeTrackIDs,+ );+ }++ @override+ Future<void> setPlaybackRate(double rate) async {+ await _channel.invokeMethod('setPlaybackRate', rate);+ }++ @override+ Future<void> setTextTrackStyle(+ TextTrackStyle textTrackStyle,+ ) async {+ await _channel.invokeMethod(+ 'setTextTrackStyle',+ textTrackStyle.toMap(),+ );+ }++ @override+ Future<void> stop() async {+ await _channel.invokeMethod('stop');+ }++ @override+ Future<void> queueJumpToItemWithId(int itemId) async {+ await _channel.invokeMethod('queueJumpToItemWithId', itemId);+ }++ @override+ Future<void> queueRemoveItemsWithIds(List<int> itemIds) async {+ await _channel.invokeMethod(+ 'queueRemoveItemsWithIds',+ itemIds,+ );+ }++ @override+ Future<void> queueInsertItemAndPlay(+ GoogleCastQueueItem item, {+ required int beforeItemWithId,+ }) async {+ await _channel.invokeMethod('queueInsertItemAndPlay', {+ 'item': item.toMap(),+ 'beforeItemWithId': beforeItemWithId,+ });+ }++ @override+ Future<void> queueInsertItems(+ List<GoogleCastQueueItem> items, {+ int? beforeItemWithId,+ }) async {+ await _channel.invokeMethod('queueInsertItems', {+ 'items': items.map((item) => item.toMap()).toList(),+ 'beforeItemWithId': beforeItemWithId,+ });+ }++ Future _onMethodCallHandler(MethodCall call) async {+ switch (call.method) {+ case 'onMediaStatusChanged':+ return _onMediaStatusChanged(call.arguments);+ case 'onQueueStatusChanged':+ return _onQueueStatusChanged(call.arguments);+ case 'onPlayerPositionChanged':+ return _onPlayerPositionChanged(call.arguments);+ default:+ }+ }++ Future<void> _onMediaStatusChanged(dynamic arguments) async {+ if (arguments == null) {+ _mediaStatusStreamController.add(null);+ return;+ }+ final mediaStatus = GoogleCastAndroidMediaStatus.fromMap(+ Map<String, dynamic>.from(jsonDecode(arguments)),+ );++ _mediaStatusStreamController.add(mediaStatus);+ }++ Future<void> _onQueueStatusChanged(dynamic arguments) async {+ if (arguments == null) {+ _queueItemsStreamController.add([]);+ return;+ }++ final map = List.from(arguments);++ final queueItems = map+ .map(+ (e) => GoogleCastAndroidQueueItem.fromMap(+ Map<String, dynamic>.from(+ Map<String, dynamic>.from(jsonDecode(e)),+ ),+ ),+ )+ .toList();+ _queueItemsStreamController.add(queueItems);+ }++ Future<void> _onPlayerPositionChanged(dynamic arguments) async {+ if (arguments == null) {+ _playerPositionStreamController.add(Duration.zero);+ return;+ }+ arguments = Map<String, dynamic>.from(arguments);++ final playerPosition = Duration(milliseconds: arguments["progress"] ?? 0);+ _playerPositionStreamController.add(playerPosition);+ }++ @override+ Future<void> queueReorderItems({+ required List<int> itemsIds,+ required int? beforeItemWithId,+ }) {+ return _channel.invokeMethod('queueReorderItems', {+ 'itemsIds': itemsIds,+ 'beforeItemWithId': beforeItemWithId,+ });+ }+}diff --git a/packages/flutter_chrome_cast/lib/_remote_media_client/ios_remote_media_client_method_channel.dart b/packages/flutter_chrome_cast/lib/_remote_media_client/ios_remote_media_client_method_channel.dartnew file mode 100644index 00000000..274b21fc--- /dev/null+++ b/packages/flutter_chrome_cast/lib/_remote_media_client/ios_remote_media_client_method_channel.dart@@ -0,0 +1,256 @@+import 'dart:async';++import 'package:flutter/foundation.dart';+import 'package:flutter/services.dart';+import 'package:flutter_chrome_cast/_remote_media_client/remote_media_client_platform.dart';+import 'package:flutter_chrome_cast/entities/cast_media_status.dart';+import 'package:flutter_chrome_cast/entities/load_options.dart';+import 'package:flutter_chrome_cast/entities/media_seek_option.dart';+import 'package:flutter_chrome_cast/entities/queue_item.dart';+import 'package:flutter_chrome_cast/entities/media_information.dart';+import 'package:flutter_chrome_cast/models/ios/ios_cast_queue_item.dart';+import 'package:flutter_chrome_cast/models/ios/ios_media_status.dart';+import 'package:rxdart/rxdart.dart';++/// iOS-specific implementation of Google Cast remote media client functionality.+class GoogleCastRemoteMediaClientIOSMethodChannel+ implements GoogleCastRemoteMediaClientPlatformInterface {+ /// Creates a new iOS remote media client method channel.+ GoogleCastRemoteMediaClientIOSMethodChannel() {+ _channel.setMethodCallHandler(_methodCallHandler);+ }++ final _channel = const MethodChannel('google_cast.remote_media_client');+ bool _queueHasNextItem = false;++ final _mediaStatusStreamController = BehaviorSubject<GoggleCastMediaStatus?>()+ ..add(null);++ final _playerPositionStreamController = BehaviorSubject<Duration>()+ ..add(Duration.zero);++ final _queueItemsStreamController =+ BehaviorSubject<List<GoogleCastQueueItem>>()..add([]);++ @override+ GoggleCastMediaStatus? get mediaStatus => _mediaStatusStreamController.value;++ @override+ Stream<GoggleCastMediaStatus?> get mediaStatusStream =>+ _mediaStatusStreamController.stream;++ @override+ Duration get playerPosition => _playerPositionStreamController.value;++ @override+ Stream<Duration> get playerPositionStream =>+ _playerPositionStreamController.stream;++ @override+ List<GoogleCastQueueItem> get queueItems => _queueItemsStreamController.value;++ @override+ Stream<List<GoogleCastQueueItem>> get queueItemsStream =>+ _queueItemsStreamController.stream;++ @override+ bool get queueHasNextItem => _queueHasNextItem;++ @override+ bool get queueHasPreviousItem {+ final index = queueItems+ .map((e) => e.itemId)+ .toList()+ .lastIndexOf(mediaStatus?.currentItemId);+ return index > 0;+ }++ @override+ Future<void> loadMedia(+ GoogleCastMediaInformation mediaInfo, {+ bool autoPlay = true,+ Duration playPosition = Duration.zero,+ double playbackRate = 1.0,+ List<int>? activeTrackIds,+ String? credentials,+ String? credentialsType,+ }) async {+ _channel.invokeMethod(+ 'loadMedia',+ mediaInfo.toMap()+ ..addAll(+ {+ 'autoPlay': autoPlay,+ 'playPosition': playPosition.inSeconds,+ 'playbackRate': playbackRate,+ 'activeTrackIds': activeTrackIds,+ 'credentials': credentials,+ 'credentialsType': credentialsType,+ }..removeWhere((key, value) => value == null),+ ));+ }++ @override+ Future<void> pause() async {+ await _channel.invokeMethod('pause');+ }++ @override+ Future<void> play() async {+ await _channel.invokeMethod('play');+ }++ @override+ Future<void> setActiveTrackIDs(List<int> activeTrackIDs) async {+ await _channel.invokeMethod('setActiveTrackIDs', activeTrackIDs.toList());+ }++ @override+ Future<void> setPlaybackRate(double rate) async {+ await _channel.invokeMethod('setPlaybackRate', rate);+ }++ @override+ Future<void> setTextTrackStyle(TextTrackStyle textTrackStyle) async {+ await _channel.invokeMethod('setTextTrackStyle', textTrackStyle.toMap());+ }++ @override+ Future<void> stop() async {+ await _channel.invokeMethod('stop');+ }++ @override+ Future<void> seek(GoogleCastMediaSeekOption option) async {+ await _channel.invokeMethod('seek', option.toMap());+ }++ @override+ Future<void> queueNextItem() async {+ await _channel.invokeMethod('queueNextItem');+ }++ @override+ Future<void> queuePrevItem() async {+ _channel.invokeMethod('queuePrevItem');+ }++// MARK: - MethodCallHandler+ Future _methodCallHandler(MethodCall call) async {+ switch (call.method) {+ case "onUpdateMediaStatus":+ return await _onUpdateMediaStatus(call.arguments);+ case "onUpdatePlayerPosition":+ return await _onUpdatePlayerPosition(call.arguments);+ case "updateQueueItems":+ return await _updateQueueItems(call.arguments);+ default:+ }+ }++ Future _onUpdatePlayerPosition(int seconds) async {+ final duration = Duration(seconds: seconds);+ _playerPositionStreamController.add(duration);+ }++ /// Recursively converts a `Map<Object?, Object?>` to `Map<String, dynamic>`.+ ///+ /// This is necessary because the platform channel may return nested maps+ /// as `Map<Object?, Object?>`, which needs to be converted for proper parsing.+ dynamic _convertToStringDynamicMap(dynamic value) {+ if (value is Map) {+ return value.map<String, dynamic>(+ (key, val) => MapEntry(key.toString(), _convertToStringDynamicMap(val)),+ );+ } else if (value is List) {+ return value.map((e) => _convertToStringDynamicMap(e)).toList();+ }+ return value;+ }++ FutureOr<void> _onUpdateMediaStatus(dynamic arguments) {+ if (arguments != null) {+ try {+ arguments =+ _convertToStringDynamicMap(arguments) as Map<String, dynamic>;+ debugPrint(+ '[Flutter] _onUpdateMediaStatus received: playerState=${arguments['playerState']}');+ final mediaStatus = GoogleCastIOSMediaStatus.fromMap(arguments);+ debugPrint(+ '[Flutter] _onUpdateMediaStatus parsed: playerState=${mediaStatus.playerState}');+ _queueHasNextItem = arguments["queueHasNextItem"];+ _mediaStatusStreamController.add(mediaStatus);+ } catch (e) {+ debugPrint('[Flutter] _onUpdateMediaStatus error: $e');+ rethrow;+ }+ }+ }++ @override+ Future<void> queueLoadItems(+ List<GoogleCastQueueItem> queueItems, {+ GoogleCastQueueLoadOptions? options,+ }) async {+ _channel.invokeMethod(+ 'queueLoadItems',+ {+ 'items': queueItems.map((item) => item.toMap()).toList(),+ if (options != null) 'options': options.toMap(),+ },+ );+ }++ @override+ Future<void> queueInsertItems(List<GoogleCastQueueItem> items,+ {int? beforeItemWithId}) async {+ _channel.invokeMethod('queueInsertItems', {+ 'items': items.map((item) => item.toMap()).toList(),+ 'beforeItemWithId': beforeItemWithId,+ });+ }++ @override+ Future<void> queueInsertItemAndPlay(+ GoogleCastQueueItem item, {+ required int beforeItemWithId,+ }) async {+ assert(beforeItemWithId >= 0, 'beforeItemWithId must be greater than 0');+ _channel.invokeMethod('queueInsertItemAndPlay', {+ 'item': item.toMap(),+ 'beforeItemWithId': beforeItemWithId,+ });+ return;+ }++ @override+ Future<void> queueJumpToItemWithId(int itemId) async {+ _channel.invokeMethod('queueJumpToItemWithId', itemId);+ }++ @override+ Future<void> queueRemoveItemsWithIds(List<int> itemIds) async {+ _channel.invokeMethod('queueRemoveItemsWithIds', itemIds);+ }++ FutureOr<void> _updateQueueItems(dynamic arguments) async {+ final items = List.from(arguments ?? []);+ final queueItems = items+ .map((item) =>+ GoogleCastQueueItemIOS.fromMap(Map<String, dynamic>.from(item)))+ .toList();+ _queueItemsStreamController.add(queueItems);+ }++ @override+ Future<void> queueReorderItems(+ {required List<int> itemsIds, required int? beforeItemWithId}) async {+ _channel.invokeMethod(+ 'queueReorderItems',+ {+ 'itemsIds': itemsIds,+ 'beforeItemWithId': beforeItemWithId,+ },+ );+ }+}diff --git a/packages/flutter_chrome_cast/lib/_remote_media_client/remote_media_client.dart b/packages/flutter_chrome_cast/lib/_remote_media_client/remote_media_client.dartnew file mode 100644index 00000000..39b20016--- /dev/null+++ b/packages/flutter_chrome_cast/lib/_remote_media_client/remote_media_client.dart@@ -0,0 +1,27 @@+import 'dart:io';++import 'package:flutter_chrome_cast/_remote_media_client/remote_media_client_platform.dart';++import 'android_remote_media_client_method_channel.dart';+import 'ios_remote_media_client_method_channel.dart';++/// Main entry point for Google Cast remote media client functionality.+///+/// This class provides a platform-agnostic interface for controlling media+/// playback on Google Cast devices. It automatically selects the appropriate+/// platform-specific implementation based on the current operating system.+class GoogleCastRemoteMediaClient {+ /// Private constructor to enforce singleton pattern.+ GoogleCastRemoteMediaClient._();++ static final GoogleCastRemoteMediaClientPlatformInterface _instance =+ Platform.isAndroid+ ? GoogleCastRemoteMediaClientAndroidMethodChannel()+ : GoogleCastRemoteMediaClientIOSMethodChannel();++ /// Gets the singleton instance of the remote media client.+ ///+ /// Returns the appropriate platform-specific implementation+ /// (Android or iOS) based on the current platform.+ static GoogleCastRemoteMediaClientPlatformInterface get instance => _instance;+}diff --git a/packages/flutter_chrome_cast/lib/_remote_media_client/remote_media_client_platform.dart b/packages/flutter_chrome_cast/lib/_remote_media_client/remote_media_client_platform.dartnew file mode 100644index 00000000..064e3943--- /dev/null+++ b/packages/flutter_chrome_cast/lib/_remote_media_client/remote_media_client_platform.dart@@ -0,0 +1,108 @@+import 'package:flutter_chrome_cast/entities/cast_media_status.dart';+import 'package:flutter_chrome_cast/entities/load_options.dart';+import 'package:flutter_chrome_cast/entities/media_information.dart';+import 'package:flutter_chrome_cast/entities/media_seek_option.dart';+import 'package:flutter_chrome_cast/entities/queue_item.dart';+import 'package:plugin_platform_interface/plugin_platform_interface.dart';++/// Platform interface for Google Cast remote media client functionality.+abstract class GoogleCastRemoteMediaClientPlatformInterface+ implements PlatformInterface {+ /// Current media status of the remote media client.+ GoggleCastMediaStatus? get mediaStatus;++ /// Stream of media status changes.+ Stream<GoggleCastMediaStatus?> get mediaStatusStream;++ /// Current player position.+ Duration get playerPosition;++ /// Stream of player position changes.+ Stream<Duration> get playerPositionStream;++ /// Stream of queue items changes.+ Stream<List<GoogleCastQueueItem>> get queueItemsStream;++ /// Current list of queue items.+ List<GoogleCastQueueItem> get queueItems;++ /// Whether the queue has a next item.+ bool get queueHasNextItem;++ /// Whether the queue has a previous item.+ bool get queueHasPreviousItem;++ /// Loads media on the remote media client.+ Future<void> loadMedia(+ GoogleCastMediaInformation mediaInfo, {+ bool autoPlay = true,+ Duration playPosition = Duration.zero,+ double playbackRate = 1.0,+ List<int>? activeTrackIds,+ String? credentials,+ String? credentialsType,+ });++ /// Loads queue items on the remote media client.+ Future<void> queueLoadItems(+ List<GoogleCastQueueItem> queueItems, {+ GoogleCastQueueLoadOptions? options,+ });++ /// Sets the playback rate.+ Future<void> setPlaybackRate(double rate);++ /// Sets the active track IDs.+ Future<void> setActiveTrackIDs(List<int> activeTrackIDs);++ /// Sets the text track style.+ Future<void> setTextTrackStyle(TextTrackStyle textTrackStyle);++ /// Pauses media playback.+ Future<void> pause();++ /// Starts or resumes media playback.+ Future<void> play();++ /// Stops media playback.+ Future<void> stop();++ /// Plays the next item in the queue.+ Future<void> queueNextItem();++ /// Plays the previous item in the queue.+ Future<void> queuePrevItem();++ /// Seeks to a specific position in the media.+ Future<void> seek(GoogleCastMediaSeekOption option);++ /// Inserts items into the queue.+ Future<void> queueInsertItems(+ List<GoogleCastQueueItem> items, {+ int? beforeItemWithId,+ });++ /// Inserts an item into the queue and plays it.+ Future<void> queueInsertItemAndPlay(+ GoogleCastQueueItem item, {+ required int beforeItemWithId,+ });++ /// Removes items from the queue by their IDs.+ Future<void> queueRemoveItemsWithIds(+ List<int> itemIds,+ );++ /// Jumps to a specific item in the queue by its ID.+ Future<void> queueJumpToItemWithId(int itemId);++ /// Reorders items in the queue.+ ///+ /// [itemsIds] - List of IDs of the items to reorder.+ /// [beforeItemWithId] - The ID of the item before which the reordered items will be placed.+ /// If null, the items will be placed at the end of the queue.+ Future<void> queueReorderItems({+ required List<int> itemsIds,+ required int? beforeItemWithId,+ });+}diff --git a/packages/flutter_chrome_cast/lib/_session_manager/_session_manager.dart b/packages/flutter_chrome_cast/lib/_session_manager/_session_manager.dartnew file mode 100644index 00000000..1e71776f--- /dev/null+++ b/packages/flutter_chrome_cast/lib/_session_manager/_session_manager.dart@@ -0,0 +1,4 @@+export 'android_cast_session_manager.dart';+export 'cast_session_manager.dart';+export 'cast_session_manager_platform.dart';+export 'ios_cast_session_manager.dart';diff --git a/packages/flutter_chrome_cast/lib/_session_manager/android_cast_session_manager.dart b/packages/flutter_chrome_cast/lib/_session_manager/android_cast_session_manager.dartnew file mode 100644index 00000000..f58bdbd0--- /dev/null+++ b/packages/flutter_chrome_cast/lib/_session_manager/android_cast_session_manager.dart@@ -0,0 +1,106 @@+import 'package:flutter/services.dart';+import 'package:flutter_chrome_cast/enums/connection_state.dart';+import 'package:flutter_chrome_cast/entities/cast_session.dart';+import 'package:flutter_chrome_cast/entities/cast_device.dart';+import 'package:flutter_chrome_cast/models/android/cast_device.dart';+import 'package:flutter_chrome_cast/models/android/cast_session.dart';+import 'package:rxdart/subjects.dart';++import 'cast_session_manager_platform.dart';++/// Android-specific implementation of Google Cast session manager functionality.+class GoogleCastSessionManagerAndroidMethodChannel+ implements GoogleCastSessionManagerPlatformInterface {+ /// Creates a new Android session manager method channel.+ GoogleCastSessionManagerAndroidMethodChannel() {+ _channel.setMethodCallHandler(_onMethodCallHandler);+ }+ final _channel =+ const MethodChannel('com.felnanuke.google_cast.session_manager');++ final _currentSessionStreamController = BehaviorSubject<GoogleCastSession?>()+ ..add(null);++ @override+ GoogleCastConnectState get connectionState =>+ _currentSessionStreamController.value?.connectionState ??+ GoogleCastConnectState.disconnected;++ @override+ GoogleCastSession? get currentSession =>+ _currentSessionStreamController.value;++ @override+ Stream<GoogleCastSession?> get currentSessionStream =>+ _currentSessionStreamController.stream;++ @override+ Future<bool> endSession() async {+ return await _channel.invokeMethod('endSession');+ }++ @override+ Future<bool> endSessionAndStopCasting() async {+ return await _channel.invokeMethod('endSessionAndStopCasting');+ }++ @override+ bool get hasConnectedSession =>+ _currentSessionStreamController.value?.connectionState ==+ GoogleCastConnectState.connected;++ @override+ Future<void> setDefaultSessionOptions() {+ throw UnimplementedError('Only works in IOS');+ }++ @override+ Future<bool> startSessionWithDevice(GoogleCastDevice device) async {+ device as GoogleCastAndroidDevice;+ return (await _channel.invokeMethod(+ 'startSessionWithDeviceId',+ device.deviceID,+ )) ==+ true;+ }++ @override+ Future<bool> startSessionWithOpenURLOptions() {+ // TODO: implement startSessionWithOpenURLOptions+ throw UnimplementedError();+ }++ @override+ Future<bool> suspendSessionWithReason() {+ // TODO: implement suspendSessionWithReason+ throw UnimplementedError();+ }++ Future _onMethodCallHandler(MethodCall call) async {+ switch (call.method) {+ case "onSessionChanged":+ _onSessionChanged(call.arguments);+ return;+ default:+ }+ }++ void _onSessionChanged(dynamic arguments) {+ try {+ if (arguments == null) {+ _currentSessionStreamController.add(null);+ return;+ }+ final map = Map<String, dynamic>.from(arguments);+ final session = GoogleCastSessionAndroid.fromMap(map);+ _currentSessionStreamController.add(session);+ } catch (e) {+ rethrow;+ }+ }++ @override+ void setDeviceVolume(double value) {+ _channel.invokeMethod('setStreamVolume', value);+ }+}diff --git a/packages/flutter_chrome_cast/lib/_session_manager/cast_session_manager.dart b/packages/flutter_chrome_cast/lib/_session_manager/cast_session_manager.dartnew file mode 100644index 00000000..1a56e6b7--- /dev/null+++ b/packages/flutter_chrome_cast/lib/_session_manager/cast_session_manager.dart@@ -0,0 +1,26 @@+import 'dart:io';++import 'package:flutter_chrome_cast/_session_manager/android_cast_session_manager.dart';+import 'package:flutter_chrome_cast/_session_manager/ios_cast_session_manager.dart';++import 'cast_session_manager_platform.dart';++/// Main entry point for Google Cast session management functionality.+///+/// This class provides a platform-agnostic interface for managing Cast sessions,+/// including starting, ending, and monitoring session state. It automatically+/// selects the appropriate platform-specific implementation based on the current OS.+class GoogleCastSessionManager {+ static final GoogleCastSessionManagerPlatformInterface _instance =+ Platform.isAndroid+ ? GoogleCastSessionManagerAndroidMethodChannel()+ : GoogleCastSessionManagerIOSMethodChannel();++ /// Gets the singleton instance of the session manager.+ ///+ /// Returns the appropriate platform-specific implementation+ /// (Android or iOS) based on the current platform.+ static GoogleCastSessionManagerPlatformInterface get instance => _instance;++ GoogleCastSessionManager._();+}diff --git a/packages/flutter_chrome_cast/lib/_session_manager/cast_session_manager_platform.dart b/packages/flutter_chrome_cast/lib/_session_manager/cast_session_manager_platform.dartnew file mode 100644index 00000000..fa26af48--- /dev/null+++ b/packages/flutter_chrome_cast/lib/_session_manager/cast_session_manager_platform.dart@@ -0,0 +1,116 @@+import 'package:flutter_chrome_cast/entities/cast_session.dart';+import 'package:flutter_chrome_cast/entities/cast_device.dart';+import 'package:flutter_chrome_cast/enums/connection_state.dart';+import 'package:plugin_platform_interface/plugin_platform_interface.dart';++/// <p>A class that manages sessions. </p>+/// <p>The method <a class="el notranslate" href="/cast/docs/reference/ios/interface_g_c_k_session_manager#a211d476c2e9b265ed7510d12f4b29c02">startSessionWithDevice: (GCKSessionManager)</a> is used to create a new session with a given <a class="el notranslate" href="/cast/docs/reference/ios/interface_g_c_k_device" data-title="An object representing a receiver device. ">GCKDevice</a>. The session manager uses the <a class="el notranslate" href="/cast/docs/reference/ios/interface_g_c_k_device_provider" data-title="An abstract base class for performing device discovery and session construction. ">GCKDeviceProvider</a> for that device type to construct a new <a class="el notranslate" href="/cast/docs/reference/ios/interface_g_c_k_session" data-title="An abstract base class representing a session with a receiver device. ">GCKSession</a> object, to which it then delegates all session requests.</p>+/// <p><a class="el notranslate" href="/cast/docs/reference/ios/interface_g_c_k_session_manager" data-title="A class that manages sessions. ">GCKSessionManager</a> handles the automatic resumption of suspended sessions (that is, resuming sessions that were ended when the application went to the background, or in the event that the application crashed or was forcibly terminated by the user). When the application resumes or restarts, the session manager will wait for a short time for the device provider of the suspended session's device to discover that device again, and if it does, it will attempt to reconnect to that device and re-establish the session automatically.</p>+/// <p>If the application has created a <a class="el notranslate" href="/cast/docs/reference/ios/interface_g_c_k_u_i_cast_button" data-title="A subclass of UIButton that implements a "Cast" button. ">GCKUICastButton</a> without providing a target and selector, then a user tap on the button will display the default Cast dialog and it will automatically start and stop sessions based on user selection or disconnection of a device. If however the application is providing its own device selection/control dialog UI, then it should use the <a class="el notranslate" href="/cast/docs/reference/ios/interface_g_c_k_session_manager" data-title="A class that manages sessions. ">GCKSessionManager</a> directly to create and control sessions.</p>+/// <p>Whether or not the application uses the <a class="el notranslate" href="/cast/docs/reference/ios/interface_g_c_k_session_manager" data-title="A class that manages sessions. ">GCKSessionManager</a> to control sessions, it can attach a <a class="el notranslate" href="/cast/docs/reference/ios/protocol_g_c_k_session_manager_listener-p" data-title="The GCKSessionManager listener protocol. ">GCKSessionManagerListener</a> to be notified of session events, and can also use KVO to monitor the <a class="el notranslate" href="/cast/docs/reference/ios/interface_g_c_k_session_manager#a8b48906a8910f328343e2260e6bef6a0" data-title="The current session connection state. ">connectionState</a> property to track the current session lifecycle state.</p>+/// <dl class="section since"><dt>Since</dt><dd>3.0 </dd></dl>++abstract class GoogleCastSessionManagerPlatformInterface+ extends PlatformInterface {+ /// Creates a new [GoogleCastSessionManagerPlatformInterface].+ GoogleCastSessionManagerPlatformInterface({required super.token});++ /// Tests if a session is currently being managed by this session manager, and it is currently connected.++ /// This will be YES if the session state is ConnectionStateConnected.+ bool get hasConnectedSession;++ /// The current session, if any.+ GoogleCastSession? get currentSession;++ /// Stream of current session changes.+ Stream<GoogleCastSession?> get currentSessionStream;++ /// readnonatomicassign++ /// The current session connection state.++ GoogleCastConnectState get connectionState;++ /// Starts a new session with the given device, using the default session options that were registered for the device category, if any.++ /// This is an asynchronous operation.++ /// Parameters+ /// device The device to use for this session.++ /// Returns+ /// YES if the operation has been started successfully, NO if there is a session currently established or if the operation could not be started.+ Future<bool> startSessionWithDevice(GoogleCastDevice device);++ /// Attempts to join or start a session with options that were supplied to the UIApplicationDelegate::application:openURL:options: method.++ /// Typically this is a request to join an existing Cast session on a particular device that was initiated by another app.++ /// Parameters+ /// openURLOptions The options that were extracted from the URL.+// / sessionOptions The options for this session, if any. May be nil.++// Returns+// YES if the operation has been started successfully, NO if there is a session currently established, or the openURL options do not contain the required Cast options.++// Since+// 4.0++ Future<bool> startSessionWithOpenURLOptions();++ /// Suspends the current session.++ /// This is an asynchronous operation.++ /// Parameters+ ///+ /// reason The reason for the suspension.++ /// Returns+ /// YES if the operation has been started successfully, NO if there is no session currently established or if the operation could not be started.++ Future<bool> suspendSessionWithReason();++ ///Ends the current session.++ /// This is an asynchronous operation.++ /// Returns+ /// YES if the operation has been started successfully, NO if there is no session currently established or if the operation could not be started.++ Future<bool> endSession();++ /// Ends the current session and stops casting if one sender device is connected; otherwise, optionally stops casting if multiple sender devices are connected.++ /// Use the stopCasting parameter to indicate whether casting on the receiver should stop when the session ends. This parameter only applies when multiple sender devices are connected. For example, the same app is open on multiple sender devices and each sender device has an active Cast session with the same receiver device.++ /// If you set stopCasting to YES, the receiver app stops casting when multiple devices are connected.+ /// If stopCasting is NO and other devices have an active session, the receiver keeps playing.+ /// If only one sender device is connected, the receiver app stops casting the media and ignores the stopCasting value, even if it's set to NO.++ /// Parameters+ /// stopCasting Whether casting on the receiver should stop when the session ends. Only used when multiple sender devices are connected.++ /// Returns+ /// YES if the operation to end the session started successfully, NO if there is no session currently established or if the operation could not be started.++ Future<bool> endSessionAndStopCasting();++ /// Sets the default session options for devices in a specific category (iOS only).+ ///+ /// This method is only available on iOS platforms and works with GCKSessionOptions.+ /// Use this to configure default session behavior for specific device categories.+ ///+ /// Implementation note:+ /// For native iOS, this maps to:+ /// - sessionOptions: nullable GCKSessionOptions+ /// - forDeviceCategory: (NSString *) category+ Future<void> setDefaultSessionOptions(+ // nullable GCKSessionOptions *\tsessionOptions+ // forDeviceCategory: \t\t(NSString *) \tcategory+ );++ /// Sets the device volume.+ void setDeviceVolume(double value);+}diff --git a/packages/flutter_chrome_cast/lib/_session_manager/ios_cast_session_manager.dart b/packages/flutter_chrome_cast/lib/_session_manager/ios_cast_session_manager.dartnew file mode 100644index 00000000..17dba49a--- /dev/null+++ b/packages/flutter_chrome_cast/lib/_session_manager/ios_cast_session_manager.dart@@ -0,0 +1,100 @@+import 'package:flutter/services.dart';+import 'package:flutter_chrome_cast/lib.dart';+import 'package:rxdart/subjects.dart';++/// iOS-specific implementation of Google Cast session manager functionality.+class GoogleCastSessionManagerIOSMethodChannel+ implements GoogleCastSessionManagerPlatformInterface {+ /// Creates a new iOS session manager method channel.+ GoogleCastSessionManagerIOSMethodChannel() {+ _channel.setMethodCallHandler(+ (call) => _methodCallHandler(call),+ );+ }++ final _channel = const MethodChannel('google_cast.session_manager');++ @override+ Stream<GoogleCastSession?> get currentSessionStream =>+ _currentSessionStreamController.stream;++ final _currentSessionStreamController = BehaviorSubject<GoogleCastSession?>()+ ..add(null);++ @override+ Future<bool> startSessionWithDevice(GoogleCastDevice device) async {+ device as GoogleCastIosDevice;+ return await _channel.invokeMethod(+ 'startSessionWithDevice',+ device.index,+ );+ }++ @override+ GoogleCastConnectState get connectionState =>+ currentSession?.connectionState ?? GoogleCastConnectState.disconnected;++ /// Returns the current cast session if available.+ ///+ /// This method is not implemented for iOS and will throw an [UnimplementedError].+ /// Use [currentSession] instead which is properly implemented for iOS.+ GoogleCastSession? get currentCastSession => throw UnimplementedError();++ @override+ GoogleCastSession? get currentSession =>+ _currentSessionStreamController.value;++ @override+ Future<bool> endSession() async {+ return await _channel.invokeMethod('endSession');+ }++ @override+ Future<bool> endSessionAndStopCasting() async {+ return await _channel.invokeMethod('endSessionAndStopCasting');+ }++ @override+ bool get hasConnectedSession =>+ connectionState == GoogleCastConnectState.connected;++ @override+ Future<void> setDefaultSessionOptions() {+ // TODO: implement setDefaultSessionOptions+ throw UnimplementedError();+ }++ @override+ Future<bool> startSessionWithOpenURLOptions() {+ // TODO: implement startSessionWithOpenURLOptions+ throw UnimplementedError();+ }++ @override+ Future<bool> suspendSessionWithReason() {+ // TODO: implement suspendSessionWithReason+ throw UnimplementedError();+ }++ Future<dynamic> _methodCallHandler(MethodCall call) async {+ switch (call.method) {+ case 'onCurrentSessionChanged':+ return _onCurrentSessionChanged(call.arguments);+ }+ }++ void _onCurrentSessionChanged(dynamic arguments) async {+ try {+ final session = IOSGoogleCastSessions.fromMap(+ arguments == null ? null : Map<String, dynamic>.from(arguments));+ _currentSessionStreamController.add(session);+ } catch (e) {+ rethrow;+ }+ }++ @override+ void setDeviceVolume(double value) {+ _channel.invokeMethod('setDeviceVolume', value);+ }+}diff --git a/packages/flutter_chrome_cast/lib/cast_context.dart b/packages/flutter_chrome_cast/lib/cast_context.dartnew file mode 100644index 00000000..6dafe30b--- /dev/null+++ b/packages/flutter_chrome_cast/lib/cast_context.dart@@ -0,0 +1,6 @@+/// Google Cast Context functionality+///+/// This module provides access to Google Cast context management.+library cast_context;++export '_google_cast_context/_google_cast_context.dart';diff --git a/packages/flutter_chrome_cast/lib/common.dart b/packages/flutter_chrome_cast/lib/common.dartnew file mode 100644index 00000000..f6bc2b9e--- /dev/null+++ b/packages/flutter_chrome_cast/lib/common.dart@@ -0,0 +1,6 @@+/// Common types and classes for Chrome Cast+///+/// This module provides access to common types and classes.+library common;++export 'common/common.dart';diff --git a/packages/flutter_chrome_cast/lib/common/break.dart b/packages/flutter_chrome_cast/lib/common/break.dartnew file mode 100644index 00000000..c898adec--- /dev/null+++ b/packages/flutter_chrome_cast/lib/common/break.dart@@ -0,0 +1,78 @@+import 'dart:convert';++///Represents a break (e.g. ad break)+///included in the main video.+class CastBreak {+ ///List of break clip IDs included in this break.++ final List<String> breakClipIds;++ ///Duration of break in seconds.+ final Duration? duration;++ ///Unique ID of a break.+ final String id;++ /// Indicates whether the break is embedded in the main stream.++ final bool isEmbedded;++ /// Whether a break was watched. This is marked as+ /// true when the break begins to play.+ /// A sender can change color of a progress+ /// bar marker corresponding to this break+ /// once this field changes from false to+ /// true denoting that the end-user+ /// already watched this break.++ final bool isWatched;++ ///Location of the break inside the main video. -1 represents the end of the main video in seconds.++ final int position;++ /// Creates a new [CastBreak] instance.+ CastBreak({+ required this.breakClipIds,+ this.duration,+ required this.id,+ required this.isEmbedded,+ required this.isWatched,+ required this.position,+ });++ /// Converts this break to a map representation.+ Map<String, dynamic> toMap() {+ return {+ 'breakClipIds': breakClipIds,+ 'duration': duration?.inSeconds,+ 'id': id,+ 'isEmbedded': isEmbedded,+ 'isWatched': isWatched,+ 'position': position,+ };+ }++ /// Creates a [CastBreak] from a map representation.+ factory CastBreak.fromMap(Map<String, dynamic> map) {+ return CastBreak(+ breakClipIds: map['breakClipIds'] != null+ ? List<String>.from(map['breakClipIds'])+ : [],+ duration: map['duration'] != null+ ? Duration(seconds: map['duration'].round())+ : null,+ id: map['id'] ?? '',+ isEmbedded: map['isEmbedded'] ?? false,+ isWatched: map['isWatched'] ?? false,+ position: map['position']?.toInt() ?? 0,+ );+ }++ /// Converts this break to a JSON string.+ String toJson() => json.encode(toMap());++ /// Creates a [CastBreak] from a JSON string.+ factory CastBreak.fromJson(String source) =>+ CastBreak.fromMap(json.decode(source));+}diff --git a/packages/flutter_chrome_cast/lib/common/break_clips.dart b/packages/flutter_chrome_cast/lib/common/break_clips.dartnew file mode 100644index 00000000..5288243d--- /dev/null+++ b/packages/flutter_chrome_cast/lib/common/break_clips.dart@@ -0,0 +1,146 @@+import 'dart:convert';++import 'package:flutter_chrome_cast/common/hls_segment_format.dart';+import 'package:flutter_chrome_cast/common/vast_ads_request.dart';++///Represents a break clip (e.g. a clip of an ad during an ad break)++class CastBreakClips {+ ///URL of the page that the sender will display,+ ///when the end user clicks the link on the sender+ ///UI, while the receiver is playing this clip.++ final String? clickThroughUrl;++ /// The URL or content ID of the break media playing on the receiver.++ final String? contentId;++ ///The content MIME type.+ final String? contentType;++ ///Optional break media URL, to allow using contentId+ ///for the real ID. If contentUrl is provided, it will+ /// be used as the media URL, otherwise+ /// the contentId will be used as the media URL.++ final String? contentUrl;++ ///Application-specific break clip data.+ final Map<String, dynamic>? customData;++ ///Duration of a break clip in seconds.+ final Duration? duration;++ ///The format of the HLS media segment.+ final CastHlsSegmentFormat? hlsSegmentFormat;++ ///Unique ID of break clip.+ final String id;++ /// URL of content that the sender will+ /// display while the receiver is playing this clip.++ final String? posterUrl;++ ///Title of a break clip. Sender might display this on its screen, if provided.+ final String? title;++ ///VAST ad request configuration. Used if contentId or contentUrl is not provided.+ final VastAdsRequest? vastAdsRequest;++ ///The time in seconds when this break clip becomes skippable.+ /// 5 means that end user can skip this break clip after 5 seconds.+ /// If this field is not defined or is a negative value, it means that+ /// current break clip is not shippable.++ final Duration? whenSkippable;++ /// Creates a new [CastBreakClips] instance.+ ///+ /// [clickThroughUrl] - URL of the page that the sender will display when clicked.+ /// [contentId] - The content ID of the break media.+ /// [contentType] - The content MIME type.+ /// [contentUrl] - Optional break media URL.+ /// [customData] - Application-specific break clip data.+ /// [duration] - Duration of a break clip in seconds.+ /// [hlsSegmentFormat] - The format of the HLS media segment.+ /// [id] - Unique ID of break clip, required.+ /// [posterUrl] - URL of content that the sender will display.+ /// [title] - Title of a break clip.+ /// [vastAdsRequest] - VAST ad request configuration, required.+ /// [whenSkippable] - The time in seconds when this break clip becomes skippable.+ CastBreakClips({+ this.clickThroughUrl,+ this.contentId,+ this.contentType,+ this.contentUrl,+ this.customData,+ this.duration,+ this.hlsSegmentFormat,+ required this.id,+ this.posterUrl,+ this.title,+ this.vastAdsRequest,+ this.whenSkippable,+ });++ /// Converts the break clip object to a map for serialization.+ Map<String, dynamic> toMap() {+ return {+ 'clickThroughUrl': clickThroughUrl,+ 'contentId': contentId,+ 'contentType': contentType,+ 'contentUrl': contentUrl,+ 'customData': customData,+ 'duration': duration?.inSeconds,+ 'hlsSegmentFormat': hlsSegmentFormat?.name,+ 'id': id,+ 'posterUrl': posterUrl,+ 'title': title,+ 'vastAdsRequest': vastAdsRequest?.toMap(),+ 'whenSkippable': whenSkippable?.inSeconds,+ };+ }++ /// Creates a [CastBreakClips] instance from a map.+ ///+ /// [map] - The map to create the instance from.+ factory CastBreakClips.fromMap(Map<String, dynamic> map) {+ return CastBreakClips(+ clickThroughUrl: map['clickThroughUrl'],+ contentId: map['contentId'],+ contentType: map['contentType'],+ contentUrl: map['contentUrl'],+ customData: map['customData'] != null+ ? Map<String, dynamic>.from(map['customData'])+ : null,+ duration: map['duration'] != null+ ? Duration(seconds: map['duration'].round())+ : null,+ hlsSegmentFormat: map['hlsSegmentFormat'] != null+ ? CastHlsSegmentFormat.fromMap(map['hlsSegmentFormat'])+ : null,+ id: map['id'] ?? '',+ posterUrl: map['posterUrl'],+ title: map['title'],+ vastAdsRequest: map['vastAdsRequest'] != null+ ? VastAdsRequest.fromMap(map['vastAdsRequest'])+ : null,+ whenSkippable: map['whenSkippable'] != null+ ? Duration(seconds: map['whenSkippable'].round())+ : null,+ );+ }++ /// Converts the [CastBreakClips] to a JSON string.+ ///+ /// Returns a JSON string representation of this object.+ String toJson() => json.encode(toMap());++ /// Creates a [CastBreakClips] from a JSON string.+ ///+ /// [source] - The JSON string to create the instance from.+ factory CastBreakClips.fromJson(String source) =>+ CastBreakClips.fromMap(json.decode(source));+}diff --git a/packages/flutter_chrome_cast/lib/common/cast_status_event.dart b/packages/flutter_chrome_cast/lib/common/cast_status_event.dartnew file mode 100644index 00000000..23633e5f--- /dev/null+++ b/packages/flutter_chrome_cast/lib/common/cast_status_event.dart@@ -0,0 +1,45 @@+/// Represents different types of cast status events.+///+/// These events are used to categorize different types of status updates+/// that can be received from a Google Cast session.+enum CastStatusType {+ /// Media status events related to playback state, position, etc.+ mediaStatus('MEDIA_STATUS'),++ /// Receiver status events related to device state, volume, etc.+ receiverStatus('RECEIVER_STATUS'),++ /// Unknown or unhandled status event type.+ unknow('UNKNOW');++ /// The raw string value associated with this status type.+ final String rawValue;++ /// Creates a cast status type with the given raw value.+ const CastStatusType(this.rawValue);++ /// Creates a [CastStatusType] from a string value.+ ///+ /// Returns [CastStatusType.unknow] if the string doesn't match any known type.+ factory CastStatusType.fromString(String name) {+ return CastStatusType.values.firstWhere(+ (element) => element.rawValue == name,+ orElse: () => CastStatusType.unknow);+ }+}++/// Represents a cast message event received from a Google Cast session.+///+/// This class encapsulates status updates and other messages that are+/// sent from the Cast receiver to the sender application.+class CastMessageEvent {+ /// The type of status event this message represents.+ final CastStatusType type;++ /// Creates a new cast message event.+ ///+ /// [type] specifies the category of this status event.+ CastMessageEvent({+ required this.type,+ });+}diff --git a/packages/flutter_chrome_cast/lib/common/common.dart b/packages/flutter_chrome_cast/lib/common/common.dartnew file mode 100644index 00000000..17b10af7--- /dev/null+++ b/packages/flutter_chrome_cast/lib/common/common.dart@@ -0,0 +1,18 @@+export 'break.dart';+export 'break_clips.dart';+export 'cast_status_event.dart';+export 'font_generic_family.dart';+export 'hls_segment_format.dart';+export 'hls_video_segment_format.dart';+export 'image.dart';+export 'live_seekable_range.dart';+export 'queue_data.dart';+export 'rfc5646_language.dart';+export 'text_track_edge_type.dart';+export 'text_track_font_style.dart';+export 'text_track_style.dart';+export 'text_track_window_type.dart';+export 'user_action.dart';+export 'user_action_state.dart';+export 'vast_ads_request.dart';+export 'volume.dart';diff --git a/packages/flutter_chrome_cast/lib/common/font_generic_family.dart b/packages/flutter_chrome_cast/lib/common/font_generic_family.dartnew file mode 100644index 00000000..cabcd444--- /dev/null+++ b/packages/flutter_chrome_cast/lib/common/font_generic_family.dart@@ -0,0 +1,52 @@+/// Represents generic font families for text tracks in Google Cast.+///+/// These values correspond to the CSS generic font families that can be+/// used for styling text tracks (captions/subtitles) in Cast media.+enum TextTrackFontGenericFamily {+ /// Sans-serif fonts (e.g., Arial, Helvetica).+ sansSerif,++ /// Monospaced sans-serif fonts (e.g., Courier New).+ monospacedSansSerif,++ /// Serif fonts (e.g., Times New Roman, Georgia).+ serif,++ /// Monospaced serif fonts.+ monospacedSerif,++ /// Casual or informal fonts.+ casual,++ /// Cursive or script fonts.+ cursive,++ /// Small capitals variant fonts.+ smallCapitals;++ factory TextTrackFontGenericFamily.fromMap(String value) {+ // Try matching by name (lowerCamelCase)+ for (final v in values) {+ if (v.name == value) return v;+ }+ // Fallback: match legacy UPPER_SNAKE_CASE+ switch (value) {+ case 'SANS_SERIF':+ return TextTrackFontGenericFamily.sansSerif;+ case 'MONOSPACED_SANS_SERIF':+ return TextTrackFontGenericFamily.monospacedSansSerif;+ case 'SERIF':+ return TextTrackFontGenericFamily.serif;+ case 'MONOSPACED_SERIF':+ return TextTrackFontGenericFamily.monospacedSerif;+ case 'CASUAL':+ return TextTrackFontGenericFamily.casual;+ case 'CURSIVE':+ return TextTrackFontGenericFamily.cursive;+ case 'SMALL_CAPITALS':+ return TextTrackFontGenericFamily.smallCapitals;+ default:+ return TextTrackFontGenericFamily.sansSerif;+ }+ }+}diff --git a/packages/flutter_chrome_cast/lib/common/hls_segment_format.dart b/packages/flutter_chrome_cast/lib/common/hls_segment_format.dartnew file mode 100644index 00000000..e0c44eaf--- /dev/null+++ b/packages/flutter_chrome_cast/lib/common/hls_segment_format.dart@@ -0,0 +1,53 @@+/// Format of an HLS audio segment.+///+/// Represents the different audio codec formats that can be used+/// in HLS (HTTP Live Streaming) segments for Google Cast media.+enum CastHlsSegmentFormat {+ /// Advanced Audio Coding format.+ aac,++ /// Dolby Digital (AC-3) format.+ ac3,++ /// MPEG-1 Audio Layer III format.+ mp3,++ /// MPEG Transport Stream format.+ ts,++ /// Transport Stream with AAC audio.+ tsAac,++ /// Enhanced AC-3 (Dolby Digital Plus) format.+ eAc3,++ /// Fragmented MP4 format.+ fmp4,++ /// No specific format or unknown format.+ none;++ factory CastHlsSegmentFormat.fromMap(String value) {+ // Try matching by name (lowerCamelCase)+ for (final v in values) {+ if (v.name == value) return v;+ }+ // Fallback: match legacy UPPER_SNAKE_CASE+ switch (value) {+ case 'AAC':+ return CastHlsSegmentFormat.aac;+ case 'AC3':+ return CastHlsSegmentFormat.ac3;+ case 'MP3':+ return CastHlsSegmentFormat.mp3;+ case 'TS':+ return CastHlsSegmentFormat.ts;+ case 'TS_AAC':+ return CastHlsSegmentFormat.tsAac;+ case 'E_AC3':+ return CastHlsSegmentFormat.eAc3;+ default:+ return CastHlsSegmentFormat.none;+ }+ }+}diff --git a/packages/flutter_chrome_cast/lib/common/hls_video_segment_format.dart b/packages/flutter_chrome_cast/lib/common/hls_video_segment_format.dartnew file mode 100644index 00000000..9cd9c770--- /dev/null+++ b/packages/flutter_chrome_cast/lib/common/hls_video_segment_format.dart@@ -0,0 +1,27 @@+/// Enum representing the HLS video segment format types.+enum HlsVideoSegmentFormat {+ /// MPEG-2 Transport Stream format.+ mpeg2Ts,++ /// Fragmented MP4 format.+ fmp4,++ /// No specific format.+ none;++ factory HlsVideoSegmentFormat.fromMap(String value) {+ // Try matching by name (lowerCamelCase)+ for (final v in values) {+ if (v.name == value) return v;+ }+ // Fallback: match legacy UPPER_SNAKE_CASE+ switch (value) {+ case 'MPEG2_TS':+ return HlsVideoSegmentFormat.mpeg2Ts;+ case 'FMP4':+ return HlsVideoSegmentFormat.fmp4;+ default:+ return HlsVideoSegmentFormat.none;+ }+ }+}diff --git a/packages/flutter_chrome_cast/lib/common/image.dart b/packages/flutter_chrome_cast/lib/common/image.dartnew file mode 100644index 00000000..45199270--- /dev/null+++ b/packages/flutter_chrome_cast/lib/common/image.dart@@ -0,0 +1,52 @@+import 'dart:convert';++/// Represents an image for Google Cast.+class GoogleCastImage {+ ///url URI URI for the image+ final Uri url;++ ///height integer optional Height of the image+ final int? height;++ ///width integer optional Width of the image+ final int? width;++ /// Creates a new [GoogleCastImage] instance.+ GoogleCastImage({+ required this.url,+ this.height,+ this.width,+ });++ /// Converts this image to a map representation.+ Map<String, dynamic> toMap() {+ return {+ 'url': url.toString(),+ 'height': height,+ 'width': width,+ };+ }++ /// Creates a [GoogleCastImage] from a map representation.+ /// Returns null if the URL is missing or invalid.+ static GoogleCastImage? fromMap(Map<String, dynamic> map) {+ final urlString = map['url'];+ if (urlString == null || urlString is! String || urlString.isEmpty) {+ return null;+ }+ final uri = Uri.tryParse(urlString);+ if (uri == null) return null;+ return GoogleCastImage(+ url: uri,+ height: map['height']?.toInt(),+ width: map['width']?.toInt(),+ );+ }++ /// Converts this image to a JSON string.+ String toJson() => json.encode(toMap());++ /// Creates a [GoogleCastImage] from a JSON string.+ static GoogleCastImage? fromJson(String source) =>+ GoogleCastImage.fromMap(json.decode(source));+}diff --git a/packages/flutter_chrome_cast/lib/common/live_seekable_range.dart b/packages/flutter_chrome_cast/lib/common/live_seekable_range.dartnew file mode 100644index 00000000..c8f2d84c--- /dev/null+++ b/packages/flutter_chrome_cast/lib/common/live_seekable_range.dart@@ -0,0 +1,83 @@+import 'dart:convert';++///Provides the live seekable range with start and end time in seconds.+class GoogleCastMediaLiveSeekableRange {+ ///End of the seekable range in seconds.+ /// This member is only updated sporadically,+ /// so its value is often out of date. Use+ /// the getEstimatedLiveSeekableRange method+ /// to get an estimate of the real position+ /// based on the last information reported+ /// by the receiver.+ final Duration? end;++ ///A boolean value indicates whether+ ///a live stream is ended. If it+ ///is done, the end of live seekable+ /// range should stop updating.+ final bool? isLiveDone;++ ///A boolean value indicates whether+ /// the live seekable range is a moving window.+ /// If false, it will be either a expanding+ /// range or a fixed range meaning live has ended.+ final bool? isMovingWindow;++ ///Start of the seekable range in seconds.+ ///This member is only updated sporadically,+ /// so its value is often out of date. Use+ /// the getEstimatedLiveSeekableRange method+ /// to get an estimate of the real position+ /// based on the last information reported+ /// by the receiver.+ final Duration? start;++ /// Creates a new [GoogleCastMediaLiveSeekableRange] instance.+ ///+ /// [end] - End of the seekable range in seconds.+ /// [isLiveDone] - Whether the live stream is ended.+ /// [isMovingWindow] - Whether the live seekable range is a moving window.+ /// [start] - Start of the seekable range in seconds.+ GoogleCastMediaLiveSeekableRange({+ this.end,+ this.isLiveDone,+ this.isMovingWindow,+ this.start,+ });++ /// Converts the [GoogleCastMediaLiveSeekableRange] to a map.+ ///+ /// Returns a [Map] representation of this object.+ Map<String, dynamic> toMap() {+ return {+ 'end': end?.inSeconds,+ 'isLiveDone': isLiveDone,+ 'isMovingWindow': isMovingWindow,+ 'start': start?.inSeconds,+ };+ }++ /// Creates a [GoogleCastMediaLiveSeekableRange] from a map.+ ///+ /// [map] - The map to create the instance from.+ factory GoogleCastMediaLiveSeekableRange.fromMap(Map<String, dynamic> map) {+ return GoogleCastMediaLiveSeekableRange(+ end: map['end'] != null ? Duration(seconds: map['end'].toInt()) : null,+ isLiveDone: map['isLiveDone'],+ isMovingWindow: map['isMovingWindow'],+ start:+ map['start'] != null ? Duration(seconds: map['start'].toInt()) : null,+ );+ }++ /// Converts the [GoogleCastMediaLiveSeekableRange] to a JSON string.+ ///+ /// Returns a JSON string representation of this object.+ String toJson() => json.encode(toMap());++ /// Creates a [GoogleCastMediaLiveSeekableRange] from a JSON string.+ ///+ /// [source] - The JSON string to create the instance from.+ factory GoogleCastMediaLiveSeekableRange.fromJson(String source) =>+ GoogleCastMediaLiveSeekableRange.fromMap(json.decode(source));+}diff --git a/packages/flutter_chrome_cast/lib/common/queue_data.dart b/packages/flutter_chrome_cast/lib/common/queue_data.dartnew file mode 100644index 00000000..83b52411--- /dev/null+++ b/packages/flutter_chrome_cast/lib/common/queue_data.dart@@ -0,0 +1,67 @@+// import 'dart:convert';++// import 'package:flutter_chrome_cast/entities/queue_item.dart';+// import 'package:flutter_chrome_cast/common/repeat_mode.dart';+// export 'package:flutter_chrome_cast/entities/queue_item.dart';+// export 'package:flutter_chrome_cast/common/repeat_mode.dart';++// class GoogleCastMediaQueueData {+// final String? id;+// final String? name;+// final String? description;+// final GoogleCastMediaRepeatMode? repeatMode;++// /// if you will run LOAD command, you will+// /// prefer put only one item+// /// in queue with id equals 0 and+// /// then you can use QUEUE_INSERT+// /// command to add items to queue+// final List<GoogleCastQueueItem>? items;+// final int? startIndex;+// final Duration? startTime;+// GoogleCastMediaQueueData({+// this.id,+// this.name,+// this.description,+// this.repeatMode,+// this.items,+// this.startIndex,+// this.startTime,+// });++// Map<String, dynamic> toMap() {+// return {+// 'id': id,+// 'name': name,+// 'description': description,+// 'repeatMode': repeatMode?.name,+// 'items': items?.map((x) => x.toMap()).toList(),+// 'startIndex': startIndex,+// 'startTime': startTime?.inSeconds,+// };+// }++// factory GoogleCastMediaQueueData.fromMap(Map<String, dynamic> map) {+// return GoogleCastMediaQueueData(+// id: map['id'],+// name: map['name'],+// description: map['description'],+// repeatMode: map['repeatMode'] != null+// ? GoogleCastMediaRepeatMode.values[map['repeatMode']]+// : null,+// items: map['items'] != null+// ? List<GoogleCastQueueItem>.from(+// map['items']?.map((x) => GoogleCastQueueItem.fromMap(x)))+// : null,+// startIndex: map['startIndex']?.toInt(),+// startTime: map['startTime'] != null+// ? Duration(seconds: map['startTime']?.toInt() ?? 0)+// : null,+// );+// }++// String toJson() => json.encode(toMap());++// factory GoogleCastMediaQueueData.fromJson(String source) =>+// GoogleCastMediaQueueData.fromMap(json.decode(source));+// }diff --git a/packages/flutter_chrome_cast/lib/common/rfc5646_language.dart b/packages/flutter_chrome_cast/lib/common/rfc5646_language.dartnew file mode 100644index 00000000..ac3ffb6c--- /dev/null+++ b/packages/flutter_chrome_cast/lib/common/rfc5646_language.dart@@ -0,0 +1,727 @@+/// Enum representing RFC 5646 language codes.+///+/// This enum contains language codes following the RFC 5646 standard+/// for identifying languages and language variants.+enum Rfc5646Language {+ /// Afrikaans language.+ afrikaans('af'),++ /// Afrikaans as spoken in South Africa.+ afrikaansSouthAfrica('af-ZA'),++ /// Arabic language.+ arabic('ar'),++ /// Arabic as spoken in United Arab Emirates.+ arabicUae('ar-AE'),++ /// Arabic as spoken in Bahrain.+ arabicBahrain('ar-BH'),++ /// Arabic as spoken in Algeria.+ arabicAlgeria('ar-DZ'),++ /// Arabic as spoken in Egypt.+ arabicEgypt('ar-EG'),++ /// Arabic as spoken in Iraq.+ arabicIraq('ar-IQ'),++ /// Arabic as spoken in Jordan.+ arabicJordan('ar-JO'),++ /// Arabic as spoken in Kuwait.+ arabicKuwait('ar-KW'),++ /// Arabic as spoken in Lebanon.+ arabicLebanon('ar-LB'),++ /// Arabic as spoken in Libya.+ arabicLibya('ar-LY'),++ /// Arabic as spoken in Morocco.+ arabicMorocco('ar-MA'),++ /// Arabic as spoken in Oman.+ arabicOman('ar-OM'),++ /// Arabic as spoken in Qatar.+ arabicQatar('ar-QA'),++ /// Arabic as spoken in Saudi Arabia.+ arabicSaudiArabia('ar-SA'),++ /// Arabic as spoken in Syria.+ arabicSyria('ar-SY'),++ /// Arabic as spoken in Tunisia.+ arabicTunisia('ar-TN'),++ /// Arabic as spoken in Yemen.+ arabicYemen('ar-YE'),++ /// Azeri Latin script.+ azeriLatin('az'),++ /// Azeri Latin script as used in Azerbaijan.+ azeriLatinAzerbaijan('az-AZ'),++ /// Azeri Cyrillic script as used in Azerbaijan.+ azeriCyrillicAzerbaijan('az-Cyrl-AZ'),++ /// Belarusian language.+ belarusian('be'),++ /// Belarusian as spoken in Belarus.+ belarusianBelarus('be-BY'),++ /// Bulgarian language.+ bulgarian('bg'),++ /// Bulgarian as spoken in Bulgaria.+ bulgarianBulgaria('bg-BG'),++ /// Bosnian as spoken in Bosnia and Herzegovina.+ bosnianBosniaAndHerzegovina('bs-BA'),++ /// Catalan language.+ catalan('ca'),++ /// Catalan as spoken in Spain.+ catalanSpain('ca-ES'),++ /// Czech language.+ czech('cs'),++ /// Czech as spoken in Czech Republic.+ czechCzechRepublic('cs-CZ'),++ /// Welsh language.+ welsh('cy'),++ /// Welsh as spoken in United Kingdom.+ welshUnitedKingdom('cy-GB'),++ /// Danish language.+ danish('da'),++ /// Danish as spoken in Denmark.+ danishDenmark('da-DK'),++ /// German language.+ german('de'),++ /// German as spoken in Austria.+ germanAustria('de-AT'),++ /// German as spoken in Switzerland.+ germanSwitzerland('de-CH'),++ /// German as spoken in Germany.+ germanGermany('de-DE'),++ /// German as spoken in Liechtenstein.+ germanLiechtenstein('de-LI'),++ /// German as spoken in Luxembourg.+ germanLuxembourg('de-LU'),++ /// Divehi language.+ divehi('dv'),++ /// Divehi as spoken in Maldives.+ divehiMaldives('dv-MV'),++ /// Greek language.+ greek('el'),++ /// Greek as spoken in Greece.+ greekGreece('el-GR'),++ /// English language.+ english('en'),++ /// English as spoken in Australia.+ englishAustralia('en-AU'),++ /// English as spoken in Belize.+ englishBelize('en-BZ'),++ /// English as spoken in Canada.+ englishCanada('en-CA'),++ /// English as spoken in Caribbean.+ englishCaribbean('en-CB'),++ /// English as spoken in United Kingdom.+ englishUnitedKingdom('en-GB'),++ /// English as spoken in Ireland.+ englishIreland('en-IE'),++ /// English as spoken in Jamaica.+ englishJamaica('en-JM'),++ /// English as spoken in New Zealand.+ englishNewZealand('en-NZ'),++ /// English as spoken in Republic of the Philippines.+ englishRepublicOfThePhilippines('en-PH'),++ /// English as spoken in Trinidad and Tobago.+ englishTrinidadAndTobago('en-TT'),++ /// English as spoken in United States.+ englishUnitedStates('en-US'),++ /// English as spoken in South Africa.+ englishSouthAfrica('en-ZA'),++ /// English as spoken in Zimbabwe.+ englishZimbabwe('en-ZW'),++ /// Esperanto language.+ esperanto('eo'),++ /// Spanish language.+ spanish('es'),++ /// Spanish as spoken in Argentina.+ spanishArgentina('es-AR'),++ /// Spanish as spoken in Bolivia.+ spanishBolivia('es-BO'),++ /// Spanish as spoken in USA.+ spanishEua('es-US'),++ /// Spanish as spoken in Chile.+ spanishChile('es-CL'),++ /// Spanish as spoken in Colombia.+ spanishColombia('es-CO'),++ /// Spanish as spoken in Costa Rica.+ spanishCostaRica('es-CR'),++ /// Spanish as spoken in the Dominican Republic.+ spanishDominicanRepublic('es-DO'),++ /// Spanish as spoken in Ecuador.+ spanishEcuador('es-EC'),++ /// Spanish as spoken in Spain.+ spanishSpain('es-ES'),++ /// Spanish as spoken in Guatemala.+ spanishGuatemala('es-GT'),++ /// Spanish as spoken in Honduras.+ spanishHonduras('es-HN'),++ /// Spanish as spoken in Mexico.+ spanishMexico('es-MX'),++ /// Spanish as spoken in Nicaragua.+ spanishNicaragua('es-NI'),++ /// Spanish as spoken in Panama.+ spanishPanama('es-PA'),++ /// Spanish as spoken in Peru.+ spanishPeru('es-PE'),++ /// Spanish as spoken in Puerto Rico.+ spanishPuertoRico('es-PR'),++ /// Spanish as spoken in Paraguay.+ spanishParaguay('es-PY'),++ /// Spanish as spoken in El Salvador.+ spanishElSalvador('es-SV'),++ /// Spanish as spoken in Uruguay.+ spanishUruguay('es-UY'),++ /// Spanish as spoken in Venezuela.+ spanishVenezuela('es-VE'),++ /// Estonian language.+ estonian('et'),++ /// Estonian as spoken in Estonia.+ estonianEstonia('et-EE'),++ /// Basque language.+ basque('eu'),++ /// Basque as spoken in Spain.+ basqueSpain('eu-ES'),++ /// Farsi language.+ farsi('fa'),++ /// Farsi as spoken in Iran.+ farsiIran('fa-IR'),++ /// Finnish language.+ finnish('fi'),++ /// Finnish as spoken in Finland.+ finnishFinland('fi-FI'),++ /// Faroese language.+ faroese('fo'),++ /// Faroese as spoken in Faroe Islands.+ faroeseFaroeIslands('fo-FO'),++ /// French language.+ french('fr'),++ /// French as spoken in Belgium.+ frenchBelgium('fr-BE'),++ /// French as spoken in Canada.+ frenchCanada('fr-CA'),++ /// French as spoken in Switzerland.+ frenchSwitzerland('fr-CH'),++ /// French as spoken in France.+ frenchFrance('fr-FR'),++ /// French as spoken in Luxembourg.+ frenchLuxembourg('fr-LU'),++ /// French as spoken in Monaco.+ frenchPrincipalityOfMonaco('fr-MC'),++ /// Galician language.+ galician('gl'),++ /// Galician as spoken in Spain.+ galicianSpain('gl-ES'),++ /// Gujarati language.+ gujarati('gu'),++ /// Gujarati as spoken in India.+ gujaratiIndia('gu-IN'),++ /// Hebrew language.+ hebrew('he'),++ /// Hebrew as spoken in Israel.+ hebrewIsrael('he-IL'),++ /// Hindi language.+ hindi('hi'),++ /// Hindi as spoken in India.+ hindiIndia('hi-IN'),++ /// Croatian language.+ croatian('hr'),++ /// Croatian as spoken in Bosnia and Herzegovina.+ croatianBosniaAndHerzegovina('hr-BA'),++ /// Croatian as spoken in Croatia.+ croatianCroatia('hr-HR'),++ /// Hungarian language.+ hungarian('hu'),++ /// Hungarian as spoken in Hungary.+ hungarianHungary('hu-HU'),++ /// Armenian language.+ armenian('hy'),++ /// Armenian as spoken in Armenia.+ armenianArmenia('hy-AM'),++ /// Indonesian language.+ indonesian('id'),++ /// Indonesian as spoken in Indonesia.+ indonesianIndonesia('id-ID'),++ /// Icelandic language.+ icelandic('is'),++ /// Icelandic as spoken in Iceland.+ icelandicIceland('is-IS'),++ /// Italian language.+ italian('it'),++ /// Italian as spoken in Switzerland.+ italianSwitzerland('it-CH'),++ /// Italian as spoken in Italy.+ italianItaly('it-IT'),++ /// Japanese language.+ japanese('ja'),++ /// Japanese as spoken in Japan.+ japaneseJapan('ja-JP'),++ /// Georgian language.+ georgian('ka'),++ /// Georgian as spoken in Georgia.+ georgianGeorgia('ka-GE'),++ /// Kazakh language.+ kazakh('kk'),++ /// Kazakh as spoken in Kazakhstan.+ kazakhKazakhstan('kk-KZ'),++ /// Kannada language.+ kannada('kn'),++ /// Kannada as spoken in India.+ kannadaIndia('kn-IN'),++ /// Korean language.+ korean('ko'),++ /// Korean as spoken in Korea.+ koreanKorea('ko-KR'),++ /// Konkani language.+ konkani('kok'),++ /// Konkani as spoken in India.+ konkaniIndia('kok-IN'),++ /// Kyrgyz language.+ kyrgyz('ky'),++ /// Kyrgyz as spoken in Kyrgyzstan.+ kyrgyzKyrgyzstan('ky-KG'),++ /// Lithuanian language.+ lithuanian('lt'),++ /// Lithuanian as spoken in Lithuania.+ lithuanianLithuania('lt-LT'),++ /// Latvian language.+ latvian('lv'),++ /// Latvian as spoken in Latvia.+ latvianLatvia('lv-LV'),++ /// Maori language.+ maori('mi'),++ /// Maori as spoken in New Zealand.+ maoriNewZealand('mi-NZ'),++ /// Macedonian language.+ fyroMacedonian('mk'),++ /// Macedonian as spoken in North Macedonia.+ fyroMacedonianFormerYugoslavRepublicOfMacedonia('mk-MK'),++ /// Mongolian language.+ mongolian('mn'),++ /// Mongolian as spoken in Mongolia.+ mongolianMongolia('mn-MN'),++ /// Marathi language.+ marathi('mr'),++ /// Marathi as spoken in India.+ marathiIndia('mr-IN'),++ /// Malay language.+ malay('ms'),++ /// Malay as spoken in Brunei Darussalam.+ malayBruneiDarussalam('ms-BN'),++ /// Malay as spoken in Malaysia.+ malayMalaysia('ms-MY'),++ /// Maltese language.+ maltese('mt'),++ /// Maltese as spoken in Malta.+ malteseMalta('mt-MT'),++ /// Norwegian BokmΓ₯l language.+ norwegianBokml('nb'),++ /// Norwegian BokmΓ₯l as spoken in Norway.+ norwegianBokmlNorway('nb-NO'),++ /// Dutch language.+ dutch('nl'),++ /// Dutch as spoken in Belgium.+ dutchBelgium('nl-BE'),++ /// Dutch as spoken in the Netherlands.+ dutchNetherlands('nl-NL'),++ /// Norwegian Nynorsk as spoken in Norway.+ norwegianNynorskNorway('nn-NO'),++ /// Northern Sotho language.+ northernSotho('ns'),++ /// Northern Sotho as spoken in South Africa.+ northernSothoSouthAfrica('ns-ZA'),++ /// Punjabi language.+ punjabi('pa'),++ /// Punjabi as spoken in India.+ punjabiIndia('pa-IN'),++ /// Polish language.+ polish('pl'),++ /// Polish as spoken in Poland.+ polishPoland('pl-PL'),++ /// Pashto language.+ pashto('ps'),++ /// Pashto as spoken in Afghanistan.+ pashtoAfghanistan('ps-AR'),++ /// Portuguese language.+ portuguese('pt'),++ /// Portuguese as spoken in Brazil.+ portugueseBrazil('pt-BR'),++ /// Portuguese as spoken in Portugal.+ portuguesePortugal('pt-PT'),++ /// Quechua language.+ quechua('qu'),++ /// Quechua as spoken in Bolivia.+ quechuaBolivia('qu-BO'),++ /// Quechua as spoken in Ecuador.+ quechuaEcuador('qu-EC'),++ /// Quechua as spoken in Peru.+ quechuaPeru('qu-PE'),++ /// Romanian language.+ romanian('ro'),++ /// Romanian as spoken in Romania.+ romanianRomania('ro-RO'),++ /// Russian language.+ russian('ru'),++ /// Russian as spoken in Russia.+ russianRussia('ru-RU'),++ /// Sanskrit language.+ sanskrit('sa'),++ /// Sanskrit as spoken in India.+ sanskritIndia('sa-IN'),++ /// Sami language.+ sami('se'),++ /// Sami as spoken in Finland.+ samiFinland('se-FI'),++ /// Sami as spoken in Norway.+ samiNorway('se-NO'),++ /// Sami as spoken in Sweden.+ samiSweden('se-SE'),++ /// Slovak language.+ slovak('sk'),++ /// Slovak as spoken in Slovakia.+ slovakSlovakia('sk-SK'),++ /// Slovenian language.+ slovenian('sl'),++ /// Slovenian as spoken in Slovenia.+ slovenianSlovenia('sl-SI'),++ /// Albanian language.+ albanian('sq'),++ /// Albanian as spoken in Albania.+ albanianAlbania('sq-AL'),++ /// Serbian Latin script as spoken in Bosnia and Herzegovina.+ serbianLatinBosniaAndHerzegovina('sr-BA'),++ /// Serbian Cyrillic script as spoken in Bosnia and Herzegovina.+ serbianCyrillicBosniaAndHerzegovina('sr-Cyrl-BA'),++ /// Serbian Latin script as spoken in Serbia and Montenegro.+ serbianLatinSerbiaAndMontenegro('sr-SP'),++ /// Serbian Cyrillic script as spoken in Serbia and Montenegro.+ serbianCyrillicSerbiaAndMontenegro('sr-Cyrl-SP'),++ /// Swedish language.+ swedish('sv'),++ /// Swedish as spoken in Finland.+ swedishFinland('sv-FI'),++ /// Swedish as spoken in Sweden.+ swedishSweden('sv-SE'),++ /// Swahili language.+ swahili('sw'),++ /// Swahili as spoken in Kenya.+ swahiliKenya('sw-KE'),++ /// Syriac language.+ syriac('syr'),++ /// Syriac as spoken in Syria.+ syriacSyria('syr-SY'),++ /// Tamil language.+ tamil('ta'),++ /// Tamil as spoken in India.+ tamilIndia('ta-IN'),++ /// Telugu language.+ telugu('te'),++ /// Telugu as spoken in India.+ teluguIndia('te-IN'),++ /// Thai language.+ thai('th'),++ /// Thai as spoken in Thailand.+ thaiThailand('th-TH'),++ /// Tagalog language.+ tagalog('tl'),++ /// Tagalog as spoken in Philippines.+ tagalogPhilippines('tl-PH'),++ /// Tswana language.+ tswana('tn'),++ /// Tswana as spoken in South Africa.+ tswanaSouthAfrica('tn-ZA'),++ /// Turkish language.+ turkish('tr'),++ /// Turkish as spoken in Turkey.+ turkishTurkey('tr-TR'),++ /// Tatar language.+ tatar('tt'),++ /// Tatar as spoken in Russia.+ tatarRussia('tt-RU'),++ /// Tsonga language.+ tsonga('ts'),++ /// Ukrainian language.+ ukrainian('uk'),++ /// Ukrainian as spoken in Ukraine.+ ukrainianUkraine('uk-UA'),++ /// Urdu language.+ urdu('ur'),++ /// Urdu as spoken in Islamic Republic Of Pakistan.+ urduIslamicRepublicOfPakistan('ur-PK'),++ /// Uzbek Latin script.+ uzbekLatin('uz'),++ /// Uzbek Latin script as spoken in Uzbekistan.+ uzbekLatinUzbekistan('uz-UZ'),++ /// Uzbek Cyrillic script as spoken in Uzbekistan.+ uzbekCyrillicUzbekistan('uz-Cyrl-UZ'),++ /// Vietnamese language.+ vietnamese('vi'),++ /// Vietnamese as spoken in Viet Nam.+ vietnameseVietNam('vi-VN'),++ /// Xhosa language.+ xhosa('xh'),++ /// Xhosa as spoken in South Africa.+ xhosaSouthAfrica('xh-ZA'),++ /// Chinese language.+ chinese('zh'),++ /// Chinese as spoken in China.+ chineseS('zh-CN'),++ /// Chinese as spoken in Hong Kong.+ chineseHongKong('zh-HK'),++ /// Chinese as spoken in Macau.+ chineseMacau('zh-MO'),++ /// Chinese as spoken in Singapore.+ chineseSingapore('zh-SG'),++ /// Chinese as spoken in Taiwan.+ chineseT('zh-TW'),++ /// Zulu language.+ zulu('zu'),++ /// Zulu as spoken in South Africa.+ zuluSouthAfrica('zu-ZA');++ /// The string value representing the language code.+ final String value;++ /// Creates a [Rfc5646Language] with the given [value].+ const Rfc5646Language(this.value);++ @override+ String toString() {+ return value;+ }++ /// Creates a [Rfc5646Language] from a string value.+ ///+ /// [value] - The string representation of the language code.+ ///+ /// Returns the corresponding [Rfc5646Language] enum value.+ /// Throws a [StateError] if no matching language code is found.+ factory Rfc5646Language.fromMap(String? value) {+ if (value == null) return english;+ return values.firstWhere((element) => element.toString() == value,+ orElse: () => english);+ }+}diff --git a/packages/flutter_chrome_cast/lib/common/text_track_edge_type.dart b/packages/flutter_chrome_cast/lib/common/text_track_edge_type.dartnew file mode 100644index 00000000..8a1201ec--- /dev/null+++ b/packages/flutter_chrome_cast/lib/common/text_track_edge_type.dart@@ -0,0 +1,39 @@+/// Enum representing text track edge types for styling captions.+enum TextTrackEdgeType {+ /// No edge effect.+ none,++ /// Outline edge effect.+ outline,++ /// Drop shadow edge effect.+ dropShadow,++ /// Raised edge effect.+ raised,++ /// Depressed edge effect.+ depressed;++ factory TextTrackEdgeType.fromMap(String value) {+ // Try matching by name (lowerCamelCase)+ for (final v in values) {+ if (v.name == value) return v;+ }+ // Fallback: match legacy UPPER_SNAKE_CASE+ switch (value) {+ case 'NONE':+ return TextTrackEdgeType.none;+ case 'OUTLINE':+ return TextTrackEdgeType.outline;+ case 'DROP_SHADOW':+ return TextTrackEdgeType.dropShadow;+ case 'RAISED':+ return TextTrackEdgeType.raised;+ case 'DEPRESSED':+ return TextTrackEdgeType.depressed;+ default:+ throw ArgumentError('Unknown TextTrackEdgeType: $value');+ }+ }+}diff --git a/packages/flutter_chrome_cast/lib/common/text_track_font_style.dart b/packages/flutter_chrome_cast/lib/common/text_track_font_style.dartnew file mode 100644index 00000000..feb1c7fd--- /dev/null+++ b/packages/flutter_chrome_cast/lib/common/text_track_font_style.dart@@ -0,0 +1,34 @@+///Possible text track font style.+enum TextTrackFontStyle {+ /// Normal font style.+ normal,++ /// Bold font style.+ bold,++ /// Bold italic font style.+ boldItalic,++ /// Italic font style.+ italic;++ factory TextTrackFontStyle.fromMap(String value) {+ // Try matching by name (lowerCamelCase)+ for (final v in values) {+ if (v.name == value) return v;+ }+ // Fallback: match legacy UPPER_SNAKE_CASE+ switch (value) {+ case 'NORMAL':+ return TextTrackFontStyle.normal;+ case 'BOLD':+ return TextTrackFontStyle.bold;+ case 'BOLD_ITALIC':+ return TextTrackFontStyle.boldItalic;+ case 'ITALIC':+ return TextTrackFontStyle.italic;+ default:+ return TextTrackFontStyle.normal;+ }+ }+}diff --git a/packages/flutter_chrome_cast/lib/common/text_track_style.dart b/packages/flutter_chrome_cast/lib/common/text_track_style.dartnew file mode 100644index 00000000..4767cd40--- /dev/null+++ b/packages/flutter_chrome_cast/lib/common/text_track_style.dart@@ -0,0 +1,158 @@+import 'dart:convert';++import 'package:flutter/material.dart';++import 'package:flutter_chrome_cast/common/text_track_font_style.dart';+import 'package:flutter_chrome_cast/common/text_track_window_type.dart';++import 'font_generic_family.dart';++///Describes style information for a text track. Colors+///are represented as strings β#RRGGBBAAβ where XX are+///the two hexadecimal symbols that represent the+/// 0-255 value for the specific channel/color.+/// It follows CSS 8-digit hex color notation.+/// (See http://dev.w3.org/csswg/css-color/#hex-notation).+class TextTrackStyle {+ ///Background RGBA color, represented as "#RRGGBBAA".+ /// The alpha channel should be used for+ /// transparent backgrounds.++ final Color? backgroundColor;++ ///Custom application data.+ final Map<String, dynamic>? customData;++ ///RGBA color for the edge, represented as+ /// "#RRGGBBAA". This value will be+ /// ignored if edgeType is NONE.++ /// Edge color for the text track.+ final Color? edgeColor;++ /// Edge type for the text track.+ final TextTrackStyle? edgeType;++ /// If the font is not available in the receiver the fontGenericFamily will be used.++ final String? fontFamily;++ /// Generic font family for the text track.+ final TextTrackFontGenericFamily? fontGenericFamily;++ /// The font scaling factor for the text track (the default is 1.0).+ final int? fontScale;++ /// Font style for the text track.+ final TextTrackFontStyle? fontStyle;++ ///Foreground RGBA color, represented as "#RRGGBBAA".+ final Color? foregroundColor;++ ///RGBA color for the window, represented as+ ///"#RRGGBBAA". This value will be+ ///ignored if windowType is NONE.+ final Color? windowColor;++ ///Rounded corner radius absolute value in pixels (px).+ /// This value will be ignored if windowType+ /// is not ROUNDED_CORNERS.+ final double? windowRoundedCornerRadius;++ ///The window concept is defined in CEA-608 and CEA-708,+ /// See http://goo.gl/M3ea0X. In WebVTT is called a region.++ final TextTrackWindowType? windowType;++ /// Creates a new [TextTrackStyle].+ TextTrackStyle({+ this.backgroundColor,+ this.customData,+ this.edgeColor,+ this.edgeType,+ this.fontFamily,+ this.fontGenericFamily,+ this.fontScale,+ this.fontStyle,+ this.foregroundColor,+ this.windowColor,+ this.windowRoundedCornerRadius,+ this.windowType,+ });++ /// Converts this text track style to a map representation.+ Map<String, dynamic> toMap() {+ return {+ 'backgroundColor': backgroundColor?.hexColor,+ 'customData': customData,+ 'edgeColor': edgeColor?.hexColor,+ 'edgeType': edgeType?.toMap(),+ 'fontFamily': fontFamily,+ 'fontGenericFamily': fontGenericFamily?.name,+ 'fontScale': fontScale,+ 'fontStyle': fontStyle?.name,+ 'foregroundColor': foregroundColor?.hexColor,+ 'windowColor': windowColor?.hexColor,+ 'windowRoundedCornerRadius': windowRoundedCornerRadius,+ 'windowType': windowType?.name,+ };+ }++ /// Creates a [TextTrackStyle] from a map representation.+ factory TextTrackStyle.fromMap(Map<String, dynamic> map) {+ return TextTrackStyle(+ backgroundColor: map['backgroundColor'] != null+ ? HColor.fromHex(map['backgroundColor'])+ : null,+ customData: map['customData'] != null+ ? Map<String, dynamic>.from(map['customData'])+ : null,+ edgeColor:+ map['edgeColor'] != null ? HColor.fromHex(map['edgeColor']) : null,+ edgeType: map['edgeType'] != null+ ? TextTrackStyle.fromMap(map['edgeType'])+ : null,+ fontFamily: map['fontFamily'],+ fontGenericFamily: map['fontGenericFamily'] != null+ ? TextTrackFontGenericFamily.fromMap(map['fontGenericFamily'])+ : null,+ fontScale: map['fontScale']?.toInt(),+ fontStyle: map['fontStyle'] != null+ ? TextTrackFontStyle.fromMap(map['fontStyle'])+ : null,+ foregroundColor: map['foregroundColor'] != null+ ? HColor.fromHex(map['foregroundColor'])+ : null,+ windowColor: map['windowColor'] != null+ ? HColor.fromHex(map['windowColor'])+ : null,+ windowRoundedCornerRadius: map['windowRoundedCornerRadius']?.toDouble(),+ windowType: map['windowType'] != null+ ? TextTrackWindowType.fromMap(map['windowType'])+ : null,+ );+ }++ /// Converts this text track style to a JSON string.+ String toJson() => json.encode(toMap());++ /// Creates a [TextTrackStyle] from a JSON string.+ factory TextTrackStyle.fromJson(String source) =>+ TextTrackStyle.fromMap(json.decode(source));+}++/// Extension on [Color] to provide hex color functionality.+extension HColor on Color {+ /// Gets the hex color string representation.+ String get hexColor {+ return '#${toARGB32().toRadixString(16).padLeft(8, '0')}';+ }++ /// Creates a [Color] from a hex string.+ static Color fromHex(String hexString) {+ final buffer = StringBuffer();+ if (hexString.length == 6 || hexString.length == 7) buffer.write('ff');+ buffer.write(hexString.replaceFirst('#', ''));+ return Color(int.parse(buffer.toString(), radix: 16));+ }+}diff --git a/packages/flutter_chrome_cast/lib/common/text_track_window_type.dart b/packages/flutter_chrome_cast/lib/common/text_track_window_type.dartnew file mode 100644index 00000000..83f135a0--- /dev/null+++ b/packages/flutter_chrome_cast/lib/common/text_track_window_type.dart@@ -0,0 +1,29 @@+///Possible text track window types.+enum TextTrackWindowType {+ /// No window background.+ none,++ /// Normal rectangular window.+ normal,++ /// Window with rounded corners.+ roundedCorners;++ factory TextTrackWindowType.fromMap(String value) {+ // Try matching by name (lowerCamelCase)+ for (final v in values) {+ if (v.name == value) return v;+ }+ // Fallback: match legacy UPPER_SNAKE_CASE+ switch (value) {+ case 'NONE':+ return TextTrackWindowType.none;+ case 'NORMAL':+ return TextTrackWindowType.normal;+ case 'ROUNDED_CORNERS':+ return TextTrackWindowType.roundedCorners;+ default:+ return TextTrackWindowType.none;+ }+ }+}diff --git a/packages/flutter_chrome_cast/lib/common/user_action.dart b/packages/flutter_chrome_cast/lib/common/user_action.dartnew file mode 100644index 00000000..d6bde74b--- /dev/null+++ b/packages/flutter_chrome_cast/lib/common/user_action.dart@@ -0,0 +1,39 @@+/// User actions.+enum UserAction {+ /// User indicates a like preference for the currently playing content.+ like,++ /// User indicates a dislike preference for the currently playing content.+ dislike,++ /// User wants to follow or star currently playing content.+ follow,++ /// User wants to stop following currently playing content.+ unfollow;++ factory UserAction.fromMap(String value) {+ // Try matching by name (lowerCamelCase)+ for (final v in values) {+ if (v.name == value) return v;+ }+ // Fallback: match legacy UPPER_SNAKE_CASE+ switch (value) {+ case 'LIKE':+ return UserAction.like;+ case 'DISLIKE':+ return UserAction.dislike;+ case 'FOLLOW':+ return UserAction.follow;+ case 'UNFOLLOW':+ return UserAction.unfollow;+ default:+ throw ArgumentError('Unknown UserAction: $value');+ }+ }++ @override+ String toString() {+ return name;+ }+}diff --git a/packages/flutter_chrome_cast/lib/common/user_action_state.dart b/packages/flutter_chrome_cast/lib/common/user_action_state.dartnew file mode 100644index 00000000..4c2af2bd--- /dev/null+++ b/packages/flutter_chrome_cast/lib/common/user_action_state.dart@@ -0,0 +1,56 @@+import 'dart:convert';++import 'package:flutter_chrome_cast/common/user_action.dart';++/// Represents the state of a user action in a cast session.+class UserActionState {+ ///User actions custom data.+ final Map<String, dynamic>? customData;++ /// The user action associated with this state.+ final UserAction? userAction;++ /// Creates a new [UserActionState] instance.+ ///+ /// [customData] - Custom data associated with the user action.+ /// [userAction] - The user action.+ UserActionState({+ this.customData,+ this.userAction,+ });++ /// Converts the [UserActionState] to a map.+ ///+ /// Returns a [Map] representation of this object.+ Map<String, dynamic> toMap() {+ return {+ 'customData': customData,+ 'userAction': userAction?.name,+ };+ }++ /// Creates a [UserActionState] from a map.+ ///+ /// [map] - The map to create the instance from.+ factory UserActionState.fromMap(Map<String, dynamic> map) {+ return UserActionState(+ customData: map['customData'] != null+ ? Map<String, dynamic>.from(map['customData'])+ : null,+ userAction: map['userAction'] != null+ ? UserAction.fromMap(map['userAction'])+ : null,+ );+ }++ /// Converts the [UserActionState] to a JSON string.+ ///+ /// Returns a JSON string representation of this object.+ String toJson() => json.encode(toMap());++ /// Creates a [UserActionState] from a JSON string.+ ///+ /// [source] - The JSON string to create the instance from.+ factory UserActionState.fromJson(String source) =>+ UserActionState.fromMap(json.decode(source));+}diff --git a/packages/flutter_chrome_cast/lib/common/vast_ads_request.dart b/packages/flutter_chrome_cast/lib/common/vast_ads_request.dartnew file mode 100644index 00000000..8d62db1b--- /dev/null+++ b/packages/flutter_chrome_cast/lib/common/vast_ads_request.dart@@ -0,0 +1,56 @@+import 'dart:convert';++///VAST ad request configuration.+class VastAdsRequest {+ /// Specifies a VAST document to be used as+ /// the ads response instead of making a request+ /// via an ad tag URL. This can be useful for debugging+ /// and other situations where a VAST+ /// response is already available.++ final String? adsResponse;++ /// URL for VAST file.++ final String? adTagUrl;++ /// Creates a new [VastAdsRequest] instance.+ ///+ /// [adsResponse] - Specifies a VAST document to be used as the ads response.+ /// [adTagUrl] - URL for VAST file.+ VastAdsRequest({+ this.adsResponse,+ this.adTagUrl,+ });++ /// Converts the [VastAdsRequest] to a map.+ ///+ /// Returns a [Map] representation of this object.+ Map<String, dynamic> toMap() {+ return {+ 'adsResponse': adsResponse,+ 'adTagUrl': adTagUrl,+ };+ }++ /// Creates a [VastAdsRequest] from a map.+ ///+ /// [map] - The map to create the instance from.+ factory VastAdsRequest.fromMap(Map<String, dynamic> map) {+ return VastAdsRequest(+ adsResponse: map['adsResponse'],+ adTagUrl: map['adTagUrl'],+ );+ }++ /// Converts the [VastAdsRequest] to a JSON string.+ ///+ /// Returns a JSON string representation of this object.+ String toJson() => json.encode(toMap());++ /// Creates a [VastAdsRequest] from a JSON string.+ ///+ /// [source] - The JSON string to create the instance from.+ factory VastAdsRequest.fromJson(String source) =>+ VastAdsRequest.fromMap(json.decode(source));+}diff --git a/packages/flutter_chrome_cast/lib/common/volume.dart b/packages/flutter_chrome_cast/lib/common/volume.dartnew file mode 100644index 00000000..0f3d2634--- /dev/null+++ b/packages/flutter_chrome_cast/lib/common/volume.dart@@ -0,0 +1,56 @@+import 'dart:convert';++/// Represents the volume settings for a cast media session.+class CastMediaVolume {+ ///Optional current stream volume level as+ /// a value between 0.0 and 1.0 where 1.0+ /// is the maximum volume.+ num? level;++ ///Optional whether the Cast device is muted,+ /// independent of the volume level.+ bool? muted;++ /// Creates a new [CastMediaVolume] instance.+ ///+ /// [level] - The volume level between 0.0 and 1.0.+ /// [muted] - Whether the volume is muted.+ ///+ /// Throws an assertion error if level is not between 0 and 1.+ CastMediaVolume(this.level, this.muted)+ : assert(+ level == null || (level >= 0 && level <= 1),+ 'level must be between 0 and 1',+ );++ /// Converts the [CastMediaVolume] to a map.+ ///+ /// Returns a [Map] representation of this object.+ Map<String, dynamic> toMap() {+ return {+ 'level': level,+ 'muted': muted,+ };+ }++ /// Creates a [CastMediaVolume] from a map.+ ///+ /// [map] - The map to create the instance from.+ factory CastMediaVolume.fromMap(Map<String, dynamic> map) {+ return CastMediaVolume(+ map['level'],+ map['muted'],+ );+ }++ /// Converts the [CastMediaVolume] to a JSON string.+ ///+ /// Returns a JSON string representation of this object.+ String toJson() => json.encode(toMap());++ /// Creates a [CastMediaVolume] from a JSON string.+ ///+ /// [source] - The JSON string to create the instance from.+ factory CastMediaVolume.fromJson(String source) =>+ CastMediaVolume.fromMap(json.decode(source));+}diff --git a/packages/flutter_chrome_cast/lib/discovery.dart b/packages/flutter_chrome_cast/lib/discovery.dartnew file mode 100644index 00000000..9ddf21d7--- /dev/null+++ b/packages/flutter_chrome_cast/lib/discovery.dart@@ -0,0 +1,6 @@+/// Device Discovery functionality+///+/// This module provides access to device discovery features.+library discovery;++export '_discovery_manager/_discovery_manager.dart';diff --git a/packages/flutter_chrome_cast/lib/entities.dart b/packages/flutter_chrome_cast/lib/entities.dartnew file mode 100644index 00000000..74bc7086--- /dev/null+++ b/packages/flutter_chrome_cast/lib/entities.dart@@ -0,0 +1,6 @@+/// Entities for Chrome Cast+///+/// This module provides access to all entities.+library entities;++export 'entities/entities.dart';diff --git a/packages/flutter_chrome_cast/lib/entities/break_status.dart b/packages/flutter_chrome_cast/lib/entities/break_status.dartnew file mode 100644index 00000000..9a37fe4a--- /dev/null+++ b/packages/flutter_chrome_cast/lib/entities/break_status.dart@@ -0,0 +1,68 @@+import 'dart:convert';++/// Represents current status of a break, including IDs and timing information.+class GoogleCastBrakeStatus {+ /// ID of the current break clip.+ final String? breakClipId;++ /// ID of the current break.+ final String? breakId;++ /// Time in seconds elapsed after the current break clip starts.+ /// This member is only updated sporadically, so its value is often out of date.+ /// Use the getEstimatedBreakClipTime method to get an estimate of the real playback position.+ final Duration? currentBreakClipTime;++ /// Time in seconds elapsed after the current break starts.+ /// This member is only updated sporadically, so its value is often out of date.+ /// Use the getEstimatedBreakTime method to get an estimate of the real playback position.+ final Duration? currentBreakTime;++ /// The time in seconds when this break clip becomes skippable.+ /// If not defined, the current break clip is not skippable.+ final Duration? whenSkippable;++ /// Creates a new [GoogleCastBrakeStatus] instance.+ GoogleCastBrakeStatus({+ this.breakClipId,+ this.breakId,+ this.currentBreakClipTime,+ this.currentBreakTime,+ this.whenSkippable,+ });++ /// Converts the object to a map for serialization.+ Map<String, dynamic> toMap() {+ return {+ 'breakClipId': breakClipId,+ 'breakId': breakId,+ 'currentBreakClipTime': currentBreakClipTime?.inSeconds,+ 'currentBreakTime': currentBreakTime?.inSeconds,+ 'whenSkippable': whenSkippable?.inSeconds,+ };+ }++ /// Creates a [GoogleCastBrakeStatus] from a map.+ factory GoogleCastBrakeStatus.fromMap(Map<String, dynamic> map) {+ return GoogleCastBrakeStatus(+ breakClipId: map['breakClipId'],+ breakId: map['breakId'],+ currentBreakClipTime: map['currentBreakClipTime'] != null+ ? Duration(seconds: map['currentBreakClipTime'].toInt())+ : null,+ currentBreakTime: map['currentBreakTime'] != null+ ? Duration(seconds: map['currentBreakTime'].toInt())+ : null,+ whenSkippable: map['whenSkippable'] != null+ ? Duration(seconds: map['whenSkippable'].toInt())+ : null,+ );+ }++ /// Converts the object to a JSON string.+ String toJson() => json.encode(toMap());++ /// Creates a [GoogleCastBrakeStatus] from a JSON string.+ factory GoogleCastBrakeStatus.fromJson(String source) =>+ GoogleCastBrakeStatus.fromMap(json.decode(source));+}diff --git a/packages/flutter_chrome_cast/lib/entities/cast_device.dart b/packages/flutter_chrome_cast/lib/entities/cast_device.dartnew file mode 100644index 00000000..46ff616c--- /dev/null+++ b/packages/flutter_chrome_cast/lib/entities/cast_device.dart@@ -0,0 +1,55 @@+/// Represents a Google Cast device discovered on the network.+///+/// This class contains all the information about a Cast-capable device+/// that has been discovered during the device discovery process.+class GoogleCastDevice {+ /// Unique identifier for the device.+ final String deviceID;++ /// Human-readable name of the device (e.g., "Living Room TV").+ final String friendlyName;++ /// Model name of the device (e.g., "Chromecast", "Google Home").+ final String? modelName;++ /// Current status text displayed by the device.+ final String? statusText;++ /// Version information of the device firmware/software.+ final String deviceVersion;++ /// Whether the device is on the same local network.+ final bool isOnLocalNetwork;++ /// Category or type of the device.+ final String category;++ /// Globally unique identifier for the device.+ final String uniqueID;++ /// Creates a new Google Cast device instance.+ ///+ /// All parameters except [modelName] and [statusText] are required.+ GoogleCastDevice({+ required this.deviceID,+ required this.friendlyName,+ required this.modelName,+ required this.statusText,+ required this.deviceVersion,+ required this.isOnLocalNetwork,+ required this.category,+ required this.uniqueID,+ });++ @override+ bool operator ==(Object other) {+ if (identical(this, other)) return true;++ return other is GoogleCastDevice && other.deviceID == deviceID;+ }++ @override+ int get hashCode {+ return deviceID.hashCode;+ }+}diff --git a/packages/flutter_chrome_cast/lib/entities/cast_media_status.dart b/packages/flutter_chrome_cast/lib/entities/cast_media_status.dartnew file mode 100644index 00000000..678bd066--- /dev/null+++ b/packages/flutter_chrome_cast/lib/entities/cast_media_status.dart@@ -0,0 +1,78 @@+import 'package:flutter_chrome_cast/common/live_seekable_range.dart';+import 'package:flutter_chrome_cast/enums/repeat_mode.dart';+import 'package:flutter_chrome_cast/entities/media_information.dart';+import 'package:flutter_chrome_cast/enums/idle_reason.dart';+import 'package:flutter_chrome_cast/enums/player_state.dart';+import 'break_status.dart';++/// Represents the status of a media session, including player state, volume, repeat mode, and more.+class GoggleCastMediaStatus {+ /// Unique ID for the playback of this specific session.+ final int mediaSessionID;++ /// Describes the state of the player as one of the following: [CastMediaPlayerState].+ final CastMediaPlayerState playerState;++ /// If the playerState is IDLE and the reason it became IDLE is known, this property is provided.+ final GoogleCastMediaIdleReason? idleReason;++ /// Indicates whether the media time is progressing, and at what rate.+ /// 1.0 is regular time, 0.5 is slow motion.+ final num playbackRate;++ /// The media information for the current session.+ final GoogleCastMediaInformation? mediaInformation;++ /// The current position of the media player since the beginning of the content, in seconds.+ /// For live streams, this is the time from the beginning of the event.+ final num volume;++ /// The stream muted state.+ final bool isMuted;++ /// The repeat mode for playing the queue.+ final GoogleCastMediaRepeatMode repeatMode;++ /// Item ID of the item that was active in the queue (it may not be playing)+ /// at the time the media status change happened.+ final int? currentItemId;++ /// List of IDs corresponding to the active Tracks.+ final List<int>? activeTrackIds;++ /// Status of a break when a break is playing+ /// on the receiver. This field will be+ /// defined when the receiver is playing+ /// a break, empty when a break is not playing,+ /// but is present in the content, and+ /// undefined if the content contains+ /// no breaks.+ final GoogleCastBrakeStatus? adBreakStatus;++ /// Seekable range of a live or event stream. I+ /// t uses relative media time in seconds.+ /// It will be undefined for VOD streams.+ final GoogleCastMediaLiveSeekableRange? liveSeekableRange;++ /// Item ID of the item that is currently loading+ /// on the receiver. Null if no item is currently+ /// loading.++ /// Queue data+ // final GoogleCastMediaQueueData? queueData;+ GoggleCastMediaStatus({+ required this.mediaSessionID,+ required this.playerState,+ this.idleReason,+ required this.playbackRate,+ this.mediaInformation,+ required this.volume,+ required this.isMuted,+ required this.repeatMode,+ this.currentItemId,+ this.activeTrackIds,+ this.adBreakStatus,+ this.liveSeekableRange,+ // this.queueData,+ });+}diff --git a/packages/flutter_chrome_cast/lib/entities/cast_options.dart b/packages/flutter_chrome_cast/lib/entities/cast_options.dartnew file mode 100644index 00000000..fc826918--- /dev/null+++ b/packages/flutter_chrome_cast/lib/entities/cast_options.dart@@ -0,0 +1,61 @@+/// Configuration options for Google Cast functionality.+class GoogleCastOptions {+ /// Whether physical volume buttons will control device volume.+ final bool physicalVolumeButtonsWillControlDeviceVolume;++ /// Whether to disable discovery autostart.+ final bool disableDiscoveryAutostart;++ /// Whether to disable analytics logging.+ final bool disableAnalyticsLogging;++ /// Whether to suspend sessions when backgrounded.+ final bool suspendSessionsWhenBackgrounded;++ /// Whether to stop receiver application when ending session.+ final bool stopReceiverApplicationWhenEndingSession;++ /// Whether to start discovery after first tap on cast button.+ final bool startDiscoveryAfterFirstTapOnCastButton;++ /// Whether to automatically stop casting and end the session when the app is killed/terminated.+ ///+ /// When set to `true`, the plugin will automatically call `endSessionAndStopCasting()`+ /// when the app is terminated (killed by user or system). This ensures the Chromecast+ /// device stops playing when the app is closed.+ ///+ /// When set to `false` (default), casting will continue on the receiver device even+ /// after the app is killed, allowing the user to resume control later.+ ///+ /// Note: This works for normal app closure and most system-initiated kills.+ /// Force-kills (swipe away from recent apps) may not always trigger this behavior+ /// depending on the platform and circumstances.+ final bool stopCastingOnAppTerminated;++ /// Creates a new [GoogleCastOptions] instance.+ GoogleCastOptions({+ this.physicalVolumeButtonsWillControlDeviceVolume = true,+ this.disableDiscoveryAutostart = false,+ this.disableAnalyticsLogging = false,+ this.suspendSessionsWhenBackgrounded = true,+ this.stopReceiverApplicationWhenEndingSession = false,+ this.startDiscoveryAfterFirstTapOnCastButton = true,+ this.stopCastingOnAppTerminated = false,+ });++ /// Converts this options object to a map representation.+ Map<String, dynamic> toMap() {+ return {+ 'physicalVolumeButtonsWillControlDeviceVolume':+ physicalVolumeButtonsWillControlDeviceVolume,+ 'disableDiscoveryAutostart': disableDiscoveryAutostart,+ 'disableAnalyticsLogging': disableAnalyticsLogging,+ 'suspendSessionsWhenBackgrounded': suspendSessionsWhenBackgrounded,+ 'stopReceiverApplicationWhenEndingSession':+ stopReceiverApplicationWhenEndingSession,+ 'startDiscoveryAfterFirstTapOnCastButton':+ startDiscoveryAfterFirstTapOnCastButton,+ 'stopCastingOnAppTerminated': stopCastingOnAppTerminated,+ };+ }+}diff --git a/packages/flutter_chrome_cast/lib/entities/cast_session.dart b/packages/flutter_chrome_cast/lib/entities/cast_session.dartnew file mode 100644index 00000000..d89b7548--- /dev/null+++ b/packages/flutter_chrome_cast/lib/entities/cast_session.dart@@ -0,0 +1,33 @@+import 'package:flutter_chrome_cast/entities/cast_device.dart';+import 'package:flutter_chrome_cast/enums/connection_state.dart';++/// Represents a Google Cast session.+abstract class GoogleCastSession {+ /// The device associated with this session.+ final GoogleCastDevice? device;++ /// The unique session ID.+ final String? sessionID;++ /// The current connection state.+ final GoogleCastConnectState connectionState;++ /// Whether the current device is muted.+ final bool currentDeviceMuted;++ /// The current device volume level.+ final double currentDeviceVolume;++ /// The device status text.+ final String deviceStatusText;++ /// Creates a new [GoogleCastSession].+ GoogleCastSession({+ required this.device,+ required this.sessionID,+ required this.connectionState,+ required this.currentDeviceMuted,+ required this.currentDeviceVolume,+ required this.deviceStatusText,+ });+}diff --git a/packages/flutter_chrome_cast/lib/entities/discovery_criteria.dart b/packages/flutter_chrome_cast/lib/entities/discovery_criteria.dartnew file mode 100644index 00000000..fd73f859--- /dev/null+++ b/packages/flutter_chrome_cast/lib/entities/discovery_criteria.dart@@ -0,0 +1,63 @@+/// Represents criteria for discovering Google Cast devices.+abstract class GoogleCastDiscoveryCriteria {+ /// Initializes discovery criteria with the provided configuration.+ static GoogleCastDiscoveryCriteriaInitialize initialize(+ GoogleCastDiscoveryCriteriaInitialize initializeWith) =>+ initializeWith;++ /// this command is useful to native execute a custom command++ /// Default application ID for Cast devices.+ static const String kDefaultApplicationId = 'CC1AD845';++ /// Set of application IDs to discover.+ Set<String>? get applicationIds;++ /// Whether application IDs are set.+ bool? get hasApplicationIds;++ /// Set of namespaces to discover.+ Set<String>? get namespaces;++ /// Whether namespaces are set.+ bool? get hasNamespaces;++ /// Set of all subtypes.+ Set<String>? get allSubtypes;+}++/// Provides initialization options for Google Cast discovery criteria.+class GoogleCastDiscoveryCriteriaInitialize {+ /// The data map containing discovery configuration.+ final Map<String, dynamic> data;++ /// Creates a new [GoogleCastDiscoveryCriteriaInitialize] with the given data.+ GoogleCastDiscoveryCriteriaInitialize._({+ required this.data,+ });++ /// Initializes with an application ID.+ factory GoogleCastDiscoveryCriteriaInitialize.initWithApplicationID(+ String applicationID) {+ return GoogleCastDiscoveryCriteriaInitialize._(+ data: <String, dynamic>{+ 'method': 'initWithApplicationID',+ 'applicationID': applicationID,+ },+ );+ }++ /// Initializes with a set of namespaces.+ factory GoogleCastDiscoveryCriteriaInitialize.initWithNamespaces(+ Set<String> namespaces) {+ return GoogleCastDiscoveryCriteriaInitialize._(+ data: <String, dynamic>{+ 'method': 'initWithNamespaces',+ 'namespaces': namespaces,+ },+ );+ }++ /// Converts the object to a map for serialization.+ Map<String, dynamic> toMap() => data;+}diff --git a/packages/flutter_chrome_cast/lib/entities/entities.dart b/packages/flutter_chrome_cast/lib/entities/entities.dartnew file mode 100644index 00000000..60061081--- /dev/null+++ b/packages/flutter_chrome_cast/lib/entities/entities.dart@@ -0,0 +1,13 @@+export 'break_status.dart';+export 'cast_device.dart';+export 'cast_media_status.dart';+export 'cast_options.dart';+export 'cast_session.dart';+export 'discovery_criteria.dart';+export 'load_options.dart';+export 'media_information.dart';+export 'media_metadata/media_metadata.dart';+export 'media_seek_option.dart';+export 'queue_item.dart';+export 'request.dart';+export 'track.dart';diff --git a/packages/flutter_chrome_cast/lib/entities/load_options.dart b/packages/flutter_chrome_cast/lib/entities/load_options.dartnew file mode 100644index 00000000..ff099a0b--- /dev/null+++ b/packages/flutter_chrome_cast/lib/entities/load_options.dart@@ -0,0 +1,34 @@+import 'package:flutter_chrome_cast/enums/repeat_mode.dart';++/// Configuration options for loading queue items in Google Cast.+class GoogleCastQueueLoadOptions {+ /// Starting index in the queue.+ final int startIndex;++ /// Position to start playback.+ final Duration playPosition;++ /// Repeat mode for the queue.+ final GoogleCastMediaRepeatMode repeatMode;++ /// Custom data to send with the request.+ final Map<String, dynamic>? customData;++ /// Creates a new [GoogleCastQueueLoadOptions].+ GoogleCastQueueLoadOptions({+ this.startIndex = 0,+ this.playPosition = Duration.zero,+ this.repeatMode = GoogleCastMediaRepeatMode.off,+ this.customData,+ });++ /// Converts these options to a map representation.+ Map<String, dynamic> toMap({bool android = false}) {+ return {+ 'startIndex': startIndex,+ 'playPosition': playPosition.inSeconds,+ 'repeatMode': repeatMode.value,+ 'customData': customData,+ };+ }+}diff --git a/packages/flutter_chrome_cast/lib/entities/media_information.dart b/packages/flutter_chrome_cast/lib/entities/media_information.dartnew file mode 100644index 00000000..9996ddf0--- /dev/null+++ b/packages/flutter_chrome_cast/lib/entities/media_information.dart@@ -0,0 +1,157 @@+import 'package:flutter_chrome_cast/common/break.dart';+import 'package:flutter_chrome_cast/common/break_clips.dart';+import 'package:flutter_chrome_cast/common/hls_segment_format.dart';+import 'package:flutter_chrome_cast/common/hls_video_segment_format.dart';+import 'package:flutter_chrome_cast/common/text_track_style.dart';+import 'package:flutter_chrome_cast/entities/track.dart';+import 'package:flutter_chrome_cast/common/user_action_state.dart';+import 'package:flutter_chrome_cast/common/vast_ads_request.dart';+import 'package:flutter_chrome_cast/enums/stream_type.dart';++import 'media_metadata/cast_media_metadata.dart';++export 'package:flutter_chrome_cast/common/break.dart';+export 'package:flutter_chrome_cast/common/break_clips.dart';+export 'package:flutter_chrome_cast/common/hls_segment_format.dart';+export 'package:flutter_chrome_cast/common/hls_video_segment_format.dart';+export 'package:flutter_chrome_cast/common/text_track_style.dart';+export 'package:flutter_chrome_cast/entities/track.dart';+export 'package:flutter_chrome_cast/common/user_action_state.dart';+export 'package:flutter_chrome_cast/common/vast_ads_request.dart';+export 'package:flutter_chrome_cast/enums/stream_type.dart';++/// Holds all metadata and configuration for a media item, including content ID, type, metadata, breaks, tracks, and more.+class GoogleCastMediaInformation {+ /// Alternate entity to be used to load the media in Android TV app.+ /// If set, this will override the value set in entity if the+ /// receiver is an Android TV app. On the receiver side, the+ /// entity can be accessed from MediaInfo#getEntity().+ final String? atvEntity;++ /// Partial list of break clips that includes current break clip that receiver is playing or ones that receiver will play shortly after.+ /// This is to avoid overflow of MediaStatus message.+ final List<CastBreakClips>? breakClips;++ /// Service-specific identifier of the content currently loaded by the media player.+ /// This is a free form string and is specific+ /// to the application. In most cases, this will be the URL to the+ /// media, but the sender can choose to pass a string that the receiver can+ /// interpret properly. Max length: 1k+ final String contentId;++ /// Describes the type of media artifact as one of the following:++ /// NONE+ /// BUFFERED+ /// LIVE+ final CastMediaStreamType streamType;++ /// MIME content type of the media being played.+ final String contentType;++ /// The media metadata object, one of the following:++ /// 0 GenericMediaMetadata+ /// 1 MovieMediaMetadata+ /// 2 TvShowMediaMetadata+ /// 3 MusicTrackMediaMetadata+ /// 4 PhotoMediaMetadata+ final GoogleCastMediaMetadata? metadata;++ /// Optional duration of the currently playing stream in seconds.+ final Duration? duration;++ /// Optional application-specific blob of data defined by either the sender application or the receiver application+ final Map<String, dynamic>? customData;++ /// List of breaks.+ final List<CastBreak>? breaks;++ /// Optional media URL, to allow using contentId for real ID.+ /// If contentUrl is provided, it will be used+ /// as media URL, otherwise the contentId will+ /// be used as the media URL.+ final Uri? contentUrl;++ /// Optional media entity, commonly a Google Assistant deep link.++ final String? entity;++ /// The format of the HLS audio segment.+ final CastHlsSegmentFormat? hlsSegmentFormat;++ /// The format of the HLS video segment.+ final HlsVideoSegmentFormat? hlsVideoSegmentFormat;++ /// Provides absolute time (Epoch Unix time in seconds)+ /// for live streams. For live event it+ /// would be the time the event started,+ /// otherwise it will be start of the+ /// seekable range when the streaming started.++ final DateTime? startAbsoluteTime;++ /// The requested text track style. If not provided,+ /// the device style preferences (if existing) will be used.++ final TextTrackStyle? textTrackStyle;++ /// Array of Track objects.+ final List<GoogleCastMediaTrack>? tracks;++ /// Indicates the user action state for media.+ /// Indicate user like, dislike, or+ /// follow actions for the media.++ final List<UserActionState>? userActionStates;++ /// VMAP ad request configuration. Used if breaks and breakClips are not provided.++ final VastAdsRequest? vmapAdsRequest;++ /// Creates a new [GoogleCastMediaInformation] instance.+ GoogleCastMediaInformation({+ this.atvEntity,+ this.breakClips,+ required this.contentId,+ required this.streamType,+ required this.contentType,+ this.metadata,+ this.duration,+ this.customData,+ this.breaks,+ this.contentUrl,+ this.entity,+ this.hlsSegmentFormat,+ this.hlsVideoSegmentFormat,+ this.startAbsoluteTime,+ this.textTrackStyle,+ this.tracks,+ this.userActionStates,+ this.vmapAdsRequest,+ });++ /// Converts the object to a map for serialization.+ Map<String, dynamic> toMap() {+ return {+ 'atvEntity': atvEntity,+ 'breakClips': breakClips?.map((x) => x.toMap()).toList(),+ 'contentID': contentId,+ 'streamType': streamType.value,+ 'contentType': contentType,+ 'metadata': metadata?.toMap(),+ 'duration': duration?.inSeconds,+ 'customData': customData,+ 'breaks': breaks?.map((x) => x.toMap()).toList(),+ 'contentURL': contentUrl?.toString(),+ 'entity': entity,+ 'hlsSegmentFormat': hlsSegmentFormat?.name,+ 'hlsVideoSegmentFormat': hlsVideoSegmentFormat?.name,+ 'startAbsoluteTime': startAbsoluteTime?.millisecondsSinceEpoch,+ 'textTrackStyle': textTrackStyle?.toMap(),+ 'tracks': tracks?.map((x) => x.toMap()).toList(),+ 'userActionStates': userActionStates?.map((x) => x.toMap()).toList(),+ 'vmapAdsRequest': vmapAdsRequest?.toMap(),+ }..removeWhere((key, value) => value == null);+ }+}diff --git a/packages/flutter_chrome_cast/lib/entities/media_metadata/cast_media_metadata.dart b/packages/flutter_chrome_cast/lib/entities/media_metadata/cast_media_metadata.dartnew file mode 100644index 00000000..7782147d--- /dev/null+++ b/packages/flutter_chrome_cast/lib/entities/media_metadata/cast_media_metadata.dart@@ -0,0 +1,25 @@+import 'package:flutter_chrome_cast/common/image.dart';+import 'package:flutter_chrome_cast/enums/media_metadata_type.dart';++/// Holds metadata type and images for a media item.+class GoogleCastMediaMetadata {+ /// The type of media metadata.+ final GoogleCastMediaMetadataType metadataType;++ /// List of images associated with the media.+ final List<GoogleCastImage>? images;++ /// Creates a new [GoogleCastMediaMetadata] instance.+ GoogleCastMediaMetadata({+ required this.metadataType,+ this.images,+ });++ /// Converts the object to a map for serialization.+ Map<String, dynamic> toMap() {+ return {+ 'metadataType': metadataType.value,+ 'images': images?.map((x) => x.toMap()).toList(),+ };+ }+}diff --git a/packages/flutter_chrome_cast/lib/entities/media_metadata/generic_media_metadata.dart b/packages/flutter_chrome_cast/lib/entities/media_metadata/generic_media_metadata.dartnew file mode 100644index 00000000..c74db7b8--- /dev/null+++ b/packages/flutter_chrome_cast/lib/entities/media_metadata/generic_media_metadata.dart@@ -0,0 +1,46 @@+import 'package:flutter_chrome_cast/enums/media_metadata_type.dart';+import 'cast_media_metadata.dart';++///Describes a generic media artifact.+class GoogleCastGenericMediaMetadata extends GoogleCastMediaMetadata {+ ///optional Descriptive title of the content.+ /// Player can independently retrieve title+ /// using content_id or it can be given by+ /// the sender in the Load message+ final String? title;++ /// optional Descriptive subtitle of the content.+ /// Player can independently retrieve title using+ /// content_id or it can be given by the sender+ /// in the Load message+ final String? subtitle;++ ///optional Array of URL(s) to an image associated with the content.+ ///The initial value of the field can be provided by the sender in the+ ///Load message. Should provide recommended sizes++ ///optional ISO 8601 date and time+ /// this content was released. Player can+ /// independently retrieve title using+ /// content_id or it can be given+ /// by the sender in the Load message+ final DateTime? releaseDate;++ /// Creates a generic media metadata instance.+ GoogleCastGenericMediaMetadata({+ this.title,+ this.subtitle,+ super.images,+ this.releaseDate,+ }) : super(metadataType: GoogleCastMediaMetadataType.genericMediaMetadata);+ @override+ Map<String, dynamic> toMap() {+ return {+ 'metadataType': metadataType.value,+ 'title': title,+ 'subtitle': subtitle,+ 'images': images?.map((x) => x.toMap()).toList(),+ 'releaseDate': releaseDate?.millisecondsSinceEpoch,+ }..removeWhere((key, value) => value == null);+ }+}diff --git a/packages/flutter_chrome_cast/lib/entities/media_metadata/media_metadata.dart b/packages/flutter_chrome_cast/lib/entities/media_metadata/media_metadata.dartnew file mode 100644index 00000000..4eb39373--- /dev/null+++ b/packages/flutter_chrome_cast/lib/entities/media_metadata/media_metadata.dart@@ -0,0 +1,6 @@+export 'cast_media_metadata.dart';+export 'generic_media_metadata.dart';+export 'movie_media_metadata.dart';+export 'music_track_media_metadata.dart';+export 'photo_media_metadata.dart';+export 'tv_show_media_metadata.dart';diff --git a/packages/flutter_chrome_cast/lib/entities/media_metadata/movie_media_metadata.dart b/packages/flutter_chrome_cast/lib/entities/media_metadata/movie_media_metadata.dartnew file mode 100644index 00000000..6310d2da--- /dev/null+++ b/packages/flutter_chrome_cast/lib/entities/media_metadata/movie_media_metadata.dart@@ -0,0 +1,61 @@+import 'package:flutter_chrome_cast/enums/media_metadata_type.dart';++import 'cast_media_metadata.dart';++///Describes a movie media artifact.+class GoogleCastMovieMediaMetadata extends GoogleCastMediaMetadata {+ /// Creates a movie media metadata instance.+ GoogleCastMovieMediaMetadata({+ this.title,+ this.subtitle,+ this.studio,+ super.images,+ this.releaseDate,+ }) : super(+ metadataType: GoogleCastMediaMetadataType.movieMediaMetadata,+ );++ /// optional Descriptive title+ /// of the content. Player can+ /// independently retrieve title using+ /// content_id or it can be given by+ /// the sender in the Load message+ final String? title;++ ///optional Descriptive subtitle+ /// of the content. Player can+ /// independently retrieve title+ /// using content_id or it can be+ /// given by the sender in+ /// the Load message+ final String? subtitle;++ ///optional Studio which released the content.+ /// Player can independently retrieve studio+ /// using content_id or it can be given by+ /// the sender in the Load message+ final String? studio;++ /// optional Array of URL(s) to an image associated+ /// with the content. The initial value of the field+ /// can be provided by the sender in the Load message.+ /// Should provide recommended sizes++ ///optional ISO 8601 date and time this content+ ///was released. Player can independently retrieve+ ///title using content_id or it can be given by the+ /// sender in the Load message+ final DateTime? releaseDate;++ @override+ Map<String, dynamic> toMap() {+ return {+ 'metadataType': metadataType.value,+ 'title': title,+ 'subtitle': subtitle,+ 'studio': studio,+ 'images': images?.map((x) => x.toMap()).toList(),+ 'releaseDate': releaseDate?.millisecondsSinceEpoch,+ };+ }+}diff --git a/packages/flutter_chrome_cast/lib/entities/media_metadata/music_track_media_metadata.dart b/packages/flutter_chrome_cast/lib/entities/media_metadata/music_track_media_metadata.dartnew file mode 100644index 00000000..36d50be3--- /dev/null+++ b/packages/flutter_chrome_cast/lib/entities/media_metadata/music_track_media_metadata.dart@@ -0,0 +1,85 @@+import 'package:flutter_chrome_cast/enums/media_metadata_type.dart';++import 'cast_media_metadata.dart';++///Describes a music track media artifact.+class GoogleCastMusicMediaMetadata extends GoogleCastMediaMetadata {+ /// Creates a music track media metadata instance.+ GoogleCastMusicMediaMetadata({+ this.albumName,+ this.title,+ this.albumArtist,+ this.artist,+ this.composer,+ this.trackNumber,+ this.discNumber,+ super.images,+ this.releaseDate,+ }) : super(metadataType: GoogleCastMediaMetadataType.musicTrackMediaMetadata);++ /// optional Album or collection from which this track+ /// is drawn. Player can independently retrieve albumName+ /// using content_id or it can be given by the sender+ /// in the Load message+ final String? albumName;++ /// optional Name of the track+ /// (for example, song title). Player can+ /// independently retrieve title using+ /// content_id or it can be given by+ /// the sender in the Load message+ final String? title;++ ///optional Name of the artist associated with+ /// the album featuring this track. Player can+ /// independently retrieve albumArtist using+ /// content_id or it can be given by the+ /// sender in the Load message+ final String? albumArtist;++ ///optional Name of the artist associated+ /// with the media track. Player can+ /// independently retrieve artist using+ /// content_id or it can be given+ /// by the sender in the Load message+ final String? artist;++ ///optional Name of the composer associated with the+ /// media track. Player can independently retrieve+ /// composer using content_id or it can be+ /// given by the sender in the Load message+ final String? composer;++ ///optional Number of the track on the album+ final int? trackNumber;++ ///optional Number of the volume (for example, a disc) of the album+ final int? discNumber;++ ///optional Array of URL(s) to an image associated+ ///with the content. The initial value of the+ ///field can be provided by the sender in+ ///the Load message. Should provide recommended sizes++ ///optional ISO 8601 date and time+ /// this content was released. Player+ /// can independently retrieve releaseDate+ /// using content_id or it can be given+ /// by the sender in the Load message+ final DateTime? releaseDate;+ @override+ Map<String, dynamic> toMap() {+ return {+ 'metadataType': metadataType.value,+ 'albumName': albumName,+ 'title': title,+ 'albumArtist': albumArtist,+ 'artist': artist,+ 'composer': composer,+ 'trackNumber': trackNumber,+ 'discNumber': discNumber,+ 'images': images?.map((x) => x.toMap()).toList(),+ 'releaseDate': releaseDate?.millisecondsSinceEpoch,+ };+ }+}diff --git a/packages/flutter_chrome_cast/lib/entities/media_metadata/photo_media_metadata.dart b/packages/flutter_chrome_cast/lib/entities/media_metadata/photo_media_metadata.dartnew file mode 100644index 00000000..66f8a30b--- /dev/null+++ b/packages/flutter_chrome_cast/lib/entities/media_metadata/photo_media_metadata.dart@@ -0,0 +1,82 @@+import 'package:flutter_chrome_cast/lib.dart';++/// Describes a photo media artifact.+class GoogleCastPhotoMediaMetadata extends GoogleCastMediaMetadata {+ /// Creates a photo media metadata instance.+ GoogleCastPhotoMediaMetadata({+ this.title,+ this.artist,+ this.location,+ this.latitude,+ this.longitude,+ this.width,+ this.height,+ this.creationDateTime,+ }) : super(metadataType: GoogleCastMediaMetadataType.photoMediaMetadata);++ ///string optional Title of the photograph.+ /// Player can independently retrieve title+ /// using content_id or it can be given by the sender in the Load message+ final String? title;++ ///string optional Name of the photographer.+ /// Player can independently retrieve artist+ /// using content_id or it can be given by+ /// the sender in the Load message+ final String? artist;++ ///string optional Verbal location where+ /// the photograph was taken; for example,+ /// "Madrid, Spain." Player can independently+ /// retrieve location using content_id or it+ /// can be given by the sender in the Load message+ final String? location;++ ///double optional Geographical latitude+ /// value for the location where the+ /// photograph was taken. Player can independently+ /// retrieve latitude using content_id or+ /// it can be given by the sender in the Load message+ final double? latitude;++ ///double optional Geographical longitude+ ///value for the location where the photograph+ /// was taken. Player can independently retrieve+ /// longitude using content_id or it can be+ /// given by the sender in the Load message+ final double? longitude;++ ///integer optional Width in pixels of the photograph.+ /// Player can independently retrieve width using+ /// content_id or it can be given by the sender+ /// in the Load message+ final int? width;++ ///integer optional Height in pixels of the photograph.+ /// Player can independently retrieve height using+ /// content_id or it can be given by the sender+ /// in the Load message+ final int? height;++ ///string (ISO 8601) optional ISO 8601 date+ ///and time this photograph was taken. Player+ /// can independently retrieve creationDateTime+ /// using content_id or it can be given by+ /// the sender in the Load message+ final DateTime? creationDateTime;++ @override+ Map<String, dynamic> toMap() {+ return {+ 'metadataType': metadataType.value,+ 'title': title,+ 'artist': artist,+ 'location': location,+ 'latitude': latitude,+ 'longitude': longitude,+ 'width': width,+ 'height': height,+ 'creationDateTime': creationDateTime?.millisecondsSinceEpoch,+ };+ }+}diff --git a/packages/flutter_chrome_cast/lib/entities/media_metadata/tv_show_media_metadata.dart b/packages/flutter_chrome_cast/lib/entities/media_metadata/tv_show_media_metadata.dartnew file mode 100644index 00000000..04dfdda9--- /dev/null+++ b/packages/flutter_chrome_cast/lib/entities/media_metadata/tv_show_media_metadata.dart@@ -0,0 +1,56 @@+import 'package:flutter_chrome_cast/enums/media_metadata_type.dart';++import 'cast_media_metadata.dart';++///Describes a television show episode media artifact.+class GoogleCastTvShowMediaMetadata extends GoogleCastMediaMetadata {+ /// Creates a TV show media metadata instance.+ GoogleCastTvShowMediaMetadata({+ this.seriesTitle,+ this.season,+ this.episode,+ super.images,+ this.originalAirDate,+ }) : super(metadataType: GoogleCastMediaMetadataType.tvShowMediaMetadata);++ ///optional Descriptive title of the t.v. series.+ ///Player can independently retrieve title+ ///using content_id or it can be given+ /// by the sender in the Load message+ final String? seriesTitle;++ /// optional Descriptive subtitle of the t.v.+ /// episode. Player can independently retrieve+ /// title using content_id or it can be+ /// given by the sender in the Load message++ ///optional Season number of the t.v. show+ final int? season;++ ///optional Episode number (in the season) of the t.v. show+ final int? episode;++ ///optional Array of URL(s) to an image associated+ /// with the content. The initial value of the+ /// field can be provided by the sender in+ /// the Load message. Should provide recommended sizes++ ///optional ISO 8601 date and time+ /// this episode was released. Player+ /// can independently retrieve originalAirDate+ /// using content_id or it can be given+ /// by the sender in the Load message+ final DateTime? originalAirDate;++ @override+ Map<String, dynamic> toMap() {+ return {+ 'metadataType': metadataType.value,+ 'seriesTitle': seriesTitle,+ 'season': season,+ 'episode': episode,+ 'images': images?.map((x) => x.toMap()).toList(),+ 'creationDate': originalAirDate?.millisecondsSinceEpoch,+ };+ }+}diff --git a/packages/flutter_chrome_cast/lib/entities/media_seek_option.dart b/packages/flutter_chrome_cast/lib/entities/media_seek_option.dartnew file mode 100644index 00000000..bf1e58db--- /dev/null+++ b/packages/flutter_chrome_cast/lib/entities/media_seek_option.dart@@ -0,0 +1,34 @@+import 'package:flutter_chrome_cast/enums/media_resume_state.dart';++///Enum defining the media control channel resume state.+class GoogleCastMediaSeekOption {+ /// The position to seek to.+ final Duration position;++ /// Whether the seek is relative to current position.+ final bool relative;++ /// The resume state after seeking.+ final GoogleCastMediaResumeState resumeState;++ /// Whether to seek to infinity (live content).+ final bool seekToInfinity;++ /// Creates a new [GoogleCastMediaSeekOption].+ GoogleCastMediaSeekOption({+ required this.position,+ this.relative = false,+ this.resumeState = GoogleCastMediaResumeState.play,+ this.seekToInfinity = false,+ });++ /// Converts these seek options to a map representation.+ Map<String, dynamic> toMap() {+ return {+ 'position': position.inSeconds,+ 'relative': relative,+ 'resumeState': resumeState.index,+ 'seekToInfinity': seekToInfinity,+ };+ }+}diff --git a/packages/flutter_chrome_cast/lib/entities/queue_item.dart b/packages/flutter_chrome_cast/lib/entities/queue_item.dartnew file mode 100644index 00000000..2a7a07ce--- /dev/null+++ b/packages/flutter_chrome_cast/lib/entities/queue_item.dart@@ -0,0 +1,55 @@+import 'media_information.dart';++///Represents an item in a media queue.+class GoogleCastQueueItem {+ /// Array of Track trackIds that should be active. If the array is not provided, the default tracks will be active. If two incompatible trackIds are provided (for example two active audio tracks) the command will fail with INVALID_PARAMETER.+ final List<int>? activeTrackIds;++ /// Whether the media will automatically play.+ final bool autoPlay;++ /// Custom data set by the receiver application.+ final Map<String, dynamic>? customData;++ /// Unique identifier of the item in the queue. If used in chrome.cast.media.QueueLoad or chrome.cast.media.QueueInsert it must be null (as it will be assigned by the receiver when an item is first created/inserted). For other operations it is mandatory.+ final int? itemId;++ /// Media description.+ final GoogleCastMediaInformation mediaInformation;++ /// Playback duration of the item in seconds. If it is larger than the actual duration - startTime it will be limited to the actual duration - startTime. It can be negative, in such case the duration will be the actual item duration minus the duration provided. A duration of value zero effectively means that the item will not be played.+ final Duration? playbackDuration;++ /// This parameter is a hint for the receiver to preload this media item before it is played. It allows for a smooth transition between items played from the queue.+ ///The time is expressed in seconds, relative to the beginning of this item playback (usually the end of the previous item playback). Only positive values are valid. For example, if the value is 10 seconds, this item will be preloaded 10 seconds before the previous item has finished. The receiver will try to honor this value but will not guarantee it, for example if the value is larger than the previous item duration the receiver may just preload this item shortly after the previous item has started playing (there will never be two items being preloaded in parallel). Also, if an item is inserted in the queue just after the currentItem and the time to preload is higher than the time left on the currentItem, the preload will just happen as soon as possible.+ final Duration? preLoadTime;++ /// Seconds from the beginning of the media to start playback.+ final Duration? startTime;++ /// Creates a queue item instance.+ GoogleCastQueueItem({+ this.activeTrackIds,+ this.autoPlay = true,+ this.customData,+ this.itemId,+ required this.mediaInformation,+ this.playbackDuration,+ this.preLoadTime,+ this.startTime,+ });++ /// Converts the queue item to a map.+ Map<String, dynamic> toMap() {+ return {+ 'activeTrackIds': activeTrackIds,+ 'autoplay': autoPlay,+ 'customData': customData,+ 'itemId': itemId,+ 'media': mediaInformation.toMap(),+ 'playbackDuration': playbackDuration?.inSeconds,+ 'preloadTime': preLoadTime?.inSeconds,+ 'startTime': startTime?.inSeconds,+ }..removeWhere((key, value) => value == null);+ }+}diff --git a/packages/flutter_chrome_cast/lib/entities/request.dart b/packages/flutter_chrome_cast/lib/entities/request.dartnew file mode 100644index 00000000..a478a835--- /dev/null+++ b/packages/flutter_chrome_cast/lib/entities/request.dart@@ -0,0 +1,35 @@+/// Represents a request, including progress, external status, request ID, and error.+class GoogleCastRequest {+ /// Whether the request is in progress.+ final bool inProgress;++ /// Whether the request is external.+ final bool isExternal;++ /// The unique request ID.+ final int requestID;++ /// Error message, if any.+ final String? error;++ /// Creates a new [GoogleCastRequest] instance.+ GoogleCastRequest({+ required this.inProgress,+ required this.isExternal,+ required this.requestID,+ this.error,+ });++ /// Creates a [GoogleCastRequest] from a map, typically decoded from JSON.+ ///+ /// The [map] must contain the keys 'inProgress', 'isExternal', and 'requestID'.+ /// The 'error' key is optional.+ factory GoogleCastRequest.fromMap(Map<String, dynamic> map) {+ return GoogleCastRequest(+ inProgress: map['inProgress'] as bool? ?? false,+ isExternal: map['isExternal'] as bool? ?? false,+ requestID: map['requestID'] as int? ?? map['requestId'] as int? ?? 0,+ error: map['error'] as String?,+ );+ }+}diff --git a/packages/flutter_chrome_cast/lib/entities/track.dart b/packages/flutter_chrome_cast/lib/entities/track.dartnew file mode 100644index 00000000..30612429--- /dev/null+++ b/packages/flutter_chrome_cast/lib/entities/track.dart@@ -0,0 +1,87 @@+import 'dart:convert';++import 'package:flutter_chrome_cast/common/rfc5646_language.dart';+import 'package:flutter_chrome_cast/enums/text_track_type.dart';+import 'package:flutter_chrome_cast/enums/track_type.dart';+import 'package:flutter_chrome_cast/models/android/extensions/track_type.dart';++/// Represents a media track, including content type, ID, type, and serialization helpers.+class GoogleCastMediaTrack {+ /// Custom data for the track.+ final Map<String, dynamic>? customData;++ /// Language of the track.+ final Rfc5646Language? language;++ /// Name of the track.+ final String? name;++ /// Subtype of the track.+ final TextTrackType? subtype;++ /// Content ID of the track.+ final String? trackContentId;++ /// Content type of the track.+ final String trackContentType;++ /// Unique identifier of the track within the context of a MediaInfo object.+ final int trackId;++ /// The type of track.+ final TrackType type;++ /// Creates a new [GoogleCastMediaTrack] instance.+ GoogleCastMediaTrack({+ this.customData,+ this.language,+ this.name,+ this.subtype,+ this.trackContentId,+ required this.trackContentType,+ required this.trackId,+ required this.type,+ });++ /// Converts the object to a map for serialization.+ Map<String, dynamic> toMap() {+ return {+ 'customData': customData,+ 'language': language?.toString(),+ 'name': name,+ 'subtype': subtype?.index,+ 'trackContentId': trackContentId,+ 'trackContentType': trackContentType,+ 'trackId': trackId,+ 'type': type.index,+ };+ }++ /// Creates a [GoogleCastMediaTrack] from a map.+ factory GoogleCastMediaTrack.fromMap(Map<String, dynamic> map) {+ return GoogleCastMediaTrack(+ customData: Map<String, dynamic>.from(map['customData'] ?? {}),+ language: map['language'] != null+ ? Rfc5646Language.fromMap(map['language'])+ : null,+ name: map['name'],+ subtype: map['subtype'] != null+ ? TextTrackType.values.firstWhere(+ (e) => e.name == map['subtype'],+ orElse: () => TextTrackType.unknown,+ )+ : null,+ trackContentId: map['trackContentId'],+ trackContentType: map['trackContentType'],+ trackId: map['trackId']?.toInt() ?? 0,+ type: GoogleCastTrackTypeAndroid.fromMap(map['type']),+ );+ }++ /// Converts the object to a JSON string.+ String toJson() => json.encode(toMap());++ /// Creates a [GoogleCastMediaTrack] from a JSON string.+ factory GoogleCastMediaTrack.fromJson(String source) =>+ GoogleCastMediaTrack.fromMap(json.decode(source));+}diff --git a/packages/flutter_chrome_cast/lib/enums.dart b/packages/flutter_chrome_cast/lib/enums.dartnew file mode 100644index 00000000..9c86bc1c--- /dev/null+++ b/packages/flutter_chrome_cast/lib/enums.dart@@ -0,0 +1,6 @@+/// Enums for Chrome Cast+///+/// This module provides access to all enums and constants.+library enums;++export 'enums/enums.dart';diff --git a/packages/flutter_chrome_cast/lib/enums/connection_state.dart b/packages/flutter_chrome_cast/lib/enums/connection_state.dartnew file mode 100644index 00000000..d70edc37--- /dev/null+++ b/packages/flutter_chrome_cast/lib/enums/connection_state.dart@@ -0,0 +1,17 @@+/// Represents the connection state of a Google Cast session.+///+/// This enum defines the possible states of a Cast connection,+/// from disconnected to fully connected and ready for media control.+enum GoogleCastConnectState {+ /// Disconnected from the device or application.+ disconnected,++ /// Connecting to the device or application.+ connecting,++ /// Connected to the device or application.+ connected,++ ///Disconnecting from the device.+ disconnecting,+}diff --git a/packages/flutter_chrome_cast/lib/enums/enums.dart b/packages/flutter_chrome_cast/lib/enums/enums.dartnew file mode 100644index 00000000..bfb7a6c4--- /dev/null+++ b/packages/flutter_chrome_cast/lib/enums/enums.dart@@ -0,0 +1,9 @@+export 'connection_state.dart';+export 'idle_reason.dart';+export 'media_metadata_type.dart';+export 'media_resume_state.dart';+export 'player_state.dart';+export 'repeat_mode.dart';+export 'stream_type.dart';+export 'text_track_type.dart';+export 'track_type.dart';diff --git a/packages/flutter_chrome_cast/lib/enums/idle_reason.dart b/packages/flutter_chrome_cast/lib/enums/idle_reason.dartnew file mode 100644index 00000000..f3039187--- /dev/null+++ b/packages/flutter_chrome_cast/lib/enums/idle_reason.dart@@ -0,0 +1,20 @@+/// Represents the reason why media playback became idle.+///+/// This enum defines the different reasons why a Cast media session+/// might transition to an idle state, indicating why playback stopped.+enum GoogleCastMediaIdleReason {+ /// No specific reason or unknown reason.+ none,++ /// The media playback completed naturally.+ finished,++ /// A sender requested to stop playback using the STOP command.+ cancelled,++ /// INTERRUPTED - A sender requested playing a different media using the LOAD command.+ interrupted,++ ///ERROR The media was interrupted due to an error; for example, if the player could not download the media due to network issues+ error;+}diff --git a/packages/flutter_chrome_cast/lib/enums/media_metadata_type.dart b/packages/flutter_chrome_cast/lib/enums/media_metadata_type.dartnew file mode 100644index 00000000..994c3c29--- /dev/null+++ b/packages/flutter_chrome_cast/lib/enums/media_metadata_type.dart@@ -0,0 +1,31 @@+/// Enum representing different types of media metadata for Google Cast.+enum GoogleCastMediaMetadataType {+ /// Generic media metadata type.+ genericMediaMetadata(0),++ /// Movie media metadata type.+ movieMediaMetadata(1),++ /// TV show media metadata type.+ tvShowMediaMetadata(2),++ /// Music track media metadata type.+ musicTrackMediaMetadata(3),++ /// Photo media metadata type.+ photoMediaMetadata(4);++ /// The integer value representing this metadata type.+ final int value;++ /// Creates a [GoogleCastMediaMetadataType] with the given [value].+ const GoogleCastMediaMetadataType(this.value);++ /// Creates a [GoogleCastMediaMetadataType] from an integer value.+ factory GoogleCastMediaMetadataType.fromMap(int value) {+ return values.firstWhere(+ (element) => element.value == value,+ orElse: () => genericMediaMetadata,+ );+ }+}diff --git a/packages/flutter_chrome_cast/lib/enums/media_resume_state.dart b/packages/flutter_chrome_cast/lib/enums/media_resume_state.dartnew file mode 100644index 00000000..58cfbe42--- /dev/null+++ b/packages/flutter_chrome_cast/lib/enums/media_resume_state.dart@@ -0,0 +1,11 @@+/// Enum representing different media resume states for Google Cast.+enum GoogleCastMediaResumeState {+ ///A resume state indicating that the player state should be left unchanged.+ unchanged,++ ///A resume state indicating that the player should be playing, regardless of its current state.+ play,++ ///A resume state indicating that the player should be paused, regardless of its current state.+ pause;+}diff --git a/packages/flutter_chrome_cast/lib/enums/player_state.dart b/packages/flutter_chrome_cast/lib/enums/player_state.dartnew file mode 100644index 00000000..d5372e4e--- /dev/null+++ b/packages/flutter_chrome_cast/lib/enums/player_state.dart@@ -0,0 +1,24 @@+/// Represents the current state of the media player.+///+/// This enum defines the different states that a Cast media player+/// can be in during media playback and control operations.+enum CastMediaPlayerState {+ /// Unknown or uninitialized state.+ unknown,++ /// IDLE - Player has not been loaded yet or has finished playback.+ idle,++ /// Player is actively playing content.+ playing,++ /// Player is paused.+ paused,++ /// Player is in PLAY mode but not actively playing content (currentTime is not changing).+ /// This typically occurs when the player is loading or buffering content.+ buffering,++ /// Player is loading media.+ loading;+}diff --git a/packages/flutter_chrome_cast/lib/enums/repeat_mode.dart b/packages/flutter_chrome_cast/lib/enums/repeat_mode.dartnew file mode 100644index 00000000..0dcc3785--- /dev/null+++ b/packages/flutter_chrome_cast/lib/enums/repeat_mode.dart@@ -0,0 +1,29 @@+///Possible states of queue repeat mode.+enum GoogleCastMediaRepeatMode {+ ///A repeat mode indicating that the repeat mode should be left unchanged.+ unchanged('UNCHANGED'),++ ///Items are played in order, and when the+ /// queue is completed (the last item has ended)+ /// the media session is terminated.+ off('OFF'),++ ///The current item will be repeated indefinitely.+ single('SINGLE'),++ ///The items in the queue will be played+ /// indefinitely. When the last item has+ /// ended, the first item will be played again.+ all('ALL'),++ ///The items in the queue will be played indefinitely.+ /// When the last item has ended, the list of items+ /// will be randomly shuffled by the receiver, and+ /// the queue will continue to play starting from the+ /// first item of the shuffled items.+ allAndShuffle('ALL_AND_SHUFFLE');++ /// The value used in the platform channel.+ final String value;+ const GoogleCastMediaRepeatMode(this.value);+}diff --git a/packages/flutter_chrome_cast/lib/enums/stream_type.dart b/packages/flutter_chrome_cast/lib/enums/stream_type.dartnew file mode 100644index 00000000..31fd9e28--- /dev/null+++ b/packages/flutter_chrome_cast/lib/enums/stream_type.dart@@ -0,0 +1,29 @@+/// Represents the type of media stream for Google Cast playback.+///+/// This enum defines the different types of media streams that can be+/// played through Google Cast, affecting how the media is handled and controlled.+enum CastMediaStreamType {+ /// No stream type specified or unknown.+ none('NONE'),++ /// Pre-recorded content that can be buffered and seeked.+ buffered('BUFFERED'),++ /// Live streaming content that cannot be seeked.+ live('LIVE');++ /// The string value used in Cast protocol communication.+ final String value;++ /// Creates a stream type with the given protocol value.+ const CastMediaStreamType(this.value);++ /// Creates a [CastMediaStreamType] from a string value.+ ///+ /// Returns [CastMediaStreamType.none] if the value doesn't match any known type.+ factory CastMediaStreamType.fromMap(String value) =>+ CastMediaStreamType.values.firstWhere(+ (element) => element.value == value,+ orElse: () => CastMediaStreamType.none,+ );+}diff --git a/packages/flutter_chrome_cast/lib/enums/text_track_type.dart b/packages/flutter_chrome_cast/lib/enums/text_track_type.dartnew file mode 100644index 00000000..91459fc8--- /dev/null+++ b/packages/flutter_chrome_cast/lib/enums/text_track_type.dart@@ -0,0 +1,37 @@+/// Enum representing different types of text tracks for Google Cast.+enum TextTrackType {+ /// Unknown text track type.+ unknown,++ ///Transcription or translation of the dialogue,+ /// suitable for when the sound is available+ /// but not understood (e.g. because the user+ /// does not understand the language of+ /// the media resource's soundtrack).+ subtitles,++ ///Transcription or translation of the dialogue,+ /// sound effects, relevant musical cues, and+ /// other relevant audio information, suitable+ /// for when the soundtrack is unavailable+ /// (e.g. because it is muted or because+ /// the user is deaf). Displayed over the+ /// video; labeled as appropriate for+ /// the hard-of-hearing.+ captions,++ ///Textual descriptions of the video component+ /// of the media resource, intended for audio synthesis+ /// when the visual component is unavailable+ /// (e.g. because the user is interacting with the+ /// application without a screen, or because the user is blind).+ /// Synthesized as separate audio track.+ descriptions,++ ///Chapter titles, intended to be used+ /// for navigating the media resource.+ chapters,++ /// Tracks intended for use from script.+ metadata;+}diff --git a/packages/flutter_chrome_cast/lib/enums/track_type.dart b/packages/flutter_chrome_cast/lib/enums/track_type.dartnew file mode 100644index 00000000..cd10cb5e--- /dev/null+++ b/packages/flutter_chrome_cast/lib/enums/track_type.dart@@ -0,0 +1,14 @@+/// Enum representing different types of media tracks.+enum TrackType {+ /// Unknown track type.+ unknown,++ /// Text track (e.g., subtitles, captions).+ text,++ /// Audio track.+ audio,++ /// Video track.+ video,+}diff --git a/packages/flutter_chrome_cast/lib/flutter_chrome_cast.dart b/packages/flutter_chrome_cast/lib/flutter_chrome_cast.dartnew file mode 100644index 00000000..bb6403c7--- /dev/null+++ b/packages/flutter_chrome_cast/lib/flutter_chrome_cast.dart@@ -0,0 +1,52 @@+/// Flutter Chrome Cast Plugin+///+/// A comprehensive library for integrating Google Cast functionality into Flutter apps.+///+/// ## Main Import+/// ```dart+/// import 'package:flutter_chrome_cast/flutter_chrome_cast.dart';+/// ```+///+/// ## Selective Imports+/// For better performance and cleaner code, you can import only what you need:+///+/// ```dart+/// // Core casting functionality+/// import 'package:flutter_chrome_cast/cast_context.dart';+/// import 'package:flutter_chrome_cast/discovery.dart';+/// import 'package:flutter_chrome_cast/session.dart';+/// import 'package:flutter_chrome_cast/media.dart';+///+/// // UI Widgets+/// import 'package:flutter_chrome_cast/widgets.dart';+///+/// // Models and Entities+/// import 'package:flutter_chrome_cast/models.dart';+/// import 'package:flutter_chrome_cast/entities.dart';+///+/// // Enums and Constants+/// import 'package:flutter_chrome_cast/enums.dart';+/// ```+library flutter_chrome_cast;++// Core functionality+export 'cast_context.dart';+export 'discovery.dart';+export 'session.dart';+export 'media.dart';++// UI Components+export 'widgets.dart';++// Data structures+export 'models.dart';+export 'entities.dart';+export 'enums.dart';++// Utilities+export 'utils.dart';++// Common types+export 'common.dart';++export 'themes.dart';diff --git a/packages/flutter_chrome_cast/lib/lib.dart b/packages/flutter_chrome_cast/lib/lib.dartnew file mode 100644index 00000000..4f24d493--- /dev/null+++ b/packages/flutter_chrome_cast/lib/lib.dart@@ -0,0 +1,19 @@+/// @deprecated Use 'package:flutter_chrome_cast/flutter_chrome_cast.dart' instead+///+/// This file exports everything for backward compatibility but is deprecated.+/// For better performance and cleaner imports, use the new modular imports:+///+/// ```dart+/// // Main import (all functionality)+/// import 'package:flutter_chrome_cast/flutter_chrome_cast.dart';+///+/// // Or selective imports+/// import 'package:flutter_chrome_cast/cast_context.dart';+/// import 'package:flutter_chrome_cast/discovery.dart';+/// import 'package:flutter_chrome_cast/session.dart';+/// import 'package:flutter_chrome_cast/media.dart';+/// import 'package:flutter_chrome_cast/widgets.dart';+/// ```+library flutter_chrome_cast_legacy;++export 'flutter_chrome_cast.dart';diff --git a/packages/flutter_chrome_cast/lib/media.dart b/packages/flutter_chrome_cast/lib/media.dartnew file mode 100644index 00000000..6a8c1e85--- /dev/null+++ b/packages/flutter_chrome_cast/lib/media.dart@@ -0,0 +1,6 @@+/// Media Control functionality+///+/// This module provides access to remote media client features.+library media;++export '_remote_media_client/_remote_media_client.dart';diff --git a/packages/flutter_chrome_cast/lib/models.dart b/packages/flutter_chrome_cast/lib/models.dartnew file mode 100644index 00000000..07bd8f44--- /dev/null+++ b/packages/flutter_chrome_cast/lib/models.dart@@ -0,0 +1,6 @@+/// Models for Chrome Cast+///+/// This module provides access to all models.+library models;++export 'models/models.dart';diff --git a/packages/flutter_chrome_cast/lib/models/android/android.dart b/packages/flutter_chrome_cast/lib/models/android/android.dartnew file mode 100644index 00000000..99ebbba5--- /dev/null+++ b/packages/flutter_chrome_cast/lib/models/android/android.dart@@ -0,0 +1,8 @@+export 'android_cast_options.dart';+export 'android_media_information.dart';+export 'android_media_status.dart';+export 'android_queue_item.dart';+export 'cast_device.dart';+export 'cast_session.dart';+export 'extensions/extensions.dart';+export 'metadata/metadata.dart';diff --git a/packages/flutter_chrome_cast/lib/models/android/android_cast_options.dart b/packages/flutter_chrome_cast/lib/models/android/android_cast_options.dartnew file mode 100644index 00000000..5bfdf26d--- /dev/null+++ b/packages/flutter_chrome_cast/lib/models/android/android_cast_options.dart@@ -0,0 +1,26 @@+import 'package:flutter_chrome_cast/lib.dart';++/// Android-specific cast options configuration.+class GoogleCastOptionsAndroid extends GoogleCastOptions {+ /// The Cast application ID.+ final String appId;++ /// Creates a new [GoogleCastOptionsAndroid].+ ///+ /// [appId] is required and specifies the Cast application ID.+ ///+ /// [stopCastingOnAppTerminated] when set to true, will automatically stop+ /// casting and end the session when the app is killed/terminated. Defaults to false.+ GoogleCastOptionsAndroid({+ required this.appId,+ super.stopCastingOnAppTerminated,+ });++ @override+ Map<String, dynamic> toMap() {+ return super.toMap()+ ..addAll({+ 'appId': appId,+ });+ }+}diff --git a/packages/flutter_chrome_cast/lib/models/android/android_media_information.dart b/packages/flutter_chrome_cast/lib/models/android/android_media_information.dartnew file mode 100644index 00000000..360fc42d--- /dev/null+++ b/packages/flutter_chrome_cast/lib/models/android/android_media_information.dart@@ -0,0 +1,105 @@+import 'package:flutter_chrome_cast/lib.dart';++/// Android-specific extension of [GoogleCastMediaInformation].+class GoogleCastMediaInformationAndroid extends GoogleCastMediaInformation {+ /// Creates a new [GoogleCastMediaInformationAndroid] instance.+ GoogleCastMediaInformationAndroid({+ required super.contentId,+ required super.streamType,+ required super.contentType,+ super.atvEntity,+ super.breakClips,+ super.breaks,+ super.contentUrl,+ super.customData,+ super.duration,+ super.entity,+ super.hlsSegmentFormat,+ super.hlsVideoSegmentFormat,+ super.metadata,+ super.startAbsoluteTime,+ super.textTrackStyle,+ super.tracks,+ super.userActionStates,+ super.vmapAdsRequest,+ });++ /// Creates a [GoogleCastMediaInformationAndroid] from a map.+ factory GoogleCastMediaInformationAndroid.fromMap(Map<String, dynamic> map) {+ return GoogleCastMediaInformationAndroid(+ atvEntity: map['atvEntity'],+ breakClips: map['breakClips'] != null+ ? List<CastBreakClips>.from(+ map['breakClips']?.map((x) => CastBreakClips.fromMap(x)))+ : null,+ contentId: map['contentId'] ?? '',+ streamType: GoogleCastAndroidStreamType.fromMap(map['streamType']),+ contentType: map['contentType'] ?? '',+ metadata: map['metadata'] != null+ ? _getCastMediaMetadata(Map.from(map['metadata']))+ : null,+ duration: map['duration'] != null+ ? Duration(seconds: map['duration'].round())+ : null,+ customData: Map<String, dynamic>.from(map['customData'] ?? {}),+ breaks: map['breaks'] != null+ ? List<CastBreak>.from(+ map['breaks']?.map((x) => CastBreak.fromMap(x)))+ : null,+ contentUrl: Uri.tryParse(map['contentUrl'] ?? ''),+ entity: map['entity'],+ hlsSegmentFormat: map['hlsSegmentFormat'] != null+ ? CastHlsSegmentFormat.fromMap(map['hlsSegmentFormat'])+ : null,+ hlsVideoSegmentFormat: map['hlsVideoSegmentFormat'] != null+ ? HlsVideoSegmentFormat.fromMap(map['hlsVideoSegmentFormat'])+ : null,+ startAbsoluteTime: map['startAbsoluteTime'] != null+ ? DateTime.fromMillisecondsSinceEpoch(map['startAbsoluteTime'])+ : null,+ textTrackStyle: map['textTrackStyle'] != null+ ? TextTrackStyle.fromMap(map['textTrackStyle'])+ : null,+ tracks: map['tracks'] != null+ ? List<GoogleCastMediaTrack>.from(map['tracks']?.map((x) =>+ GoogleCastMediaTrack.fromMap(Map<String, dynamic>.from(x))))+ : null,+ userActionStates: map['userActionStates'] != null+ ? List<UserActionState>.from(+ map['userActionStates']?.map((x) => UserActionState.fromMap(x)))+ : null,+ vmapAdsRequest: map['vmapAdsRequest'] != null+ ? VastAdsRequest.fromMap(map['vmapAdsRequest'])+ : null,+ );+ }+}++GoogleCastMediaMetadata? _getCastMediaMetadata(Map<String, dynamic> map) {+ final type = map['metadataType'] as int;+ GoogleCastMediaMetadata? metadata;+ switch (type) {+ //Generic+ case 0:+ metadata = GoogleCastGenericMediaMetadataAndroid.fromMap(map);+ break;+ //MOVIE+ case 1:+ metadata = GoogleCastMovieMediaMetadataAndroid.fromMap(map);+ break;+ //TV SHOW+ case 2:+ metadata = GoogleCastTvShowMediaMetadataAndroid.fromMap(map);+ break;+ //Music+ case 3:+ metadata = GoogleCastMusicMediaMetadataAndroid.fromMap(map);+ break;+ //Photo+ case 4:+ metadata = GooglCastPhotoMediaMetadataAndroid.fromMap(map);+ break;+ default:+ }+ return metadata;+}diff --git a/packages/flutter_chrome_cast/lib/models/android/android_media_status.dart b/packages/flutter_chrome_cast/lib/models/android/android_media_status.dartnew file mode 100644index 00000000..739e68b8--- /dev/null+++ b/packages/flutter_chrome_cast/lib/models/android/android_media_status.dart@@ -0,0 +1,55 @@+import 'dart:convert';++import 'package:flutter_chrome_cast/lib.dart';++/// Android-specific implementation of media status.+class GoogleCastAndroidMediaStatus extends GoggleCastMediaStatus {+ /// Creates an Android media status instance.+ GoogleCastAndroidMediaStatus({+ required super.mediaSessionID,+ required super.playerState,+ required super.playbackRate,+ required super.volume,+ required super.isMuted,+ required super.repeatMode,+ super.activeTrackIds,+ super.adBreakStatus,+ super.currentItemId,+ super.idleReason,+ super.liveSeekableRange,+ super.mediaInformation,+ });++ /// Creates a media status instance from a map.+ factory GoogleCastAndroidMediaStatus.fromMap(Map<String, dynamic> map) {+ return GoogleCastAndroidMediaStatus(+ mediaSessionID: map['mediaSessionId']?.toInt() ?? 0,+ playerState: CastMediaPlayerStateAndroid.fromMap(map['playerState']),+ idleReason: map['idleReason'] != null+ ? GoogleCastIdleReasonAndroid.fromMap(map['idleReason'])+ : null,+ playbackRate: map['playbackRate'] ?? 1,+ mediaInformation: map['media'] != null+ ? GoogleCastMediaInformationAndroid.fromMap(+ Map<String, dynamic>.from(map['media']))+ : null,++ volume: map['volume']?['level'] ?? 0,+ isMuted: map['volume']?['muted'] ?? true,+ repeatMode: GoogleCastRepeatModeAndroid.fromMap(map['repeatMode']),+ currentItemId: map['currentItemId']?.toInt(),+ activeTrackIds:+ List<int>.from(jsonDecode(map['activeTrackIds'] ?? '[]') ?? []),++ // adBreakStatus: map['adBreakStatus'] != null+ // ? GoogleCastBrakeStatus.fromMap(map['adBreakStatus'])+ // : null,+ liveSeekableRange: map['liveSeekableRange'] != null+ ? GoogleCastMediaLiveSeekableRange.fromMap(map['liveSeekableRange'])+ : null,+ // queueData: map['queueData'] != null+ // ? GoogleCastMediaQueueData.fromMap(map['queueData'])+ // : null,+ );+ }+}diff --git a/packages/flutter_chrome_cast/lib/models/android/android_queue_item.dart b/packages/flutter_chrome_cast/lib/models/android/android_queue_item.dartnew file mode 100644index 00000000..3de52110--- /dev/null+++ b/packages/flutter_chrome_cast/lib/models/android/android_queue_item.dart@@ -0,0 +1,33 @@+import 'package:flutter_chrome_cast/lib.dart';++/// Android-specific implementation of queue item.+class GoogleCastAndroidQueueItem extends GoogleCastQueueItem {+ /// Creates an Android queue item instance.+ GoogleCastAndroidQueueItem({+ required super.mediaInformation,+ super.activeTrackIds,+ super.autoPlay,+ super.customData,+ super.itemId,+ super.playbackDuration,+ super.preLoadTime,+ super.startTime,+ });++ /// Creates a queue item instance from a map.+ factory GoogleCastAndroidQueueItem.fromMap(Map<String, dynamic> map) {+ return GoogleCastAndroidQueueItem(+ mediaInformation: GoogleCastMediaInformationAndroid.fromMap(+ Map<String, dynamic>.from(map['media'])),+ activeTrackIds: List.from(map['activeTracksIds'] ?? []),+ autoPlay: map['autoplay'] ?? false,+ customData: map['customData'],+ itemId: map['itemId'],+ playbackDuration: map['playbackDuration'] == null+ ? null+ : Duration(seconds: map['playbackDuration']),+ preLoadTime: Duration(seconds: map['preLoadTime'] ?? 0),+ startTime: Duration(seconds: map['startTime'] ?? 0),+ );+ }+}diff --git a/packages/flutter_chrome_cast/lib/models/android/cast_device.dart b/packages/flutter_chrome_cast/lib/models/android/cast_device.dartnew file mode 100644index 00000000..31d4c06c--- /dev/null+++ b/packages/flutter_chrome_cast/lib/models/android/cast_device.dart@@ -0,0 +1,40 @@+import 'package:flutter_chrome_cast/lib.dart';++/// Extension for creating a list of [GoogleCastAndroidDevice] from a map.+extension GoogleCastAndroidDevices on GoogleCastAndroidDevice {+ /// Creates a list of [GoogleCastAndroidDevice] from a list of maps.+ static List<GoogleCastAndroidDevice> fromMap(List maps) {+ final devices =+ maps.map((e) => GoogleCastAndroidDevice.fromMap(e)).toList();+ return devices;+ }+}++/// Android-specific device representation.+class GoogleCastAndroidDevice extends GoogleCastDevice {+ /// Creates a new [GoogleCastAndroidDevice] instance.+ GoogleCastAndroidDevice({+ required super.deviceID,+ required super.friendlyName,+ required super.modelName,+ required super.statusText,+ required super.deviceVersion,+ required super.isOnLocalNetwork,+ required super.category,+ required super.uniqueID,+ });++ /// Creates a [GoogleCastAndroidDevice] from a map.+ factory GoogleCastAndroidDevice.fromMap(Map<String, dynamic> map) {+ return GoogleCastAndroidDevice(+ deviceID: map['id'],+ friendlyName: map['name'],+ modelName: map['model_name'],+ deviceVersion: map['device_version'],+ category: '',+ isOnLocalNetwork: map['is_on_local_network'],+ statusText: null,+ uniqueID: map['id'],+ );+ }+}diff --git a/packages/flutter_chrome_cast/lib/models/android/cast_session.dart b/packages/flutter_chrome_cast/lib/models/android/cast_session.dartnew file mode 100644index 00000000..2a88119e--- /dev/null+++ b/packages/flutter_chrome_cast/lib/models/android/cast_session.dart@@ -0,0 +1,41 @@+import 'package:flutter_chrome_cast/lib.dart';++/// Represents a Google Cast session on Android devices.+///+/// This class extends [GoogleCastSession] and provides Android-specific+/// session details and mapping utilities.+class GoogleCastSessionAndroid extends GoogleCastSession {+ /// Creates a [GoogleCastSessionAndroid] instance with the given parameters.+ ///+ /// [device] is the Android device associated with the session.+ /// [sessionID] is the unique identifier for the session.+ /// [connectionState] indicates the current connection state.+ /// [currentDeviceMuted] is true if the device is muted.+ /// [currentDeviceVolume] is the current volume level.+ /// [deviceStatusText] is a status message from the device.+ GoogleCastSessionAndroid({+ required super.device,+ required super.sessionID,+ required super.connectionState,+ required super.currentDeviceMuted,+ required super.currentDeviceVolume,+ required super.deviceStatusText,+ });++ /// Creates a [GoogleCastSessionAndroid] from a map, typically received from platform channels.+ ///+ /// The [map] parameter should contain keys for device, sessionID, connectionState, isMute, volume, and statusMessage.+ factory GoogleCastSessionAndroid.fromMap(Map<String, dynamic> map) {+ final device = map['device'];+ return GoogleCastSessionAndroid(+ device: device != null+ ? GoogleCastAndroidDevice.fromMap(Map.from(map['device']))+ : null,+ sessionID: map['sessionID'],+ connectionState: GoogleCastConnectState.values[map['connectionState']],+ currentDeviceMuted: map['isMute'],+ currentDeviceVolume: map['volume'],+ deviceStatusText: map['statusMessage'] ?? '',+ );+ }+}diff --git a/packages/flutter_chrome_cast/lib/models/android/extensions/cast_media_player_state.dart b/packages/flutter_chrome_cast/lib/models/android/extensions/cast_media_player_state.dartnew file mode 100644index 00000000..8a5326a8--- /dev/null+++ b/packages/flutter_chrome_cast/lib/models/android/extensions/cast_media_player_state.dart@@ -0,0 +1,12 @@+import 'package:flutter_chrome_cast/enums/player_state.dart';++/// Android-specific extension for cast media player state.+extension CastMediaPlayerStateAndroid on CastMediaPlayerState {+ /// Creates a player state from a map value.+ static CastMediaPlayerState fromMap(String value) {+ return CastMediaPlayerState.values.firstWhere(+ (element) => element.name.toUpperCase() == value.toUpperCase(),+ orElse: () => CastMediaPlayerState.idle,+ );+ }+}diff --git a/packages/flutter_chrome_cast/lib/models/android/extensions/date_time.dart b/packages/flutter_chrome_cast/lib/models/android/extensions/date_time.dartnew file mode 100644index 00000000..fcd86fae--- /dev/null+++ b/packages/flutter_chrome_cast/lib/models/android/extensions/date_time.dart@@ -0,0 +1,13 @@+/// Extension for DateTime string parsing.+extension DateTimeString on DateTime {+ /// Tries to parse a date string in YYYYMMDD format.+ static DateTime? tryParse(String value) {+ final year = int.tryParse(value.substring(0, 4));+ final month = int.tryParse(value.substring(4, 6));+ final day = int.tryParse(value.substring(6, 8));+ if (year != null && month != null && day != null) {+ return DateTime(year, month, day);+ }+ return null;+ }+}diff --git a/packages/flutter_chrome_cast/lib/models/android/extensions/extensions.dart b/packages/flutter_chrome_cast/lib/models/android/extensions/extensions.dartnew file mode 100644index 00000000..15f96610--- /dev/null+++ b/packages/flutter_chrome_cast/lib/models/android/extensions/extensions.dart@@ -0,0 +1,7 @@+export 'cast_media_player_state.dart';+export 'date_time.dart';+export 'idle_reason.dart';+export 'repeat_mode.dart';+export 'stream_type.dart';+export 'text_track_type.dart';+export 'track_type.dart';diff --git a/packages/flutter_chrome_cast/lib/models/android/extensions/idle_reason.dart b/packages/flutter_chrome_cast/lib/models/android/extensions/idle_reason.dartnew file mode 100644index 00000000..8415c277--- /dev/null+++ b/packages/flutter_chrome_cast/lib/models/android/extensions/idle_reason.dart@@ -0,0 +1,12 @@+import 'package:flutter_chrome_cast/lib.dart';++/// Android-specific extension for idle reason.+extension GoogleCastIdleReasonAndroid on GoogleCastMediaIdleReason {+ /// Creates an idle reason from a map value.+ static GoogleCastMediaIdleReason fromMap(String value) {+ return GoogleCastMediaIdleReason.values.firstWhere(+ (element) => element.name.toUpperCase() == value.toUpperCase(),+ orElse: () => GoogleCastMediaIdleReason.none,+ );+ }+}diff --git a/packages/flutter_chrome_cast/lib/models/android/extensions/repeat_mode.dart b/packages/flutter_chrome_cast/lib/models/android/extensions/repeat_mode.dartnew file mode 100644index 00000000..7e7dbabb--- /dev/null+++ b/packages/flutter_chrome_cast/lib/models/android/extensions/repeat_mode.dart@@ -0,0 +1,12 @@+import 'package:flutter_chrome_cast/lib.dart';++/// Android-specific extension for repeat mode.+extension GoogleCastRepeatModeAndroid on GoogleCastMediaRepeatMode {+ /// Creates a repeat mode from a map value.+ static GoogleCastMediaRepeatMode fromMap(String value) {+ return GoogleCastMediaRepeatMode.values.firstWhere(+ (element) => element.name.toUpperCase() == value.toUpperCase(),+ orElse: () => GoogleCastMediaRepeatMode.unchanged,+ );+ }+}diff --git a/packages/flutter_chrome_cast/lib/models/android/extensions/stream_type.dart b/packages/flutter_chrome_cast/lib/models/android/extensions/stream_type.dartnew file mode 100644index 00000000..8fda818a--- /dev/null+++ b/packages/flutter_chrome_cast/lib/models/android/extensions/stream_type.dart@@ -0,0 +1,12 @@+import 'package:flutter_chrome_cast/lib.dart';++/// Android-specific extension for stream type.+extension GoogleCastAndroidStreamType on CastMediaStreamType {+ /// Creates a stream type from a map value.+ static CastMediaStreamType fromMap(String value) {+ return CastMediaStreamType.values.firstWhere(+ (element) => element.value == value,+ orElse: () => CastMediaStreamType.none,+ );+ }+}diff --git a/packages/flutter_chrome_cast/lib/models/android/extensions/text_track_type.dart b/packages/flutter_chrome_cast/lib/models/android/extensions/text_track_type.dartnew file mode 100644index 00000000..ec84295a--- /dev/null+++ b/packages/flutter_chrome_cast/lib/models/android/extensions/text_track_type.dart@@ -0,0 +1,12 @@+import 'package:flutter_chrome_cast/lib.dart';++/// Android-specific extension for text track type.+extension GoogleCastTextTrackStyleAndroid on TextTrackType {+ /// Creates a text track type from a map value.+ static TextTrackType fromMap(String value) {+ return TextTrackType.values.firstWhere(+ (element) => element.name.toUpperCase() == value.toUpperCase(),+ orElse: () => TextTrackType.unknown,+ );+ }+}diff --git a/packages/flutter_chrome_cast/lib/models/android/extensions/track_type.dart b/packages/flutter_chrome_cast/lib/models/android/extensions/track_type.dartnew file mode 100644index 00000000..cd3ed491--- /dev/null+++ b/packages/flutter_chrome_cast/lib/models/android/extensions/track_type.dart@@ -0,0 +1,12 @@+import 'package:flutter_chrome_cast/lib.dart';++/// Android-specific extension for track type.+extension GoogleCastTrackTypeAndroid on TrackType {+ /// Creates a track type from a map value.+ static TrackType fromMap(String value) {+ return TrackType.values.firstWhere(+ (element) => element.name.toUpperCase() == value.toUpperCase(),+ orElse: () => TrackType.unknown,+ );+ }+}diff --git a/packages/flutter_chrome_cast/lib/models/android/metadata/generic.dart b/packages/flutter_chrome_cast/lib/models/android/metadata/generic.dartnew file mode 100644index 00000000..792d50ec--- /dev/null+++ b/packages/flutter_chrome_cast/lib/models/android/metadata/generic.dart@@ -0,0 +1,29 @@+import 'package:flutter_chrome_cast/lib.dart';++/// Android-specific implementation of generic media metadata.+class GoogleCastGenericMediaMetadataAndroid+ extends GoogleCastGenericMediaMetadata {+ /// Creates an Android generic media metadata instance.+ GoogleCastGenericMediaMetadataAndroid({+ required super.title,+ required super.subtitle,+ required super.images,+ super.releaseDate,+ });++ /// Creates a generic media metadata instance from a map.+ factory GoogleCastGenericMediaMetadataAndroid.fromMap(+ Map<String, dynamic> map) {+ return GoogleCastGenericMediaMetadataAndroid(+ title: map['title'],+ subtitle: map['subtitle'],+ images: map['images'] != null+ ? List<GoogleCastImage>.from(+ map['images']?.map((x) => GoogleCastImage.fromMap(x)))+ : null,+ releaseDate: map['releaseDate'] != null+ ? DateTimeString.tryParse(map['releaseDate'] ?? '')+ : null,+ );+ }+}diff --git a/packages/flutter_chrome_cast/lib/models/android/metadata/metadata.dart b/packages/flutter_chrome_cast/lib/models/android/metadata/metadata.dartnew file mode 100644index 00000000..b873cb71--- /dev/null+++ b/packages/flutter_chrome_cast/lib/models/android/metadata/metadata.dart@@ -0,0 +1,5 @@+export 'generic.dart';+export 'movie.dart';+export 'music.dart';+export 'photo.dart';+export 'tv_show.dart';diff --git a/packages/flutter_chrome_cast/lib/models/android/metadata/movie.dart b/packages/flutter_chrome_cast/lib/models/android/metadata/movie.dartnew file mode 100644index 00000000..92657c73--- /dev/null+++ b/packages/flutter_chrome_cast/lib/models/android/metadata/movie.dart@@ -0,0 +1,32 @@+import 'package:flutter_chrome_cast/common/image.dart';+import 'package:flutter_chrome_cast/entities/media_metadata/movie_media_metadata.dart';+import 'package:flutter_chrome_cast/models/android/extensions/date_time.dart';++/// Android-specific implementation of movie media metadata.+class GoogleCastMovieMediaMetadataAndroid extends GoogleCastMovieMediaMetadata {+ /// Creates an Android movie media metadata instance.+ GoogleCastMovieMediaMetadataAndroid({+ super.images,+ super.releaseDate,+ super.studio,+ super.subtitle,+ super.title,+ });++ /// Creates a movie media metadata instance from a map.+ factory GoogleCastMovieMediaMetadataAndroid.fromMap(+ Map<String, dynamic> map) {+ return GoogleCastMovieMediaMetadataAndroid(+ title: map['title'],+ subtitle: map['subtitle'],+ studio: map['studio'],+ images: map['images'] != null+ ? List<GoogleCastImage>.from(+ map['images']?.map((x) => GoogleCastImage.fromMap(x)))+ : null,+ releaseDate: map['releaseDate'] != null+ ? DateTimeString.tryParse(map['releaseDate'] ?? '')+ : null,+ );+ }+}diff --git a/packages/flutter_chrome_cast/lib/models/android/metadata/music.dart b/packages/flutter_chrome_cast/lib/models/android/metadata/music.dartnew file mode 100644index 00000000..1385fd89--- /dev/null+++ b/packages/flutter_chrome_cast/lib/models/android/metadata/music.dart@@ -0,0 +1,40 @@+import 'package:flutter_chrome_cast/common/image.dart';+import 'package:flutter_chrome_cast/entities/media_metadata/music_track_media_metadata.dart';+import 'package:flutter_chrome_cast/models/android/extensions/date_time.dart';++/// Android-specific implementation of music media metadata.+class GoogleCastMusicMediaMetadataAndroid extends GoogleCastMusicMediaMetadata {+ /// Creates an Android music media metadata instance.+ GoogleCastMusicMediaMetadataAndroid({+ super.albumArtist,+ super.albumName,+ super.artist,+ super.composer,+ super.discNumber,+ super.images,+ super.releaseDate,+ super.title,+ super.trackNumber,+ });++ /// Creates a music media metadata instance from a map.+ factory GoogleCastMusicMediaMetadataAndroid.fromMap(+ Map<String, dynamic> map) {+ return GoogleCastMusicMediaMetadataAndroid(+ albumName: map['albumName'],+ title: map['title'],+ albumArtist: map['albumArtist'],+ artist: map['artist'],+ composer: map['composer'],+ trackNumber: map['trackNumber']?.toInt(),+ discNumber: map['discNumber']?.toInt(),+ images: map['images'] != null+ ? List<GoogleCastImage>.from(+ map['images']?.map((x) => GoogleCastImage.fromMap(x)))+ : null,+ releaseDate: map['releaseDate'] != null+ ? DateTimeString.tryParse(map['releaseDate'])+ : null,+ );+ }+}diff --git a/packages/flutter_chrome_cast/lib/models/android/metadata/photo.dart b/packages/flutter_chrome_cast/lib/models/android/metadata/photo.dartnew file mode 100644index 00000000..ac290aee--- /dev/null+++ b/packages/flutter_chrome_cast/lib/models/android/metadata/photo.dart@@ -0,0 +1,32 @@+import 'package:flutter_chrome_cast/lib.dart';++/// Android-specific implementation of photo media metadata.+class GooglCastPhotoMediaMetadataAndroid extends GoogleCastPhotoMediaMetadata {+ /// Creates an Android photo media metadata instance.+ GooglCastPhotoMediaMetadataAndroid({+ super.artist,+ super.creationDateTime,+ super.height,+ super.latitude,+ super.location,+ super.longitude,+ super.title,+ super.width,+ });++ /// Creates a photo media metadata instance from a map.+ factory GooglCastPhotoMediaMetadataAndroid.fromMap(Map<String, dynamic> map) {+ return GooglCastPhotoMediaMetadataAndroid(+ title: map['title'],+ artist: map['artist'],+ location: map['location'],+ latitude: map['latitude']?.toDouble(),+ longitude: map['longitude']?.toDouble(),+ width: map['width']?.toInt(),+ height: map['height']?.toInt(),+ creationDateTime: map['creationDateTime'] != null+ ? DateTimeString.tryParse(map['creationDateTime'])+ : null,+ );+ }+}diff --git a/packages/flutter_chrome_cast/lib/models/android/metadata/tv_show.dart b/packages/flutter_chrome_cast/lib/models/android/metadata/tv_show.dartnew file mode 100644index 00000000..0931750c--- /dev/null+++ b/packages/flutter_chrome_cast/lib/models/android/metadata/tv_show.dart@@ -0,0 +1,31 @@+import 'package:flutter_chrome_cast/lib.dart';++/// Android-specific implementation of TV show media metadata.+class GoogleCastTvShowMediaMetadataAndroid+ extends GoogleCastTvShowMediaMetadata {+ /// Creates an Android TV show media metadata instance.+ GoogleCastTvShowMediaMetadataAndroid({+ super.episode,+ super.images,+ super.originalAirDate,+ super.season,+ super.seriesTitle,+ });++ /// Creates a TV show media metadata instance from a map.+ factory GoogleCastTvShowMediaMetadataAndroid.fromMap(+ Map<String, dynamic> map) {+ return GoogleCastTvShowMediaMetadataAndroid(+ seriesTitle: map['seriesTitle'],+ season: map['season']?.toInt(),+ episode: map['episode']?.toInt(),+ images: map['images'] != null+ ? List<GoogleCastImage>.from(+ map['images']?.map((x) => GoogleCastImage.fromMap(x)))+ : null,+ originalAirDate: map['originalAirDate'] != null+ ? DateTimeString.tryParse(map['originalAirDate'])+ : null,+ );+ }+}diff --git a/packages/flutter_chrome_cast/lib/models/ios/ios.dart b/packages/flutter_chrome_cast/lib/models/ios/ios.dartnew file mode 100644index 00000000..7dd66641--- /dev/null+++ b/packages/flutter_chrome_cast/lib/models/ios/ios.dart@@ -0,0 +1,7 @@+export 'ios_cast_device.dart';+export 'ios_cast_options.dart';+export 'ios_cast_queue_item.dart';+export 'ios_cast_sessions.dart';+export 'ios_media_information.dart';+export 'ios_media_status.dart';+export 'ios_request.dart';diff --git a/packages/flutter_chrome_cast/lib/models/ios/ios_cast_device.dart b/packages/flutter_chrome_cast/lib/models/ios/ios_cast_device.dartnew file mode 100644index 00000000..7d119265--- /dev/null+++ b/packages/flutter_chrome_cast/lib/models/ios/ios_cast_device.dart@@ -0,0 +1,40 @@+import 'package:flutter_chrome_cast/entities/cast_device.dart';++/// Represents a Google Cast device specific to iOS platforms.+///+/// This class extends [GoogleCastDevice] to include iOS-specific properties+/// and construction from a map structure typically returned by iOS platform channels.+class GoogleCastIosDevice extends GoogleCastDevice {+ /// Optional index of the device in the iOS discovery list.+ final int? index;++ /// Creates a new [GoogleCastIosDevice] instance.+ ///+ /// All parameters except [index] are required and are passed to the base [GoogleCastDevice].+ GoogleCastIosDevice({+ required super.deviceID,+ required super.friendlyName,+ required super.modelName,+ required super.statusText,+ required super.deviceVersion,+ required super.isOnLocalNetwork,+ required super.category,+ required super.uniqueID,+ required this.index,+ });++ /// Creates a [GoogleCastIosDevice] from a map, typically from platform channel data.+ factory GoogleCastIosDevice.fromMap(Map<String, dynamic> map) {+ return GoogleCastIosDevice(+ deviceID: map['deviceID'] as String,+ friendlyName: map['friendlyName'] ?? '',+ modelName: map['modelName'],+ statusText: map['statusText'],+ deviceVersion: map['deviceVersion'] ?? '',+ isOnLocalNetwork: map['isOnLocalNetwork'] as bool,+ category: map['category'] as String,+ uniqueID: map['uniqueID'] as String,+ index: map['index'],+ );+ }+}diff --git a/packages/flutter_chrome_cast/lib/models/ios/ios_cast_options.dart b/packages/flutter_chrome_cast/lib/models/ios/ios_cast_options.dartnew file mode 100644index 00000000..d210988c--- /dev/null+++ b/packages/flutter_chrome_cast/lib/models/ios/ios_cast_options.dart@@ -0,0 +1,33 @@+import 'package:flutter_chrome_cast/entities/discovery_criteria.dart';+import 'package:flutter_chrome_cast/entities/cast_options.dart';++/// iOS-specific Google Cast options.+///+/// This class extends [GoogleCastOptions] to provide additional configuration+/// for iOS, such as specifying discovery criteria for Cast devices.+class IOSGoogleCastOptions extends GoogleCastOptions {+ /// The discovery criteria used to find Cast devices on iOS.+ final GoogleCastDiscoveryCriteriaInitialize _discoveryCriteria;++ /// Creates an instance of [IOSGoogleCastOptions] with the given [discoveryCriteria].+ ///+ /// [stopCastingOnAppTerminated] when set to true, will automatically stop+ /// casting and end the session when the app is killed/terminated. Defaults to false.+ IOSGoogleCastOptions(+ this._discoveryCriteria, {+ super.stopCastingOnAppTerminated,+ });++ /// Converts this iOS Cast options object to a map representation.+ ///+ /// The returned map includes all base options and the iOS-specific discovery criteria.+ @override+ Map<String, dynamic> toMap() {+ return super.toMap()+ ..addAll(+ {+ 'discoveryCriteria': _discoveryCriteria.toMap(),+ },+ );+ }+}diff --git a/packages/flutter_chrome_cast/lib/models/ios/ios_cast_queue_item.dart b/packages/flutter_chrome_cast/lib/models/ios/ios_cast_queue_item.dartnew file mode 100644index 00000000..ea346cf3--- /dev/null+++ b/packages/flutter_chrome_cast/lib/models/ios/ios_cast_queue_item.dart@@ -0,0 +1,42 @@+import 'package:flutter_chrome_cast/lib.dart';++/// Represents a queue item for Google Cast on iOS platforms.+///+/// This class extends [GoogleCastQueueItem] and provides additional+/// iOS-specific mapping and construction logic.+class GoogleCastQueueItemIOS extends GoogleCastQueueItem {+ /// Creates a [GoogleCastQueueItemIOS] instance.+ ///+ /// [mediaInformation] is required and contains the media details for the queue item.+ /// Other parameters are optional and provide additional playback and queue configuration.+ GoogleCastQueueItemIOS({+ required super.mediaInformation,+ super.activeTrackIds,+ super.autoPlay,+ super.customData,+ super.itemId,+ super.playbackDuration,+ super.preLoadTime,+ super.startTime,+ });++ /// Creates a [GoogleCastQueueItemIOS] from a [Map] representation.+ ///+ /// This factory parses the provided [map] and constructs an instance+ /// with the corresponding values, handling iOS-specific field names and types.+ factory GoogleCastQueueItemIOS.fromMap(Map<String, dynamic> map) {+ return GoogleCastQueueItemIOS(+ mediaInformation: GoogleCastMediaInformationIOS.fromMap(+ Map<String, dynamic>.from(map['mediaInformation'])),+ activeTrackIds: List.from(map['activeTracksIds'] ?? []),+ autoPlay: map['autoPlay'] ?? false,+ customData: map['customData'],+ itemId: map['itemId'],+ playbackDuration: map['playbackDuration'] == null+ ? null+ : Duration(seconds: map['playbackDuration']),+ preLoadTime: Duration(seconds: map['preLoadTime'] ?? 0),+ startTime: Duration(seconds: map['startTime'] ?? 0),+ );+ }+}diff --git a/packages/flutter_chrome_cast/lib/models/ios/ios_cast_sessions.dart b/packages/flutter_chrome_cast/lib/models/ios/ios_cast_sessions.dartnew file mode 100644index 00000000..0d8846cc--- /dev/null+++ b/packages/flutter_chrome_cast/lib/models/ios/ios_cast_sessions.dart@@ -0,0 +1,39 @@+import 'package:flutter_chrome_cast/entities/cast_session.dart';+import 'package:flutter_chrome_cast/enums/connection_state.dart';+import 'package:flutter_chrome_cast/models/ios/ios_cast_device.dart';++/// Represents a Google Cast session on iOS devices.+///+/// This class extends [GoogleCastSession] and provides additional+/// functionality specific to iOS, including a factory method for+/// creating an instance from a map (typically from JSON).+class IOSGoogleCastSessions extends GoogleCastSession {+ /// Creates an [IOSGoogleCastSessions] instance.+ ///+ /// All parameters are required and are passed to the superclass constructor.+ IOSGoogleCastSessions({+ required super.device,+ required super.sessionID,+ required super.connectionState,+ required super.currentDeviceMuted,+ required super.currentDeviceVolume,+ required super.deviceStatusText,+ });++ /// Creates an [IOSGoogleCastSessions] instance from a [Map] (e.g., JSON).+ ///+ /// Returns `null` if the input [json] is `null`.+ /// Throws if required fields are missing or of incorrect type.+ static IOSGoogleCastSessions? fromMap(Map<String, dynamic>? json) {+ if (json == null) return null;+ return IOSGoogleCastSessions(+ device: GoogleCastIosDevice.fromMap(+ Map<String, dynamic>.from(json['device'])),+ sessionID: json['sessionID'],+ connectionState: GoogleCastConnectState.values[json['connectionState']],+ currentDeviceMuted: json['currentDeviceMuted'],+ currentDeviceVolume: json['currentDeviceVolume'],+ deviceStatusText: json['deviceStatusText'] ?? '',+ );+ }+}diff --git a/packages/flutter_chrome_cast/lib/models/ios/ios_media_information.dart b/packages/flutter_chrome_cast/lib/models/ios/ios_media_information.dartnew file mode 100644index 00000000..f41b0f42--- /dev/null+++ b/packages/flutter_chrome_cast/lib/models/ios/ios_media_information.dart@@ -0,0 +1,124 @@+import 'package:flutter_chrome_cast/lib.dart';+import 'package:flutter_chrome_cast/models/ios/ios_media_track.dart';++import 'metadata/generic.dart';+import 'metadata/movie.dart';+import 'metadata/music.dart';+import 'metadata/photo.dart';+import 'metadata/tv_show.dart';++/// iOS-specific implementation of [GoogleCastMediaInformation].+///+/// This class represents the media information required to load and control media playback+/// on Google Cast devices from iOS. It extends the cross-platform [GoogleCastMediaInformation]+/// and provides a factory for constructing from a platform channel map.+///+/// Typical usage involves creating an instance with all required media details, or using+/// [GoogleCastMediaInformationIOS.fromMap] to parse data received from the native iOS layer.+///+/// See also:+/// - [GoogleCastMediaInformation] for the base class and common fields+/// - [GoogleCastRemoteMediaClient] for loading and controlling media+/// - [GoogleCastMediaTrack] for track details+/// - [GoogleCastMediaMetadataType] for supported metadata types+class GoogleCastMediaInformationIOS extends GoogleCastMediaInformation {+ /// Creates a new [GoogleCastMediaInformationIOS] instance.+ ///+ /// All parameters are forwarded to the base [GoogleCastMediaInformation].+ GoogleCastMediaInformationIOS({+ required super.contentId,+ required super.streamType,+ required super.contentType,+ super.atvEntity,+ super.breakClips,+ super.breaks,+ super.contentUrl,+ super.customData,+ super.duration,+ super.entity,+ super.hlsSegmentFormat,+ super.hlsVideoSegmentFormat,+ super.metadata,+ super.startAbsoluteTime,+ super.textTrackStyle,+ super.tracks,+ super.userActionStates,+ super.vmapAdsRequest,+ });++ /// Creates a [GoogleCastMediaInformationIOS] from a [Map] received from the platform channel.+ ///+ /// The [map] parameter must contain the expected keys and value types as sent from iOS.+ factory GoogleCastMediaInformationIOS.fromMap(Map<String, dynamic> map) {+ return GoogleCastMediaInformationIOS(+ atvEntity: map['atvEntity'],+ breakClips: map['breakClips'] != null+ ? List<CastBreakClips>.from(+ map['breakClips']?.map((x) => CastBreakClips.fromMap(x)))+ : null,+ contentId: map['contentID'] ?? '',+ streamType: CastMediaStreamType.values[map['streamType']],+ contentType: map['contentType'] ?? '',+ metadata: map['metadata'] != null+ ? _getCastMediaMetadata(Map<String, dynamic>.from(map['metadata']))+ : null,+ duration: map['duration'] != null+ ? Duration(milliseconds: (map['duration'] * 1000).round())+ : null,+ customData: map['customData'] != null+ ? Map<String, dynamic>.from(map['customData'])+ : null,+ breaks: map['breaks'] != null+ ? List<CastBreak>.from(+ map['breaks']?.map((x) => CastBreak.fromMap(x)))+ : null,+ contentUrl: Uri.tryParse(map['contentURL'] ?? ''),+ entity: map['entity'],+ hlsSegmentFormat: map['hlsSegmentFormat'] != null+ ? CastHlsSegmentFormat.fromMap(map['hlsSegmentFormat'])+ : null,+ hlsVideoSegmentFormat: map['hlsVideoSegmentFormat'] != null+ ? HlsVideoSegmentFormat.fromMap(map['hlsVideoSegmentFormat'])+ : null,+ startAbsoluteTime: map['startAbsoluteTime'] != null+ ? DateTime.fromMillisecondsSinceEpoch(map['startAbsoluteTime'])+ : null,+ textTrackStyle: map['textTrackStyle'] != null+ ? TextTrackStyle.fromMap(map['textTrackStyle'])+ : null,+ tracks: map['tracks'] != null+ ? List<GoogleCastMediaTrack>.from(+ map['tracks']?.map(+ (x) => IosMediaTrack.fromMap(x),+ ),+ )+ : null,+ userActionStates: map['userActionStates'] != null+ ? List<UserActionState>.from(+ map['userActionStates']?.map((x) => UserActionState.fromMap(x)))+ : null,+ vmapAdsRequest: map['vmapAdsRequest'] != null+ ? VastAdsRequest.fromMap(map['vmapAdsRequest'])+ : null,+ );+ }+}++GoogleCastMediaMetadata? _getCastMediaMetadata(Map<String, dynamic> map) {+ final typeIndex = map['type'] ?? map['metadataType'];+ if (typeIndex == null) return null;+ final type = GoogleCastMediaMetadataType.values[typeIndex];+ if (type == GoogleCastMediaMetadataType.genericMediaMetadata) {+ return GoogleCastGenericMediaMetadataIOS.fromMap(map);+ } else if (type == GoogleCastMediaMetadataType.movieMediaMetadata) {+ return GoogleCastMovieMediaMetadataIOS.fromMap(map);+ } else if (type == GoogleCastMediaMetadataType.tvShowMediaMetadata) {+ return GoogleCastTvShowMediaMetadataIOS.fromMap(map);+ } else if (type == GoogleCastMediaMetadataType.musicTrackMediaMetadata) {+ return GoogleCastMusicMediaMetadataIOS.fromMap(map);+ } else if (type == GoogleCastMediaMetadataType.photoMediaMetadata) {+ return GooglCastPhotoMediaMetadataIOS.fromMap(map);+ } else {+ return null;+ }+}diff --git a/packages/flutter_chrome_cast/lib/models/ios/ios_media_status.dart b/packages/flutter_chrome_cast/lib/models/ios/ios_media_status.dartnew file mode 100644index 00000000..ba7a8054--- /dev/null+++ b/packages/flutter_chrome_cast/lib/models/ios/ios_media_status.dart@@ -0,0 +1,62 @@+import 'package:flutter_chrome_cast/lib.dart';++/// Represents the media status for a Google Cast session on iOS.+///+/// This class extends [GoggleCastMediaStatus] and provides additional+/// iOS-specific mapping and construction from platform channel data.+class GoogleCastIOSMediaStatus extends GoggleCastMediaStatus {+ /// Creates a new [GoogleCastIOSMediaStatus] instance.+ ///+ /// All parameters are forwarded to the base [GoggleCastMediaStatus].+ GoogleCastIOSMediaStatus({+ required super.mediaSessionID,+ required super.playerState,+ required super.playbackRate,+ required super.volume,+ required super.isMuted,+ required super.repeatMode,+ super.activeTrackIds,+ super.adBreakStatus,+ super.currentItemId,+ super.idleReason,+ super.liveSeekableRange,+ super.mediaInformation,+ // super.queueData,+ });++ /// Creates a [GoogleCastIOSMediaStatus] from a map received from the platform channel.+ ///+ /// The [map] parameter must contain the expected keys and value types as sent from iOS.+ factory GoogleCastIOSMediaStatus.fromMap(Map<String, dynamic> map) {+ return GoogleCastIOSMediaStatus(+ mediaSessionID: map['mediaSessionID']?.toInt() ?? 0,+ playerState: CastMediaPlayerState.values[map['playerState']],+ idleReason: map['idleReason'] != null+ ? GoogleCastMediaIdleReason.values[map['idleReason']]+ : null,+ playbackRate: map['playbackRate'] ?? 0,+ mediaInformation: map['mediaInformation'] != null+ ? GoogleCastMediaInformationIOS.fromMap(+ Map<String, dynamic>.from(map['mediaInformation']))+ : null,++ volume: map['volume'] ?? 0,+ isMuted: map['isMuted'] ?? true,+ repeatMode: GoogleCastMediaRepeatMode.values[(map['repeatMode'])],+ currentItemId: map['currentItemId']?.toInt(),++ activeTrackIds: map['activeTrackIds'] != null+ ? List<int>.from(map['activeTrackIds'])+ : [],+ // adBreakStatus: map['adBreakStatus'] != null+ // ? GoogleCastBrakeStatus.fromMap(map['adBreakStatus'])+ // : null,+ liveSeekableRange: map['liveSeekableRange'] != null+ ? GoogleCastMediaLiveSeekableRange.fromMap(map['liveSeekableRange'])+ : null,+ // queueData: map['queueData'] != null+ // ? GoogleCastMediaQueueData.fromMap(map['queueData'])+ // : null,+ );+ }+}diff --git a/packages/flutter_chrome_cast/lib/models/ios/ios_media_track.dart b/packages/flutter_chrome_cast/lib/models/ios/ios_media_track.dartnew file mode 100644index 00000000..c4c67eca--- /dev/null+++ b/packages/flutter_chrome_cast/lib/models/ios/ios_media_track.dart@@ -0,0 +1,41 @@+import 'package:flutter_chrome_cast/lib.dart';++/// Represents a media track for iOS platforms, extending [GoogleCastMediaTrack].+///+/// This class is used to model media track information specific to iOS when working+/// with Google Cast. It provides a convenient way to construct a media track from a map.+class IosMediaTrack extends GoogleCastMediaTrack {+ /// Creates an [IosMediaTrack] instance.+ ///+ /// [trackContentType], [trackId], and [type] are required. Other parameters are optional.+ IosMediaTrack({+ required super.trackContentType,+ required super.trackId,+ required super.type,+ super.customData,+ super.language,+ super.name,+ super.subtype,+ super.trackContentId,+ });++ /// Creates an [IosMediaTrack] from a [Map] representation, typically from platform channels.+ ///+ /// The [json] map should contain keys matching the expected track properties.+ factory IosMediaTrack.fromMap(Map json) {+ return IosMediaTrack(+ trackContentType: json['content_type'] ?? '',+ trackId: json['id'],+ type: TrackType.values[json['type']],+ language: Rfc5646Language.fromMap(json['language_code']),+ name: json['name'],+ subtype: json['subtype'] != null+ ? TextTrackType.values[json['subtype']]+ : null,+ trackContentId: json['content_id'],+ customData: json['custom_data'] != null+ ? Map<String, dynamic>.from(json['custom_data'])+ : null,+ );+ }+}diff --git a/packages/flutter_chrome_cast/lib/models/ios/ios_request.dart b/packages/flutter_chrome_cast/lib/models/ios/ios_request.dartnew file mode 100644index 00000000..9dc8bb21--- /dev/null+++ b/packages/flutter_chrome_cast/lib/models/ios/ios_request.dart@@ -0,0 +1,32 @@+import 'package:flutter_chrome_cast/entities/request.dart';++/// Represents a request specific to iOS for Google Cast operations.+///+/// Extends [GoogleCastRequest] to include iOS-specific request handling.+class GoogleCastIosRequest extends GoogleCastRequest {+ /// Creates a [GoogleCastIosRequest] instance.+ ///+ /// [inProgress] indicates if the request is currently in progress.+ /// [isExternal] specifies if the request is external.+ /// [requestID] is the unique identifier for the request.+ /// [error] is an optional error message if the request failed.+ GoogleCastIosRequest({+ required super.inProgress,+ required super.isExternal,+ required super.requestID,+ super.error,+ });++ /// Creates a [GoogleCastIosRequest] from a map, typically decoded from JSON.+ ///+ /// The [map] must contain the keys 'inProgress', 'isExternal', and 'requestID'.+ /// The 'error' key is optional.+ factory GoogleCastIosRequest.fromMap(Map<String, dynamic> map) {+ return GoogleCastIosRequest(+ inProgress: map['inProgress'] as bool,+ isExternal: map['isExternal'] as bool,+ requestID: map['requestID'] as int,+ error: map['error'] as String?,+ );+ }+}diff --git a/packages/flutter_chrome_cast/lib/models/ios/metadata/generic.dart b/packages/flutter_chrome_cast/lib/models/ios/metadata/generic.dartnew file mode 100644index 00000000..0ad4f56b--- /dev/null+++ b/packages/flutter_chrome_cast/lib/models/ios/metadata/generic.dart@@ -0,0 +1,29 @@+import 'package:flutter_chrome_cast/lib.dart';++/// iOS-specific implementation of generic media metadata.+class GoogleCastGenericMediaMetadataIOS extends GoogleCastGenericMediaMetadata {+ /// Creates an iOS generic media metadata instance.+ GoogleCastGenericMediaMetadataIOS({+ required super.title,+ required super.subtitle,+ required super.images,+ super.releaseDate,+ });++ /// Creates a generic media metadata instance from a map.+ factory GoogleCastGenericMediaMetadataIOS.fromMap(Map<String, dynamic> map) {+ return GoogleCastGenericMediaMetadataIOS(+ title: map['title'] as String?,+ subtitle: map['subtitle'] as String?,+ images: map['images'] != null+ ? (map['images'] as List)+ .map((x) => GoogleCastImage.fromMap(Map<String, dynamic>.from(x)))+ .whereType<GoogleCastImage>()+ .toList()+ : null,+ releaseDate: map['releaseDate'] != null && map['releaseDate'] is int+ ? DateTime.fromMillisecondsSinceEpoch(map['releaseDate'])+ : null,+ );+ }+}diff --git a/packages/flutter_chrome_cast/lib/models/ios/metadata/metadata.dart b/packages/flutter_chrome_cast/lib/models/ios/metadata/metadata.dartnew file mode 100644index 00000000..b873cb71--- /dev/null+++ b/packages/flutter_chrome_cast/lib/models/ios/metadata/metadata.dart@@ -0,0 +1,5 @@+export 'generic.dart';+export 'movie.dart';+export 'music.dart';+export 'photo.dart';+export 'tv_show.dart';diff --git a/packages/flutter_chrome_cast/lib/models/ios/metadata/movie.dart b/packages/flutter_chrome_cast/lib/models/ios/metadata/movie.dartnew file mode 100644index 00000000..cb9b0faf--- /dev/null+++ b/packages/flutter_chrome_cast/lib/models/ios/metadata/movie.dart@@ -0,0 +1,32 @@+import 'package:flutter_chrome_cast/common/image.dart';+import 'package:flutter_chrome_cast/entities/media_metadata/movie_media_metadata.dart';++/// iOS-specific implementation of movie media metadata.+class GoogleCastMovieMediaMetadataIOS extends GoogleCastMovieMediaMetadata {+ /// Creates an iOS movie media metadata instance.+ GoogleCastMovieMediaMetadataIOS({+ super.images,+ super.releaseDate,+ super.studio,+ super.subtitle,+ super.title,+ });++ /// Creates a movie media metadata instance from a map.+ factory GoogleCastMovieMediaMetadataIOS.fromMap(Map<String, dynamic> map) {+ return GoogleCastMovieMediaMetadataIOS(+ title: map['title'] as String?,+ subtitle: map['subtitle'] as String?,+ studio: map['studio'] as String?,+ images: map['images'] != null+ ? (map['images'] as List)+ .map((x) => GoogleCastImage.fromMap(Map<String, dynamic>.from(x)))+ .whereType<GoogleCastImage>()+ .toList()+ : null,+ releaseDate: map['releaseDate'] != null && map['releaseDate'] is int+ ? DateTime.fromMillisecondsSinceEpoch(map['releaseDate'])+ : null,+ );+ }+}diff --git a/packages/flutter_chrome_cast/lib/models/ios/metadata/music.dart b/packages/flutter_chrome_cast/lib/models/ios/metadata/music.dartnew file mode 100644index 00000000..d618adf8--- /dev/null+++ b/packages/flutter_chrome_cast/lib/models/ios/metadata/music.dart@@ -0,0 +1,40 @@+import 'package:flutter_chrome_cast/common/image.dart';+import 'package:flutter_chrome_cast/entities/media_metadata/music_track_media_metadata.dart';++/// iOS-specific implementation of music media metadata.+class GoogleCastMusicMediaMetadataIOS extends GoogleCastMusicMediaMetadata {+ /// Creates an iOS music media metadata instance.+ GoogleCastMusicMediaMetadataIOS({+ super.albumArtist,+ super.albumName,+ super.artist,+ super.composer,+ super.discNumber,+ super.images,+ super.releaseDate,+ super.title,+ super.trackNumber,+ });++ /// Creates a music media metadata instance from a map.+ factory GoogleCastMusicMediaMetadataIOS.fromMap(Map<String, dynamic> map) {+ return GoogleCastMusicMediaMetadataIOS(+ albumName: map['albumTitle'] as String?,+ title: map['title'] as String?,+ albumArtist: map['albumArtist'] as String?,+ artist: map['artist'] as String?,+ composer: map['composer'] as String?,+ trackNumber: map['trackNumber']?.toInt(),+ discNumber: map['discNumber']?.toInt(),+ images: map['images'] != null+ ? (map['images'] as List)+ .map((x) => GoogleCastImage.fromMap(Map<String, dynamic>.from(x)))+ .whereType<GoogleCastImage>()+ .toList()+ : null,+ releaseDate: map['releaseDate'] != null && map['releaseDate'] is int+ ? DateTime.fromMillisecondsSinceEpoch(map['releaseDate'])+ : null,+ );+ }+}diff --git a/packages/flutter_chrome_cast/lib/models/ios/metadata/photo.dart b/packages/flutter_chrome_cast/lib/models/ios/metadata/photo.dartnew file mode 100644index 00000000..80750cff--- /dev/null+++ b/packages/flutter_chrome_cast/lib/models/ios/metadata/photo.dart@@ -0,0 +1,32 @@+import 'package:flutter_chrome_cast/lib.dart';++/// iOS-specific implementation of photo media metadata.+class GooglCastPhotoMediaMetadataIOS extends GoogleCastPhotoMediaMetadata {+ /// Creates an iOS photo media metadata instance.+ GooglCastPhotoMediaMetadataIOS({+ super.artist,+ super.creationDateTime,+ super.height,+ super.latitude,+ super.location,+ super.longitude,+ super.title,+ super.width,+ });++ /// Creates a photo media metadata instance from a map.+ factory GooglCastPhotoMediaMetadataIOS.fromMap(Map<String, dynamic> map) {+ return GooglCastPhotoMediaMetadataIOS(+ title: map['title'],+ artist: map['albumArtist'],+ location: map['locationName'],+ latitude: map['locationLatitude']?.toDouble(),+ longitude: map['locationLongitude']?.toDouble(),+ width: map['width']?.toInt(),+ height: map['height']?.toInt(),+ creationDateTime: map['creationDate'] != null+ ? DateTime.fromMillisecondsSinceEpoch(map['creationDate'] ?? 0)+ : null,+ );+ }+}diff --git a/packages/flutter_chrome_cast/lib/models/ios/metadata/tv_show.dart b/packages/flutter_chrome_cast/lib/models/ios/metadata/tv_show.dartnew file mode 100644index 00000000..8540cea5--- /dev/null+++ b/packages/flutter_chrome_cast/lib/models/ios/metadata/tv_show.dart@@ -0,0 +1,31 @@+import 'package:flutter_chrome_cast/lib.dart';++/// iOS-specific implementation of TV show media metadata.+class GoogleCastTvShowMediaMetadataIOS extends GoogleCastTvShowMediaMetadata {+ /// Creates an iOS TV show media metadata instance.+ GoogleCastTvShowMediaMetadataIOS({+ super.episode,+ super.images,+ super.originalAirDate,+ super.season,+ super.seriesTitle,+ });++ /// Creates a TV show media metadata instance from a map.+ factory GoogleCastTvShowMediaMetadataIOS.fromMap(Map<String, dynamic> map) {+ return GoogleCastTvShowMediaMetadataIOS(+ seriesTitle: map['seriesTitle'] as String?,+ season: map['seasonNumber']?.toInt(),+ episode: map['episodeNumber']?.toInt(),+ images: map['images'] != null+ ? (map['images'] as List)+ .map((x) => GoogleCastImage.fromMap(Map<String, dynamic>.from(x)))+ .whereType<GoogleCastImage>()+ .toList()+ : null,+ originalAirDate: map['releaseDate'] != null+ ? DateTimeString.tryParse(map['releaseDate'])+ : null,+ );+ }+}diff --git a/packages/flutter_chrome_cast/lib/models/models.dart b/packages/flutter_chrome_cast/lib/models/models.dartnew file mode 100644index 00000000..eec0e9c8--- /dev/null+++ b/packages/flutter_chrome_cast/lib/models/models.dart@@ -0,0 +1,2 @@+export 'android/android.dart';+export 'ios/ios.dart';diff --git a/packages/flutter_chrome_cast/lib/session.dart b/packages/flutter_chrome_cast/lib/session.dartnew file mode 100644index 00000000..0b3f2032--- /dev/null+++ b/packages/flutter_chrome_cast/lib/session.dart@@ -0,0 +1,6 @@+/// Session Management functionality+///+/// This module provides access to cast session management.+library session;++export '_session_manager/_session_manager.dart';diff --git a/packages/flutter_chrome_cast/lib/themes.dart b/packages/flutter_chrome_cast/lib/themes.dartnew file mode 100644index 00000000..2edfc08b--- /dev/null+++ b/packages/flutter_chrome_cast/lib/themes.dart@@ -0,0 +1,4 @@+library themes;++export './widgets/themes/google_cast_player_texts.dart';+export './widgets/themes/google_cast_player_theme.dart';diff --git a/packages/flutter_chrome_cast/lib/utils.dart b/packages/flutter_chrome_cast/lib/utils.dartnew file mode 100644index 00000000..2d106479--- /dev/null+++ b/packages/flutter_chrome_cast/lib/utils.dart@@ -0,0 +1,7 @@+/// Utilities for Chrome Cast+///+/// This module provides access to utility functions and extensions.+library utils;++export './utils/extensions.dart';+export './utils/functions.dart';diff --git a/packages/flutter_chrome_cast/lib/utils/extensions.dart b/packages/flutter_chrome_cast/lib/utils/extensions.dartnew file mode 100644index 00000000..dc7d74d8--- /dev/null+++ b/packages/flutter_chrome_cast/lib/utils/extensions.dart@@ -0,0 +1,108 @@+import 'package:flutter_chrome_cast/lib.dart';++/// Extensions for [GoogleCastMediaMetadata] to provide additional functionality.+extension GoogleCastMediaMetadataExtensions on GoogleCastMediaMetadata {+ /// Extracts the title from the metadata based on the metadata type.+ String? get extractedTitle {+ final type = metadataType;+ String? title;+ final metadata = this;++ switch (type) {+ case GoogleCastMediaMetadataType.tvShowMediaMetadata:+ metadata as GoogleCastTvShowMediaMetadata;+ title = metadata.seriesTitle;+ break;+ case GoogleCastMediaMetadataType.genericMediaMetadata:+ metadata as GoogleCastGenericMediaMetadata;+ title = metadata.title;+ break;+ case GoogleCastMediaMetadataType.movieMediaMetadata:+ metadata as GoogleCastMovieMediaMetadata;+ title = metadata.title;+ break;+ case GoogleCastMediaMetadataType.musicTrackMediaMetadata:+ metadata as GoogleCastMusicMediaMetadata;+ title = metadata.title;+ break;+ case GoogleCastMediaMetadataType.photoMediaMetadata:+ metadata as GoogleCastPhotoMediaMetadata;+ title = metadata.title;+ break;+ default:+ }+ return title;+ }++ /// Extracts the subtitle from the metadata based on the metadata type.+ String? get extractedSubtitle {+ final type = metadataType;+ String? subtitle;+ final metadata = this;++ switch (type) {+ case GoogleCastMediaMetadataType.tvShowMediaMetadata:+ metadata as GoogleCastTvShowMediaMetadata;+ // For TV shows, create subtitle from season and episode info+ if (metadata.season != null && metadata.episode != null) {+ subtitle = 'S${metadata.season}E${metadata.episode}';+ } else if (metadata.season != null) {+ subtitle = 'Season ${metadata.season}';+ } else if (metadata.episode != null) {+ subtitle = 'Episode ${metadata.episode}';+ }+ break;+ case GoogleCastMediaMetadataType.genericMediaMetadata:+ metadata as GoogleCastGenericMediaMetadata;+ subtitle = metadata.subtitle;+ break;+ case GoogleCastMediaMetadataType.movieMediaMetadata:+ metadata as GoogleCastMovieMediaMetadata;+ subtitle = metadata.subtitle;+ break;+ case GoogleCastMediaMetadataType.musicTrackMediaMetadata:+ metadata as GoogleCastMusicMediaMetadata;+ // For music, use album name or artist as subtitle+ subtitle = metadata.albumName ?? metadata.artist;+ break;+ case GoogleCastMediaMetadataType.photoMediaMetadata:+ metadata as GoogleCastPhotoMediaMetadata;+ subtitle = metadata.artist;+ break;+ default:+ }+ //replace line breaks with spaces+ if (subtitle != null) {+ subtitle = subtitle.replaceAll('\n', ' ').replaceAll('\r', ' ');+ }+ return subtitle;+ }+}++/// Extensions for [Duration] to provide formatting functionality.+extension DurationExtension on Duration {+ /// Formats the duration as a readable string.+ String get formatted {+ int seconds = inSeconds;+ final days = seconds ~/ Duration.secondsPerDay;+ seconds -= days * Duration.secondsPerDay;+ final hours = seconds ~/ Duration.secondsPerHour;+ seconds -= hours * Duration.secondsPerHour;+ final minutes = seconds ~/ Duration.secondsPerMinute;+ seconds -= minutes * Duration.secondsPerMinute;++ final List<String> tokens = [];+ if (days != 0) {+ tokens.add('${days}d');+ }+ if (tokens.isNotEmpty || hours != 0) {+ tokens.add('$hours');+ }++ tokens.add('$minutes'.padLeft(2, '0'));++ tokens.add('$seconds'.padLeft(2, '0'));++ return tokens.join(':');+ }+}diff --git a/packages/flutter_chrome_cast/lib/utils/functions.dart b/packages/flutter_chrome_cast/lib/utils/functions.dartnew file mode 100644index 00000000..a201eaa8--- /dev/null+++ b/packages/flutter_chrome_cast/lib/utils/functions.dart@@ -0,0 +1,21 @@+import '../entities/entities.dart';++/// Calculates the playback percentage based on current position and total duration.+///+/// This function computes how much of the media has been played as a percentage+/// (0.0 to 1.0) based on the current playback position and the total media duration.+///+/// Returns null if either the current duration or media duration is null or zero.+/// Returns 1.0 if the percentage would exceed 100% (should not normally happen).+///+/// [mediaStatus] - The current media status containing duration information+/// [currentDuration] - The current playback position+double? getPlayerPercentage(+ GoggleCastMediaStatus mediaStatus, Duration? currentDuration) {+ if (currentDuration == null || currentDuration.inSeconds == 0) return null;+ final mediaDuration = mediaStatus.mediaInformation?.duration;+ if (mediaDuration == null || mediaDuration.inSeconds == 0) return null;+ final percentage = currentDuration.inSeconds / mediaDuration.inSeconds;+ if (percentage > 1) return 1;+ return percentage;+}diff --git a/packages/flutter_chrome_cast/lib/widgets.dart b/packages/flutter_chrome_cast/lib/widgets.dartnew file mode 100644index 00000000..906a7578--- /dev/null+++ b/packages/flutter_chrome_cast/lib/widgets.dart@@ -0,0 +1,8 @@+/// UI Widgets for Chrome Cast+///+/// This module provides all the UI widgets for cast functionality.+library widgets;++export './widgets/cast_volume.dart';+export './widgets/expanded_player.dart';+export './widgets/mini_controller.dart';diff --git a/packages/flutter_chrome_cast/lib/widgets/cast_volume.dart b/packages/flutter_chrome_cast/lib/widgets/cast_volume.dartnew file mode 100644index 00000000..ccbdc84a--- /dev/null+++ b/packages/flutter_chrome_cast/lib/widgets/cast_volume.dart@@ -0,0 +1,115 @@+import 'package:flutter/material.dart';+import 'package:flutter_chrome_cast/_session_manager/cast_session_manager.dart';+import 'package:get/get_rx/get_rx.dart';++/// A widget that provides volume control for Google Cast devices.+///+/// This widget displays a volume icon that, when tapped, shows a popup+/// with a slider to control the volume of the currently connected Cast device.+class GoogleCastVolume extends StatefulWidget {+ /// Color of the volume icon.+ final Color? iconColor;++ /// Size of the volume icon.+ final double? iconSize;++ /// Background color of the volume control popup.+ final Color? popupBackgroundColor;++ /// Color of the active portion of the volume slider.+ final Color? sliderActiveColor;++ /// Color of the inactive portion of the volume slider.+ final Color? sliderInactiveColor;++ /// Color of the volume slider thumb/handle.+ final Color? sliderThumbColor;++ /// Creates a Google Cast volume control widget.+ ///+ /// All styling parameters are optional and will use default Material Design+ /// colors if not specified.+ const GoogleCastVolume({+ super.key,+ this.iconColor,+ this.iconSize,+ this.popupBackgroundColor,+ this.sliderActiveColor,+ this.sliderInactiveColor,+ this.sliderThumbColor,+ });++ @override+ State<GoogleCastVolume> createState() => _GoogleCastVolumeState();+}++class _GoogleCastVolumeState extends State<GoogleCastVolume> {+ @override+ void initState() {+ GoogleCastSessionManager.instance.currentSessionStream.listen((event) {+ volumeLevel.value = event?.currentDeviceVolume ?? 0;+ volumeMuted.value = event?.currentDeviceMuted ?? false;+ });+ super.initState();+ }++ final volumeLevel = 0.5.obs;+ final volumeMuted = false.obs;+ bool isSliderTapDown = false;++ @override+ Widget build(BuildContext context) {+ return PopupMenuButton(+ padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 4),+ shape: RoundedRectangleBorder(+ borderRadius: BorderRadius.circular(10),+ ),+ color: widget.popupBackgroundColor,+ icon: StreamBuilder(+ stream: volumeMuted.stream,+ builder: (context, snapshot) {+ return Icon(+ volumeMuted.value || volumeLevel.value == 0+ ? Icons.volume_off+ : Icons.volume_up,+ color: widget.iconColor ?? Colors.white,+ size: widget.iconSize ?? 44,+ );+ }),+ itemBuilder: (context) {+ return [+ PopupMenuItem(+ enabled: false,+ child: StreamBuilder(+ stream: volumeLevel.stream,+ builder: (context, snapshot) {+ return Slider(+ value: volumeLevel.value,+ onChanged: _onVolumeChanged,+ onChangeStart: _onVolumeChangedStart,+ onChangeEnd: _onVolumeChangedEnd,+ activeColor: widget.sliderActiveColor,+ inactiveColor: widget.sliderInactiveColor,+ thumbColor: widget.sliderThumbColor,+ );+ },+ ),+ ),+ ];+ },+ );+ }++ void _onVolumeChangedEnd(double value) {+ isSliderTapDown = false;+ GoogleCastSessionManager.instance.setDeviceVolume(value);+ }++ void _onVolumeChangedStart(double value) {+ isSliderTapDown = true;+ }++ void _onVolumeChanged(double value) {+ volumeLevel.value = value;+ }+}diff --git a/packages/flutter_chrome_cast/lib/widgets/expanded_player.dart b/packages/flutter_chrome_cast/lib/widgets/expanded_player.dartnew file mode 100644index 00000000..fe6da4fd--- /dev/null+++ b/packages/flutter_chrome_cast/lib/widgets/expanded_player.dart@@ -0,0 +1,1098 @@+import 'dart:ui';+import 'package:flutter/cupertino.dart';+import 'package:flutter/material.dart';+import 'package:marquee/marquee.dart';+import 'package:flutter_chrome_cast/lib.dart' hide GoogleCastPlayerTexts;+import 'package:flutter_chrome_cast/themes.dart';++/// A full-screen cast player controller widget that displays media information,+/// playback controls, and cast session details.+///+/// This widget provides a rich media player interface with customizable theming+/// and text content. It supports drag-to-dismiss gestures and displays:+/// - Media artwork and title+/// - Playback progress and controls+/// - Caption/subtitle selection+/// - Volume control+/// - Cast device information+///+/// Example usage:+/// ```dart+/// ExpandedGoogleCastPlayerController(+/// toggleExpand: () => Navigator.pop(context),+/// theme: ExpandedGoogleCastPlayerTheme(+/// backgroundColor: Colors.black,+/// titleTextStyle: TextStyle(fontSize: 24, color: Colors.white),+/// ),+/// texts: ExpandedGoogleCastPlayerTexts(+/// nowPlaying: 'Now Playing',+/// unknownTitle: 'Unknown Media',+/// castingToDevice: (device) => 'Playing on $device',+/// ),+/// )+/// ```+class ExpandedGoogleCastPlayerController extends StatefulWidget {+ /// Callback function called when the user wants to collapse the expanded player+ final void Function()? toggleExpand;++ /// Theme configuration for customizing the visual appearance+ final GoogleCastPlayerTheme? theme;++ /// Text configuration for customizing all displayed text content+ final GoogleCastPlayerTexts? texts;++ /// Creates an expanded Google Cast player controller.+ const ExpandedGoogleCastPlayerController(+ {super.key, this.toggleExpand, this.theme, this.texts});++ @override+ State<ExpandedGoogleCastPlayerController> createState() =>+ _ExpandedGoogleCastPlayerControllerState();+}++class _ExpandedGoogleCastPlayerControllerState+ extends State<ExpandedGoogleCastPlayerController>+ with TickerProviderStateMixin {+ bool _isSliding = false;+ double _sliderPercentage = 0;+ late AnimationController _playPauseController;+ late AnimationController _dragController;+ double _dragOffset = 0;+ bool _isDragging = false;++ @override+ void initState() {+ super.initState();+ _playPauseController = AnimationController(+ vsync: this,+ duration: const Duration(milliseconds: 300),+ value: 1.0,+ );+ _dragController = AnimationController(+ vsync: this,+ duration: const Duration(milliseconds: 250),+ );+ }++ @override+ void dispose() {+ _playPauseController.dispose();+ _dragController.dispose();+ super.dispose();+ }++ @override+ Widget build(BuildContext context) {+ final theme = widget.theme;+ final texts = widget.texts ?? const GoogleCastPlayerTexts();+ return StreamBuilder<GoggleCastMediaStatus?>(+ stream: GoogleCastRemoteMediaClient.instance.mediaStatusStream,+ builder: (context, snapshot) {+ // Use snapshot.data to get the latest value from the stream+ final mediaStatus =+ snapshot.data ?? GoogleCastRemoteMediaClient.instance.mediaStatus;+ final deviceName = GoogleCastSessionManager+ .instance.currentSession?.device?.friendlyName;+ if (mediaStatus == null) return const SizedBox.shrink();+ return GestureDetector(+ onVerticalDragStart: (details) {+ _dragController.stop();+ setState(() {+ _isDragging = true;+ });+ },+ onVerticalDragUpdate: (details) {+ setState(() {+ _dragOffset += details.delta.dy;+ // Apply resistance when dragging upward+ if (_dragOffset < 0) {+ _dragOffset *= 0.2; // More resistance upward+ }+ // Add some velocity-based smoothing+ final velocity = details.delta.dy.abs();+ if (velocity > 5) {+ _dragOffset *= 0.95; // Slight smoothing for fast drags+ }+ _dragOffset = _dragOffset.clamp(-50.0, 300.0);+ });+ },+ onVerticalDragEnd: (details) {+ final velocity = details.velocity.pixelsPerSecond.dy;+ final shouldDismiss = _dragOffset > 60 ||+ velocity > 600; // More responsive thresholds++ if (shouldDismiss) {+ widget.toggleExpand?.call();+ } else {+ // Smooth animation back to original position+ final startOffset = _dragOffset;+ _dragController.reset();++ // Create a temporary listener for this animation+ void animationListener() {+ setState(() {+ _dragOffset = startOffset * (1 - _dragController.value);+ });+ }++ _dragController.addListener(animationListener);++ _dragController+ .animateTo(+ 1.0,+ duration: const Duration(milliseconds: 400),+ curve: Curves.elasticOut,+ )+ .then((_) {+ _dragController.removeListener(animationListener);+ setState(() {+ _dragOffset = 0;+ _isDragging = false;+ });+ });+ }+ },+ child: Transform.translate(+ offset: Offset(0, _dragOffset),+ child: Opacity(+ opacity: _isDragging+ ? (1 - (_dragOffset / 300))+ .clamp(0.4, 1.0) // Slower opacity fade for better UX+ : 1.0,+ child: Scaffold(+ extendBodyBehindAppBar: true,+ appBar: AppBar(+ elevation: 0,+ backgroundColor: Colors.transparent,+ leading: Container(+ decoration: BoxDecoration(+ color: Colors.black.withValues(alpha: 0.7),+ borderRadius: BorderRadius.circular(16),+ border: Border.all(+ color: Colors.white.withValues(alpha: 0.2),+ width: 1,+ ),+ ),+ margin: const EdgeInsets.all(8),+ child: IconButton(+ onPressed: widget.toggleExpand,+ icon: const Icon(+ CupertinoIcons.chevron_down,+ color: Colors.white,+ ),+ ),+ ),+ title: Hero(+ tag: 'com.felnanuke.google_cast.controller.title',+ child: Text(+ texts.nowPlaying,+ style: theme?.titleTextStyle ??+ Theme.of(context).textTheme.titleLarge,+ ),+ ),+ actions: [+ Container(+ decoration: BoxDecoration(+ color: Colors.black.withValues(alpha: 0.7),+ borderRadius: BorderRadius.circular(16),+ border: Border.all(+ color: Colors.white.withValues(alpha: 0.2),+ width: 1,+ ),+ ),+ margin: const EdgeInsets.all(8),+ child: IconButton(+ onPressed: _onCastPressed,+ icon: const Icon(+ Icons.cast,+ color: Colors.white,+ ),+ ),+ )+ ],+ ),+ body: Stack(+ fit: StackFit.expand,+ children: [+ if (theme?.backgroundWidget != null)+ theme!.backgroundWidget!+ else+ Hero(+ tag:+ 'com.felnanuke.google_cast.controller.background',+ child: _buildBackgroundImage(mediaStatus),+ ),+ // Blurred overlay for better contrast+ BackdropFilter(+ filter: ImageFilter.blur(sigmaX: 16, sigmaY: 16),+ child: Container(+ color: Colors.black.withValues(alpha: 0.3),+ ),+ ),+ // Drag handle indicator+ Positioned(+ top: 8,+ left: 0,+ right: 0,+ child: Center(+ child: AnimatedContainer(+ duration: const Duration(milliseconds: 150),+ width: _isDragging ? 70 : 40,+ height: _isDragging ? 5 : 4,+ decoration: BoxDecoration(+ color: _isDragging+ ? Colors.white.withValues(alpha: 0.9)+ : Colors.white.withValues(alpha: 0.5),+ borderRadius: BorderRadius.circular(3),+ boxShadow: _isDragging+ ? [+ BoxShadow(+ color:+ Colors.white.withValues(alpha: 0.4),+ blurRadius: 12,+ spreadRadius: 2,+ ),+ ]+ : [+ BoxShadow(+ color:+ Colors.black.withValues(alpha: 0.3),+ blurRadius: 4,+ offset: const Offset(0, 1),+ ),+ ],+ ),+ ),+ ),+ ),+ Container(+ decoration: BoxDecoration(+ borderRadius: BorderRadius.circular(32),+ gradient: theme?.backgroundGradient ??+ LinearGradient(+ tileMode: TileMode.clamp,+ begin: Alignment.topCenter,+ end: Alignment.bottomCenter,+ colors: [+ const Color(0xFF232526),+ const Color(0xFF414345),+ Colors.black.withValues(alpha: 0.7),+ ]),+ ),+ ),+ // Media Image Display+ Center(+ child: Padding(+ padding: const EdgeInsets.symmetric(horizontal: 32),+ child: Column(+ mainAxisAlignment: MainAxisAlignment.center,+ children: [+ // Media Image+ Container(+ constraints: BoxConstraints(+ maxWidth: theme?.imageMaxWidth ?? 300,+ maxHeight: theme?.imageMaxHeight ?? 300,+ ),+ decoration: BoxDecoration(+ borderRadius: theme?.imageBorderRadius ??+ BorderRadius.circular(16),+ boxShadow: theme?.imageShadow ??+ [+ BoxShadow(+ color: Colors.black+ .withValues(alpha: 0.4),+ blurRadius: 20,+ offset: const Offset(0, 8),+ ),+ ],+ ),+ child: ClipRRect(+ borderRadius: theme?.imageBorderRadius ??+ BorderRadius.circular(16),+ child: Hero(+ tag:+ 'com.felnanuke.google_cast.controller.image',+ child: AspectRatio(+ aspectRatio: 1.0,+ child: _buildMediaImage(mediaStatus),+ ),+ ),+ ),+ ),+ const SizedBox(height: 24),+ // Media Title and Subtitle with marquee scrolling+ Container(+ width: double.infinity,+ padding:+ const EdgeInsets.symmetric(horizontal: 16),+ child: _buildTitleAndSubtitle(+ mediaStatus, texts, theme, context),+ ),+ const SizedBox(+ height:+ 160), // Increased space for controls and device name positioning+ ],+ ),+ ),+ ),+ Positioned(+ bottom:+ 220, // Moved even higher to avoid slider overlap+ left: 16,+ right: 16,+ child: Center(+ child: Container(+ margin: const EdgeInsets.symmetric(horizontal: 32),+ padding: const EdgeInsets.symmetric(+ horizontal: 16, vertical: 8),+ decoration: BoxDecoration(+ color: Colors.black.withValues(alpha: 0.4),+ borderRadius: BorderRadius.circular(16),+ boxShadow: [+ BoxShadow(+ color: Colors.black.withValues(alpha: 0.2),+ blurRadius: 8,+ offset: const Offset(0, 2),+ ),+ ],+ ),+ child: Text(+ texts.castingToDevice(+ deviceName ?? 'Unknown Device'),+ style: theme?.deviceTextStyle ??+ Theme.of(context)+ .textTheme+ .titleSmall+ ?.copyWith(+ color: Colors.white,+ ),+ textAlign: TextAlign.center,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ ),+ ),+ ),+ ),+ Positioned(+ bottom: 24,+ left: 0,+ right: 0,+ child: Column(+ mainAxisSize: MainAxisSize.min,+ children: [+ Padding(+ padding:+ const EdgeInsets.symmetric(horizontal: 24),+ child: Row(+ mainAxisAlignment:+ MainAxisAlignment.spaceEvenly,+ children: [+ StreamBuilder<Duration?>(+ stream: GoogleCastRemoteMediaClient+ .instance.playerPositionStream,+ builder: (context, snapshot) {+ return SizedBox(+ width: 48,+ child: Text(+ (mediaStatus.mediaInformation+ ?.streamType ==+ CastMediaStreamType+ .live &&+ (mediaStatus.mediaInformation+ ?.duration ==+ null ||+ mediaStatus+ .mediaInformation!+ .duration!+ .inSeconds ==+ 0))+ ? ''+ : _isSliding+ ? _getDurationToSeek(+ _sliderPercentage,+ mediaStatus)+ .formatted+ : GoogleCastRemoteMediaClient+ .instance+ .playerPosition+ .formatted,+ style: theme?.timeTextStyle ??+ Theme.of(context)+ .textTheme+ .bodySmall+ ?.copyWith(+ color: Colors.white,+ ),+ ),+ );+ },+ ),+ _buildSlider(mediaStatus, theme),+ SizedBox(+ width: 48,+ child: Text(+ (mediaStatus.mediaInformation+ ?.streamType ==+ CastMediaStreamType.live &&+ (mediaStatus.mediaInformation+ ?.duration ==+ null ||+ mediaStatus+ .mediaInformation!+ .duration!+ .inSeconds ==+ 0))+ ? 'LIVE'+ : mediaStatus.mediaInformation+ ?.duration?.formatted ??+ '-',+ style: theme?.timeTextStyle ??+ Theme.of(context)+ .textTheme+ .bodySmall+ ?.copyWith(+ color: Colors.white,+ ),+ ),+ ),+ ],+ ),+ ),+ const SizedBox(height: 12),+ Container(+ padding: const EdgeInsets.symmetric(+ horizontal: 16, vertical: 12),+ decoration: BoxDecoration(+ color: Colors.black.withValues(alpha: 0.4),+ borderRadius: BorderRadius.circular(32),+ boxShadow: [+ BoxShadow(+ color: Colors.black.withValues(alpha: 0.15),+ blurRadius: 12,+ offset: const Offset(0, 4),+ ),+ ],+ ),+ child: Column(+ mainAxisSize: MainAxisSize.min,+ children: [+ // Main playback controls row+ Row(+ mainAxisAlignment:+ MainAxisAlignment.spaceEvenly,+ children: [+ IconButton(+ onPressed: _previous,+ icon: const Icon(Icons.skip_previous),+ iconSize: theme?.iconSize ?? 40,+ color: theme?.iconColor ?? Colors.white,+ ),+ IconButton(+ onPressed: _seekBackward30,+ icon: const Icon(Icons.replay_30),+ iconSize: theme?.iconSize ?? 40,+ color: theme?.iconColor ?? Colors.white,+ ),+ GestureDetector(+ behavior: HitTestBehavior.opaque,+ onTap: () {+ debugPrint(+ '[Flutter] Play/Pause GestureDetector tapped! playerState: ${mediaStatus.playerState} (index: ${mediaStatus.playerState.index})');+ _togglePlayAndPause(+ mediaStatus.playerState);+ // Treat buffering as playing for animation (not loading - loading means resuming)+ final isPlaying = mediaStatus+ .playerState ==+ CastMediaPlayerState+ .playing ||+ mediaStatus.playerState ==+ CastMediaPlayerState+ .buffering ||+ mediaStatus.playerState ==+ CastMediaPlayerState.loading;+ if (isPlaying) {+ _playPauseController.reverse();+ } else {+ _playPauseController.forward();+ }+ },+ child: Container(+ padding: const EdgeInsets.all(8),+ child: AnimatedIcon(+ icon: AnimatedIcons.play_pause,+ progress: _playPauseController,+ color: theme?.iconColor ??+ Colors.white,+ size: theme?.iconSize != null+ ? theme!.iconSize! + 16+ : 56,+ ),+ ),+ ),+ IconButton(+ onPressed: _seekForward30,+ icon: const Icon(Icons.forward_30),+ iconSize: theme?.iconSize ?? 40,+ color: theme?.iconColor ?? Colors.white,+ ),+ IconButton(+ color: theme?.iconColor ?? Colors.white,+ onPressed: GoogleCastRemoteMediaClient+ .instance.queueHasNextItem+ ? _next+ : null,+ disabledColor:+ theme?.disabledIconColor ??+ Colors.grey,+ icon: const Icon(Icons.skip_next),+ iconSize: theme?.iconSize ?? 40,+ ),+ ],+ ),+ const SizedBox(height: 8),+ // Additional controls row+ Row(+ mainAxisAlignment:+ MainAxisAlignment.spaceEvenly,+ children: [+ PopupMenuButton<int>(+ itemBuilder: (context) =>+ _buildCaptionMenuItems(+ mediaStatus, texts, theme),+ onSelected: (trackId) =>+ _toggleTextTrack(+ trackId, mediaStatus),+ icon: Icon(+ Icons.closed_caption,+ color:+ theme?.iconColor ?? Colors.white,+ ),+ iconSize: theme?.iconSize ?? 40,+ color: theme?.popupBackgroundColor ??+ const Color(0xFF333333),+ shape: RoundedRectangleBorder(+ borderRadius:+ BorderRadius.circular(8),+ ),+ ),+ GoogleCastVolume(+ iconColor:+ theme?.iconColor ?? Colors.white,+ iconSize: theme?.iconSize ?? 40,+ popupBackgroundColor:+ theme?.popupBackgroundColor ??+ const Color(0xFF333333),+ sliderActiveColor:+ theme?.volumeSliderActiveColor,+ sliderInactiveColor:+ theme?.volumeSliderInactiveColor,+ sliderThumbColor:+ theme?.volumeSliderThumbColor,+ ),+ ],+ ),+ ],+ ),+ )+ ],+ ),+ ),+ ],+ ),+ ),+ ),+ ),+ );+ });+ }++ Expanded _buildSlider(+ GoggleCastMediaStatus? mediaStatus, GoogleCastPlayerTheme? theme) {+ return Expanded(+ child: StreamBuilder<Duration>(+ stream: GoogleCastRemoteMediaClient.instance.playerPositionStream,+ builder: (context, snapshot) {+ return SliderTheme(+ data: SliderTheme.of(context).copyWith(+ thumbShape: const RoundSliderThumbShape(enabledThumbRadius: 10),+ overlayShape: const RoundSliderOverlayShape(overlayRadius: 18),+ trackHeight: 4,+ activeTrackColor:+ theme?.iconColor ?? Theme.of(context).colorScheme.primary,+ inactiveTrackColor:+ theme?.iconColor?.withValues(alpha: 0.3) ?? Colors.white30,+ thumbColor: theme?.iconColor ?? Colors.white,+ overlayColor:+ (theme?.iconColor ?? Colors.white).withValues(alpha: 0.2),+ ),+ child: Slider(+ value: (mediaStatus?.mediaInformation?.streamType ==+ CastMediaStreamType.live &&+ (mediaStatus?.mediaInformation?.duration == null ||+ mediaStatus+ ?.mediaInformation?.duration?.inSeconds ==+ 0))+ ? 1.0+ : _isSliding+ ? _sliderPercentage+ : _getProgressPercentage(+ mediaStatus,+ GoogleCastRemoteMediaClient.instance.playerPosition,+ ),+ onChanged: (mediaStatus?.mediaInformation?.streamType ==+ CastMediaStreamType.live &&+ (mediaStatus?.mediaInformation?.duration == null ||+ mediaStatus+ ?.mediaInformation?.duration?.inSeconds ==+ 0))+ ? null+ : _onSliderChanged,+ onChangeStart: (mediaStatus?.mediaInformation?.streamType ==+ CastMediaStreamType.live &&+ (mediaStatus?.mediaInformation?.duration == null ||+ mediaStatus+ ?.mediaInformation?.duration?.inSeconds ==+ 0))+ ? null+ : _onSliderStarts,+ onChangeEnd: (mediaStatus?.mediaInformation?.streamType ==+ CastMediaStreamType.live &&+ (mediaStatus?.mediaInformation?.duration == null ||+ mediaStatus+ ?.mediaInformation?.duration?.inSeconds ==+ 0))+ ? null+ : (value) => _onSliderEnd.call(value, mediaStatus!),+ ),+ );+ }),+ );+ }++ void _onCastPressed() async {+ try {+ await GoogleCastSessionManager.instance.endSession();+ } catch (e) {+ // Handle potential errors silently+ // In a production app, you might want to show a snackbar or log the error+ debugPrint('Failed to end cast session: $e');+ }+ }++ void _previous() => GoogleCastRemoteMediaClient.instance.queuePrevItem();++ void _togglePlayAndPause(CastMediaPlayerState playerState) {+ debugPrint(+ '[Flutter] _togglePlayAndPause called with state: $playerState (index: ${playerState.index})');+ switch (playerState) {+ case CastMediaPlayerState.playing:+ case CastMediaPlayerState.buffering:+ case CastMediaPlayerState.loading:+ // When playing or buffering - pause the media+ debugPrint('[Flutter] Calling pause()');+ GoogleCastRemoteMediaClient.instance.pause();+ break;+ case CastMediaPlayerState.paused:+ case CastMediaPlayerState.idle:+ case CastMediaPlayerState.unknown:+ // When paused, idle, loading, or unknown - play the media+ debugPrint('[Flutter] Calling play()');+ GoogleCastRemoteMediaClient.instance.play();+ break;+ }+ }++ void _next() => GoogleCastRemoteMediaClient.instance.queueNextItem();++ void _seekBackward30() {+ debugPrint('[Flutter] _seekBackward30 called');+ GoogleCastRemoteMediaClient.instance.seek(+ GoogleCastMediaSeekOption(+ position: const Duration(seconds: -30),+ relative: true,+ resumeState: GoogleCastMediaResumeState.play,+ ),+ );+ }++ void _seekForward30() {+ GoogleCastRemoteMediaClient.instance.seek(+ GoogleCastMediaSeekOption(+ position: const Duration(seconds: 30),+ relative: true,+ resumeState: GoogleCastMediaResumeState.play,+ ),+ );+ }++ double _getProgressPercentage(+ GoggleCastMediaStatus? mediaStatus, Duration playerPosition) {+ final mediaDuration =+ mediaStatus?.mediaInformation?.duration ?? Duration.zero;++ if (mediaDuration.inSeconds == 0) return 0;++ if (playerPosition.inSeconds == 0) return 0;++ return playerPosition.inSeconds / mediaDuration.inSeconds;+ }++ void _onSliderStarts(double value) {+ setState(() {+ _isSliding = true;+ _sliderPercentage = value;+ });+ }++ void _onSliderChanged(double value) {+ setState(() {+ _sliderPercentage = value;+ });+ }++ void _onSliderEnd(double value, GoggleCastMediaStatus mediaStatus) {+ setState(() {+ _isSliding = false;+ });+ final durationToSeek = _getDurationToSeek(value, mediaStatus);+ debugPrint('[Flutter] Slider seek to: ${durationToSeek.inSeconds} seconds');+ GoogleCastRemoteMediaClient.instance.seek(+ GoogleCastMediaSeekOption(+ position: durationToSeek,+ resumeState: GoogleCastMediaResumeState.play,+ ),+ );+ }++ Duration _getDurationToSeek(double value, GoggleCastMediaStatus mediaStatus) {+ final duration = mediaStatus.mediaInformation?.duration ?? Duration.zero;+ final secondsToSeek = duration.inSeconds * value;+ final durationToSeek = Duration(seconds: secondsToSeek.round());+ return durationToSeek;+ }++ Widget _buildMediaImage(GoggleCastMediaStatus? mediaStatus) {+ final theme = widget.theme;+ final images = mediaStatus?.mediaInformation?.metadata?.images;++ // Try to find the best image (largest one or first available)+ String? imageUrl;+ if (images != null && images.isNotEmpty) {+ // Sort by size and pick the largest, or just use the first one+ final sortedImages = List<GoogleCastImage>.from(images);+ sortedImages.sort((a, b) {+ final aSize = (a.width ?? 0) * (a.height ?? 0);+ final bSize = (b.width ?? 0) * (b.height ?? 0);+ return bSize.compareTo(aSize); // Descending order+ });+ imageUrl = sortedImages.first.url.toString();+ }++ if (imageUrl != null && imageUrl.isNotEmpty) {+ return Image.network(+ imageUrl,+ fit: theme?.imageFit ?? BoxFit.cover,+ loadingBuilder: (context, child, loadingProgress) {+ if (loadingProgress == null) return child;+ return Container(+ color: Colors.grey[800],+ child: Center(+ child: CircularProgressIndicator(+ value: loadingProgress.expectedTotalBytes != null+ ? loadingProgress.cumulativeBytesLoaded /+ loadingProgress.expectedTotalBytes!+ : null,+ color: Colors.white54,+ ),+ ),+ );+ },+ errorBuilder: (context, error, stackTrace) =>+ theme?.noImageFallback ??+ Container(+ color: Colors.grey[800],+ child: const Icon(+ Icons.music_note,+ size: 80,+ color: Colors.white54,+ ),+ ),+ );+ }++ // Use custom fallback or default+ return theme?.noImageFallback ??+ Container(+ color: Colors.grey[800],+ child: Icon(+ _getMediaIcon(+ mediaStatus?.mediaInformation?.metadata?.metadataType),+ size: 80,+ color: Colors.white54,+ ),+ );+ }++ IconData _getMediaIcon(GoogleCastMediaMetadataType? metadataType) {+ switch (metadataType) {+ case GoogleCastMediaMetadataType.movieMediaMetadata:+ return Icons.movie;+ case GoogleCastMediaMetadataType.musicTrackMediaMetadata:+ return Icons.music_note;+ case GoogleCastMediaMetadataType.tvShowMediaMetadata:+ return Icons.tv;+ case GoogleCastMediaMetadataType.photoMediaMetadata:+ return Icons.photo;+ case GoogleCastMediaMetadataType.genericMediaMetadata:+ default:+ return Icons.play_circle_filled;+ }+ }++ Widget _buildBackgroundImage(GoggleCastMediaStatus? mediaStatus) {+ final images = mediaStatus?.mediaInformation?.metadata?.images;++ // Try to find the best image for background+ String? imageUrl;+ if (images != null && images.isNotEmpty) {+ final sortedImages = List<GoogleCastImage>.from(images);+ sortedImages.sort((a, b) {+ final aSize = (a.width ?? 0) * (a.height ?? 0);+ final bSize = (b.width ?? 0) * (b.height ?? 0);+ return bSize.compareTo(aSize); // Descending order+ });+ imageUrl = sortedImages.first.url.toString();+ }++ if (imageUrl != null && imageUrl.isNotEmpty) {+ return Image.network(+ imageUrl,+ fit: BoxFit.cover,+ errorBuilder: (context, error, stackTrace) => Container(+ color: Colors.grey[900],+ child: const Icon(+ Icons.music_note,+ size: 100,+ color: Colors.white54,+ ),+ ),+ );+ }++ return Container(+ color: Colors.grey[900],+ child: Icon(+ _getMediaIcon(mediaStatus?.mediaInformation?.metadata?.metadataType),+ size: 100,+ color: Colors.white54,+ ),+ );+ }++ /// Build menu items for available text tracks+ List<PopupMenuEntry<int>> _buildCaptionMenuItems(+ GoggleCastMediaStatus? mediaStatus,+ GoogleCastPlayerTexts texts,+ GoogleCastPlayerTheme? theme) {+ final tracks = mediaStatus?.mediaInformation?.tracks;+ final activeTrackIds = mediaStatus?.activeTrackIds ?? [];++ if (tracks == null || tracks.isEmpty) {+ return [+ PopupMenuItem<int>(+ enabled: false,+ child: Text(+ texts.noCaptionsAvailable,+ style: theme?.popupTextStyle ??+ TextStyle(+ color: theme?.popupTextColor ?? Colors.white,+ ),+ ),+ ),+ ];+ }++ final textTracks = tracks+ .where((track) =>+ track.type == TrackType.text ||+ track.subtype == TextTrackType.subtitles ||+ track.subtype == TextTrackType.captions)+ .toList();++ if (textTracks.isEmpty) {+ return [];+ }++ final menuItems = <PopupMenuEntry<int>>[];++ // Add "Off" option+ menuItems.add(+ PopupMenuItem<int>(+ value: -1,+ child: Row(+ children: [+ Icon(+ activeTrackIds.isEmpty ? Icons.check : null,+ color: theme?.popupTextColor ?? Colors.white,+ size: 20,+ ),+ const SizedBox(width: 8),+ Text(+ texts.captionsOff,+ style: theme?.popupTextStyle ??+ TextStyle(+ color: theme?.popupTextColor ?? Colors.white,+ ),+ ),+ ],+ ),+ ),+ );++ // Add available text tracks+ for (final track in textTracks) {+ final isActive = activeTrackIds.contains(track.trackId);+ menuItems.add(+ PopupMenuItem<int>(+ value: track.trackId,+ child: Row(+ children: [+ Icon(+ isActive ? Icons.check : null,+ color: theme?.popupTextColor ?? Colors.white,+ size: 20,+ ),+ const SizedBox(width: 8),+ Expanded(+ child: Text(+ track.name ??+ track.language?.toString() ??+ texts.trackFallback(track.trackId),+ overflow: TextOverflow.ellipsis,+ style: theme?.popupTextStyle ??+ TextStyle(+ color: theme?.popupTextColor ?? Colors.white,+ ),+ ),+ ),+ ],+ ),+ ),+ );+ }++ return menuItems;+ }++ /// Toggle text track on/off+ void _toggleTextTrack(int trackId, GoggleCastMediaStatus? mediaStatus) {+ final activeTrackIds = List<int>.from(mediaStatus?.activeTrackIds ?? []);++ if (trackId == -1) {+ // Turn off all text tracks+ final tracks = mediaStatus?.mediaInformation?.tracks;+ if (tracks != null) {+ final textTrackIds = tracks+ .where((track) =>+ track.type == TrackType.text ||+ track.subtype == TextTrackType.subtitles ||+ track.subtype == TextTrackType.captions)+ .map((track) => track.trackId)+ .toList();++ activeTrackIds.removeWhere((id) => textTrackIds.contains(id));+ }+ } else {+ // Toggle specific track+ if (activeTrackIds.contains(trackId)) {+ activeTrackIds.remove(trackId);+ } else {+ // Remove other text tracks first (only one text track at a time)+ final tracks = mediaStatus?.mediaInformation?.tracks;+ if (tracks != null) {+ final textTrackIds = tracks+ .where((track) =>+ track.type == TrackType.text ||+ track.subtype == TextTrackType.subtitles ||+ track.subtype == TextTrackType.captions)+ .map((track) => track.trackId)+ .toList();++ activeTrackIds.removeWhere((id) => textTrackIds.contains(id));+ }+ activeTrackIds.add(trackId);+ }+ }++ // Update active tracks+ GoogleCastRemoteMediaClient.instance.setActiveTrackIDs(activeTrackIds);+ }++ /// Build title and subtitle with marquee scrolling, displayed vertically+ Widget _buildTitleAndSubtitle(+ GoggleCastMediaStatus mediaStatus,+ GoogleCastPlayerTexts texts,+ GoogleCastPlayerTheme? theme,+ BuildContext context) {+ final title = mediaStatus.mediaInformation?.metadata?.extractedTitle ??+ texts.unknownTitle;+ final subtitle = mediaStatus.mediaInformation?.metadata?.extractedSubtitle;++ final titleStyle = theme?.titleTextStyle ??+ Theme.of(context).textTheme.headlineSmall?.copyWith(+ color: Colors.white,+ fontWeight: FontWeight.bold,+ );++ final subtitleStyle = theme?.titleTextStyle?.copyWith(+ fontSize: (theme.titleTextStyle?.fontSize ?? 20) * 0.8,+ fontWeight: FontWeight.normal,+ color: Colors.white70,+ ) ??+ Theme.of(context).textTheme.titleMedium?.copyWith(+ color: Colors.white70,+ fontWeight: FontWeight.normal,+ );++ return Column(+ mainAxisSize: MainAxisSize.min,+ children: [+ // Title with marquee+ SizedBox(+ height: 40,+ child: _buildMarqueeText(title, titleStyle),+ ),+ if (subtitle != null && subtitle.isNotEmpty) ...[+ const SizedBox(height: 8),+ // Subtitle with marquee - constrained height to prevent overlap+ ConstrainedBox(+ constraints: const BoxConstraints(+ maxHeight: 30,+ minHeight: 30,+ ),+ child: _buildMarqueeText(subtitle, subtitleStyle),+ ),+ ],+ ],+ );+ }++ /// Build a marquee text widget+ Widget _buildMarqueeText(String text, TextStyle? style) {+ return Marquee(+ text: text,+ style: style,+ scrollAxis: Axis.horizontal,+ crossAxisAlignment: CrossAxisAlignment.center,+ blankSpace: 50.0,+ velocity: 50.0,+ pauseAfterRound: const Duration(seconds: 2),+ startPadding: 10.0,+ accelerationDuration: const Duration(milliseconds: 500),+ accelerationCurve: Curves.linear,+ decelerationDuration: const Duration(milliseconds: 500),+ decelerationCurve: Curves.easeOut,+ startAfter: const Duration(milliseconds: 1000),+ );+ }+}diff --git a/packages/flutter_chrome_cast/lib/widgets/mini_controller.dart b/packages/flutter_chrome_cast/lib/widgets/mini_controller.dartnew file mode 100644index 00000000..2824df8c--- /dev/null+++ b/packages/flutter_chrome_cast/lib/widgets/mini_controller.dart@@ -0,0 +1,465 @@+import 'package:flutter/material.dart';+import 'package:flutter_chrome_cast/lib.dart' hide GoogleCastPlayerTheme;+import 'package:marquee/marquee.dart';++import '../themes.dart';++/// A floating mini controller widget for Google Cast media playback.+///+/// This widget provides a beautiful, floating mini controller that displays:+/// - Media artwork with rounded corners and shadows+/// - Media title and casting device information+/// - Play/pause controls with theme-aware styling+/// - A sleek progress indicator+///+/// The widget consumes and respects the `ExpandedGoogleCastPlayerTheme` for consistent styling.+///+/// Example usage:+/// ```dart+/// GoogleCastMiniController(+/// theme: ExpandedGoogleCastPlayerTheme(+/// backgroundColor: Colors.white,+/// titleTextStyle: TextStyle(+/// fontSize: 16,+/// fontWeight: FontWeight.w600,+/// color: Colors.black,+/// ),+/// deviceTextStyle: TextStyle(+/// fontSize: 12,+/// color: Colors.grey[600],+/// ),+/// iconColor: Colors.blue,+/// iconSize: 28,+/// imageBorderRadius: BorderRadius.circular(12),+/// imageShadow: [+/// BoxShadow(+/// color: Colors.black26,+/// blurRadius: 8,+/// offset: Offset(0, 2),+/// ),+/// ],+/// ),+/// margin: EdgeInsets.all(16),+/// borderRadius: BorderRadius.circular(16),+/// showDeviceName: true,+/// )+/// ```+class GoogleCastMiniController extends StatefulWidget {+ /// Theme configuration for customizing the visual appearance+ final GoogleCastPlayerTheme? theme;++ /// Custom margin for the mini controller+ final EdgeInsets? margin;++ /// Custom border radius for the mini controller+ final BorderRadius? borderRadius;++ /// Whether to show the device name+ final bool showDeviceName;++ /// Creates a new [GoogleCastMiniController].+ const GoogleCastMiniController({+ super.key,+ this.theme,+ this.margin,+ this.borderRadius,+ this.showDeviceName = true,+ });++ @override+ State<GoogleCastMiniController> createState() =>+ _GoogleCastMiniControllerState();+}++class _GoogleCastMiniControllerState extends State<GoogleCastMiniController> {+ bool isExpanded = false;++ @override+ Widget build(BuildContext context) {+ return StreamBuilder<GoogleCastSession?>(+ stream: GoogleCastSessionManager.instance.currentSessionStream,+ builder: (context, snapshot) {+ return StreamBuilder<GoggleCastMediaStatus?>(+ stream: GoogleCastRemoteMediaClient.instance.mediaStatusStream,+ builder: ((context, snapshot) {+ final mediaStatus = snapshot.data;+ final hasConnectedSession =+ GoogleCastSessionManager.instance.hasConnectedSession;++ if (!hasConnectedSession) return const SizedBox.shrink();++ if (mediaStatus == null) return const SizedBox.shrink();++ if (isExpanded) {+ return ExpandedGoogleCastPlayerController(+ toggleExpand: _toggleExpand,+ theme: widget.theme ??+ GoogleCastPlayerTheme(+ titleTextStyle: TextStyle(color: Colors.white)),+ );+ }+ return Align(+ alignment: Alignment.bottomCenter,+ child: Container(+ margin: widget.margin ?? const EdgeInsets.all(16),+ child: _miniPlayerController(mediaStatus),+ ),+ );+ }),+ );+ });+ }++ Widget _miniPlayerController(GoggleCastMediaStatus mediaStatus) {+ final theme = widget.theme;+ final borderRadius = widget.borderRadius ?? BorderRadius.circular(16);++ return Container(+ constraints: const BoxConstraints(+ minHeight: 84,+ maxHeight: 96,+ ),+ decoration: BoxDecoration(+ color: theme?.backgroundColor ?? Colors.white,+ borderRadius: borderRadius,+ boxShadow: [+ BoxShadow(+ color: Colors.black.withValues(alpha: 0.15),+ blurRadius: 20,+ offset: const Offset(0, 8),+ spreadRadius: 0,+ ),+ BoxShadow(+ color: Colors.black.withValues(alpha: 0.1),+ blurRadius: 6,+ offset: const Offset(0, 2),+ spreadRadius: 0,+ ),+ ],+ ),+ child: Material(+ color: Colors.transparent,+ borderRadius: borderRadius,+ child: InkWell(+ onTap: _toggleExpand,+ borderRadius: borderRadius,+ child: Padding(+ padding: const EdgeInsets.all(12),+ child: Column(+ mainAxisSize: MainAxisSize.min,+ children: [+ Flexible(+ child: Row(+ crossAxisAlignment: CrossAxisAlignment.center,+ children: [+ _image(mediaStatus),+ const SizedBox(width: 16),+ Expanded(+ child: ConstrainedBox(+ constraints: const BoxConstraints(+ minHeight: 40,+ maxHeight: 80,+ ),+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ mainAxisSize: MainAxisSize.min,+ mainAxisAlignment: MainAxisAlignment.center,+ children: [+ Flexible(child: _buildTitle(mediaStatus)),+ const SizedBox(height: 2),+ Flexible(child: _buildSubtitle(mediaStatus)),+ ],+ ),+ ),+ ),+ const SizedBox(width: 12),+ Container(+ decoration: BoxDecoration(+ color: (theme?.iconColor ?? Colors.grey[800])+ ?.withValues(alpha: 0.1),+ borderRadius: BorderRadius.circular(24),+ ),+ child: IconButton(+ onPressed: () =>+ _togglePlayAndPause.call(mediaStatus.playerState),+ icon:+ _getIconFromPlayerState(mediaStatus.playerState),+ iconSize: theme?.iconSize ?? 28,+ color: theme?.iconColor ?? Colors.grey[800],+ padding: const EdgeInsets.all(8),+ ),+ ),+ ],+ ),+ ),+ const SizedBox(height: 8),+ _buildProgressIndicator(mediaStatus),+ ],+ ),+ ),+ ),+ ),+ );+ }++ Widget _image(GoggleCastMediaStatus mediaStatus) {+ final metadata = mediaStatus.mediaInformation?.metadata;+ final images = metadata?.images;+ final theme = widget.theme;++ if (images != null && images.isNotEmpty) {+ // Try to find the best image for the mini controller+ final sortedImages = List<GoogleCastImage>.from(images);+ sortedImages.sort((a, b) {+ final aSize = (a.width ?? 0) * (a.height ?? 0);+ final bSize = (b.width ?? 0) * (b.height ?? 0);+ return bSize.compareTo(aSize); // Descending order+ });++ return Container(+ width: 56,+ height: 56,+ decoration: BoxDecoration(+ borderRadius: theme?.imageBorderRadius ?? BorderRadius.circular(12),+ boxShadow: theme?.imageShadow ??+ [+ BoxShadow(+ color: Colors.black.withValues(alpha: 0.2),+ blurRadius: 8,+ offset: const Offset(0, 2),+ ),+ ],+ ),+ child: Hero(+ tag: 'com.felnanuke.google_cast.controller.image',+ child: ClipRRect(+ borderRadius: theme?.imageBorderRadius ?? BorderRadius.circular(12),+ child: Image.network(+ sortedImages.first.url.toString(),+ fit: theme?.imageFit ?? BoxFit.cover,+ loadingBuilder: (context, child, loadingProgress) {+ if (loadingProgress == null) return child;+ return Container(+ decoration: BoxDecoration(+ color: Colors.grey[300],+ borderRadius:+ theme?.imageBorderRadius ?? BorderRadius.circular(12),+ ),+ child: const Center(+ child: SizedBox(+ width: 16,+ height: 16,+ child: CircularProgressIndicator(strokeWidth: 2),+ ),+ ),+ );+ },+ errorBuilder: (context, error, stackTrace) => Container(+ decoration: BoxDecoration(+ color: Colors.grey[300],+ borderRadius:+ theme?.imageBorderRadius ?? BorderRadius.circular(12),+ ),+ child: Icon(+ _getMediaIcon(metadata?.metadataType),+ size: 24,+ color: Colors.grey[600],+ ),+ ),+ ),+ ),+ ),+ );+ }++ // Fallback when no image is available+ return Container(+ width: 56,+ height: 56,+ decoration: BoxDecoration(+ color: Colors.grey[300],+ borderRadius: theme?.imageBorderRadius ?? BorderRadius.circular(12),+ boxShadow: theme?.imageShadow ??+ [+ BoxShadow(+ color: Colors.black.withValues(alpha: 0.2),+ blurRadius: 8,+ offset: const Offset(0, 2),+ ),+ ],+ ),+ child: Icon(+ _getMediaIcon(metadata?.metadataType),+ size: 24,+ color: Colors.grey[600],+ ),+ );+ }++ IconData _getMediaIcon(GoogleCastMediaMetadataType? metadataType) {+ switch (metadataType) {+ case GoogleCastMediaMetadataType.movieMediaMetadata:+ return Icons.movie;+ case GoogleCastMediaMetadataType.musicTrackMediaMetadata:+ return Icons.music_note;+ case GoogleCastMediaMetadataType.tvShowMediaMetadata:+ return Icons.tv;+ case GoogleCastMediaMetadataType.photoMediaMetadata:+ return Icons.photo;+ case GoogleCastMediaMetadataType.genericMediaMetadata:+ default:+ return Icons.play_circle_filled;+ }+ }++ /// Helper method to create scrolling text using marquee package+ Widget _buildScrollingText({+ required String text,+ required TextStyle style,+ }) {+ if (text.isEmpty) {+ return const SizedBox.shrink();+ }++ return Marquee(+ text: text,+ style: style,+ scrollAxis: Axis.horizontal,+ crossAxisAlignment: CrossAxisAlignment.start,+ blankSpace: 20.0,+ velocity: 30.0,+ pauseAfterRound: const Duration(seconds: 2),+ startPadding: 0.0,+ accelerationDuration: const Duration(seconds: 1),+ accelerationCurve: Curves.linear,+ decelerationDuration: const Duration(milliseconds: 500),+ decelerationCurve: Curves.easeOut,+ );+ }++ Widget _buildTitle(GoggleCastMediaStatus mediaStatus) {+ final title = mediaStatus.mediaInformation?.metadata?.extractedTitle ?? '';+ final theme = widget.theme;++ return Hero(+ tag: 'com.felnanuke.google_cast.controller.title',+ child: _buildScrollingText(+ text: title,+ style: theme?.titleTextStyle ??+ TextStyle(+ fontSize: 16,+ fontWeight: FontWeight.w600,+ color: Colors.grey[900],+ ),+ ),+ );+ }++ Widget _buildSubtitle(GoggleCastMediaStatus mediaStatus) {+ final subtitle =+ mediaStatus.mediaInformation?.metadata?.extractedSubtitle ?? '';+ final theme = widget.theme;++ // Only show subtitle if it exists and is not empty+ if (subtitle.isEmpty) {+ return const SizedBox.shrink();+ }++ return _buildScrollingText(+ text: subtitle,+ style: (theme?.deviceTextStyle ??+ TextStyle(+ fontSize: 12,+ color: Colors.grey[600],+ fontWeight: FontWeight.w400,+ ))+ .copyWith(+ fontSize: 11,+ fontWeight: FontWeight.w300, // Slightly lighter weight for subtitle+ ),+ );+ }++ void _togglePlayAndPause(CastMediaPlayerState playerState) {+ switch (playerState) {+ case CastMediaPlayerState.playing:+ case CastMediaPlayerState.buffering:+ case CastMediaPlayerState.loading:+ // When playing or buffering - pause the media+ GoogleCastRemoteMediaClient.instance.pause();+ break;+ case CastMediaPlayerState.paused:+ case CastMediaPlayerState.idle:+ case CastMediaPlayerState.unknown:+ // When paused, idle, loading, or unknown - play the media+ GoogleCastRemoteMediaClient.instance.play();+ break;+ }+ }++ Widget _getIconFromPlayerState(CastMediaPlayerState playerState) {+ final theme = widget.theme;+ IconData iconData;+ switch (playerState) {+ case CastMediaPlayerState.playing:+ case CastMediaPlayerState.buffering:+ iconData = Icons.pause_rounded;+ break;+ case CastMediaPlayerState.paused:+ case CastMediaPlayerState.idle:+ case CastMediaPlayerState.unknown:+ iconData = Icons.play_arrow_rounded;+ break;+ case CastMediaPlayerState.loading:+ return SizedBox(+ width: theme?.iconSize ?? 28,+ height: theme?.iconSize ?? 28,+ child: CircularProgressIndicator(+ strokeWidth: 2,+ valueColor: AlwaysStoppedAnimation<Color>(+ theme?.iconColor ?? Colors.grey[800]!,+ ),+ ),+ );+ }+ return Icon(+ iconData,+ color: theme?.iconColor ?? Colors.grey[800],+ size: theme?.iconSize ?? 28,+ );+ }++ Widget _buildProgressIndicator(GoggleCastMediaStatus mediaStatus) {+ final theme = widget.theme;++ return StreamBuilder<Duration?>(+ stream: GoogleCastRemoteMediaClient.instance.playerPositionStream,+ builder: (_, snapshot) => Container(+ height: 3,+ decoration: BoxDecoration(+ borderRadius: BorderRadius.circular(1.5),+ color: Colors.grey[300],+ ),+ child: ClipRRect(+ borderRadius: BorderRadius.circular(1.5),+ child: LinearProgressIndicator(+ value: getPlayerPercentage(mediaStatus, snapshot.data),+ backgroundColor: Colors.transparent,+ valueColor: AlwaysStoppedAnimation<Color>(+ theme?.iconColor ?? Colors.blue,+ ),+ minHeight: 3,+ ),+ ),+ ),+ );+ }++ void _toggleExpand() {+ setState(() {+ isExpanded = !isExpanded;+ });+ }++ Size get size => MediaQuery.of(context).size;+}diff --git a/packages/flutter_chrome_cast/lib/widgets/themes/google_cast_player_texts.dart b/packages/flutter_chrome_cast/lib/widgets/themes/google_cast_player_texts.dartnew file mode 100644index 00000000..a106ab1b--- /dev/null+++ b/packages/flutter_chrome_cast/lib/widgets/themes/google_cast_player_texts.dart@@ -0,0 +1,53 @@+/// Text configuration for customizing text labels in the ExpandedGoogleCastPlayerController widget.+///+/// This class allows you to customize all text content displayed in the expanded player,+/// making it easy to support internationalization or custom branding.+///+/// Example usage:+/// ```dart+/// ExpandedGoogleCastPlayerController(+/// texts: ExpandedGoogleCastPlayerTexts(+/// nowPlaying: 'Reproduciendo ahora',+/// unknownTitle: 'TΓtulo desconocido',+/// castingToDevice: (deviceName) => 'Transmitiendo a $deviceName',+/// noCaptionsAvailable: 'Sin subtΓtulos disponibles',+/// captionsOff: 'Desactivar',+/// trackFallback: (trackId) => 'Pista $trackId',+/// ),+/// )+/// ```+class GoogleCastPlayerTexts {+ /// Text displayed when media title is unknown or empty+ final String unknownTitle;++ /// Text displayed in the app bar header+ final String nowPlaying;++ /// Function that returns text showing which device is being cast to.+ /// The [deviceName] parameter contains the friendly name of the cast device.+ final String Function(String deviceName) castingToDevice;++ /// Text displayed when no caption tracks are available+ final String noCaptionsAvailable;++ /// Text displayed for the option to turn off captions+ final String captionsOff;++ /// Function that returns fallback text for caption track names.+ /// The [trackId] parameter contains the numeric ID of the track.+ final String Function(int trackId) trackFallback;++ /// Creates a new [GoogleCastPlayerTexts].+ const GoogleCastPlayerTexts({+ this.unknownTitle = 'Unknown Title',+ this.nowPlaying = 'Now Playing',+ this.castingToDevice = _defaultCastingToDevice,+ this.noCaptionsAvailable = 'No captions available',+ this.captionsOff = 'Off',+ this.trackFallback = _defaultTrackFallback,+ });++ static String _defaultCastingToDevice(String deviceName) =>+ 'Casting to $deviceName';+ static String _defaultTrackFallback(int trackId) => 'Track $trackId';+}diff --git a/packages/flutter_chrome_cast/lib/widgets/themes/google_cast_player_theme.dart b/packages/flutter_chrome_cast/lib/widgets/themes/google_cast_player_theme.dartnew file mode 100644index 00000000..16e83acb--- /dev/null+++ b/packages/flutter_chrome_cast/lib/widgets/themes/google_cast_player_theme.dart@@ -0,0 +1,92 @@+import 'package:flutter/cupertino.dart';++/// Theme data for customizing the ExpandedGoogleCastPlayerController widget.+class GoogleCastPlayerTheme {+ /// Background color for the player.+ final Color? backgroundColor;++ /// Background gradient for the player.+ final Gradient? backgroundGradient;++ /// Text style for the media title.+ final TextStyle? titleTextStyle;++ /// Text style for the device name.+ final TextStyle? deviceTextStyle;++ /// Text style for time displays.+ final TextStyle? timeTextStyle;++ /// Color for icons.+ final Color? iconColor;++ /// Color for disabled icons.+ final Color? disabledIconColor;++ /// Size of icons.+ final double? iconSize;++ /// Custom background widget.+ final Widget? backgroundWidget;++ /// Border radius for media images.+ final BorderRadius? imageBorderRadius;++ /// Shadow for media images.+ final List<BoxShadow>? imageShadow;++ /// Maximum width for media images.+ final double? imageMaxWidth;++ /// Maximum height for media images.+ final double? imageMaxHeight;++ /// Fit for media images.+ final BoxFit? imageFit;++ /// Fallback widget when no image is available.+ final Widget? noImageFallback;++ /// Background color for popup menus (like captions menu)+ final Color? popupBackgroundColor;++ /// Text color for popup menu items+ final Color? popupTextColor;++ /// Text style for popup menu items+ final TextStyle? popupTextStyle;++ /// Volume slider active color+ final Color? volumeSliderActiveColor;++ /// Volume slider inactive color+ final Color? volumeSliderInactiveColor;++ /// Volume slider thumb color+ final Color? volumeSliderThumbColor;++ /// Creates a new [GoogleCastPlayerTheme].+ const GoogleCastPlayerTheme({+ this.backgroundColor,+ this.backgroundGradient,+ this.titleTextStyle,+ this.deviceTextStyle,+ this.timeTextStyle,+ this.iconColor,+ this.disabledIconColor,+ this.iconSize,+ this.backgroundWidget,+ this.imageBorderRadius,+ this.imageShadow,+ this.imageMaxWidth,+ this.imageMaxHeight,+ this.imageFit,+ this.noImageFallback,+ this.popupBackgroundColor,+ this.popupTextColor,+ this.popupTextStyle,+ this.volumeSliderActiveColor,+ this.volumeSliderInactiveColor,+ this.volumeSliderThumbColor,+ });+}diff --git a/packages/flutter_chrome_cast/pubspec.yaml b/packages/flutter_chrome_cast/pubspec.yamlnew file mode 100644index 00000000..46b8a703--- /dev/null+++ b/packages/flutter_chrome_cast/pubspec.yaml@@ -0,0 +1,35 @@+name: flutter_chrome_cast+description: A Flutter plugin for integrating Google Cast devices. Discover, connect, and control media playback on Chromecast and Cast-enabled devices.+version: 1.4.1+repository: https://github.com/felnanuke2/flutter_google_cast+license: BSD-3-Clause++environment:+ sdk: ">=2.17.1 <4.0.0"+ flutter: ">=3.0.0"++dependencies:+ flutter:+ sdk: flutter+ get: ^4.7.2+ marquee: ^2.2.3+ permission_handler: ^12.0.0+1+ plugin_platform_interface: ^2.1.8+ rxdart: ^0.28.0++dev_dependencies:+ flutter_test:+ sdk: flutter+ flutter_lints: ^6.0.0+ pigeon: ^25.3.2++# For information on the generic Dart part of this file, see the+# following page: https://dart.dev/tools/pub/pubspec++# The following section is specific to Flutter packages.+flutter:+ plugin:+ platforms:+ android:+ package: com.felnanuke.google_cast+ pluginClass: GoogleCastPlugin\ No newline at end of filediff --git a/pubspec.lock b/pubspec.lockindex 76e29fcb..b4b523dd 100644--- a/pubspec.lock+++ b/pubspec.lock@@ -375,10 +375,9 @@ packages:flutter_chrome_cast:dependency: "direct main"description:- name: flutter_chrome_cast- sha256: "2d87e9dc8c625faaf13fc2c8036ebe6e4675f358e36e646e7d18c18973108279"- url: "https://pub.dev"- source: hosted+ path: "packages/flutter_chrome_cast"+ relative: true+ source: pathversion: "1.4.1"flutter_epub_viewer:dependency: "direct main"diff --git a/pubspec.yaml b/pubspec.yamlindex fae4a2b3..2c3d9ac0 100644--- a/pubspec.yaml+++ b/pubspec.yaml@@ -85,8 +85,11 @@ dependencies:# Pausing for interruptionsaudio_session: ^0.1.21- # chromecast- flutter_chrome_cast: ^1.2.6+ # chromecast. Vendored without its iOS side: Absorb only casts from+ # Android, and the plugin's Swift package pulls a Cast SDK that now wants+ # iOS 16, which broke the iOS build for nothing.+ flutter_chrome_cast:+ path: packages/flutter_chrome_cast# Log sharingshare_plus: ^10.0.0