diff --git a/android/app/build.gradle b/android/app/build.gradle index 39d8d25..49aa662 100644 --- a/android/app/build.gradle +++ b/android/app/build.gradle @@ -29,7 +29,7 @@ apply from: "../archive_apk.gradle" android { namespace "com.kouyuxingqiu.wow_english" // compileSdkVersion flutter.compileSdkVersion - compileSdkVersion 34 + compileSdkVersion 35 // 暂时没有ndk需求 // ndkVersion flutter.ndkVersion diff --git a/android/build.gradle b/android/build.gradle index 615fa7d..fecbc78 100644 --- a/android/build.gradle +++ b/android/build.gradle @@ -1,7 +1,7 @@ apply from: "/Users/stay/StudioProjects/ishowMavenRepositories.gradle" buildscript { - ext.kotlin_version = '1.8.21' + ext.kotlin_version = '1.8.22' repositories { maven { url 'https://maven.aliyun.com/repository/google' } maven { url "https://maven.aliyun.com/repository/public" } @@ -12,8 +12,7 @@ buildscript { } dependencies { - // AGP版本,目前自动创建的Gradle版本是用的7.5.0 - classpath 'com.android.tools.build:gradle:7.3.0' + classpath 'com.android.tools.build:gradle:8.1.0' classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" } } diff --git a/android/gradle/wrapper/gradle-wrapper.properties b/android/gradle/wrapper/gradle-wrapper.properties index 33b6059..c9a50f6 100644 --- a/android/gradle/wrapper/gradle-wrapper.properties +++ b/android/gradle/wrapper/gradle-wrapper.properties @@ -2,5 +2,4 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -#distributionUrl=https\://services.gradle.org/distributions/gradle-7.5-all.zip -distributionUrl=https://mirrors.cloud.tencent.com/gradle/gradle-7.5-all.zip +distributionUrl=https://mirrors.cloud.tencent.com/gradle/gradle-8.3-all.zip diff --git a/lib/common/utils/video_playback_diagnostics.dart b/lib/common/utils/video_playback_diagnostics.dart new file mode 100644 index 0000000..0fdbe5b --- /dev/null +++ b/lib/common/utils/video_playback_diagnostics.dart @@ -0,0 +1,54 @@ +import 'dart:async'; + +import 'package:flutter/foundation.dart'; +import 'package:video_player/video_player.dart'; +import 'package:wow_english/utils/toast_util.dart'; + +/// Shared timeout and user-visible diagnostics for video_player based screens. +class VideoPlaybackDiagnostics { + static const initializeTimeout = Duration(seconds: 10); + static const commandTimeout = Duration(seconds: 5); + static const bufferingWarningDelay = Duration(seconds: 10); + + /// Starts native player disposal while keeping a stuck teardown bounded. + static Future disposeController( + VideoPlayerController controller, { + required String context, + }) async { + try { + await controller.dispose().timeout(commandTimeout); + } catch (error) { + debugPrint('$context播放器释放失败或超时: $error'); + } + } + + static String messageFor(Object error, {required String stage}) { + final detail = error.toString().toLowerCase(); + if (error is TimeoutException) { + if (stage == '视频初始化') return '视频初始化超时,请检查网络或设备解码能力'; + if (stage == '播放器配置') return '播放器配置超时,设备可能不支持当前播放参数'; + if (stage == '恢复播放进度') return '恢复播放进度超时'; + return '$stage超时'; + } + if (detail.contains('decoder') || + detail.contains('codec') || + detail.contains('mediacodec') || + detail.contains('acodec')) { + return '视频解码器启动失败,可能是设备兼容性问题'; + } + if (detail.contains('http') || + detail.contains('socket') || + detail.contains('network') || + detail.contains('connection') || + detail.contains('source error') || + detail.contains('sourceerror')) { + return '视频网络请求失败,请检查网络或视频地址'; + } + return '$stage失败,请重试'; + } + + static void show(String message, {int? videoId}) { + final idSuffix = videoId == null ? '' : '(视频ID: $videoId)'; + showToast('$message$idSuffix', duration: const Duration(seconds: 4)); + } +} diff --git a/lib/common/utils/video_rendering_preference.dart b/lib/common/utils/video_rendering_preference.dart new file mode 100644 index 0000000..6f8f39c --- /dev/null +++ b/lib/common/utils/video_rendering_preference.dart @@ -0,0 +1,19 @@ +import 'package:flutter/foundation.dart'; +import 'package:video_player/video_player.dart'; +import 'package:wow_english/utils/sp_util.dart'; + +/// User-selectable Android video output path for device compatibility testing. +class VideoRenderingPreference { + static const _usePlatformViewKey = 'video_player_use_platform_view'; + + static bool get usesPlatformView => + SpUtil.getInstance().get(_usePlatformViewKey) ?? false; + + static VideoViewType get viewType => + defaultTargetPlatform == TargetPlatform.android && usesPlatformView + ? VideoViewType.platformView + : VideoViewType.textureView; + + static Future setUsesPlatformView(bool value) => + SpUtil.getInstance().setData(_usePlatformViewKey, value); +} diff --git a/lib/pages/repeataftercontent/widgets/repeat_video_widget.dart b/lib/pages/repeataftercontent/widgets/repeat_video_widget.dart index 3b9c9fa..a49fcb8 100644 --- a/lib/pages/repeataftercontent/widgets/repeat_video_widget.dart +++ b/lib/pages/repeataftercontent/widgets/repeat_video_widget.dart @@ -1,7 +1,11 @@ +import 'dart:async'; + import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:video_player/video_player.dart'; +import 'package:wow_english/common/utils/video_playback_diagnostics.dart'; +import 'package:wow_english/common/utils/video_rendering_preference.dart'; import 'package:wow_english/models/read_content_entity.dart'; import '../bloc/repeat_after_content_bloc.dart'; @@ -23,32 +27,75 @@ class _RepeatVideoWidgetState extends State { String _totalTime = '00:00'; double _playDegree = 0.5; int _currentPlayIndex = 0; + Object? _loadError; + Timer? _bufferingTimer; + VoidCallback? _controllerListener; + bool _bufferingWarningShown = false; + int _loadGeneration = 0; String formatDuration(Duration duration) { - String minutes = duration.inMinutes.remainder(60).toString().padLeft(2, '0'); - String seconds = duration.inSeconds.remainder(60).toString().padLeft(2, '0'); + String minutes = + duration.inMinutes.remainder(60).toString().padLeft(2, '0'); + String seconds = + duration.inSeconds.remainder(60).toString().padLeft(2, '0'); return "$minutes:$seconds"; } void _addListener() { - _controller!.addListener(() { - if(_controller!.value.isInitialized) { - if (_controller!.value.isPlaying) { - setState(() { - double currentSecond = (_controller!.value.position.inMinutes.remainder(60)*60+_controller!.value.position.inSeconds.remainder(60)).toDouble(); - int totalSecond = _controller!.value.duration.inMinutes.remainder(60)*60+_controller!.value.duration.inSeconds.remainder(60); - _currentTime = formatDuration(_controller!.value.position); - _playDegree = currentSecond/totalSecond; - if(_playDegree < 0) { - _playDegree = 0.0; - } + _controllerListener = _onControllerChanged; + _controller?.addListener(_controllerListener!); + } + + void _onControllerChanged() { + final controller = _controller; + if (!mounted || controller == null) return; + _updateBufferingWatch(controller); + if (controller.value.hasError && _loadError == null) { + final error = controller.value.errorDescription ?? '未知播放器错误'; + debugPrint('课程儿歌/视频播放失败: $error'); + VideoPlaybackDiagnostics.show( + VideoPlaybackDiagnostics.messageFor(error, stage: '视频播放/解码'), + ); + setState(() => _loadError = error); + return; + } + if (!controller.value.isInitialized || !controller.value.isPlaying) return; + setState(() { + final currentSecond = + (controller.value.position.inMinutes.remainder(60) * 60 + + controller.value.position.inSeconds.remainder(60)) + .toDouble(); + final totalSecond = + controller.value.duration.inMinutes.remainder(60) * 60 + + controller.value.duration.inSeconds.remainder(60); + _currentTime = formatDuration(controller.value.position); + _playDegree = totalSecond == 0 ? 0 : currentSecond / totalSecond; + _playDegree = _playDegree.clamp(0.0, 1.0); + }); + } - if(_playDegree > 1) { - _playDegree = 1.0; - } - }); - } + void _updateBufferingWatch(VideoPlayerController controller) { + if (!controller.value.isBuffering) { + _bufferingTimer?.cancel(); + _bufferingTimer = null; + _bufferingWarningShown = false; + return; + } + if (_bufferingTimer != null || _bufferingWarningShown) return; + _bufferingTimer = Timer(VideoPlaybackDiagnostics.bufferingWarningDelay, () { + _bufferingTimer = null; + if (!mounted || + controller != _controller || + !controller.value.isBuffering) { + return; } + _bufferingWarningShown = true; + final error = controller.value.errorDescription; + final message = error == null + ? '视频持续缓冲,网络或设备解码可能异常' + : VideoPlaybackDiagnostics.messageFor(error, stage: '视频播放/解码'); + debugPrint('课程儿歌/视频持续缓冲: $message ${error ?? ''}'); + VideoPlaybackDiagnostics.show(message); }); } @@ -56,127 +103,207 @@ class _RepeatVideoWidgetState extends State { void initState() { super.initState(); var videoUrl = ''; - if(widget.videoUrls.isNotEmpty) { - videoUrl = widget.videoUrls[_currentPlayIndex]?.videoUrl??''; + if (widget.videoUrls.isNotEmpty) { + videoUrl = widget.videoUrls[_currentPlayIndex]?.videoUrl ?? ''; } - _initVideo(videoUrl); + unawaited(_initVideo(videoUrl)); } @override Widget build(BuildContext context) { return Center( - child: _controller!.value.isInitialized ? BlocListener( - listener: (context, state){ - if (state is VideoPlayChangeState) { - if (context.read().videoPlaying) { - _controller!.play(); - } else { - _controller!.pause(); - } - } - - if (state is ChangeVideoPlayIndexState) { - if(state.isNext) { - if (_currentPlayIndex != (widget.videoUrls.length-1)) { - _currentPlayIndex++; - _destroyVideo(); - _initVideo(widget.videoUrls[_currentPlayIndex]!.videoUrl!); - } - } else { - if (_currentPlayIndex > 0) { - _currentPlayIndex--; - _destroyVideo(); - _initVideo(widget.videoUrls[_currentPlayIndex]!.videoUrl!); - } - } - } - }, - child: SizedBox( - child: Column( - children: [ - Expanded( - child: Stack( - children: [ - Container( - width: double.infinity, - height: double.infinity, - alignment: Alignment.center, - decoration: BoxDecoration( - color: Colors.black, - border: Border.all( - width: 1.0, - color: const Color(0xFF140C10), + child: _loadError != null + ? Column( + mainAxisSize: MainAxisSize.min, + children: [ + const Text('视频加载失败,请重试'), + const SizedBox(height: 8), + ElevatedButton( + onPressed: () => unawaited(_initVideo( + widget.videoUrls.isEmpty + ? '' + : widget.videoUrls[_currentPlayIndex]?.videoUrl ?? '', + )), + child: const Text('重试'), + ), + ], + ) + : _controller?.value.isInitialized == true + ? BlocListener( + listener: (context, state) { + if (state is VideoPlayChangeState) { + unawaited(_setPlayback( + context.read().videoPlaying, + )); + } + if (state is ChangeVideoPlayIndexState) { + final nextIndex = state.isNext + ? _currentPlayIndex + 1 + : _currentPlayIndex - 1; + if (nextIndex >= 0 && + nextIndex < widget.videoUrls.length) { + _currentPlayIndex = nextIndex; + unawaited(_initVideo( + widget.videoUrls[nextIndex]?.videoUrl ?? '', + )); + } + } + }, + child: SizedBox( + child: Column( + children: [ + Expanded( + child: Stack( + children: [ + Container( + width: double.infinity, + height: double.infinity, + alignment: Alignment.center, + decoration: BoxDecoration( + color: Colors.black, + border: Border.all( + width: 1.0, + color: const Color(0xFF140C10), + ), + borderRadius: BorderRadius.circular(5.r), + ), + child: AspectRatio( + aspectRatio: _controller!.value.aspectRatio, + child: VideoPlayer(_controller!), + ), + ), + Positioned( + left: 0, + right: 0, + bottom: 0, + child: LinearProgressIndicator( + color: const Color(0xFF78B72D), + backgroundColor: const Color(0xFF7E756C), + value: _playDegree, + ), + ), + ], ), - borderRadius: BorderRadius.circular(5.r) - ), - child: AspectRatio( - aspectRatio: _controller!.value.aspectRatio, - child: VideoPlayer(_controller!), - ), + ), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [Text(_currentTime), Text(_totalTime)], + ), + ], ), - Positioned( - left: 0, - right: 0, - bottom: 0, - child: LinearProgressIndicator( - color: const Color(0xFF78B72D), - backgroundColor: const Color(0xFF7E756C), - value: _playDegree, - )) - ], + ), + ) + : Container( + color: Colors.white, + child: const CircularProgressIndicator(), ), - ), - Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - Text(_currentTime), - Text(_totalTime), - ], - ) - ], - ), - ) - ) - : - Container( - color: Colors.white, - child: const CircularProgressIndicator(), - // Text( - // '视频加载中....', - // style: TextStyle( - // fontSize: 20.sp, - // color: Colors.black - // ), - // ), - ), ); } - void _initVideo(String videoUrl) { - if(videoUrl.isNotEmpty) { - Uri uri = Uri.parse(videoUrl); - _controller = VideoPlayerController.networkUrl(uri) - ..initialize().then((_){ - setState(() { - _currentTime = formatDuration(_controller!.value.position); - _totalTime = formatDuration(_controller!.value.duration); - _controller!.setLooping(false); - _controller!.setVolume(100); - _controller!.play(); - }); - _addListener(); - }); + Future _initVideo(String videoUrl) async { + final generation = ++_loadGeneration; + _bufferingTimer?.cancel(); + _bufferingWarningShown = false; + await _destroyController(); + if (!mounted || generation != _loadGeneration) return; + _loadError = null; + final url = videoUrl.trim(); + if (url.isEmpty) { + _loadError = StateError('课程视频地址为空'); + VideoPlaybackDiagnostics.show('课程视频地址为空'); + if (mounted) setState(() {}); + return; + } + final controller = VideoPlayerController.networkUrl( + Uri.parse(url), + viewType: VideoRenderingPreference.viewType, + ); + _controller = controller; + if (mounted) setState(() {}); + var stage = '视频初始化'; + try { + await controller + .initialize() + .timeout(VideoPlaybackDiagnostics.initializeTimeout); + if (!mounted || + generation != _loadGeneration || + controller != _controller) { + await controller.dispose(); + return; + } + stage = '播放器配置'; + await controller + .setLooping(false) + .timeout(VideoPlaybackDiagnostics.commandTimeout); + await controller + .setVolume(1) + .timeout(VideoPlaybackDiagnostics.commandTimeout); + _addListener(); + _updateBufferingWatch(controller); + await controller.play().timeout(VideoPlaybackDiagnostics.commandTimeout); + if (!mounted || generation != _loadGeneration) return; + setState(() { + _currentTime = formatDuration(controller.value.position); + _totalTime = formatDuration(controller.value.duration); + }); + } catch (error) { + final failedCurrentController = controller == _controller; + if (failedCurrentController) { + _bufferingTimer?.cancel(); + _bufferingTimer = null; + } + await VideoPlaybackDiagnostics.disposeController( + controller, + context: '课程儿歌/视频初始化失败($stage)', + ); + if (!mounted || + generation != _loadGeneration || + !failedCurrentController) { + return; + } + _controller = null; + final message = VideoPlaybackDiagnostics.messageFor(error, stage: stage); + debugPrint('课程儿歌/视频加载失败(stage=$stage): $error'); + VideoPlaybackDiagnostics.show(message); + setState(() => _loadError = error); } } - void _destroyVideo() { - _controller?.dispose(); - _controller?.removeListener(() {}); + Future _setPlayback(bool shouldPlay) async { + final controller = _controller; + if (controller?.value.isInitialized != true) return; + try { + final operation = shouldPlay ? controller!.play() : controller!.pause(); + await operation.timeout(VideoPlaybackDiagnostics.commandTimeout); + } catch (error) { + debugPrint('课程视频播放状态切换失败: $error'); + VideoPlaybackDiagnostics.show( + VideoPlaybackDiagnostics.messageFor(error, stage: '播放器控制'), + ); + } + } + + Future _destroyController() async { + final controller = _controller; + final listener = _controllerListener; + _controllerListener = null; + _controller = null; + if (controller != null) { + if (listener != null) { + controller.removeListener(listener); + } + await VideoPlaybackDiagnostics.disposeController( + controller, + context: '课程儿歌/视频切换', + ); + } } @override void dispose() { - _destroyVideo(); + _loadGeneration++; + _bufferingTimer?.cancel(); + unawaited(_destroyController()); super.dispose(); } } \ No newline at end of file diff --git a/lib/pages/shopping/bloc.dart b/lib/pages/shopping/bloc.dart index b3abdbd..1ebb5dd 100644 --- a/lib/pages/shopping/bloc.dart +++ b/lib/pages/shopping/bloc.dart @@ -15,13 +15,17 @@ import '../../utils/toast_util.dart'; import 'event.dart'; import 'state.dart'; +const bool isWechatPayOptionVisible = false; + class ShoppingBloc extends Bloc { ProductEntity? _productData; ProductEntity? get productData => _productData; - PaymentChannel _curPaymentChannel = PaymentChannel.wechatPay; + PaymentChannel _curPaymentChannel = isWechatPayOptionVisible + ? PaymentChannel.wechatPay + : PaymentChannel.aliPay; PaymentChannel get curPaymentChannel => _curPaymentChannel; diff --git a/lib/pages/shopping/view.dart b/lib/pages/shopping/view.dart index de81065..c607b9a 100644 --- a/lib/pages/shopping/view.dart +++ b/lib/pages/shopping/view.dart @@ -149,17 +149,26 @@ Widget _paymentWidget() => BlocBuilder( fontFamily: 'PingFangSC-Regular')), ), const SizedBox(height: 18.0), - buildRadioOption( - value: PaymentChannel.wechatPay.payChannelType, - icon: AssetImage('weixin'.assetPng), - text: PaymentChannel.wechatPay.payChannelName, - isSelected: bloc.curPaymentChannel.payChannelType == - PaymentChannel.wechatPay.payChannelType, - onSelect: (newValue) { - bloc.add(ChangePaymentChannelEvent(PaymentChannel.wechatPay)); - }, + Visibility( + visible: isWechatPayOptionVisible, + child: Column( + children: [ + buildRadioOption( + value: PaymentChannel.wechatPay.payChannelType, + icon: AssetImage('weixin'.assetPng), + text: PaymentChannel.wechatPay.payChannelName, + isSelected: bloc.curPaymentChannel.payChannelType == + PaymentChannel.wechatPay.payChannelType, + onSelect: (newValue) { + bloc.add( + ChangePaymentChannelEvent(PaymentChannel.wechatPay), + ); + }, + ), + const SizedBox(height: 15.0), + ], + ), ), - const SizedBox(height: 15.0), buildRadioOption( value: PaymentChannel.aliPay.payChannelType, icon: AssetImage('zhifubao'.assetPng), diff --git a/lib/pages/user/setting/setting_page.dart b/lib/pages/user/setting/setting_page.dart index 2660f18..d35fab8 100644 --- a/lib/pages/user/setting/setting_page.dart +++ b/lib/pages/user/setting/setting_page.dart @@ -1,7 +1,9 @@ +import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter_easyloading/flutter_easyloading.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:package_info_plus/package_info_plus.dart'; +import 'package:wow_english/common/utils/video_rendering_preference.dart'; import 'package:wow_english/common/widgets/we_app_bar.dart'; import 'package:wow_english/utils/toast_util.dart'; @@ -19,9 +21,11 @@ class SettingPage extends StatefulWidget { class SettingPageState extends State { String? _version; String? _buildNum; + bool _usePlatformView = false; @override void initState() { super.initState(); + _usePlatformView = VideoRenderingPreference.usesPlatformView; _retrieveVersionInfo(); } @@ -62,6 +66,10 @@ class SettingPageState extends State { _buildItemWidget('帮助与反馈', onPress: () { pushNamed(AppRouteName.reBack); }), + if (defaultTargetPlatform == TargetPlatform.android) ...[ + 12.verticalSpace, + _buildVideoRenderingSetting(), + ], 12.verticalSpace, _buildItemWidget('Version: $_version Build:$_buildNum', onPress: () {}), @@ -73,6 +81,49 @@ class SettingPageState extends State { ); } + Widget _buildVideoRenderingSetting() { + return Container( + padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 10.h), + decoration: BoxDecoration( + border: Border.all(color: const Color(0xFF140C10), width: 1.5.w), + borderRadius: BorderRadius.circular(15.r), + color: Colors.white, + ), + child: Row( + children: [ + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + '视频兼容模式', + style: TextStyle( + color: const Color(0xFF333333), fontSize: 19.sp), + ), + 4.verticalSpace, + Text( + _usePlatformView + ? 'PlatformView(兼容测试)· 新打开的视频生效' + : 'Texture(默认)· 新打开的视频生效', + style: TextStyle( + color: const Color(0xFF777777), fontSize: 13.sp), + ), + ], + ), + ), + Switch.adaptive( + value: _usePlatformView, + onChanged: (value) async { + setState(() => _usePlatformView = value); + await VideoRenderingPreference.setUsesPlatformView(value); + showToast(value ? '已切换为 PlatformView' : '已切换为 Texture'); + }, + ), + ], + ), + ); + } + Widget _buildItemWidget(String text, {VoidCallback? onPress}) { return OutlinedButton( onPressed: () => onPress?.call(), diff --git a/lib/pages/video/lookvideo/widgets/video_widget.dart b/lib/pages/video/lookvideo/widgets/video_widget.dart index 4e29028..dd558c8 100644 --- a/lib/pages/video/lookvideo/widgets/video_widget.dart +++ b/lib/pages/video/lookvideo/widgets/video_widget.dart @@ -1,9 +1,13 @@ +import 'dart:async'; + import 'package:common_utils/common_utils.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:video_player/video_player.dart'; import 'package:wow_english/common/extension/string_extension.dart'; +import 'package:wow_english/common/utils/video_playback_diagnostics.dart'; +import 'package:wow_english/common/utils/video_rendering_preference.dart'; import 'package:wow_english/pages/video/lookvideo/bloc/look_video_bloc.dart'; import 'package:wow_english/route/route.dart'; @@ -36,6 +40,11 @@ class _VideoWidgetState extends State { String _totalTime = '00:00'; double _playDegree = 0.0; bool _hiddenTipView = false; + Object? _loadError; + Timer? _bufferingTimer; + int _loadGeneration = 0; + VoidCallback? _diagnosticListener; + bool _bufferingWarningShown = false; TimerUtil? timerUtil; String formatDuration(Duration duration) { @@ -142,19 +151,132 @@ class _VideoWidgetState extends State { @override void initState() { super.initState(); - Uri uri = Uri.parse(widget.videoUrl); - _controller = VideoPlayerController.networkUrl(uri) - ..initialize().then((_) { - startTimer(); - setState(() { - _currentTime = formatDuration(_controller!.value.position); - _totalTime = formatDuration(_controller!.value.duration); - _controller!.setLooping(!widget.isTopic); - _controller!.setVolume(100); - _controller!.play(); - }); - _addListener(); + unawaited(_initializeVideo()); + } + + Future _initializeVideo() async { + final generation = ++_loadGeneration; + _bufferingTimer?.cancel(); + _bufferingWarningShown = false; + final oldController = _controller; + if (oldController != null) { + if (_diagnosticListener != null) { + oldController.removeListener(_diagnosticListener!); + } + } + _diagnosticListener = null; + _controller = null; + _loadError = null; + if (oldController != null) { + await VideoPlaybackDiagnostics.disposeController( + oldController, + context: '课程视频切换', + ); + } + if (!mounted || generation != _loadGeneration) return; + final url = widget.videoUrl.trim(); + if (url.isEmpty) { + _loadError = StateError('课程视频地址为空'); + VideoPlaybackDiagnostics.show('课程视频地址为空'); + if (mounted) setState(() {}); + return; + } + final controller = VideoPlayerController.networkUrl( + Uri.parse(url), + viewType: VideoRenderingPreference.viewType, + ); + _controller = controller; + if (mounted) setState(() {}); + var stage = '视频初始化'; + try { + await controller + .initialize() + .timeout(VideoPlaybackDiagnostics.initializeTimeout); + if (!mounted || + generation != _loadGeneration || + controller != _controller) { + await controller.dispose(); + return; + } + stage = '播放器配置'; + await controller + .setLooping(!widget.isTopic) + .timeout(VideoPlaybackDiagnostics.commandTimeout); + await controller + .setVolume(1) + .timeout(VideoPlaybackDiagnostics.commandTimeout); + _addListener(); + _diagnosticListener = _onDiagnosticChanged; + controller.addListener(_diagnosticListener!); + _updateBufferingWatch(controller); + await controller.play().timeout(VideoPlaybackDiagnostics.commandTimeout); + if (!mounted || generation != _loadGeneration) return; + startTimer(); + setState(() { + _currentTime = formatDuration(controller.value.position); + _totalTime = formatDuration(controller.value.duration); }); + } catch (error) { + final failedCurrentController = controller == _controller; + if (failedCurrentController) { + _bufferingTimer?.cancel(); + _bufferingTimer = null; + controller.removeListener(_diagnosticListener ?? _onDiagnosticChanged); + } + await VideoPlaybackDiagnostics.disposeController( + controller, + context: '课程视频初始化失败($stage)', + ); + if (!mounted || + generation != _loadGeneration || + !failedCurrentController) { + return; + } + _controller = null; + final message = VideoPlaybackDiagnostics.messageFor(error, stage: stage); + debugPrint('课程视频加载失败(stage=$stage): $error'); + VideoPlaybackDiagnostics.show(message); + setState(() => _loadError = error); + } + } + + void _onDiagnosticChanged() { + final controller = _controller; + if (!mounted || controller == null) return; + _updateBufferingWatch(controller); + if (controller.value.hasError && _loadError == null) { + final error = controller.value.errorDescription ?? '未知播放器错误'; + debugPrint('课程视频播放失败: $error'); + VideoPlaybackDiagnostics.show( + VideoPlaybackDiagnostics.messageFor(error, stage: '视频播放/解码'), + ); + setState(() => _loadError = error); + } + } + + void _updateBufferingWatch(VideoPlayerController controller) { + if (!controller.value.isBuffering) { + _bufferingTimer?.cancel(); + _bufferingTimer = null; + _bufferingWarningShown = false; + return; + } + if (_bufferingTimer != null || _bufferingWarningShown) return; + _bufferingTimer = Timer(VideoPlaybackDiagnostics.bufferingWarningDelay, () { + _bufferingTimer = null; + if (!mounted || + controller != _controller || + !controller.value.isBuffering) { + return; + } + _bufferingWarningShown = true; + final error = controller.value.errorDescription; + final message = error == null + ? '视频持续缓冲,网络或设备解码可能异常' + : VideoPlaybackDiagnostics.messageFor(error, stage: '视频播放/解码'); + debugPrint('课程视频持续缓冲: $message ${error ?? ''}'); + VideoPlaybackDiagnostics.show(message); + }); } @override @@ -162,12 +284,18 @@ class _VideoWidgetState extends State { return BlocListener( listener: (context, state) async { if (state is SectionAgainState) { - await _controller?.seekTo(Duration.zero); - _controller?.play(); + final controller = _controller; + if (controller?.value.isInitialized == true) { + await controller!.seekTo(Duration.zero); + await controller.play(); + } } }, child: GestureDetector( onTap: () { + if (_loadError != null || _controller?.value.isInitialized != true) { + return; + } setState(() { _hiddenTipView = !_hiddenTipView; if (!_hiddenTipView) { @@ -180,7 +308,7 @@ class _VideoWidgetState extends State { }); }, onDoubleTap: () { - if (_controller!.value.isInitialized) { + if (_controller?.value.isInitialized == true) { if (_controller!.value.isPlaying) { _controller!.pause(); } else { @@ -190,65 +318,78 @@ class _VideoWidgetState extends State { } }, child: Center( - child: _controller!.value.isInitialized - ? Stack( - alignment: Alignment.center, + child: _loadError != null + ? Column( + mainAxisSize: MainAxisSize.min, children: [ - SizedBox( - height: double.infinity, - width: double.infinity, - child: AspectRatio( - aspectRatio: _controller!.value.aspectRatio, - child: VideoPlayer(_controller!), - ), - ), - Offstage( - offstage: _hiddenTipView, - child: VideoOperaWidget( - title: widget.typeTitle ?? 'song', - degree: _playDegree, - totalTime: _totalTime, - currentTime: _currentTime, - isPlay: _controller!.value.isPlaying, - actionEvent: (OperationType type) { - actionType(type); - }, - sliderChangeEvent: (double degree) { - int totalSecond = _controller! - .value.duration.inMinutes - .remainder(60) * - 60 + - _controller!.value.duration.inSeconds - .remainder(60); - int positionSecond = (totalSecond * degree).toInt(); - _controller! - .seekTo(Duration(seconds: positionSecond)); - }, - ), + const Text('视频加载失败,请重试'), + const SizedBox(height: 8), + ElevatedButton( + onPressed: _initializeVideo, + child: const Text('重试'), ), - Offstage( - offstage: _controller!.value.isPlaying, - child: IconButton( - onPressed: () { - _controller!.play(); - }, - icon: Image.asset( - 'video_stop'.assetPng, - width: 70.w, - height: 70.h, - ), - ), - ) ], ) - : Container( - color: Colors.white, - child: const CircularProgressIndicator(), - // Text( - // '视频加载中....', - // style: TextStyle(fontSize: 20.sp, color: Colors.black), - // ), - ), + : _controller?.value.isInitialized == true + ? Stack( + alignment: Alignment.center, + children: [ + SizedBox( + height: double.infinity, + width: double.infinity, + child: AspectRatio( + aspectRatio: _controller!.value.aspectRatio, + child: VideoPlayer(_controller!), + ), + ), + Offstage( + offstage: _hiddenTipView, + child: VideoOperaWidget( + title: widget.typeTitle ?? 'song', + degree: _playDegree, + totalTime: _totalTime, + currentTime: _currentTime, + isPlay: _controller!.value.isPlaying, + actionEvent: (OperationType type) { + actionType(type); + }, + sliderChangeEvent: (double degree) { + int totalSecond = _controller! + .value.duration.inMinutes + .remainder(60) * + 60 + + _controller!.value.duration.inSeconds + .remainder(60); + int positionSecond = + (totalSecond * degree).toInt(); + _controller! + .seekTo(Duration(seconds: positionSecond)); + }, + ), + ), + Offstage( + offstage: _controller!.value.isPlaying, + child: IconButton( + onPressed: () { + _controller!.play(); + }, + icon: Image.asset( + 'video_stop'.assetPng, + width: 70.w, + height: 70.h, + ), + ), + ) + ], + ) + : Container( + color: Colors.white, + child: const CircularProgressIndicator(), + // Text( + // '视频加载中....', + // style: TextStyle(fontSize: 20.sp, color: Colors.black), + // ), + ), ), ), ); @@ -256,8 +397,18 @@ class _VideoWidgetState extends State { @override void dispose() { - _controller?.dispose(); - _controller?.removeListener(() {}); + _loadGeneration++; + _bufferingTimer?.cancel(); + if (_diagnosticListener != null) { + _controller?.removeListener(_diagnosticListener!); + } + final controller = _controller; + if (controller != null) { + unawaited(VideoPlaybackDiagnostics.disposeController( + controller, + context: '课程视频页面退出', + )); + } if (timerUtil != null) { timerUtil!.cancel(); timerUtil = null; diff --git a/lib/pages/video/zone/video_zone_page.dart b/lib/pages/video/zone/video_zone_page.dart index d802dae..7d6f88a 100644 --- a/lib/pages/video/zone/video_zone_page.dart +++ b/lib/pages/video/zone/video_zone_page.dart @@ -2,12 +2,12 @@ import 'dart:async'; import 'package:cached_network_image/cached_network_image.dart'; import 'package:flutter/material.dart'; -import 'package:flutter/services.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:wow_english/common/dialogs/show_dialog.dart'; import 'package:wow_english/common/request/dao/video_dao.dart'; import 'package:wow_english/common/widgets/we_app_bar.dart'; import 'package:wow_english/route/route.dart'; +import 'package:wow_english/utils/toast_util.dart'; import 'video_zone_item.dart'; @@ -24,104 +24,93 @@ class _VideoZonePageState extends State { @override void initState() { super.initState(); - unawaited( - SystemChrome.setEnabledSystemUIMode(SystemUiMode.immersiveSticky), - ); - _itemsFuture = VideoDao.list(); + _itemsFuture = _loadItems(); } - @override - void dispose() { - unawaited( - SystemChrome.setEnabledSystemUIMode(SystemUiMode.immersiveSticky), - ); - super.dispose(); + Future> _loadItems() async { + try { + return await VideoDao.list().timeout(const Duration(seconds: 10)); + } on TimeoutException catch (error) { + debugPrint('获取视频列表超时: $error'); + showToast('视频列表加载超时,请检查网络后重试'); + rethrow; + } catch (error) { + debugPrint('获取视频列表失败: $error'); + showToast('视频列表加载失败,请稍后重试'); + rethrow; + } } void _reload() { setState(() { - _itemsFuture = VideoDao.list(); + _itemsFuture = _loadItems(); }); } @override Widget build(BuildContext context) { - return MediaQuery.removePadding( - context: context, - removeTop: true, - child: Scaffold( - backgroundColor: Colors.white, - appBar: const WEAppBar( - titleText: '视频专区', - centerTitle: false, - ), - body: FutureBuilder>( - future: _itemsFuture, - builder: (context, snapshot) { - if (snapshot.connectionState == ConnectionState.waiting) { - return const Center(child: CircularProgressIndicator()); - } - if (snapshot.hasError) { - return _VideoLoadError(onRetry: _reload); - } - final items = snapshot.data ?? const []; - if (items.isEmpty) { - return const Center( - child: Text( - '暂无视频', - style: TextStyle(color: Color(0xFF999999), fontSize: 18), - ), - ); - } - return RefreshIndicator( - onRefresh: () async { - final future = VideoDao.list(); - setState(() => _itemsFuture = future); - await future; - }, - child: LayoutBuilder( - builder: (context, constraints) { - final horizontalPadding = 30.w; - final crossAxisSpacing = 12.w; - final titleStyle = _VideoCard.createTitleStyle(context); - final titlePainter = TextPainter( - text: TextSpan(text: '视频标题', style: titleStyle), - maxLines: 1, - textDirection: Directionality.of(context), - textScaler: MediaQuery.textScalerOf(context), - )..layout(); - final cardWidth = (constraints.maxWidth - - horizontalPadding * 2 - - crossAxisSpacing * 2) / - 3; - final cardHeight = - cardWidth * 9 / 16 + 5.h + titlePainter.height; - return GridView.builder( - physics: const AlwaysScrollableScrollPhysics(), - padding: EdgeInsets.fromLTRB( - horizontalPadding, - 10.h, - horizontalPadding, - 16.h, - ), - gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( - crossAxisCount: 3, - mainAxisSpacing: 14.h, - crossAxisSpacing: crossAxisSpacing, - mainAxisExtent: cardHeight, - ), - itemCount: items.length, - itemBuilder: (context, index) => _VideoCard( - item: items[index], - onTap: () => _openVideo(items, index), - titleStyle: titleStyle, - ), - ); - }, + return Scaffold( + backgroundColor: Colors.white, + appBar: const WEAppBar( + titleText: '视频专区', + centerTitle: false, + ), + body: FutureBuilder>( + future: _itemsFuture, + builder: (context, snapshot) { + if (snapshot.connectionState == ConnectionState.waiting) { + return const Center(child: CircularProgressIndicator()); + } + if (snapshot.hasError) { + return _VideoLoadError(onRetry: _reload); + } + final items = snapshot.data ?? const []; + if (items.isEmpty) { + return const Center( + child: Text( + '暂无视频', + style: TextStyle(color: Color(0xFF999999), fontSize: 18), ), ); - }, - ), + } + return RefreshIndicator( + onRefresh: () async { + final future = _loadItems(); + setState(() => _itemsFuture = future); + try { + await future; + } catch (_) { + // The FutureBuilder shows the error state; _loadItems already toasts it. + } + }, + child: LayoutBuilder( + builder: (context, constraints) { + final titleStyle = _VideoCard.createTitleStyle(context); + return GridView.builder( + physics: const AlwaysScrollableScrollPhysics(), + padding: EdgeInsets.fromLTRB( + 14.w, + 10.h, + 14.w, + 16.h, + ), + gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( + crossAxisCount: 4, + mainAxisSpacing: 14.h, + crossAxisSpacing: 12.w, + childAspectRatio: 1.55, + ), + itemCount: items.length, + itemBuilder: (context, index) => _VideoCard( + item: items[index], + onTap: () => _openVideo(items, index), + titleStyle: titleStyle, + ), + ); + }, + ), + ); + }, ), ); } @@ -144,13 +133,7 @@ class _VideoZonePageState extends State { .toList(), 'initialVideoId': item.id, }, - ).then((_) { - if (!mounted) return; - unawaited( - SystemChrome.setEnabledSystemUIMode(SystemUiMode.immersiveSticky), - ); - _reload(); - }); + ).then((_) => _reload()); } } @@ -203,8 +186,7 @@ class _VideoCard extends StatelessWidget { child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - AspectRatio( - aspectRatio: 16 / 9, + Expanded( child: ClipRRect( borderRadius: BorderRadius.circular(12.r), child: CachedNetworkImage( diff --git a/lib/pages/video/zone/video_zone_player_page.dart b/lib/pages/video/zone/video_zone_player_page.dart index 97ff178..164aff1 100644 --- a/lib/pages/video/zone/video_zone_player_page.dart +++ b/lib/pages/video/zone/video_zone_player_page.dart @@ -6,7 +6,10 @@ import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:video_player/video_player.dart'; import 'package:wow_english/common/request/dao/video_dao.dart'; +import 'package:wow_english/common/utils/video_playback_diagnostics.dart'; import 'package:wow_english/common/utils/video_progress_cache.dart'; +import 'package:wow_english/common/utils/video_rendering_preference.dart'; +import 'package:wow_english/utils/toast_util.dart'; import 'video_zone_item.dart'; @@ -26,13 +29,20 @@ class VideoZonePlayerPage extends StatefulWidget { class _VideoZonePlayerPageState extends State with WidgetsBindingObserver { + static const _initializeTimeout = Duration(seconds: 10); + static const _playerCommandTimeout = Duration(seconds: 5); + static const _progressReadTimeout = Duration(seconds: 2); + static const _bufferingWarningDelay = Duration(seconds: 10); + VideoPlayerController? _controller; ChewieController? _chewieController; Timer? _cacheTimer; + Timer? _bufferingTimer; late int _currentIndex; double _playbackSpeed = 1; bool _switchingVideo = false; bool _handlingCompletion = false; + bool _bufferingWarningShown = false; bool? _lastIsPlaying; int? _completedReportedVideoId; Object? _loadError; @@ -56,6 +66,8 @@ class _VideoZonePlayerPageState extends State Future _loadCurrentVideo() async { final useCupertinoControls = defaultTargetPlatform == TargetPlatform.iOS; _cacheTimer?.cancel(); + _bufferingTimer?.cancel(); + _bufferingWarningShown = false; final oldController = _controller; final oldChewieController = _chewieController; if (oldController?.value.isInitialized == true) { @@ -63,25 +75,32 @@ class _VideoZonePlayerPageState extends State } oldController?.removeListener(_onVideoChanged); _lastIsPlaying = null; - final controller = - VideoPlayerController.networkUrl(Uri.parse(_currentItem.videoUrl)); + final controller = VideoPlayerController.networkUrl( + Uri.parse(_currentItem.videoUrl), + viewType: VideoRenderingPreference.viewType, + ); _controller = controller; _chewieController = null; _loadError = null; if (mounted) { setState(() {}); } - oldChewieController?.dispose(); - await oldController?.dispose(); - + var stage = '释放旧播放器'; try { - await controller.initialize().timeout(const Duration(seconds: 20)); + oldChewieController?.dispose(); + await oldController?.dispose().timeout(_playerCommandTimeout); + stage = '初始化视频流'; + await controller.initialize().timeout(_initializeTimeout); if (!mounted || controller != _controller) { await controller.dispose(); return; } - await controller.setLooping(false); - await controller.setPlaybackSpeed(_playbackSpeed); + stage = '配置播放器'; + await controller.setLooping(false).timeout(_playerCommandTimeout); + await controller + .setPlaybackSpeed(_playbackSpeed) + .timeout(_playerCommandTimeout); + stage = '读取本地播放进度'; final savedProgress = await _resumeProgressFor(_currentItem.id); if (!mounted || controller != _controller) { await controller.dispose(); @@ -89,10 +108,25 @@ class _VideoZonePlayerPageState extends State } if (savedProgress > 0 && savedProgress < controller.value.duration.inSeconds) { - await controller.seekTo(Duration(seconds: savedProgress)); + stage = '恢复播放进度'; + try { + await controller + .seekTo(Duration(seconds: savedProgress)) + .timeout(_playerCommandTimeout); + } on TimeoutException catch (error) { + debugPrint( + '恢复本地视频进度超时(videoId=${_currentItem.id}): $error', + ); + _showVideoToast('恢复进度超时,已尝试从头播放'); + } catch (error) { + debugPrint('恢复本地视频进度失败(videoId=${_currentItem.id}): $error'); + _showVideoToast('恢复进度失败,已尝试从头播放'); + } } + stage = '创建播放界面'; _lastIsPlaying = controller.value.isPlaying; controller.addListener(_onVideoChanged); + _updateBufferingWatch(controller); _chewieController = ChewieController( videoPlayerController: controller, autoPlay: true, @@ -139,15 +173,42 @@ class _VideoZonePlayerPageState extends State ); setState(() {}); } catch (error) { - if (mounted && controller == _controller) { - setState(() => _loadError = error); + final failedCurrentController = controller == _controller; + if (failedCurrentController) { + controller.removeListener(_onVideoChanged); + _bufferingTimer?.cancel(); + _bufferingTimer = null; + _cacheTimer?.cancel(); + _cacheTimer = null; + _chewieController?.dispose(); + _chewieController = null; } + await VideoPlaybackDiagnostics.disposeController( + controller, + context: '视频专区初始化失败($stage)', + ); + if (!mounted || !failedCurrentController) return; + _controller = null; + final message = _diagnosticMessage(stage, error); + debugPrint('$message (videoId=${_currentItem.id}): $error'); + _showVideoToast('$message(视频ID: ${_currentItem.id})'); + setState(() => _loadError = error); } } void _onVideoChanged() { final controller = _controller; if (!mounted || controller == null) return; + _updateBufferingWatch(controller); + if (controller.value.hasError && _loadError == null) { + final error = controller.value.errorDescription ?? '未知播放器错误'; + debugPrint('视频播放失败(videoId=${_currentItem.id}): $error'); + _showVideoToast( + '${_diagnosticMessage('播放/解码', error)}(视频ID: ${_currentItem.id})', + ); + setState(() => _loadError = error); + return; + } final isPlaying = controller.value.isPlaying; if (_lastIsPlaying != null && _lastIsPlaying != isPlaying) { unawaited(_cacheCurrentProgress()); @@ -162,6 +223,30 @@ class _VideoZonePlayerPageState extends State } } + void _updateBufferingWatch(VideoPlayerController controller) { + if (!controller.value.isBuffering) { + _bufferingTimer?.cancel(); + _bufferingTimer = null; + _bufferingWarningShown = false; + return; + } + if (_bufferingTimer != null || _bufferingWarningShown) return; + _bufferingTimer = Timer(_bufferingWarningDelay, () { + _bufferingTimer = null; + if (!mounted || + controller != _controller || + !controller.value.isBuffering) { + return; + } + _bufferingWarningShown = true; + final error = controller.value.errorDescription; + final reason = + error == null ? '网络缓冲或设备解码可能异常' : _diagnosticMessage('播放/解码', error); + debugPrint('视频持续缓冲(videoId=${_currentItem.id}): $reason ${error ?? ''}'); + _showVideoToast('视频持续缓冲超过10秒:$reason(视频ID: ${_currentItem.id})'); + }); + } + Future _playNext({bool currentCompleted = false}) async { if (_switchingVideo || _currentIndex >= widget.items.length - 1) return; _switchingVideo = true; @@ -187,6 +272,7 @@ class _VideoZonePlayerPageState extends State SystemChrome.setEnabledSystemUIMode(SystemUiMode.immersiveSticky), ); _cacheTimer?.cancel(); + _bufferingTimer?.cancel(); _controller?.removeListener(_onVideoChanged); unawaited(_reportCurrentProgress()); _chewieController?.dispose(); @@ -237,14 +323,52 @@ class _VideoZonePlayerPageState extends State Future _resumeProgressFor(int videoId) async { try { - final cached = await VideoProgressCache.get(videoId); + final cached = + await VideoProgressCache.get(videoId).timeout(_progressReadTimeout); if (cached != null) return cached.progressSeconds; + } on TimeoutException catch (error) { + debugPrint('读取本地视频进度超时(videoId=$videoId): $error'); + _showVideoToast('本地进度读取超时,已从头播放'); } catch (error) { debugPrint('读取本地视频播放进度失败: $error'); + _showVideoToast('本地进度读取失败,已从头播放'); } return 0; } + String _diagnosticMessage(String stage, Object error) { + final detail = error.toString().toLowerCase(); + if (error is TimeoutException) { + if (stage == '初始化视频流') return '视频初始化超时,请检查网络或设备解码能力'; + if (stage == '释放旧播放器') return '播放器释放超时,请退出后重试'; + if (stage == '配置播放器') return '播放器配置超时,设备可能不支持当前播放参数'; + if (stage == '恢复播放进度') return '恢复播放进度超时'; + return '$stage超时'; + } + if (detail.contains('decoder') || + detail.contains('codec') || + detail.contains('mediacodec') || + detail.contains('acodec')) { + return '视频解码器启动失败,可能是设备兼容性问题'; + } + if (detail.contains('http') || + detail.contains('socket') || + detail.contains('network') || + detail.contains('connection') || + detail.contains('source error') || + detail.contains('sourceerror')) { + return '视频网络请求失败,请检查网络或视频地址'; + } + if (stage == '初始化视频流') return '视频流初始化失败'; + if (stage == '配置播放器') return '播放器配置失败'; + if (stage == '播放/解码') return '视频播放/解码失败,请检查网络或设备兼容性'; + return '$stage失败'; + } + + void _showVideoToast(String message) { + showToast(message, duration: const Duration(seconds: 4)); + } + Future _cacheCurrentProgress() async { final controller = _controller; if (controller == null || !controller.value.isInitialized) return; diff --git a/packages/chivox_aiengine/android/build.gradle b/packages/chivox_aiengine/android/build.gradle index aa91d70..8574d3b 100644 --- a/packages/chivox_aiengine/android/build.gradle +++ b/packages/chivox_aiengine/android/build.gradle @@ -22,6 +22,7 @@ rootProject.allprojects { apply plugin: 'com.android.library' android { + namespace 'com.example.chivox_aiengine' compileSdkVersion 31 compileOptions { diff --git a/packages/video_player_android/LICENSE b/packages/video_player_android/LICENSE new file mode 100644 index 0000000..c6823b8 --- /dev/null +++ b/packages/video_player_android/LICENSE @@ -0,0 +1,25 @@ +Copyright 2013 The Flutter Authors. All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * 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. + * Neither the name of Google Inc. 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 OWNER 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. diff --git a/packages/video_player_android/android/build.gradle b/packages/video_player_android/android/build.gradle new file mode 100644 index 0000000..6eb2f8e --- /dev/null +++ b/packages/video_player_android/android/build.gradle @@ -0,0 +1,72 @@ +group 'io.flutter.plugins.videoplayer' +version '1.0-SNAPSHOT' + +buildscript { + repositories { + google() + mavenCentral() + } + + dependencies { + classpath 'com.android.tools.build:gradle:8.5.0' + } +} + +rootProject.allprojects { + repositories { + google() + mavenCentral() + } +} + +apply plugin: 'com.android.library' + +android { + namespace 'io.flutter.plugins.videoplayer' + compileSdk = flutter.compileSdkVersion + + defaultConfig { + minSdkVersion 21 + testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" + } + lintOptions { + checkAllWarnings true + warningsAsErrors true + disable 'AndroidGradlePluginVersion', 'InvalidPackage', 'GradleDependency', 'NewerVersionAvailable' + } + compileOptions { + sourceCompatibility JavaVersion.VERSION_11 + targetCompatibility JavaVersion.VERSION_11 + } + + dependencies { + def exoplayer_version = "1.4.1" + implementation "androidx.media3:media3-exoplayer:${exoplayer_version}" + implementation "androidx.media3:media3-exoplayer-hls:${exoplayer_version}" + implementation "androidx.media3:media3-exoplayer-dash:${exoplayer_version}" + implementation "androidx.media3:media3-exoplayer-rtsp:${exoplayer_version}" + implementation "androidx.media3:media3-exoplayer-smoothstreaming:${exoplayer_version}" + testImplementation 'junit:junit:4.13.2' + testImplementation 'androidx.test:core:1.6.1' + testImplementation 'org.mockito:mockito-inline:5.2.0' + testImplementation 'org.robolectric:robolectric:4.14.1' + testImplementation "androidx.media3:media3-test-utils:${exoplayer_version}" + } + + testOptions { + unitTests.includeAndroidResources = true + unitTests.returnDefaultValues = true + unitTests.all { + // The org.gradle.jvmargs property that may be set in gradle.properties does not impact + // the Java heap size when running the Android unit tests. The following property here + // sets the heap size to a size large enough to run the robolectric tests across + // multiple SDK levels. + jvmArgs "-Xmx4G" + testLogging { + events "passed", "skipped", "failed", "standardOut", "standardError" + outputs.upToDateWhen {false} + showStandardStreams = true + } + } + } +} diff --git a/packages/video_player_android/android/settings.gradle b/packages/video_player_android/android/settings.gradle new file mode 100644 index 0000000..0068171 --- /dev/null +++ b/packages/video_player_android/android/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'video_player_android' diff --git a/packages/video_player_android/android/src/main/AndroidManifest.xml b/packages/video_player_android/android/src/main/AndroidManifest.xml new file mode 100644 index 0000000..e6e98bf --- /dev/null +++ b/packages/video_player_android/android/src/main/AndroidManifest.xml @@ -0,0 +1,3 @@ + + diff --git a/packages/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/ExoPlayerEventListener.java b/packages/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/ExoPlayerEventListener.java new file mode 100644 index 0000000..e96eca8 --- /dev/null +++ b/packages/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/ExoPlayerEventListener.java @@ -0,0 +1,107 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.videoplayer; + +import androidx.annotation.NonNull; +import androidx.media3.common.PlaybackException; +import androidx.media3.common.Player; +import androidx.media3.exoplayer.ExoPlayer; + +public abstract class ExoPlayerEventListener implements Player.Listener { + private boolean isBuffering = false; + private boolean isInitialized; + protected final ExoPlayer exoPlayer; + protected final VideoPlayerCallbacks events; + + protected enum RotationDegrees { + ROTATE_0(0), + ROTATE_90(90), + ROTATE_180(180), + ROTATE_270(270); + + private final int degrees; + + RotationDegrees(int degrees) { + this.degrees = degrees; + } + + public static RotationDegrees fromDegrees(int degrees) { + for (RotationDegrees rotationDegrees : RotationDegrees.values()) { + if (rotationDegrees.degrees == degrees) { + return rotationDegrees; + } + } + throw new IllegalArgumentException("Invalid rotation degrees specified: " + degrees); + } + + public int getDegrees() { + return this.degrees; + } + } + + public ExoPlayerEventListener( + @NonNull ExoPlayer exoPlayer, @NonNull VideoPlayerCallbacks events, boolean initialized) { + this.exoPlayer = exoPlayer; + this.events = events; + this.isInitialized = initialized; + } + + private void setBuffering(boolean buffering) { + if (isBuffering == buffering) { + return; + } + isBuffering = buffering; + if (buffering) { + events.onBufferingStart(); + } else { + events.onBufferingEnd(); + } + } + + protected abstract void sendInitialized(); + + @Override + public void onPlaybackStateChanged(final int playbackState) { + switch (playbackState) { + case Player.STATE_BUFFERING: + setBuffering(true); + events.onBufferingUpdate(exoPlayer.getBufferedPosition()); + break; + case Player.STATE_READY: + if (isInitialized) { + return; + } + isInitialized = true; + sendInitialized(); + break; + case Player.STATE_ENDED: + events.onCompleted(); + break; + case Player.STATE_IDLE: + break; + } + if (playbackState != Player.STATE_BUFFERING) { + setBuffering(false); + } + } + + @Override + public void onPlayerError(@NonNull final PlaybackException error) { + setBuffering(false); + if (error.errorCode == PlaybackException.ERROR_CODE_BEHIND_LIVE_WINDOW) { + // See + // https://exoplayer.dev/live-streaming.html#behindlivewindowexception-and-error_code_behind_live_window + exoPlayer.seekToDefaultPosition(); + exoPlayer.prepare(); + } else { + events.onError("VideoError", "Video player had error " + error, null); + } + } + + @Override + public void onIsPlayingChanged(boolean isPlaying) { + events.onIsPlayingStateUpdate(isPlaying); + } +} diff --git a/packages/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/ExoPlayerState.java b/packages/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/ExoPlayerState.java new file mode 100644 index 0000000..e0e9bab --- /dev/null +++ b/packages/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/ExoPlayerState.java @@ -0,0 +1,71 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.videoplayer; + +import androidx.annotation.NonNull; +import androidx.media3.common.PlaybackParameters; +import androidx.media3.exoplayer.ExoPlayer; + +/** + * Internal state representing an {@link ExoPlayer} instance at a snapshot in time. + * + *

During the Android application lifecycle, the underlying {@link android.view.Surface} being + * rendered to by the player can be destroyed when the application is in the background and memory + * is reclaimed. Upon resume, the player will need to be recreated, but start again at the + * previous point (and settings). + */ +public final class ExoPlayerState { + /** + * Saves a representation of the current state of the player at the current point in time. + * + *

The inverse of this operation is {@link #restore(ExoPlayer)}. + * + * @param exoPlayer the active player instance. + * @return an opaque object representing the state. + */ + @NonNull + public static ExoPlayerState save(@NonNull ExoPlayer exoPlayer) { + return new ExoPlayerState( + /* position= */ exoPlayer.getCurrentPosition(), + /* repeatMode= */ exoPlayer.getRepeatMode(), + /* volume= */ exoPlayer.getVolume(), + /* playbackParameters= */ exoPlayer.getPlaybackParameters()); + } + + private ExoPlayerState( + long position, int repeatMode, float volume, PlaybackParameters playbackParameters) { + this.position = position; + this.repeatMode = repeatMode; + this.volume = volume; + this.playbackParameters = playbackParameters; + } + + /** Previous value of {@link ExoPlayer#getCurrentPosition()}. */ + private final long position; + + /** Previous value of {@link ExoPlayer#getRepeatMode()}. */ + private final int repeatMode; + + /** Previous value of {@link ExoPlayer#getVolume()}. */ + private final float volume; + + /** Previous value of {@link ExoPlayer#getPlaybackParameters()}. */ + private final PlaybackParameters playbackParameters; + + /** + * Restores the captured state onto the provided player. + * + *

This will typically be done after creating a new player, setting up a media source, and + * listening to events. + * + * @param exoPlayer the new player instance to reflect the state back to. + */ + public void restore(@NonNull ExoPlayer exoPlayer) { + exoPlayer.seekTo(position); + exoPlayer.setRepeatMode(repeatMode); + exoPlayer.setVolume(volume); + exoPlayer.setPlaybackParameters(playbackParameters); + } +} diff --git a/packages/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/HttpVideoAsset.java b/packages/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/HttpVideoAsset.java new file mode 100644 index 0000000..b13714d --- /dev/null +++ b/packages/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/HttpVideoAsset.java @@ -0,0 +1,98 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.videoplayer; + +import android.content.Context; +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import androidx.annotation.OptIn; +import androidx.annotation.VisibleForTesting; +import androidx.media3.common.MediaItem; +import androidx.media3.common.MimeTypes; +import androidx.media3.common.util.UnstableApi; +import androidx.media3.datasource.DataSource; +import androidx.media3.datasource.DefaultDataSource; +import androidx.media3.datasource.DefaultHttpDataSource; +import androidx.media3.exoplayer.source.DefaultMediaSourceFactory; +import androidx.media3.exoplayer.source.MediaSource; +import java.util.Map; + +final class HttpVideoAsset extends VideoAsset { + private static final String DEFAULT_USER_AGENT = "ExoPlayer"; + private static final String HEADER_USER_AGENT = "User-Agent"; + + @NonNull private final StreamingFormat streamingFormat; + @NonNull private final Map httpHeaders; + + HttpVideoAsset( + @Nullable String assetUrl, + @NonNull StreamingFormat streamingFormat, + @NonNull Map httpHeaders) { + super(assetUrl); + this.streamingFormat = streamingFormat; + this.httpHeaders = httpHeaders; + } + + @NonNull + @Override + public MediaItem getMediaItem() { + MediaItem.Builder builder = new MediaItem.Builder().setUri(assetUrl); + String mimeType = null; + switch (streamingFormat) { + case SMOOTH: + mimeType = MimeTypes.APPLICATION_SS; + break; + case DYNAMIC_ADAPTIVE: + mimeType = MimeTypes.APPLICATION_MPD; + break; + case HTTP_LIVE: + mimeType = MimeTypes.APPLICATION_M3U8; + break; + } + if (mimeType != null) { + builder.setMimeType(mimeType); + } + return builder.build(); + } + + @NonNull + @Override + public MediaSource.Factory getMediaSourceFactory(@NonNull Context context) { + return getMediaSourceFactory(context, new DefaultHttpDataSource.Factory()); + } + + /** + * Returns a configured media source factory, starting at the provided factory. + * + *

This method is provided for ease of testing without making real HTTP calls. + * + * @param context application context. + * @param initialFactory initial factory, to be configured. + * @return configured factory, or {@code null} if not needed for this asset type. + */ + @VisibleForTesting + MediaSource.Factory getMediaSourceFactory( + Context context, DefaultHttpDataSource.Factory initialFactory) { + String userAgent = DEFAULT_USER_AGENT; + if (!httpHeaders.isEmpty() && httpHeaders.containsKey(HEADER_USER_AGENT)) { + userAgent = httpHeaders.get(HEADER_USER_AGENT); + } + unstableUpdateDataSourceFactory(initialFactory, httpHeaders, userAgent); + DataSource.Factory dataSourceFactory = new DefaultDataSource.Factory(context, initialFactory); + return new DefaultMediaSourceFactory(context).setDataSourceFactory(dataSourceFactory); + } + + // TODO: Migrate to stable API, see https://github.com/flutter/flutter/issues/147039. + @OptIn(markerClass = UnstableApi.class) + private static void unstableUpdateDataSourceFactory( + @NonNull DefaultHttpDataSource.Factory factory, + @NonNull Map httpHeaders, + @Nullable String userAgent) { + factory.setUserAgent(userAgent).setAllowCrossProtocolRedirects(true); + if (!httpHeaders.isEmpty()) { + factory.setDefaultRequestProperties(httpHeaders); + } + } +} diff --git a/packages/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/LocalVideoAsset.java b/packages/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/LocalVideoAsset.java new file mode 100644 index 0000000..bf55b9b --- /dev/null +++ b/packages/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/LocalVideoAsset.java @@ -0,0 +1,29 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.videoplayer; + +import android.content.Context; +import androidx.annotation.NonNull; +import androidx.media3.common.MediaItem; +import androidx.media3.exoplayer.source.DefaultMediaSourceFactory; +import androidx.media3.exoplayer.source.MediaSource; + +final class LocalVideoAsset extends VideoAsset { + LocalVideoAsset(@NonNull String assetUrl) { + super(assetUrl); + } + + @NonNull + @Override + public MediaItem getMediaItem() { + return new MediaItem.Builder().setUri(assetUrl).build(); + } + + @NonNull + @Override + public MediaSource.Factory getMediaSourceFactory(@NonNull Context context) { + return new DefaultMediaSourceFactory(context); + } +} diff --git a/packages/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/Messages.java b/packages/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/Messages.java new file mode 100644 index 0000000..581cb7b --- /dev/null +++ b/packages/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/Messages.java @@ -0,0 +1,698 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. +// Autogenerated from Pigeon (v22.6.1), do not edit directly. +// See also: https://pub.dev/packages/pigeon + +package io.flutter.plugins.videoplayer; + +import static java.lang.annotation.ElementType.METHOD; +import static java.lang.annotation.RetentionPolicy.CLASS; + +import android.util.Log; +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import io.flutter.plugin.common.BasicMessageChannel; +import io.flutter.plugin.common.BinaryMessenger; +import io.flutter.plugin.common.MessageCodec; +import io.flutter.plugin.common.StandardMessageCodec; +import java.io.ByteArrayOutputStream; +import java.lang.annotation.Retention; +import java.lang.annotation.Target; +import java.nio.ByteBuffer; +import java.util.ArrayList; +import java.util.Map; +import java.util.Objects; + +/** Generated class from Pigeon. */ +@SuppressWarnings({"unused", "unchecked", "CodeBlock2Expr", "RedundantSuppression", "serial"}) +public class Messages { + + /** Error class for passing custom error details to Flutter via a thrown PlatformException. */ + public static class FlutterError extends RuntimeException { + + /** The error code. */ + public final String code; + + /** The error details. Must be a datatype supported by the api codec. */ + public final Object details; + + public FlutterError(@NonNull String code, @Nullable String message, @Nullable Object details) { + super(message); + this.code = code; + this.details = details; + } + } + + @NonNull + protected static ArrayList wrapError(@NonNull Throwable exception) { + ArrayList errorList = new ArrayList<>(3); + if (exception instanceof FlutterError) { + FlutterError error = (FlutterError) exception; + errorList.add(error.code); + errorList.add(error.getMessage()); + errorList.add(error.details); + } else { + errorList.add(exception.toString()); + errorList.add(exception.getClass().getSimpleName()); + errorList.add( + "Cause: " + exception.getCause() + ", Stacktrace: " + Log.getStackTraceString(exception)); + } + return errorList; + } + + @Target(METHOD) + @Retention(CLASS) + @interface CanIgnoreReturnValue {} + + /** Pigeon equivalent of VideoViewType. */ + public enum PlatformVideoViewType { + TEXTURE_VIEW(0), + PLATFORM_VIEW(1); + + final int index; + + PlatformVideoViewType(final int index) { + this.index = index; + } + } + + /** + * Information passed to the platform view creation. + * + *

Generated class from Pigeon that represents data sent in messages. + */ + public static final class PlatformVideoViewCreationParams { + private @NonNull Long playerId; + + public @NonNull Long getPlayerId() { + return playerId; + } + + public void setPlayerId(@NonNull Long setterArg) { + if (setterArg == null) { + throw new IllegalStateException("Nonnull field \"playerId\" is null."); + } + this.playerId = setterArg; + } + + /** Constructor is non-public to enforce null safety; use Builder. */ + PlatformVideoViewCreationParams() {} + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + PlatformVideoViewCreationParams that = (PlatformVideoViewCreationParams) o; + return playerId.equals(that.playerId); + } + + @Override + public int hashCode() { + return Objects.hash(playerId); + } + + public static final class Builder { + + private @Nullable Long playerId; + + @CanIgnoreReturnValue + public @NonNull Builder setPlayerId(@NonNull Long setterArg) { + this.playerId = setterArg; + return this; + } + + public @NonNull PlatformVideoViewCreationParams build() { + PlatformVideoViewCreationParams pigeonReturn = new PlatformVideoViewCreationParams(); + pigeonReturn.setPlayerId(playerId); + return pigeonReturn; + } + } + + @NonNull + ArrayList toList() { + ArrayList toListResult = new ArrayList<>(1); + toListResult.add(playerId); + return toListResult; + } + + static @NonNull PlatformVideoViewCreationParams fromList( + @NonNull ArrayList pigeonVar_list) { + PlatformVideoViewCreationParams pigeonResult = new PlatformVideoViewCreationParams(); + Object playerId = pigeonVar_list.get(0); + pigeonResult.setPlayerId((Long) playerId); + return pigeonResult; + } + } + + /** Generated class from Pigeon that represents data sent in messages. */ + public static final class CreateMessage { + private @Nullable String asset; + + public @Nullable String getAsset() { + return asset; + } + + public void setAsset(@Nullable String setterArg) { + this.asset = setterArg; + } + + private @Nullable String uri; + + public @Nullable String getUri() { + return uri; + } + + public void setUri(@Nullable String setterArg) { + this.uri = setterArg; + } + + private @Nullable String packageName; + + public @Nullable String getPackageName() { + return packageName; + } + + public void setPackageName(@Nullable String setterArg) { + this.packageName = setterArg; + } + + private @Nullable String formatHint; + + public @Nullable String getFormatHint() { + return formatHint; + } + + public void setFormatHint(@Nullable String setterArg) { + this.formatHint = setterArg; + } + + private @NonNull Map httpHeaders; + + public @NonNull Map getHttpHeaders() { + return httpHeaders; + } + + public void setHttpHeaders(@NonNull Map setterArg) { + if (setterArg == null) { + throw new IllegalStateException("Nonnull field \"httpHeaders\" is null."); + } + this.httpHeaders = setterArg; + } + + private @Nullable PlatformVideoViewType viewType; + + public @Nullable PlatformVideoViewType getViewType() { + return viewType; + } + + public void setViewType(@Nullable PlatformVideoViewType setterArg) { + this.viewType = setterArg; + } + + /** Constructor is non-public to enforce null safety; use Builder. */ + CreateMessage() {} + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + CreateMessage that = (CreateMessage) o; + return Objects.equals(asset, that.asset) + && Objects.equals(uri, that.uri) + && Objects.equals(packageName, that.packageName) + && Objects.equals(formatHint, that.formatHint) + && httpHeaders.equals(that.httpHeaders) + && Objects.equals(viewType, that.viewType); + } + + @Override + public int hashCode() { + return Objects.hash(asset, uri, packageName, formatHint, httpHeaders, viewType); + } + + public static final class Builder { + + private @Nullable String asset; + + @CanIgnoreReturnValue + public @NonNull Builder setAsset(@Nullable String setterArg) { + this.asset = setterArg; + return this; + } + + private @Nullable String uri; + + @CanIgnoreReturnValue + public @NonNull Builder setUri(@Nullable String setterArg) { + this.uri = setterArg; + return this; + } + + private @Nullable String packageName; + + @CanIgnoreReturnValue + public @NonNull Builder setPackageName(@Nullable String setterArg) { + this.packageName = setterArg; + return this; + } + + private @Nullable String formatHint; + + @CanIgnoreReturnValue + public @NonNull Builder setFormatHint(@Nullable String setterArg) { + this.formatHint = setterArg; + return this; + } + + private @Nullable Map httpHeaders; + + @CanIgnoreReturnValue + public @NonNull Builder setHttpHeaders(@NonNull Map setterArg) { + this.httpHeaders = setterArg; + return this; + } + + private @Nullable PlatformVideoViewType viewType; + + @CanIgnoreReturnValue + public @NonNull Builder setViewType(@Nullable PlatformVideoViewType setterArg) { + this.viewType = setterArg; + return this; + } + + public @NonNull CreateMessage build() { + CreateMessage pigeonReturn = new CreateMessage(); + pigeonReturn.setAsset(asset); + pigeonReturn.setUri(uri); + pigeonReturn.setPackageName(packageName); + pigeonReturn.setFormatHint(formatHint); + pigeonReturn.setHttpHeaders(httpHeaders); + pigeonReturn.setViewType(viewType); + return pigeonReturn; + } + } + + @NonNull + ArrayList toList() { + ArrayList toListResult = new ArrayList<>(6); + toListResult.add(asset); + toListResult.add(uri); + toListResult.add(packageName); + toListResult.add(formatHint); + toListResult.add(httpHeaders); + toListResult.add(viewType); + return toListResult; + } + + static @NonNull CreateMessage fromList(@NonNull ArrayList pigeonVar_list) { + CreateMessage pigeonResult = new CreateMessage(); + Object asset = pigeonVar_list.get(0); + pigeonResult.setAsset((String) asset); + Object uri = pigeonVar_list.get(1); + pigeonResult.setUri((String) uri); + Object packageName = pigeonVar_list.get(2); + pigeonResult.setPackageName((String) packageName); + Object formatHint = pigeonVar_list.get(3); + pigeonResult.setFormatHint((String) formatHint); + Object httpHeaders = pigeonVar_list.get(4); + pigeonResult.setHttpHeaders((Map) httpHeaders); + Object viewType = pigeonVar_list.get(5); + pigeonResult.setViewType((PlatformVideoViewType) viewType); + return pigeonResult; + } + } + + private static class PigeonCodec extends StandardMessageCodec { + public static final PigeonCodec INSTANCE = new PigeonCodec(); + + private PigeonCodec() {} + + @Override + protected Object readValueOfType(byte type, @NonNull ByteBuffer buffer) { + switch (type) { + case (byte) 129: + { + Object value = readValue(buffer); + return value == null ? null : PlatformVideoViewType.values()[((Long) value).intValue()]; + } + case (byte) 130: + return PlatformVideoViewCreationParams.fromList((ArrayList) readValue(buffer)); + case (byte) 131: + return CreateMessage.fromList((ArrayList) readValue(buffer)); + default: + return super.readValueOfType(type, buffer); + } + } + + @Override + protected void writeValue(@NonNull ByteArrayOutputStream stream, Object value) { + if (value instanceof PlatformVideoViewType) { + stream.write(129); + writeValue(stream, value == null ? null : ((PlatformVideoViewType) value).index); + } else if (value instanceof PlatformVideoViewCreationParams) { + stream.write(130); + writeValue(stream, ((PlatformVideoViewCreationParams) value).toList()); + } else if (value instanceof CreateMessage) { + stream.write(131); + writeValue(stream, ((CreateMessage) value).toList()); + } else { + super.writeValue(stream, value); + } + } + } + + /** Generated interface from Pigeon that represents a handler of messages from Flutter. */ + public interface AndroidVideoPlayerApi { + + void initialize(); + + @NonNull + Long create(@NonNull CreateMessage msg); + + void dispose(@NonNull Long playerId); + + void setLooping(@NonNull Long playerId, @NonNull Boolean looping); + + void setVolume(@NonNull Long playerId, @NonNull Double volume); + + void setPlaybackSpeed(@NonNull Long playerId, @NonNull Double speed); + + void play(@NonNull Long playerId); + + @NonNull + Long position(@NonNull Long playerId); + + void seekTo(@NonNull Long playerId, @NonNull Long position); + + void pause(@NonNull Long playerId); + + void setMixWithOthers(@NonNull Boolean mixWithOthers); + + /** The codec used by AndroidVideoPlayerApi. */ + static @NonNull MessageCodec getCodec() { + return PigeonCodec.INSTANCE; + } + + /** + * Sets up an instance of `AndroidVideoPlayerApi` to handle messages through the + * `binaryMessenger`. + */ + static void setUp( + @NonNull BinaryMessenger binaryMessenger, @Nullable AndroidVideoPlayerApi api) { + setUp(binaryMessenger, "", api); + } + + static void setUp( + @NonNull BinaryMessenger binaryMessenger, + @NonNull String messageChannelSuffix, + @Nullable AndroidVideoPlayerApi api) { + messageChannelSuffix = messageChannelSuffix.isEmpty() ? "" : "." + messageChannelSuffix; + { + BasicMessageChannel channel = + new BasicMessageChannel<>( + binaryMessenger, + "dev.flutter.pigeon.video_player_android.AndroidVideoPlayerApi.initialize" + + messageChannelSuffix, + getCodec()); + if (api != null) { + channel.setMessageHandler( + (message, reply) -> { + ArrayList wrapped = new ArrayList<>(); + try { + api.initialize(); + wrapped.add(0, null); + } catch (Throwable exception) { + wrapped = wrapError(exception); + } + reply.reply(wrapped); + }); + } else { + channel.setMessageHandler(null); + } + } + { + BasicMessageChannel channel = + new BasicMessageChannel<>( + binaryMessenger, + "dev.flutter.pigeon.video_player_android.AndroidVideoPlayerApi.create" + + messageChannelSuffix, + getCodec()); + if (api != null) { + channel.setMessageHandler( + (message, reply) -> { + ArrayList wrapped = new ArrayList<>(); + ArrayList args = (ArrayList) message; + CreateMessage msgArg = (CreateMessage) args.get(0); + try { + Long output = api.create(msgArg); + wrapped.add(0, output); + } catch (Throwable exception) { + wrapped = wrapError(exception); + } + reply.reply(wrapped); + }); + } else { + channel.setMessageHandler(null); + } + } + { + BasicMessageChannel channel = + new BasicMessageChannel<>( + binaryMessenger, + "dev.flutter.pigeon.video_player_android.AndroidVideoPlayerApi.dispose" + + messageChannelSuffix, + getCodec()); + if (api != null) { + channel.setMessageHandler( + (message, reply) -> { + ArrayList wrapped = new ArrayList<>(); + ArrayList args = (ArrayList) message; + Long playerIdArg = (Long) args.get(0); + try { + api.dispose(playerIdArg); + wrapped.add(0, null); + } catch (Throwable exception) { + wrapped = wrapError(exception); + } + reply.reply(wrapped); + }); + } else { + channel.setMessageHandler(null); + } + } + { + BasicMessageChannel channel = + new BasicMessageChannel<>( + binaryMessenger, + "dev.flutter.pigeon.video_player_android.AndroidVideoPlayerApi.setLooping" + + messageChannelSuffix, + getCodec()); + if (api != null) { + channel.setMessageHandler( + (message, reply) -> { + ArrayList wrapped = new ArrayList<>(); + ArrayList args = (ArrayList) message; + Long playerIdArg = (Long) args.get(0); + Boolean loopingArg = (Boolean) args.get(1); + try { + api.setLooping(playerIdArg, loopingArg); + wrapped.add(0, null); + } catch (Throwable exception) { + wrapped = wrapError(exception); + } + reply.reply(wrapped); + }); + } else { + channel.setMessageHandler(null); + } + } + { + BasicMessageChannel channel = + new BasicMessageChannel<>( + binaryMessenger, + "dev.flutter.pigeon.video_player_android.AndroidVideoPlayerApi.setVolume" + + messageChannelSuffix, + getCodec()); + if (api != null) { + channel.setMessageHandler( + (message, reply) -> { + ArrayList wrapped = new ArrayList<>(); + ArrayList args = (ArrayList) message; + Long playerIdArg = (Long) args.get(0); + Double volumeArg = (Double) args.get(1); + try { + api.setVolume(playerIdArg, volumeArg); + wrapped.add(0, null); + } catch (Throwable exception) { + wrapped = wrapError(exception); + } + reply.reply(wrapped); + }); + } else { + channel.setMessageHandler(null); + } + } + { + BasicMessageChannel channel = + new BasicMessageChannel<>( + binaryMessenger, + "dev.flutter.pigeon.video_player_android.AndroidVideoPlayerApi.setPlaybackSpeed" + + messageChannelSuffix, + getCodec()); + if (api != null) { + channel.setMessageHandler( + (message, reply) -> { + ArrayList wrapped = new ArrayList<>(); + ArrayList args = (ArrayList) message; + Long playerIdArg = (Long) args.get(0); + Double speedArg = (Double) args.get(1); + try { + api.setPlaybackSpeed(playerIdArg, speedArg); + wrapped.add(0, null); + } catch (Throwable exception) { + wrapped = wrapError(exception); + } + reply.reply(wrapped); + }); + } else { + channel.setMessageHandler(null); + } + } + { + BasicMessageChannel channel = + new BasicMessageChannel<>( + binaryMessenger, + "dev.flutter.pigeon.video_player_android.AndroidVideoPlayerApi.play" + + messageChannelSuffix, + getCodec()); + if (api != null) { + channel.setMessageHandler( + (message, reply) -> { + ArrayList wrapped = new ArrayList<>(); + ArrayList args = (ArrayList) message; + Long playerIdArg = (Long) args.get(0); + try { + api.play(playerIdArg); + wrapped.add(0, null); + } catch (Throwable exception) { + wrapped = wrapError(exception); + } + reply.reply(wrapped); + }); + } else { + channel.setMessageHandler(null); + } + } + { + BasicMessageChannel channel = + new BasicMessageChannel<>( + binaryMessenger, + "dev.flutter.pigeon.video_player_android.AndroidVideoPlayerApi.position" + + messageChannelSuffix, + getCodec()); + if (api != null) { + channel.setMessageHandler( + (message, reply) -> { + ArrayList wrapped = new ArrayList<>(); + ArrayList args = (ArrayList) message; + Long playerIdArg = (Long) args.get(0); + try { + Long output = api.position(playerIdArg); + wrapped.add(0, output); + } catch (Throwable exception) { + wrapped = wrapError(exception); + } + reply.reply(wrapped); + }); + } else { + channel.setMessageHandler(null); + } + } + { + BasicMessageChannel channel = + new BasicMessageChannel<>( + binaryMessenger, + "dev.flutter.pigeon.video_player_android.AndroidVideoPlayerApi.seekTo" + + messageChannelSuffix, + getCodec()); + if (api != null) { + channel.setMessageHandler( + (message, reply) -> { + ArrayList wrapped = new ArrayList<>(); + ArrayList args = (ArrayList) message; + Long playerIdArg = (Long) args.get(0); + Long positionArg = (Long) args.get(1); + try { + api.seekTo(playerIdArg, positionArg); + wrapped.add(0, null); + } catch (Throwable exception) { + wrapped = wrapError(exception); + } + reply.reply(wrapped); + }); + } else { + channel.setMessageHandler(null); + } + } + { + BasicMessageChannel channel = + new BasicMessageChannel<>( + binaryMessenger, + "dev.flutter.pigeon.video_player_android.AndroidVideoPlayerApi.pause" + + messageChannelSuffix, + getCodec()); + if (api != null) { + channel.setMessageHandler( + (message, reply) -> { + ArrayList wrapped = new ArrayList<>(); + ArrayList args = (ArrayList) message; + Long playerIdArg = (Long) args.get(0); + try { + api.pause(playerIdArg); + wrapped.add(0, null); + } catch (Throwable exception) { + wrapped = wrapError(exception); + } + reply.reply(wrapped); + }); + } else { + channel.setMessageHandler(null); + } + } + { + BasicMessageChannel channel = + new BasicMessageChannel<>( + binaryMessenger, + "dev.flutter.pigeon.video_player_android.AndroidVideoPlayerApi.setMixWithOthers" + + messageChannelSuffix, + getCodec()); + if (api != null) { + channel.setMessageHandler( + (message, reply) -> { + ArrayList wrapped = new ArrayList<>(); + ArrayList args = (ArrayList) message; + Boolean mixWithOthersArg = (Boolean) args.get(0); + try { + api.setMixWithOthers(mixWithOthersArg); + wrapped.add(0, null); + } catch (Throwable exception) { + wrapped = wrapError(exception); + } + reply.reply(wrapped); + }); + } else { + channel.setMessageHandler(null); + } + } + } + } +} diff --git a/packages/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/QueuingEventSink.java b/packages/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/QueuingEventSink.java new file mode 100644 index 0000000..222a224 --- /dev/null +++ b/packages/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/QueuingEventSink.java @@ -0,0 +1,85 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.videoplayer; + +import io.flutter.plugin.common.EventChannel; +import java.util.ArrayList; + +/** + * And implementation of {@link EventChannel.EventSink} which can wrap an underlying sink. + * + *

It delivers messages immediately when downstream is available, but it queues messages before + * the delegate event sink is set with setDelegate. + * + *

This class is not thread-safe. All calls must be done on the same thread or synchronized + * externally. + */ +final class QueuingEventSink implements EventChannel.EventSink { + private EventChannel.EventSink delegate; + private final ArrayList eventQueue = new ArrayList<>(); + private boolean done = false; + + public void setDelegate(EventChannel.EventSink delegate) { + this.delegate = delegate; + maybeFlush(); + } + + @Override + public void endOfStream() { + enqueue(new EndOfStreamEvent()); + maybeFlush(); + done = true; + } + + @Override + public void error(String code, String message, Object details) { + enqueue(new ErrorEvent(code, message, details)); + maybeFlush(); + } + + @Override + public void success(Object event) { + enqueue(event); + maybeFlush(); + } + + private void enqueue(Object event) { + if (done) { + return; + } + eventQueue.add(event); + } + + private void maybeFlush() { + if (delegate == null) { + return; + } + for (Object event : eventQueue) { + if (event instanceof EndOfStreamEvent) { + delegate.endOfStream(); + } else if (event instanceof ErrorEvent) { + ErrorEvent errorEvent = (ErrorEvent) event; + delegate.error(errorEvent.code, errorEvent.message, errorEvent.details); + } else { + delegate.success(event); + } + } + eventQueue.clear(); + } + + static class EndOfStreamEvent {} + + private static class ErrorEvent { + String code; + String message; + Object details; + + ErrorEvent(String code, String message, Object details) { + this.code = code; + this.message = message; + this.details = details; + } + } +} diff --git a/packages/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/RtspVideoAsset.java b/packages/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/RtspVideoAsset.java new file mode 100644 index 0000000..6b0edb4 --- /dev/null +++ b/packages/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/RtspVideoAsset.java @@ -0,0 +1,32 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.videoplayer; + +import android.content.Context; +import androidx.annotation.NonNull; +import androidx.annotation.OptIn; +import androidx.media3.common.MediaItem; +import androidx.media3.common.util.UnstableApi; +import androidx.media3.exoplayer.rtsp.RtspMediaSource; +import androidx.media3.exoplayer.source.MediaSource; + +final class RtspVideoAsset extends VideoAsset { + RtspVideoAsset(@NonNull String assetUrl) { + super(assetUrl); + } + + @NonNull + @Override + public MediaItem getMediaItem() { + return new MediaItem.Builder().setUri(assetUrl).build(); + } + + // TODO: Migrate to stable API, see https://github.com/flutter/flutter/issues/147039. + @OptIn(markerClass = UnstableApi.class) + @Override + public MediaSource.Factory getMediaSourceFactory(Context context) { + return new RtspMediaSource.Factory(); + } +} diff --git a/packages/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/VideoAsset.java b/packages/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/VideoAsset.java new file mode 100644 index 0000000..ba8dd55 --- /dev/null +++ b/packages/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/VideoAsset.java @@ -0,0 +1,98 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.videoplayer; + +import android.content.Context; +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import androidx.media3.common.MediaItem; +import androidx.media3.exoplayer.source.MediaSource; +import java.util.HashMap; +import java.util.Map; + +/** A video to be played by {@link VideoPlayer}. */ +public abstract class VideoAsset { + /** + * Returns an asset from a local {@code asset:///} URL, i.e. an on-device asset. + * + * @param assetUrl local asset, beginning in {@code asset:///}. + * @return the asset. + */ + @NonNull + static VideoAsset fromAssetUrl(@NonNull String assetUrl) { + if (!assetUrl.startsWith("asset:///")) { + throw new IllegalArgumentException("assetUrl must start with 'asset:///'"); + } + return new LocalVideoAsset(assetUrl); + } + + /** + * Returns an asset from a remote URL. + * + * @param remoteUrl remote asset, i.e. typically beginning with {@code https://} or similar. + * @param streamingFormat which streaming format, provided as a hint if able. + * @param httpHeaders HTTP headers to set for a request. + * @return the asset. + */ + @NonNull + static VideoAsset fromRemoteUrl( + @Nullable String remoteUrl, + @NonNull StreamingFormat streamingFormat, + @NonNull Map httpHeaders) { + return new HttpVideoAsset(remoteUrl, streamingFormat, new HashMap<>(httpHeaders)); + } + + /** + * Returns an asset from a RTSP URL. + * + * @param rtspUrl remote asset, beginning with {@code rtsp://}. + * @return the asset. + */ + @NonNull + static VideoAsset fromRtspUrl(@NonNull String rtspUrl) { + if (!rtspUrl.startsWith("rtsp://")) { + throw new IllegalArgumentException("rtspUrl must start with 'rtsp://'"); + } + return new RtspVideoAsset(rtspUrl); + } + + @Nullable protected final String assetUrl; + + protected VideoAsset(@Nullable String assetUrl) { + this.assetUrl = assetUrl; + } + + /** + * Returns the configured media item to be played. + * + * @return media item. + */ + @NonNull + public abstract MediaItem getMediaItem(); + + /** + * Returns the configured media source factory, if needed for this asset type. + * + * @param context application context. + * @return configured factory, or {@code null} if not needed for this asset type. + */ + @NonNull + public abstract MediaSource.Factory getMediaSourceFactory(@NonNull Context context); + + /** Streaming formats that can be provided to the video player as a hint. */ + enum StreamingFormat { + /** Default, if the format is either not known or not another valid format. */ + UNKNOWN, + + /** Smooth Streaming. */ + SMOOTH, + + /** MPEG-DASH (Dynamic Adaptive over HTTP). */ + DYNAMIC_ADAPTIVE, + + /** HTTP Live Streaming (HLS). */ + HTTP_LIVE + } +} diff --git a/packages/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/VideoPlayer.java b/packages/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/VideoPlayer.java new file mode 100644 index 0000000..0b46bfe --- /dev/null +++ b/packages/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/VideoPlayer.java @@ -0,0 +1,123 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.videoplayer; + +import static androidx.media3.common.Player.REPEAT_MODE_ALL; +import static androidx.media3.common.Player.REPEAT_MODE_OFF; + +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import androidx.media3.common.AudioAttributes; +import androidx.media3.common.C; +import androidx.media3.common.MediaItem; +import androidx.media3.common.PlaybackParameters; +import androidx.media3.exoplayer.ExoPlayer; +import io.flutter.view.TextureRegistry.SurfaceProducer; + +/** + * A class responsible for managing video playback using {@link ExoPlayer}. + * + *

It provides methods to control playback, adjust volume, and handle seeking. + */ +public abstract class VideoPlayer { + @NonNull private final ExoPlayerProvider exoPlayerProvider; + @NonNull private final MediaItem mediaItem; + @NonNull private final VideoPlayerOptions options; + @NonNull protected final VideoPlayerCallbacks videoPlayerEvents; + @Nullable protected final SurfaceProducer surfaceProducer; + @NonNull protected ExoPlayer exoPlayer; + + /** A closure-compatible signature since {@link java.util.function.Supplier} is API level 24. */ + public interface ExoPlayerProvider { + /** + * Returns a new {@link ExoPlayer}. + * + * @return new instance. + */ + @NonNull + ExoPlayer get(); + } + + public VideoPlayer( + @NonNull VideoPlayerCallbacks events, + @NonNull MediaItem mediaItem, + @NonNull VideoPlayerOptions options, + @Nullable SurfaceProducer surfaceProducer, + @NonNull ExoPlayerProvider exoPlayerProvider) { + this.videoPlayerEvents = events; + this.mediaItem = mediaItem; + this.options = options; + this.exoPlayerProvider = exoPlayerProvider; + this.surfaceProducer = surfaceProducer; + this.exoPlayer = createVideoPlayer(); + } + + @NonNull + protected ExoPlayer createVideoPlayer() { + ExoPlayer exoPlayer = exoPlayerProvider.get(); + exoPlayer.setMediaItem(mediaItem); + exoPlayer.prepare(); + exoPlayer.addListener(createExoPlayerEventListener(exoPlayer, surfaceProducer)); + setAudioAttributes(exoPlayer, options.mixWithOthers); + + return exoPlayer; + } + + @NonNull + protected abstract ExoPlayerEventListener createExoPlayerEventListener( + @NonNull ExoPlayer exoPlayer, @Nullable SurfaceProducer surfaceProducer); + + void sendBufferingUpdate() { + videoPlayerEvents.onBufferingUpdate(exoPlayer.getBufferedPosition()); + } + + private static void setAudioAttributes(ExoPlayer exoPlayer, boolean isMixMode) { + exoPlayer.setAudioAttributes( + new AudioAttributes.Builder().setContentType(C.AUDIO_CONTENT_TYPE_MOVIE).build(), + !isMixMode); + } + + void play() { + exoPlayer.play(); + } + + void pause() { + exoPlayer.pause(); + } + + void setLooping(boolean value) { + exoPlayer.setRepeatMode(value ? REPEAT_MODE_ALL : REPEAT_MODE_OFF); + } + + void setVolume(double value) { + float bracketedValue = (float) Math.max(0.0, Math.min(1.0, value)); + exoPlayer.setVolume(bracketedValue); + } + + void setPlaybackSpeed(double value) { + // We do not need to consider pitch and skipSilence for now as we do not handle them and + // therefore never diverge from the default values. + final PlaybackParameters playbackParameters = new PlaybackParameters(((float) value)); + + exoPlayer.setPlaybackParameters(playbackParameters); + } + + void seekTo(int location) { + exoPlayer.seekTo(location); + } + + long getPosition() { + return exoPlayer.getCurrentPosition(); + } + + @NonNull + public ExoPlayer getExoPlayer() { + return exoPlayer; + } + + public void dispose() { + exoPlayer.release(); + } +} diff --git a/packages/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/VideoPlayerCallbacks.java b/packages/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/VideoPlayerCallbacks.java new file mode 100644 index 0000000..24ecf8c --- /dev/null +++ b/packages/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/VideoPlayerCallbacks.java @@ -0,0 +1,33 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.videoplayer; + +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; + +/** + * Callbacks representing events invoked by {@link VideoPlayer}. + * + *

In the actual plugin, this will always be {@link VideoPlayerEventCallbacks}, which creates the + * expected events to send back through the plugin channel. In tests methods can be overridden in + * order to assert results. + * + *

See {@link androidx.media3.common.Player.Listener} for details. + */ +public interface VideoPlayerCallbacks { + void onInitialized(int width, int height, long durationInMs, int rotationCorrectionInDegrees); + + void onBufferingStart(); + + void onBufferingUpdate(long bufferedPosition); + + void onBufferingEnd(); + + void onCompleted(); + + void onError(@NonNull String code, @Nullable String message, @Nullable Object details); + + void onIsPlayingStateUpdate(boolean isPlaying); +} diff --git a/packages/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/VideoPlayerEventCallbacks.java b/packages/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/VideoPlayerEventCallbacks.java new file mode 100644 index 0000000..8b83ade --- /dev/null +++ b/packages/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/VideoPlayerEventCallbacks.java @@ -0,0 +1,104 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.videoplayer; + +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import androidx.annotation.VisibleForTesting; +import io.flutter.plugin.common.EventChannel; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +final class VideoPlayerEventCallbacks implements VideoPlayerCallbacks { + private final EventChannel.EventSink eventSink; + + static VideoPlayerEventCallbacks bindTo(EventChannel eventChannel) { + QueuingEventSink eventSink = new QueuingEventSink(); + eventChannel.setStreamHandler( + new EventChannel.StreamHandler() { + @Override + public void onListen(Object arguments, EventChannel.EventSink events) { + eventSink.setDelegate(events); + } + + @Override + public void onCancel(Object arguments) { + eventSink.setDelegate(null); + } + }); + return VideoPlayerEventCallbacks.withSink(eventSink); + } + + @VisibleForTesting + static VideoPlayerEventCallbacks withSink(EventChannel.EventSink eventSink) { + return new VideoPlayerEventCallbacks(eventSink); + } + + private VideoPlayerEventCallbacks(EventChannel.EventSink eventSink) { + this.eventSink = eventSink; + } + + @Override + public void onInitialized( + int width, int height, long durationInMs, int rotationCorrectionInDegrees) { + Map event = new HashMap<>(); + event.put("event", "initialized"); + event.put("width", width); + event.put("height", height); + event.put("duration", durationInMs); + if (rotationCorrectionInDegrees != 0) { + event.put("rotationCorrection", rotationCorrectionInDegrees); + } + eventSink.success(event); + } + + @Override + public void onBufferingStart() { + Map event = new HashMap<>(); + event.put("event", "bufferingStart"); + eventSink.success(event); + } + + @Override + public void onBufferingUpdate(long bufferedPosition) { + // iOS supports a list of buffered ranges, so we send as a list with a single range. + Map event = new HashMap<>(); + event.put("event", "bufferingUpdate"); + + List range = Arrays.asList(0, bufferedPosition); + event.put("values", Collections.singletonList(range)); + eventSink.success(event); + } + + @Override + public void onBufferingEnd() { + Map event = new HashMap<>(); + event.put("event", "bufferingEnd"); + eventSink.success(event); + } + + @Override + public void onCompleted() { + Map event = new HashMap<>(); + event.put("event", "completed"); + eventSink.success(event); + } + + @Override + public void onError(@NonNull String code, @Nullable String message, @Nullable Object details) { + eventSink.error(code, message, details); + } + + @Override + public void onIsPlayingStateUpdate(boolean isPlaying) { + Map event = new HashMap<>(); + event.put("event", "isPlayingStateUpdate"); + event.put("isPlaying", isPlaying); + eventSink.success(event); + } +} diff --git a/packages/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/VideoPlayerOptions.java b/packages/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/VideoPlayerOptions.java new file mode 100644 index 0000000..7c8a6aa --- /dev/null +++ b/packages/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/VideoPlayerOptions.java @@ -0,0 +1,9 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.videoplayer; + +public class VideoPlayerOptions { + public boolean mixWithOthers; +} diff --git a/packages/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/VideoPlayerPlugin.java b/packages/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/VideoPlayerPlugin.java new file mode 100644 index 0000000..3db5fd4 --- /dev/null +++ b/packages/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/VideoPlayerPlugin.java @@ -0,0 +1,262 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.videoplayer; + +import android.content.Context; +import android.util.LongSparseArray; +import androidx.annotation.NonNull; +import io.flutter.FlutterInjector; +import io.flutter.Log; +import io.flutter.embedding.engine.plugins.FlutterPlugin; +import io.flutter.plugin.common.BinaryMessenger; +import io.flutter.plugin.common.EventChannel; +import io.flutter.plugins.videoplayer.Messages.AndroidVideoPlayerApi; +import io.flutter.plugins.videoplayer.Messages.CreateMessage; +import io.flutter.plugins.videoplayer.platformview.PlatformVideoViewFactory; +import io.flutter.plugins.videoplayer.platformview.PlatformViewVideoPlayer; +import io.flutter.plugins.videoplayer.texture.TextureVideoPlayer; +import io.flutter.view.TextureRegistry; + +/** Android platform implementation of the VideoPlayerPlugin. */ +public class VideoPlayerPlugin implements FlutterPlugin, AndroidVideoPlayerApi { + private static final String TAG = "VideoPlayerPlugin"; + private final LongSparseArray videoPlayers = new LongSparseArray<>(); + private FlutterState flutterState; + private final VideoPlayerOptions options = new VideoPlayerOptions(); + + // TODO(stuartmorgan): Decouple identifiers for platform views and texture views. + /** + * The next non-texture player ID, initialized to a high number to avoid collisions with texture + * IDs (which are generated separately). + */ + private Long nextPlatformViewPlayerId = Long.MAX_VALUE; + + /** Register this with the v2 embedding for the plugin to respond to lifecycle callbacks. */ + public VideoPlayerPlugin() {} + + @Override + public void onAttachedToEngine(@NonNull FlutterPluginBinding binding) { + final FlutterInjector injector = FlutterInjector.instance(); + this.flutterState = + new FlutterState( + binding.getApplicationContext(), + binding.getBinaryMessenger(), + injector.flutterLoader()::getLookupKeyForAsset, + injector.flutterLoader()::getLookupKeyForAsset, + binding.getTextureRegistry()); + flutterState.startListening(this, binding.getBinaryMessenger()); + + binding + .getPlatformViewRegistry() + .registerViewFactory( + "plugins.flutter.dev/video_player_android", + new PlatformVideoViewFactory(videoPlayers::get)); + } + + @Override + public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) { + if (flutterState == null) { + Log.wtf(TAG, "Detached from the engine before registering to it."); + } + flutterState.stopListening(binding.getBinaryMessenger()); + flutterState = null; + onDestroy(); + } + + private void disposeAllPlayers() { + for (int i = 0; i < videoPlayers.size(); i++) { + videoPlayers.valueAt(i).dispose(); + } + videoPlayers.clear(); + } + + public void onDestroy() { + // The whole FlutterView is being destroyed. Here we release resources acquired for all + // instances + // of VideoPlayer. Once https://github.com/flutter/flutter/issues/19358 is resolved this may + // be replaced with just asserting that videoPlayers.isEmpty(). + // https://github.com/flutter/flutter/issues/20989 tracks this. + disposeAllPlayers(); + } + + @Override + public void initialize() { + disposeAllPlayers(); + } + + @Override + public @NonNull Long create(@NonNull CreateMessage arg) { + final VideoAsset videoAsset; + if (arg.getAsset() != null) { + String assetLookupKey; + if (arg.getPackageName() != null) { + assetLookupKey = + flutterState.keyForAssetAndPackageName.get(arg.getAsset(), arg.getPackageName()); + } else { + assetLookupKey = flutterState.keyForAsset.get(arg.getAsset()); + } + videoAsset = VideoAsset.fromAssetUrl("asset:///" + assetLookupKey); + } else if (arg.getUri().startsWith("rtsp://")) { + videoAsset = VideoAsset.fromRtspUrl(arg.getUri()); + } else { + VideoAsset.StreamingFormat streamingFormat = VideoAsset.StreamingFormat.UNKNOWN; + String formatHint = arg.getFormatHint(); + if (formatHint != null) { + switch (formatHint) { + case "ss": + streamingFormat = VideoAsset.StreamingFormat.SMOOTH; + break; + case "dash": + streamingFormat = VideoAsset.StreamingFormat.DYNAMIC_ADAPTIVE; + break; + case "hls": + streamingFormat = VideoAsset.StreamingFormat.HTTP_LIVE; + break; + } + } + videoAsset = VideoAsset.fromRemoteUrl(arg.getUri(), streamingFormat, arg.getHttpHeaders()); + } + + long id; + VideoPlayer videoPlayer; + if (arg.getViewType() == Messages.PlatformVideoViewType.PLATFORM_VIEW) { + id = nextPlatformViewPlayerId--; + videoPlayer = + PlatformViewVideoPlayer.create( + flutterState.applicationContext, + VideoPlayerEventCallbacks.bindTo(createEventChannel(id)), + videoAsset, + options); + } else { + TextureRegistry.SurfaceProducer handle = flutterState.textureRegistry.createSurfaceProducer(); + id = handle.id(); + videoPlayer = + TextureVideoPlayer.create( + flutterState.applicationContext, + VideoPlayerEventCallbacks.bindTo(createEventChannel(id)), + handle, + videoAsset, + options); + } + + videoPlayers.put(id, videoPlayer); + return id; + } + + @NonNull + private EventChannel createEventChannel(long id) { + return new EventChannel( + flutterState.binaryMessenger, "flutter.io/videoPlayer/videoEvents" + id); + } + + @NonNull + private VideoPlayer getPlayer(long playerId) { + VideoPlayer player = videoPlayers.get(playerId); + + // Avoid a very ugly un-debuggable NPE that results in returning a null player. + if (player == null) { + String message = "No player found with playerId <" + playerId + ">"; + if (videoPlayers.size() == 0) { + message += " and no active players created by the plugin."; + } + throw new IllegalStateException(message); + } + + return player; + } + + @Override + public void dispose(@NonNull Long playerId) { + VideoPlayer player = getPlayer(playerId); + player.dispose(); + videoPlayers.remove(playerId); + } + + @Override + public void setLooping(@NonNull Long playerId, @NonNull Boolean looping) { + VideoPlayer player = getPlayer(playerId); + player.setLooping(looping); + } + + @Override + public void setVolume(@NonNull Long playerId, @NonNull Double volume) { + VideoPlayer player = getPlayer(playerId); + player.setVolume(volume); + } + + @Override + public void setPlaybackSpeed(@NonNull Long playerId, @NonNull Double speed) { + VideoPlayer player = getPlayer(playerId); + player.setPlaybackSpeed(speed); + } + + @Override + public void play(@NonNull Long playerId) { + VideoPlayer player = getPlayer(playerId); + player.play(); + } + + @Override + public @NonNull Long position(@NonNull Long playerId) { + VideoPlayer player = getPlayer(playerId); + long position = player.getPosition(); + player.sendBufferingUpdate(); + return position; + } + + @Override + public void seekTo(@NonNull Long playerId, @NonNull Long position) { + VideoPlayer player = getPlayer(playerId); + player.seekTo(position.intValue()); + } + + @Override + public void pause(@NonNull Long playerId) { + VideoPlayer player = getPlayer(playerId); + player.pause(); + } + + @Override + public void setMixWithOthers(@NonNull Boolean mixWithOthers) { + options.mixWithOthers = mixWithOthers; + } + + private interface KeyForAssetFn { + String get(String asset); + } + + private interface KeyForAssetAndPackageName { + String get(String asset, String packageName); + } + + private static final class FlutterState { + final Context applicationContext; + final BinaryMessenger binaryMessenger; + final KeyForAssetFn keyForAsset; + final KeyForAssetAndPackageName keyForAssetAndPackageName; + final TextureRegistry textureRegistry; + + FlutterState( + Context applicationContext, + BinaryMessenger messenger, + KeyForAssetFn keyForAsset, + KeyForAssetAndPackageName keyForAssetAndPackageName, + TextureRegistry textureRegistry) { + this.applicationContext = applicationContext; + this.binaryMessenger = messenger; + this.keyForAsset = keyForAsset; + this.keyForAssetAndPackageName = keyForAssetAndPackageName; + this.textureRegistry = textureRegistry; + } + + void startListening(VideoPlayerPlugin methodCallHandler, BinaryMessenger messenger) { + AndroidVideoPlayerApi.setUp(messenger, methodCallHandler); + } + + void stopListening(BinaryMessenger messenger) { + AndroidVideoPlayerApi.setUp(messenger, null); + } + } +} diff --git a/packages/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/platformview/PlatformVideoView.java b/packages/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/platformview/PlatformVideoView.java new file mode 100644 index 0000000..02ac659 --- /dev/null +++ b/packages/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/platformview/PlatformVideoView.java @@ -0,0 +1,94 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.videoplayer.platformview; + +import android.content.Context; +import android.os.Build; +import android.view.SurfaceHolder; +import android.view.SurfaceView; +import android.view.View; +import androidx.annotation.NonNull; +import androidx.annotation.OptIn; +import androidx.media3.common.util.UnstableApi; +import androidx.media3.exoplayer.ExoPlayer; +import io.flutter.plugin.platform.PlatformView; + +/** + * A class used to create a native video view that can be embedded in a Flutter app. It wraps an + * {@link ExoPlayer} instance and displays its video content. + */ +public final class PlatformVideoView implements PlatformView { + @NonNull private final SurfaceView surfaceView; + + /** + * Constructs a new PlatformVideoView. + * + * @param context The context in which the view is running. + * @param exoPlayer The ExoPlayer instance used to play the video. + */ + @OptIn(markerClass = UnstableApi.class) + public PlatformVideoView(@NonNull Context context, @NonNull ExoPlayer exoPlayer) { + surfaceView = new SurfaceView(context); + + if (Build.VERSION.SDK_INT == Build.VERSION_CODES.P) { + // Workaround for rendering issues on Android 9 (API 28). + // On Android 9, using setVideoSurfaceView seems to lead to issues where the first frame is + // not displayed if the video is paused initially. + // To ensure the first frame is visible, the surface is directly set using holder.getSurface() + // when the surface is created, and ExoPlayer seeks to a position to force rendering of the + // first frame. + setupSurfaceWithCallback(exoPlayer); + } else { + if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.N_MR1) { + // Avoid blank space instead of a video on Android versions below 8 by adjusting video's + // z-layer within the Android view hierarchy: + surfaceView.setZOrderMediaOverlay(true); + } + exoPlayer.setVideoSurfaceView(surfaceView); + } + } + + private void setupSurfaceWithCallback(@NonNull ExoPlayer exoPlayer) { + surfaceView + .getHolder() + .addCallback( + new SurfaceHolder.Callback() { + @Override + public void surfaceCreated(@NonNull SurfaceHolder holder) { + exoPlayer.setVideoSurface(holder.getSurface()); + // Force first frame rendering: + exoPlayer.seekTo(1); + } + + @Override + public void surfaceChanged( + @NonNull SurfaceHolder holder, int format, int width, int height) { + // No implementation needed. + } + + @Override + public void surfaceDestroyed(@NonNull SurfaceHolder holder) { + exoPlayer.setVideoSurface(null); + } + }); + } + + /** + * Returns the view associated with this PlatformView. + * + * @return The SurfaceView used to display the video. + */ + @NonNull + @Override + public View getView() { + return surfaceView; + } + + /** Disposes of the resources used by this PlatformView. */ + @Override + public void dispose() { + surfaceView.getHolder().getSurface().release(); + } +} diff --git a/packages/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/platformview/PlatformVideoViewFactory.java b/packages/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/platformview/PlatformVideoViewFactory.java new file mode 100644 index 0000000..8bb8516 --- /dev/null +++ b/packages/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/platformview/PlatformVideoViewFactory.java @@ -0,0 +1,68 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.videoplayer.platformview; + +import android.content.Context; +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import androidx.media3.exoplayer.ExoPlayer; +import io.flutter.plugin.platform.PlatformView; +import io.flutter.plugin.platform.PlatformViewFactory; +import io.flutter.plugins.videoplayer.Messages; +import io.flutter.plugins.videoplayer.VideoPlayer; +import java.util.Objects; + +/** + * A factory class responsible for creating platform video views that can be embedded in a Flutter + * app. + */ +public class PlatformVideoViewFactory extends PlatformViewFactory { + private final VideoPlayerProvider videoPlayerProvider; + + /** Functional interface for providing a VideoPlayer instance based on the player ID. */ + @FunctionalInterface + public interface VideoPlayerProvider { + /** + * Retrieves a VideoPlayer instance based on the provided player ID. + * + * @param playerId The unique identifier for the video player. + * @return A VideoPlayer instance associated with the given player ID. + */ + @NonNull + VideoPlayer getVideoPlayer(@NonNull Long playerId); + } + + /** + * Constructs a new PlatformVideoViewFactory. + * + * @param videoPlayerProvider The provider used to retrieve the video player associated with the + * view. + */ + public PlatformVideoViewFactory(@NonNull VideoPlayerProvider videoPlayerProvider) { + super(Messages.AndroidVideoPlayerApi.getCodec()); + this.videoPlayerProvider = videoPlayerProvider; + } + + /** + * Creates a new instance of platform view. + * + * @param context The context in which the view is running. + * @param id The unique identifier for the view. + * @param args The arguments for creating the view. + * @return A new instance of PlatformVideoView. + */ + @NonNull + @Override + public PlatformView create(@NonNull Context context, int id, @Nullable Object args) { + final Messages.PlatformVideoViewCreationParams params = + Objects.requireNonNull((Messages.PlatformVideoViewCreationParams) args); + final Long playerId = params.getPlayerId(); + + final VideoPlayer player = videoPlayerProvider.getVideoPlayer(playerId); + final ExoPlayer exoPlayer = player.getExoPlayer(); + + return new PlatformVideoView(context, exoPlayer); + } +} diff --git a/packages/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/platformview/PlatformViewExoPlayerEventListener.java b/packages/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/platformview/PlatformViewExoPlayerEventListener.java new file mode 100644 index 0000000..82343d7 --- /dev/null +++ b/packages/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/platformview/PlatformViewExoPlayerEventListener.java @@ -0,0 +1,52 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.videoplayer.platformview; + +import androidx.annotation.NonNull; +import androidx.annotation.OptIn; +import androidx.annotation.VisibleForTesting; +import androidx.media3.common.Format; +import androidx.media3.common.util.UnstableApi; +import androidx.media3.exoplayer.ExoPlayer; +import io.flutter.plugins.videoplayer.ExoPlayerEventListener; +import io.flutter.plugins.videoplayer.VideoPlayerCallbacks; +import java.util.Objects; + +public final class PlatformViewExoPlayerEventListener extends ExoPlayerEventListener { + @VisibleForTesting + public PlatformViewExoPlayerEventListener( + @NonNull ExoPlayer exoPlayer, @NonNull VideoPlayerCallbacks events) { + this(exoPlayer, events, false); + } + + public PlatformViewExoPlayerEventListener( + @NonNull ExoPlayer exoPlayer, @NonNull VideoPlayerCallbacks events, boolean initialized) { + super(exoPlayer, events, initialized); + } + + @OptIn(markerClass = UnstableApi.class) + @Override + protected void sendInitialized() { + // We can't rely on VideoSize here, because at this point it is not available - the platform + // view was not created yet. We use the video format instead. + Format videoFormat = exoPlayer.getVideoFormat(); + RotationDegrees rotationCorrection = + RotationDegrees.fromDegrees(Objects.requireNonNull(videoFormat).rotationDegrees); + int width = videoFormat.width; + int height = videoFormat.height; + + // Switch the width/height if video was taken in portrait mode and a rotation + // correction was detected. + if (rotationCorrection == RotationDegrees.ROTATE_90 + || rotationCorrection == RotationDegrees.ROTATE_270) { + width = videoFormat.height; + height = videoFormat.width; + + rotationCorrection = RotationDegrees.fromDegrees(0); + } + + events.onInitialized(width, height, exoPlayer.getDuration(), rotationCorrection.getDegrees()); + } +} diff --git a/packages/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/platformview/PlatformViewVideoPlayer.java b/packages/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/platformview/PlatformViewVideoPlayer.java new file mode 100644 index 0000000..fea8587 --- /dev/null +++ b/packages/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/platformview/PlatformViewVideoPlayer.java @@ -0,0 +1,72 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.videoplayer.platformview; + +import android.content.Context; +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import androidx.annotation.VisibleForTesting; +import androidx.media3.common.MediaItem; +import androidx.media3.exoplayer.DefaultRenderersFactory; +import androidx.media3.exoplayer.ExoPlayer; +import io.flutter.plugins.videoplayer.ExoPlayerEventListener; +import io.flutter.plugins.videoplayer.VideoAsset; +import io.flutter.plugins.videoplayer.VideoPlayer; +import io.flutter.plugins.videoplayer.VideoPlayerCallbacks; +import io.flutter.plugins.videoplayer.VideoPlayerOptions; +import io.flutter.view.TextureRegistry.SurfaceProducer; + +/** + * A subclass of {@link VideoPlayer} that adds functionality related to platform view as a way of + * displaying the video in the app. + */ +public class PlatformViewVideoPlayer extends VideoPlayer { + @VisibleForTesting + public PlatformViewVideoPlayer( + @NonNull VideoPlayerCallbacks events, + @NonNull MediaItem mediaItem, + @NonNull VideoPlayerOptions options, + @NonNull ExoPlayerProvider exoPlayerProvider) { + super(events, mediaItem, options, /* surfaceProducer */ null, exoPlayerProvider); + } + + /** + * Creates a platform view video player. + * + * @param context application context. + * @param events event callbacks. + * @param asset asset to play. + * @param options options for playback. + * @return a video player instance. + */ + @NonNull + public static PlatformViewVideoPlayer create( + @NonNull Context context, + @NonNull VideoPlayerCallbacks events, + @NonNull VideoAsset asset, + @NonNull VideoPlayerOptions options) { + return new PlatformViewVideoPlayer( + events, + asset.getMediaItem(), + options, + () -> { + DefaultRenderersFactory renderersFactory = + new DefaultRenderersFactory(context).setEnableDecoderFallback(true); + ExoPlayer.Builder builder = + new ExoPlayer.Builder(context, renderersFactory) + .setMediaSourceFactory(asset.getMediaSourceFactory(context)); + return builder.build(); + }); + } + + @NonNull + @Override + protected ExoPlayerEventListener createExoPlayerEventListener( + @NonNull ExoPlayer exoPlayer, @Nullable SurfaceProducer surfaceProducer) { + // Platform view video player does not suspend and re-create the exoPlayer, hence initialized + // is always false. It also does not require a reference to the SurfaceProducer. + return new PlatformViewExoPlayerEventListener(exoPlayer, videoPlayerEvents, false); + } +} diff --git a/packages/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/texture/TextureExoPlayerEventListener.java b/packages/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/texture/TextureExoPlayerEventListener.java new file mode 100644 index 0000000..e6013ef --- /dev/null +++ b/packages/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/texture/TextureExoPlayerEventListener.java @@ -0,0 +1,103 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.videoplayer.texture; + +import android.os.Build; +import androidx.annotation.NonNull; +import androidx.annotation.OptIn; +import androidx.annotation.VisibleForTesting; +import androidx.media3.common.Format; +import androidx.media3.common.VideoSize; +import androidx.media3.exoplayer.ExoPlayer; +import io.flutter.plugins.videoplayer.ExoPlayerEventListener; +import io.flutter.plugins.videoplayer.VideoPlayerCallbacks; +import java.util.Objects; + +public final class TextureExoPlayerEventListener extends ExoPlayerEventListener { + private boolean surfaceProducerHandlesCropAndRotation; + + @VisibleForTesting + public TextureExoPlayerEventListener( + @NonNull ExoPlayer exoPlayer, + @NonNull VideoPlayerCallbacks events, + boolean surfaceProducerHandlesCropAndRotation) { + this(exoPlayer, events, surfaceProducerHandlesCropAndRotation, false); + } + + public TextureExoPlayerEventListener( + @NonNull ExoPlayer exoPlayer, + @NonNull VideoPlayerCallbacks events, + boolean surfaceProducerHandlesCropAndRotation, + boolean initialized) { + super(exoPlayer, events, initialized); + this.surfaceProducerHandlesCropAndRotation = surfaceProducerHandlesCropAndRotation; + } + + @Override + protected void sendInitialized() { + VideoSize videoSize = exoPlayer.getVideoSize(); + RotationDegrees rotationCorrection = RotationDegrees.ROTATE_0; + int width = videoSize.width; + int height = videoSize.height; + if (width != 0 && height != 0) { + if (Build.VERSION.SDK_INT <= 21) { + // On API 21 and below, Exoplayer may not internally handle rotation correction + // and reports it through VideoSize.unappliedRotationDegrees. We may apply it to + // fix the case of upside-down playback. + try { + RotationDegrees unappliedRotation = + RotationDegrees.fromDegrees(videoSize.unappliedRotationDegrees); + rotationCorrection = getRotationCorrectionFromUnappliedRotation(unappliedRotation); + } catch (IllegalArgumentException e) { + // Unapplied rotation other than 0, 90, 180, 270 reported by VideoSize. Because this is + // unexpected, we apply no rotation correction. + rotationCorrection = RotationDegrees.ROTATE_0; + } + } else if (surfaceProducerHandlesCropAndRotation) { + // When the SurfaceTexture backend for Impeller is used, the preview should already + // be correctly rotated. + rotationCorrection = RotationDegrees.ROTATE_0; + } else { + // The video's Format also provides a rotation correction that may be used to + // correct the rotation, so we try to use that to correct the video rotation + // when the ImageReader backend for Impeller is used. + int rawVideoFormatRotation = getRotationCorrectionFromFormat(exoPlayer); + + try { + rotationCorrection = RotationDegrees.fromDegrees(rawVideoFormatRotation); + } catch (IllegalArgumentException e) { + // Rotation correction other than 0, 90, 180, 270 reported by Format. Because this is + // unexpected we apply no rotation correction. + rotationCorrection = RotationDegrees.ROTATE_0; + } + } + } + events.onInitialized(width, height, exoPlayer.getDuration(), rotationCorrection.getDegrees()); + } + + private RotationDegrees getRotationCorrectionFromUnappliedRotation( + RotationDegrees unappliedRotationDegrees) { + RotationDegrees rotationCorrection = RotationDegrees.ROTATE_0; + + // Rotating the video with ExoPlayer does not seem to be possible with a Surface, + // so inform the Flutter code that the widget needs to be rotated to prevent + // upside-down playback for videos with unappliedRotationDegrees of 180 (other orientations + // work correctly without correction). + if (unappliedRotationDegrees == RotationDegrees.ROTATE_180) { + rotationCorrection = unappliedRotationDegrees; + } + + return rotationCorrection; + } + + @OptIn(markerClass = androidx.media3.common.util.UnstableApi.class) + // A video's Format and its rotation degrees are unstable because they are not guaranteed + // the same implementation across API versions. It is possible that this logic may need + // revisiting should the implementation change across versions of the Exoplayer API. + private int getRotationCorrectionFromFormat(ExoPlayer exoPlayer) { + Format videoFormat = Objects.requireNonNull(exoPlayer.getVideoFormat()); + return videoFormat.rotationDegrees; + } +} diff --git a/packages/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/texture/TextureVideoPlayer.java b/packages/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/texture/TextureVideoPlayer.java new file mode 100644 index 0000000..60b34fb --- /dev/null +++ b/packages/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/texture/TextureVideoPlayer.java @@ -0,0 +1,129 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.videoplayer.texture; + +import android.content.Context; +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import androidx.annotation.RestrictTo; +import androidx.annotation.VisibleForTesting; +import androidx.media3.common.MediaItem; +import androidx.media3.exoplayer.DefaultRenderersFactory; +import androidx.media3.exoplayer.ExoPlayer; +import io.flutter.plugins.videoplayer.ExoPlayerEventListener; +import io.flutter.plugins.videoplayer.ExoPlayerState; +import io.flutter.plugins.videoplayer.VideoAsset; +import io.flutter.plugins.videoplayer.VideoPlayer; +import io.flutter.plugins.videoplayer.VideoPlayerCallbacks; +import io.flutter.plugins.videoplayer.VideoPlayerOptions; +import io.flutter.view.TextureRegistry.SurfaceProducer; + +/** + * A subclass of {@link VideoPlayer} that adds functionality related to texture view as a way of + * displaying the video in the app. + * + *

It manages the lifecycle of the texture and ensures that the video is properly displayed on + * the texture. + */ +public final class TextureVideoPlayer extends VideoPlayer implements SurfaceProducer.Callback { + @Nullable private ExoPlayerState savedStateDuring; + + /** + * Creates a texture video player. + * + * @param context application context. + * @param events event callbacks. + * @param surfaceProducer produces a texture to render to. + * @param asset asset to play. + * @param options options for playback. + * @return a video player instance. + */ + @NonNull + public static TextureVideoPlayer create( + @NonNull Context context, + @NonNull VideoPlayerCallbacks events, + @NonNull SurfaceProducer surfaceProducer, + @NonNull VideoAsset asset, + @NonNull VideoPlayerOptions options) { + return new TextureVideoPlayer( + events, + surfaceProducer, + asset.getMediaItem(), + options, + () -> { + DefaultRenderersFactory renderersFactory = + new DefaultRenderersFactory(context).setEnableDecoderFallback(true); + ExoPlayer.Builder builder = + new ExoPlayer.Builder(context, renderersFactory) + .setMediaSourceFactory(asset.getMediaSourceFactory(context)); + return builder.build(); + }); + } + + @VisibleForTesting + public TextureVideoPlayer( + @NonNull VideoPlayerCallbacks events, + @NonNull SurfaceProducer surfaceProducer, + @NonNull MediaItem mediaItem, + @NonNull VideoPlayerOptions options, + @NonNull ExoPlayerProvider exoPlayerProvider) { + super(events, mediaItem, options, surfaceProducer, exoPlayerProvider); + + surfaceProducer.setCallback(this); + + this.exoPlayer.setVideoSurface(surfaceProducer.getSurface()); + } + + @NonNull + @Override + protected ExoPlayerEventListener createExoPlayerEventListener( + @NonNull ExoPlayer exoPlayer, @Nullable SurfaceProducer surfaceProducer) { + if (surfaceProducer == null) { + throw new IllegalArgumentException( + "surfaceProducer cannot be null to create an ExoPlayerEventListener for TextureVideoPlayer."); + } + boolean surfaceProducerHandlesCropAndRotation = surfaceProducer.handlesCropAndRotation(); + return new TextureExoPlayerEventListener( + exoPlayer, + videoPlayerEvents, + surfaceProducerHandlesCropAndRotation, + playerHasBeenSuspended()); + } + + @RestrictTo(RestrictTo.Scope.LIBRARY) + public void onSurfaceAvailable() { + if (savedStateDuring != null) { + exoPlayer = createVideoPlayer(); + exoPlayer.setVideoSurface(surfaceProducer.getSurface()); + savedStateDuring.restore(exoPlayer); + savedStateDuring = null; + } + } + + @RestrictTo(RestrictTo.Scope.LIBRARY) + // TODO(bparrishMines): Replace with onSurfaceCleanup once available on stable. See + // https://github.com/flutter/flutter/issues/161256. + @SuppressWarnings({"deprecation", "removal"}) + public void onSurfaceDestroyed() { + // Intentionally do not call pause/stop here, because the surface has already been released + // at this point (see https://github.com/flutter/flutter/issues/156451). + savedStateDuring = ExoPlayerState.save(exoPlayer); + exoPlayer.release(); + } + + private boolean playerHasBeenSuspended() { + return savedStateDuring != null; + } + + public void dispose() { + // Super must be called first to ensure the player is released before the surface. + super.dispose(); + + surfaceProducer.release(); + // TODO(matanlurey): Remove when embedder no longer calls-back once released. + // https://github.com/flutter/flutter/issues/156434. + surfaceProducer.setCallback(null); + } +} diff --git a/packages/video_player_android/android/src/test/java/io/flutter/plugins/videoplayer/ExoPlayerEventListenerTest.java b/packages/video_player_android/android/src/test/java/io/flutter/plugins/videoplayer/ExoPlayerEventListenerTest.java new file mode 100644 index 0000000..ac40efb --- /dev/null +++ b/packages/video_player_android/android/src/test/java/io/flutter/plugins/videoplayer/ExoPlayerEventListenerTest.java @@ -0,0 +1,148 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.videoplayer; + +import static org.mockito.ArgumentMatchers.contains; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.isNull; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import androidx.media3.common.PlaybackException; +import androidx.media3.common.Player; +import androidx.media3.exoplayer.ExoPlayer; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnit; +import org.mockito.junit.MockitoRule; +import org.robolectric.RobolectricTestRunner; + +/** + * Unit tests for {@link ExoPlayerEventListener}. + * + *

This test suite narrowly verifies that the events emitted by the underlying {@link + * androidx.media3.exoplayer.ExoPlayer} instance are translated to the callback interface we expect + * ({@link VideoPlayerCallbacks} and/or interface with the player instance as expected). + */ +@RunWith(RobolectricTestRunner.class) +public final class ExoPlayerEventListenerTest { + @Mock private ExoPlayer mockExoPlayer; + @Mock private VideoPlayerCallbacks mockCallbacks; + private ExoPlayerEventListener eventListener; + + @Rule public MockitoRule initRule = MockitoJUnit.rule(); + + /** + * A test subclass of {@link ExoPlayerEventListener} that exposes the abstract class for testing. + */ + private static final class TestExoPlayerEventListener extends ExoPlayerEventListener { + public TestExoPlayerEventListener(ExoPlayer exoPlayer, VideoPlayerCallbacks callbacks) { + super(exoPlayer, callbacks, false); + } + + @Override + protected void sendInitialized() { + // No implementation needed. + } + } + + @Before + public void setUp() { + eventListener = new TestExoPlayerEventListener(mockExoPlayer, mockCallbacks); + } + + @Test + public void onPlaybackStateChangedBufferingSendsBufferingStartAndUpdates() { + when(mockExoPlayer.getBufferedPosition()).thenReturn(10L); + eventListener.onPlaybackStateChanged(Player.STATE_BUFFERING); + + verify(mockCallbacks).onBufferingStart(); + verify(mockCallbacks).onBufferingUpdate(10L); + verifyNoMoreInteractions(mockCallbacks); + + // If it's invoked again, only the update event is called. + verify(mockCallbacks).onBufferingUpdate(10L); + verifyNoMoreInteractions(mockCallbacks); + } + + @Test + public void onPlaybackStateChangedEndedSendsOnCompleted() { + eventListener.onPlaybackStateChanged(Player.STATE_ENDED); + + verify(mockCallbacks).onCompleted(); + verifyNoMoreInteractions(mockCallbacks); + } + + @Test + public void onPlaybackStateChangedEndedAfterBufferingSendsBufferingEndAndOnCompleted() { + when(mockExoPlayer.getBufferedPosition()).thenReturn(10L); + eventListener.onPlaybackStateChanged(Player.STATE_BUFFERING); + verify(mockCallbacks).onBufferingStart(); + verify(mockCallbacks).onBufferingUpdate(10L); + + eventListener.onPlaybackStateChanged(Player.STATE_ENDED); + verify(mockCallbacks).onCompleted(); + verify(mockCallbacks).onBufferingEnd(); + + verifyNoMoreInteractions(mockCallbacks); + } + + @Test + public void onPlaybackStateChangedIdleDoNothing() { + eventListener.onPlaybackStateChanged(Player.STATE_IDLE); + + verifyNoInteractions(mockCallbacks); + } + + @Test + public void onPlaybackStateChangedIdleAfterBufferingSendsBufferingEnd() { + when(mockExoPlayer.getBufferedPosition()).thenReturn(10L); + eventListener.onPlaybackStateChanged(Player.STATE_BUFFERING); + verify(mockCallbacks).onBufferingStart(); + verify(mockCallbacks).onBufferingUpdate(10L); + + eventListener.onPlaybackStateChanged(Player.STATE_IDLE); + verify(mockCallbacks).onBufferingEnd(); + + verifyNoMoreInteractions(mockCallbacks); + } + + @Test + public void onErrorVideoErrorWhenBufferingInProgressAlsoEndBuffering() { + when(mockExoPlayer.getBufferedPosition()).thenReturn(10L); + eventListener.onPlaybackStateChanged(Player.STATE_BUFFERING); + verify(mockCallbacks).onBufferingStart(); + verify(mockCallbacks).onBufferingUpdate(10L); + + eventListener.onPlayerError( + new PlaybackException("BAD", null, PlaybackException.ERROR_CODE_AUDIO_TRACK_INIT_FAILED)); + verify(mockCallbacks).onBufferingEnd(); + verify(mockCallbacks).onError(eq("VideoError"), contains("BAD"), isNull()); + } + + @Test + public void onErrorBehindLiveWindowSeekToDefaultAndPrepare() { + eventListener.onPlayerError( + new PlaybackException("SORT_OF_OK", null, PlaybackException.ERROR_CODE_BEHIND_LIVE_WINDOW)); + + verify(mockExoPlayer).seekToDefaultPosition(); + verify(mockExoPlayer).prepare(); + verifyNoInteractions(mockCallbacks); + } + + @Test + public void onIsPlayingChangedToggled() { + eventListener.onIsPlayingChanged(true); + verify(mockCallbacks).onIsPlayingStateUpdate(true); + + eventListener.onIsPlayingChanged(false); + verify(mockCallbacks).onIsPlayingStateUpdate(false); + } +} diff --git a/packages/video_player_android/android/src/test/java/io/flutter/plugins/videoplayer/FakeVideoAsset.java b/packages/video_player_android/android/src/test/java/io/flutter/plugins/videoplayer/FakeVideoAsset.java new file mode 100644 index 0000000..8b5c441 --- /dev/null +++ b/packages/video_player_android/android/src/test/java/io/flutter/plugins/videoplayer/FakeVideoAsset.java @@ -0,0 +1,37 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.videoplayer; + +import android.content.Context; +import androidx.annotation.NonNull; +import androidx.media3.common.MediaItem; +import androidx.media3.exoplayer.source.MediaSource; +import androidx.media3.test.utils.FakeMediaSourceFactory; + +/** A fake implementation of the {@link VideoAsset} class. */ +final class FakeVideoAsset extends VideoAsset { + @NonNull private final MediaSource.Factory mediaSourceFactory; + + FakeVideoAsset(String assetUrl) { + this(assetUrl, new FakeMediaSourceFactory()); + } + + FakeVideoAsset(String assetUrl, @NonNull MediaSource.Factory mediaSourceFactory) { + super(assetUrl); + this.mediaSourceFactory = mediaSourceFactory; + } + + @NonNull + @Override + public MediaItem getMediaItem() { + return new MediaItem.Builder().setUri(assetUrl).build(); + } + + @NonNull + @Override + public MediaSource.Factory getMediaSourceFactory(@NonNull Context context) { + return mediaSourceFactory; + } +} diff --git a/packages/video_player_android/android/src/test/java/io/flutter/plugins/videoplayer/PlatformVideoViewFactoryTest.java b/packages/video_player_android/android/src/test/java/io/flutter/plugins/videoplayer/PlatformVideoViewFactoryTest.java new file mode 100644 index 0000000..a6cfa93 --- /dev/null +++ b/packages/video_player_android/android/src/test/java/io/flutter/plugins/videoplayer/PlatformVideoViewFactoryTest.java @@ -0,0 +1,40 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.videoplayer; + +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.*; + +import android.content.Context; +import androidx.media3.exoplayer.ExoPlayer; +import io.flutter.plugin.platform.PlatformView; +import io.flutter.plugins.videoplayer.platformview.PlatformVideoView; +import io.flutter.plugins.videoplayer.platformview.PlatformVideoViewFactory; +import org.junit.Test; + +public class PlatformVideoViewFactoryTest { + @Test + public void createsPlatformVideoViewBasedOnSuppliedArguments() { + final PlatformVideoViewFactory.VideoPlayerProvider videoPlayerProvider = + mock(PlatformVideoViewFactory.VideoPlayerProvider.class); + final VideoPlayer videoPlayer = mock(VideoPlayer.class); + final ExoPlayer exoPlayer = mock(ExoPlayer.class); + final Context context = mock(Context.class); + final long playerId = 1L; + + when(videoPlayerProvider.getVideoPlayer(playerId)).thenReturn(videoPlayer); + when(videoPlayer.getExoPlayer()).thenReturn(exoPlayer); + + final PlatformVideoViewFactory factory = new PlatformVideoViewFactory(videoPlayerProvider); + final Messages.PlatformVideoViewCreationParams args = + new Messages.PlatformVideoViewCreationParams.Builder().setPlayerId(playerId).build(); + + final PlatformView view = factory.create(context, 0, args); + + assertTrue(view instanceof PlatformVideoView); + verify(videoPlayerProvider).getVideoPlayer(playerId); + verify(videoPlayer).getExoPlayer(); + } +} diff --git a/packages/video_player_android/android/src/test/java/io/flutter/plugins/videoplayer/PlatformVideoViewTest.java b/packages/video_player_android/android/src/test/java/io/flutter/plugins/videoplayer/PlatformVideoViewTest.java new file mode 100644 index 0000000..274e086 --- /dev/null +++ b/packages/video_player_android/android/src/test/java/io/flutter/plugins/videoplayer/PlatformVideoViewTest.java @@ -0,0 +1,33 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.videoplayer; + +import static org.junit.Assert.assertNotNull; +import static org.mockito.Mockito.*; + +import android.content.Context; +import android.view.SurfaceView; +import androidx.media3.exoplayer.ExoPlayer; +import io.flutter.plugins.videoplayer.platformview.PlatformVideoView; +import java.lang.reflect.Field; +import org.junit.Test; + +/** Unit tests for {@link PlatformVideoViewTest}. */ +public class PlatformVideoViewTest { + @Test + public void createsSurfaceViewAndSetsItForExoPlayer() throws Exception { + final Context mockContext = mock(Context.class); + final ExoPlayer mockExoPlayer = mock(ExoPlayer.class); + + final PlatformVideoView view = new PlatformVideoView(mockContext, mockExoPlayer); + + final Field field = PlatformVideoView.class.getDeclaredField("surfaceView"); + field.setAccessible(true); + final SurfaceView surfaceView = (SurfaceView) field.get(view); + + assertNotNull(surfaceView); + verify(mockExoPlayer).setVideoSurfaceView(surfaceView); + } +} diff --git a/packages/video_player_android/android/src/test/java/io/flutter/plugins/videoplayer/PlatformViewExoPlayerEventListenerTest.java b/packages/video_player_android/android/src/test/java/io/flutter/plugins/videoplayer/PlatformViewExoPlayerEventListenerTest.java new file mode 100644 index 0000000..8aecf66 --- /dev/null +++ b/packages/video_player_android/android/src/test/java/io/flutter/plugins/videoplayer/PlatformViewExoPlayerEventListenerTest.java @@ -0,0 +1,80 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.videoplayer; + +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import androidx.media3.common.Format; +import androidx.media3.common.Player; +import androidx.media3.exoplayer.ExoPlayer; +import io.flutter.plugins.videoplayer.platformview.PlatformViewExoPlayerEventListener; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnit; +import org.mockito.junit.MockitoRule; +import org.robolectric.RobolectricTestRunner; + +/** + * Unit tests for {@link PlatformViewExoPlayerEventListener}. + * + *

This test suite narrowly verifies that the events emitted by the underlying {@link + * androidx.media3.exoplayer.ExoPlayer} instance are translated to the callback interface we expect + * ({@link VideoPlayerCallbacks} and/or interface with the player instance as expected). + */ +@RunWith(RobolectricTestRunner.class) +public final class PlatformViewExoPlayerEventListenerTest { + @Mock private ExoPlayer mockExoPlayer; + @Mock private VideoPlayerCallbacks mockCallbacks; + private ExoPlayerEventListener eventListener; + + @Rule public MockitoRule initRule = MockitoJUnit.rule(); + + @Before + public void setUp() { + eventListener = new PlatformViewExoPlayerEventListener(mockExoPlayer, mockCallbacks); + } + + @Test + public void onPlaybackStateChangedReadySendInitialized() { + eventListener = new PlatformViewExoPlayerEventListener(mockExoPlayer, mockCallbacks); + + Format format = new Format.Builder().setWidth(800).setHeight(400).build(); + when(mockExoPlayer.getVideoFormat()).thenReturn(format); + when(mockExoPlayer.getDuration()).thenReturn(10L); + + eventListener.onPlaybackStateChanged(Player.STATE_READY); + verify(mockCallbacks).onInitialized(800, 400, 10L, 0); + } + + @Test + public void onPlaybackStateChangedReadyInPortraitMode90DegreesSwapsWidthAndHeight() { + eventListener = new PlatformViewExoPlayerEventListener(mockExoPlayer, mockCallbacks); + + Format format = + new Format.Builder().setWidth(800).setHeight(400).setRotationDegrees(90).build(); + when(mockExoPlayer.getVideoFormat()).thenReturn(format); + when(mockExoPlayer.getDuration()).thenReturn(10L); + + eventListener.onPlaybackStateChanged(Player.STATE_READY); + verify(mockCallbacks).onInitialized(400, 800, 10L, 0); + } + + @Test + public void onPlaybackStateChangedReadyInPortraitMode270DegreesSwapsWidthAndHeight() { + eventListener = new PlatformViewExoPlayerEventListener(mockExoPlayer, mockCallbacks); + + Format format = + new Format.Builder().setWidth(800).setHeight(400).setRotationDegrees(270).build(); + when(mockExoPlayer.getVideoFormat()).thenReturn(format); + when(mockExoPlayer.getDuration()).thenReturn(10L); + + eventListener.onPlaybackStateChanged(Player.STATE_READY); + verify(mockCallbacks).onInitialized(400, 800, 10L, 0); + } +} diff --git a/packages/video_player_android/android/src/test/java/io/flutter/plugins/videoplayer/TextureExoPlayerEventListenerTest.java b/packages/video_player_android/android/src/test/java/io/flutter/plugins/videoplayer/TextureExoPlayerEventListenerTest.java new file mode 100644 index 0000000..7e2a3db --- /dev/null +++ b/packages/video_player_android/android/src/test/java/io/flutter/plugins/videoplayer/TextureExoPlayerEventListenerTest.java @@ -0,0 +1,188 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.videoplayer; + +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import androidx.media3.common.Format; +import androidx.media3.common.Player; +import androidx.media3.common.VideoSize; +import androidx.media3.exoplayer.ExoPlayer; +import io.flutter.plugins.videoplayer.texture.TextureExoPlayerEventListener; +import org.junit.Rule; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnit; +import org.mockito.junit.MockitoRule; +import org.robolectric.RobolectricTestRunner; +import org.robolectric.annotation.Config; + +/** + * Unit tests for {@link TextureExoPlayerEventListener}. + * + *

This test suite narrowly verifies that the events emitted by the underlying {@link + * androidx.media3.exoplayer.ExoPlayer} instance are translated to the callback interface we expect + * ({@link VideoPlayerCallbacks} and/or interface with the player instance as expected). + */ +@RunWith(RobolectricTestRunner.class) +public class TextureExoPlayerEventListenerTest { + @Mock private ExoPlayer mockExoPlayer; + @Mock private VideoPlayerCallbacks mockCallbacks; + + @Rule public MockitoRule initRule = MockitoJUnit.rule(); + + @Test + @Config(maxSdk = 21) + public void onPlaybackStateChangedReadySendInitialized_belowAndroid21() { + TextureExoPlayerEventListener eventListener = + new TextureExoPlayerEventListener(mockExoPlayer, mockCallbacks, true); + VideoSize size = new VideoSize(800, 400, 0, 0); + when(mockExoPlayer.getVideoSize()).thenReturn(size); + when(mockExoPlayer.getDuration()).thenReturn(10L); + + eventListener.onPlaybackStateChanged(Player.STATE_READY); + verify(mockCallbacks).onInitialized(800, 400, 10L, 0); + } + + @Test + @Config(minSdk = 22) + public void + onPlaybackStateChangedReadySendInitialized_whenSurfaceProducerHandlesCropAndRotation() { + TextureExoPlayerEventListener eventListener = + new TextureExoPlayerEventListener(mockExoPlayer, mockCallbacks, true); + VideoSize size = new VideoSize(800, 400, 0, 0); + when(mockExoPlayer.getVideoSize()).thenReturn(size); + when(mockExoPlayer.getDuration()).thenReturn(10L); + + eventListener.onPlaybackStateChanged(Player.STATE_READY); + verify(mockCallbacks).onInitialized(800, 400, 10L, 0); + } + + @Test + @Config(minSdk = 22) + public void + onPlaybackStateChangedReadySendInitializedWithRotationCorrectionAndWidthAndHeightSwap_whenSurfaceProducerDoesNotHandleCropAndRotation() { + TextureExoPlayerEventListener eventListener = + new TextureExoPlayerEventListener(mockExoPlayer, mockCallbacks, false); + VideoSize size = new VideoSize(800, 400, 0, 0); + int rotationCorrection = 90; + Format videoFormat = new Format.Builder().setRotationDegrees(rotationCorrection).build(); + + when(mockExoPlayer.getVideoSize()).thenReturn(size); + when(mockExoPlayer.getDuration()).thenReturn(10L); + when(mockExoPlayer.getVideoFormat()).thenReturn(videoFormat); + + eventListener.onPlaybackStateChanged(Player.STATE_READY); + verify(mockCallbacks).onInitialized(800, 400, 10L, rotationCorrection); + } + + @Test + @Config(maxSdk = 21) + public void + onPlaybackStateChangedReadyInPortraitMode90DegreesSwapWidthAndHeight_belowAndroid21() { + TextureExoPlayerEventListener eventListener = + new TextureExoPlayerEventListener(mockExoPlayer, mockCallbacks, true); + VideoSize size = new VideoSize(800, 400, 90, 0); + when(mockExoPlayer.getVideoSize()).thenReturn(size); + when(mockExoPlayer.getDuration()).thenReturn(10L); + + eventListener.onPlaybackStateChanged(Player.STATE_READY); + verify(mockCallbacks).onInitialized(800, 400, 10L, 0); + } + + @Test + @Config(minSdk = 22) + public void + onPlaybackStateChangedReadyInPortraitMode90DegreesDoesNotSwapWidthAndHeight_whenSurfaceProducerHandlesCropAndRotation() { + TextureExoPlayerEventListener eventListener = + new TextureExoPlayerEventListener(mockExoPlayer, mockCallbacks, true); + VideoSize size = new VideoSize(800, 400, 90, 0); + + when(mockExoPlayer.getVideoSize()).thenReturn(size); + when(mockExoPlayer.getDuration()).thenReturn(10L); + + eventListener.onPlaybackStateChanged(Player.STATE_READY); + verify(mockCallbacks).onInitialized(800, 400, 10L, 0); + } + + @Test + @Config(minSdk = 22) + public void + onPlaybackStateChangedReadyInPortraitMode90DegreesSwapWidthAndHeight_whenSurfaceProducerDoesNotHandleCropAndRotation() { + TextureExoPlayerEventListener eventListener = + new TextureExoPlayerEventListener(mockExoPlayer, mockCallbacks, false); + VideoSize size = new VideoSize(800, 400, 0, 0); + int rotationCorrection = 90; + Format videoFormat = new Format.Builder().setRotationDegrees(rotationCorrection).build(); + + when(mockExoPlayer.getVideoSize()).thenReturn(size); + when(mockExoPlayer.getDuration()).thenReturn(10L); + when(mockExoPlayer.getVideoFormat()).thenReturn(videoFormat); + + eventListener.onPlaybackStateChanged(Player.STATE_READY); + verify(mockCallbacks).onInitialized(800, 400, 10L, 90); + } + + @Test + @Config(maxSdk = 21) + public void + onPlaybackStateChangedReadyInPortraitMode270DegreesSwapWidthAndHeight_belowAndroid21() { + TextureExoPlayerEventListener eventListener = + new TextureExoPlayerEventListener(mockExoPlayer, mockCallbacks, true); + VideoSize size = new VideoSize(800, 400, 270, 0); + when(mockExoPlayer.getVideoSize()).thenReturn(size); + when(mockExoPlayer.getDuration()).thenReturn(10L); + + eventListener.onPlaybackStateChanged(Player.STATE_READY); + verify(mockCallbacks).onInitialized(800, 400, 10L, 0); + } + + @Test + @Config(minSdk = 22) + public void + onPlaybackStateChangedReadyInPortraitMode270DegreesDoesNotSwapWidthAndHeight_whenSurfaceProducerHandlesCropAndRotation() { + TextureExoPlayerEventListener eventListener = + new TextureExoPlayerEventListener(mockExoPlayer, mockCallbacks, true); + VideoSize size = new VideoSize(800, 400, 270, 0); + when(mockExoPlayer.getVideoSize()).thenReturn(size); + when(mockExoPlayer.getDuration()).thenReturn(10L); + + eventListener.onPlaybackStateChanged(Player.STATE_READY); + verify(mockCallbacks).onInitialized(800, 400, 10L, 0); + } + + @Test + @Config(minSdk = 22) + public void + onPlaybackStateChangedReadyInPortraitMode270DegreesDoesNotSwapWidthAndHeight_whenSurfaceProducerDoesNotHandleCropAndRotation() { + TextureExoPlayerEventListener eventListener = + new TextureExoPlayerEventListener(mockExoPlayer, mockCallbacks, false); + VideoSize size = new VideoSize(800, 400, 0, 0); + int rotationCorrection = 270; + Format videoFormat = new Format.Builder().setRotationDegrees(rotationCorrection).build(); + + when(mockExoPlayer.getVideoSize()).thenReturn(size); + when(mockExoPlayer.getDuration()).thenReturn(10L); + when(mockExoPlayer.getVideoFormat()).thenReturn(videoFormat); + + eventListener.onPlaybackStateChanged(Player.STATE_READY); + verify(mockCallbacks).onInitialized(800, 400, 10L, 270); + } + + @Test + @Config(maxSdk = 21) + public void onPlaybackStateChangedReadyFlipped180DegreesInformEventHandler_belowAndroid21() { + TextureExoPlayerEventListener eventListener = + new TextureExoPlayerEventListener(mockExoPlayer, mockCallbacks, true); + VideoSize size = new VideoSize(800, 400, 180, 0); + when(mockExoPlayer.getVideoSize()).thenReturn(size); + when(mockExoPlayer.getDuration()).thenReturn(10L); + + eventListener.onPlaybackStateChanged(Player.STATE_READY); + verify(mockCallbacks).onInitialized(800, 400, 10L, 180); + } +} diff --git a/packages/video_player_android/android/src/test/java/io/flutter/plugins/videoplayer/TextureVideoPlayerTest.java b/packages/video_player_android/android/src/test/java/io/flutter/plugins/videoplayer/TextureVideoPlayerTest.java new file mode 100644 index 0000000..4bbc89d --- /dev/null +++ b/packages/video_player_android/android/src/test/java/io/flutter/plugins/videoplayer/TextureVideoPlayerTest.java @@ -0,0 +1,233 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.videoplayer; + +import static org.junit.Assert.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.*; + +import android.view.Surface; +import androidx.media3.common.AudioAttributes; +import androidx.media3.common.C; +import androidx.media3.common.PlaybackParameters; +import androidx.media3.common.Player; +import androidx.media3.common.VideoSize; +import androidx.media3.exoplayer.ExoPlayer; +import io.flutter.plugins.videoplayer.texture.TextureVideoPlayer; +import io.flutter.view.TextureRegistry; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.InOrder; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnit; +import org.mockito.junit.MockitoRule; +import org.robolectric.RobolectricTestRunner; + +/** + * Unit tests for {@link TextureVideoPlayer}. + * + *

This test suite narrowly verifies that {@link TextureVideoPlayer} interfaces with the + * {@link ExoPlayer} interface exactly as it did when the test suite was created. That is, + * if the behavior changes, this test will need to change. However, this suite should catch bugs + * related to "this is a safe refactor with no behavior changes". + */ +@RunWith(RobolectricTestRunner.class) +public final class TextureVideoPlayerTest { + private static final String FAKE_ASSET_URL = "https://flutter.dev/movie.mp4"; + private FakeVideoAsset fakeVideoAsset; + + @Mock private VideoPlayerCallbacks mockEvents; + @Mock private TextureRegistry.SurfaceProducer mockProducer; + @Mock private ExoPlayer mockExoPlayer; + @Captor private ArgumentCaptor attributesCaptor; + @Captor private ArgumentCaptor callbackCaptor; + @Captor private ArgumentCaptor listenerCaptor; + + @Rule public MockitoRule initRule = MockitoJUnit.rule(); + + @Before + public void setUp() { + fakeVideoAsset = new FakeVideoAsset(FAKE_ASSET_URL); + when(mockProducer.getSurface()).thenReturn(mock(Surface.class)); + when(mockProducer.handlesCropAndRotation()).thenReturn(true); + } + + private VideoPlayer createVideoPlayer() { + return createVideoPlayer(new VideoPlayerOptions()); + } + + private TextureVideoPlayer createVideoPlayer(VideoPlayerOptions options) { + return new TextureVideoPlayer( + mockEvents, mockProducer, fakeVideoAsset.getMediaItem(), options, () -> mockExoPlayer); + } + + @Test + public void loadsAndPreparesProvidedMediaEnablesAudioFocusByDefault() { + VideoPlayer videoPlayer = createVideoPlayer(); + + verify(mockExoPlayer).setMediaItem(fakeVideoAsset.getMediaItem()); + verify(mockExoPlayer).prepare(); + verify(mockProducer).getSurface(); + verify(mockExoPlayer).setVideoSurface(any()); + + verify(mockExoPlayer).setAudioAttributes(attributesCaptor.capture(), eq(true)); + assertEquals(attributesCaptor.getValue().contentType, C.AUDIO_CONTENT_TYPE_MOVIE); + + videoPlayer.dispose(); + } + + @Test + public void onSurfaceProducerDestroyedAndAvailableReleasesAndThenRecreatesAndResumesPlayer() { + VideoPlayer videoPlayer = createVideoPlayer(); + + verify(mockProducer).setCallback(callbackCaptor.capture()); + verify(mockExoPlayer, never()).release(); + + when(mockExoPlayer.getCurrentPosition()).thenReturn(10L); + when(mockExoPlayer.getRepeatMode()).thenReturn(Player.REPEAT_MODE_ALL); + when(mockExoPlayer.getVolume()).thenReturn(0.5f); + when(mockExoPlayer.getPlaybackParameters()).thenReturn(new PlaybackParameters(2.5f)); + + TextureRegistry.SurfaceProducer.Callback producerLifecycle = callbackCaptor.getValue(); + simulateSurfaceDestruction(producerLifecycle); + + verify(mockExoPlayer).release(); + + // Create a new mock exo player so that we get a new instance. + mockExoPlayer = mock(ExoPlayer.class); + producerLifecycle.onSurfaceAvailable(); + + verify(mockExoPlayer).setVideoSurface(any()); + verify(mockExoPlayer).seekTo(10L); + verify(mockExoPlayer).setRepeatMode(Player.REPEAT_MODE_ALL); + verify(mockExoPlayer).setVolume(0.5f); + verify(mockExoPlayer).setPlaybackParameters(new PlaybackParameters(2.5f)); + + videoPlayer.dispose(); + } + + @Test + public void onSurfaceProducerDestroyedDoesNotStopOrPauseVideo() { + VideoPlayer videoPlayer = createVideoPlayer(); + + verify(mockProducer).setCallback(callbackCaptor.capture()); + TextureRegistry.SurfaceProducer.Callback producerLifecycle = callbackCaptor.getValue(); + simulateSurfaceDestruction(producerLifecycle); + + verify(mockExoPlayer, never()).stop(); + verify(mockExoPlayer, never()).pause(); + verify(mockExoPlayer, never()).setPlayWhenReady(anyBoolean()); + + videoPlayer.dispose(); + } + + @Test + public void onDisposeSurfaceProducerCallbackIsDisconnected() { + // Regression test for https://github.com/flutter/flutter/issues/156158. + VideoPlayer videoPlayer = createVideoPlayer(); + verify(mockProducer).setCallback(any()); + + videoPlayer.dispose(); + verify(mockProducer).setCallback(null); + } + + @Test + public void onInitializedCalledWhenVideoPlayerInitiallyCreated() { + VideoPlayer videoPlayer = createVideoPlayer(); + + // Pretend we have a video, and capture the registered event listener. + when(mockExoPlayer.getVideoSize()).thenReturn(new VideoSize(300, 200)); + verify(mockExoPlayer).addListener(listenerCaptor.capture()); + Player.Listener listener = listenerCaptor.getValue(); + + // Trigger an event that would trigger onInitialized. + listener.onPlaybackStateChanged(Player.STATE_READY); + verify(mockEvents).onInitialized(anyInt(), anyInt(), anyLong(), anyInt()); + + videoPlayer.dispose(); + } + + @Test + public void onSurfaceAvailableDoesNotSendInitializeEventAgain() { + // The VideoPlayer contract assumes that the event "initialized" is sent exactly once + // (duplicate events cause an error to be thrown at the shared Dart layer). This test verifies + // that the onInitialized event is sent exactly once per player. + // + // Regression test for https://github.com/flutter/flutter/issues/154602. + VideoPlayer videoPlayer = createVideoPlayer(); + when(mockExoPlayer.getVideoSize()).thenReturn(new VideoSize(300, 200)); + + // Capture the lifecycle events so we can simulate onSurfaceAvailableDestroyed. + verify(mockProducer).setCallback(callbackCaptor.capture()); + TextureRegistry.SurfaceProducer.Callback producerLifecycle = callbackCaptor.getValue(); + + // Trigger destroyed/available. + simulateSurfaceDestruction(producerLifecycle); + producerLifecycle.onSurfaceAvailable(); + + // Initial listener, and the new one from the resume. + verify(mockExoPlayer, times(2)).addListener(listenerCaptor.capture()); + Player.Listener listener = listenerCaptor.getValue(); + + // Now trigger that same event, which would happen in the case of a background/resume. + listener.onPlaybackStateChanged(Player.STATE_READY); + + // Was not called because it was a result of a background/resume. + verify(mockEvents, never()).onInitialized(anyInt(), anyInt(), anyLong(), anyInt()); + + videoPlayer.dispose(); + } + + @Test + public void onSurfaceAvailableWithoutDestroyDoesNotRecreate() { + // Initially create the video player, which creates the initial surface. + VideoPlayer videoPlayer = createVideoPlayer(); + verify(mockProducer).getSurface(); + verify(mockProducer).handlesCropAndRotation(); + + // Capture the lifecycle events so we can simulate onSurfaceAvailable/Destroyed. + verify(mockProducer).setCallback(callbackCaptor.capture()); + TextureRegistry.SurfaceProducer.Callback producerLifecycle = callbackCaptor.getValue(); + + // Calling onSurfaceAvailable does not do anything, since the surface was never destroyed. + producerLifecycle.onSurfaceAvailable(); + verifyNoMoreInteractions(mockProducer); + + videoPlayer.dispose(); + } + + @Test + public void disposeReleasesExoPlayerBeforeTexture() { + VideoPlayer videoPlayer = createVideoPlayer(); + + videoPlayer.dispose(); + + // Regression test for https://github.com/flutter/flutter/issues/156158. + // The player must be destroyed before the surface it is writing to. + InOrder inOrder = inOrder(mockExoPlayer, mockProducer); + inOrder.verify(mockExoPlayer).release(); + inOrder.verify(mockProducer).release(); + } + + // TODO(matanlurey): Replace with inline calls to onSurfaceAvailable once + // available on stable; see https://github.com/flutter/flutter/issues/155131. + // This separate method only exists to scope the suppression. + @SuppressWarnings({"deprecation", "removal"}) + void simulateSurfaceCreation(TextureRegistry.SurfaceProducer.Callback producerLifecycle) { + producerLifecycle.onSurfaceCreated(); + } + + // TODO(bparrishMines): Replace with inline calls to onSurfaceCleanup once available on stable; + // see https://github.com/flutter/flutter/issues/16125. This separate method only exists to scope + // the suppression. + @SuppressWarnings({"deprecation", "removal"}) + void simulateSurfaceDestruction(TextureRegistry.SurfaceProducer.Callback producerLifecycle) { + producerLifecycle.onSurfaceDestroyed(); + } +} diff --git a/packages/video_player_android/android/src/test/java/io/flutter/plugins/videoplayer/VideoAssetTest.java b/packages/video_player_android/android/src/test/java/io/flutter/plugins/videoplayer/VideoAssetTest.java new file mode 100644 index 0000000..6e95d05 --- /dev/null +++ b/packages/video_player_android/android/src/test/java/io/flutter/plugins/videoplayer/VideoAssetTest.java @@ -0,0 +1,154 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.videoplayer; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThrows; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.ArgumentMatchers.anyMap; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import android.net.Uri; +import androidx.media3.common.MediaItem; +import androidx.media3.datasource.DefaultHttpDataSource; +import androidx.media3.exoplayer.source.MediaSource; +import androidx.test.core.app.ApplicationProvider; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.RobolectricTestRunner; + +/** + * Unit tests for {@link VideoAsset}. + * + *

This test suite narrowly verifies that the {@link VideoAsset} factory methods, {@link + * VideoAsset#fromRemoteUrl(String, VideoAsset.StreamingFormat, Map)} and {@link + * VideoAsset#fromAssetUrl(String)} follow the contract they have documented. + * + *

In other tests of the player, a fake asset is likely to be used. + */ +@RunWith(RobolectricTestRunner.class) +public final class VideoAssetTest { + @Test + public void localVideoRequiresAssetUrl() { + assertThrows( + IllegalArgumentException.class, + () -> VideoAsset.fromAssetUrl("https://not.local/video.mp4")); + } + + @Test + public void localVideoCreatesMediaItem() { + VideoAsset asset = VideoAsset.fromAssetUrl("asset:///asset-key"); + MediaItem mediaItem = asset.getMediaItem(); + + assert mediaItem.localConfiguration != null; + assertEquals(mediaItem.localConfiguration.uri, Uri.parse("asset:///asset-key")); + } + + private static DefaultHttpDataSource.Factory mockHttpFactory() { + DefaultHttpDataSource.Factory httpFactory = mock(DefaultHttpDataSource.Factory.class); + when(httpFactory.setUserAgent(anyString())).thenReturn(httpFactory); + when(httpFactory.setAllowCrossProtocolRedirects(anyBoolean())).thenReturn(httpFactory); + when(httpFactory.setDefaultRequestProperties(anyMap())).thenReturn(httpFactory); + return httpFactory; + } + + @Test + public void remoteVideoByDefaultSetsUserAgentAndCrossProtocolRedirects() { + VideoAsset asset = + VideoAsset.fromRemoteUrl( + "https://flutter.dev/video.mp4", VideoAsset.StreamingFormat.UNKNOWN, new HashMap<>()); + + DefaultHttpDataSource.Factory mockFactory = mockHttpFactory(); + + // Cast to HttpVideoAsset to call a testing-only method to intercept calls. + ((HttpVideoAsset) asset) + .getMediaSourceFactory(ApplicationProvider.getApplicationContext(), mockFactory); + + verify(mockFactory).setUserAgent("ExoPlayer"); + verify(mockFactory).setAllowCrossProtocolRedirects(true); + verify(mockFactory, never()).setDefaultRequestProperties(anyMap()); + } + + @Test + public void remoteVideoOverridesUserAgentIfProvided() { + Map headers = new HashMap<>(); + headers.put("User-Agent", "FantasticalVideoBot"); + + VideoAsset asset = + VideoAsset.fromRemoteUrl( + "https://flutter.dev/video.mp4", VideoAsset.StreamingFormat.UNKNOWN, headers); + + DefaultHttpDataSource.Factory mockFactory = mockHttpFactory(); + + // Cast to HttpVideoAsset to call a testing-only method to intercept calls. + ((HttpVideoAsset) asset) + .getMediaSourceFactory(ApplicationProvider.getApplicationContext(), mockFactory); + + verify(mockFactory).setUserAgent("FantasticalVideoBot"); + verify(mockFactory).setAllowCrossProtocolRedirects(true); + verify(mockFactory).setDefaultRequestProperties(headers); + } + + // This tests that without using the overrides we get a working, non-mocked object. + // + // I guess you could also start a local HTTP server, and try fetching with it, YMMV. + @Test + public void remoteVideoGetMediaSourceFactoryInProductionReturnsRealMediaSource() { + VideoAsset asset = + VideoAsset.fromRemoteUrl( + "https://flutter.dev/video.mp4", VideoAsset.StreamingFormat.UNKNOWN, new HashMap<>()); + + MediaSource source = + asset + .getMediaSourceFactory(ApplicationProvider.getApplicationContext()) + .createMediaSource(asset.getMediaItem()); + assertEquals( + Uri.parse("https://flutter.dev/video.mp4"), + Objects.requireNonNull(source.getMediaItem().localConfiguration).uri); + } + + @Test + public void remoteVideoSetsAdditionalHttpHeadersIfProvided() { + Map headers = new HashMap<>(); + headers.put("X-Cache-Forever", "true"); + + VideoAsset asset = + VideoAsset.fromRemoteUrl( + "https://flutter.dev/video.mp4", VideoAsset.StreamingFormat.UNKNOWN, headers); + + DefaultHttpDataSource.Factory mockFactory = mockHttpFactory(); + + // Cast to HttpVideoAsset to call a testing-only method to intercept calls. + ((HttpVideoAsset) asset) + .getMediaSourceFactory(ApplicationProvider.getApplicationContext(), mockFactory); + + verify(mockFactory).setUserAgent("ExoPlayer"); + verify(mockFactory).setAllowCrossProtocolRedirects(true); + verify(mockFactory).setDefaultRequestProperties(headers); + } + + @Test + public void rtspVideoRequiresRtspUrl() { + assertThrows( + IllegalArgumentException.class, () -> VideoAsset.fromRtspUrl("https://not.rtsp/video.mp4")); + } + + @Test + public void rtspVideoCreatesMediaItem() { + VideoAsset asset = VideoAsset.fromRtspUrl("rtsp://test:pass@flutter.dev/stream"); + MediaItem mediaItem = asset.getMediaItem(); + + assert mediaItem.localConfiguration != null; + assertEquals( + mediaItem.localConfiguration.uri, Uri.parse("rtsp://test:pass@flutter.dev/stream")); + } +} diff --git a/packages/video_player_android/android/src/test/java/io/flutter/plugins/videoplayer/VideoPlayerEventCallbacksTest.java b/packages/video_player_android/android/src/test/java/io/flutter/plugins/videoplayer/VideoPlayerEventCallbacksTest.java new file mode 100644 index 0000000..d955384 --- /dev/null +++ b/packages/video_player_android/android/src/test/java/io/flutter/plugins/videoplayer/VideoPlayerEventCallbacksTest.java @@ -0,0 +1,151 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.videoplayer; + +import static org.junit.Assert.assertEquals; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.verify; + +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnit; +import org.mockito.junit.MockitoRule; +import org.robolectric.RobolectricTestRunner; + +/** + * Unit tests {@link VideoPlayerEventCallbacks}. + * + *

This test suite narrowly verifies that calling the provided event callbacks, such as + * {@link VideoPlayerEventCallbacks#onBufferingUpdate(long)}, produces the expected data as an + * encoded {@link Map}. + * + *

In other words, this tests that "the Java-side of the event channel works as expected". + */ +@RunWith(RobolectricTestRunner.class) +public final class VideoPlayerEventCallbacksTest { + private VideoPlayerEventCallbacks eventCallbacks; + + @Mock private QueuingEventSink mockEventSink; + + @Captor private ArgumentCaptor> eventCaptor; + + @Rule public MockitoRule initRule = MockitoJUnit.rule(); + + @Before + public void setUp() { + eventCallbacks = VideoPlayerEventCallbacks.withSink(mockEventSink); + } + + @Test + public void onInitializedSendsWidthHeightAndDuration() { + eventCallbacks.onInitialized(800, 400, 10L, 0); + + verify(mockEventSink).success(eventCaptor.capture()); + + Map actual = eventCaptor.getValue(); + Map expected = new HashMap<>(); + expected.put("event", "initialized"); + expected.put("duration", 10L); + expected.put("width", 800); + expected.put("height", 400); + + assertEquals(expected, actual); + } + + @Test + public void onInitializedIncludesRotationCorrectIfNonZero() { + eventCallbacks.onInitialized(800, 400, 10L, 180); + + verify(mockEventSink).success(eventCaptor.capture()); + + Map actual = eventCaptor.getValue(); + Map expected = new HashMap<>(); + expected.put("event", "initialized"); + expected.put("duration", 10L); + expected.put("width", 800); + expected.put("height", 400); + expected.put("rotationCorrection", 180); + + assertEquals(expected, actual); + } + + @Test + public void onBufferingStart() { + eventCallbacks.onBufferingStart(); + + verify(mockEventSink).success(eventCaptor.capture()); + + Map actual = eventCaptor.getValue(); + Map expected = new HashMap<>(); + expected.put("event", "bufferingStart"); + assertEquals(expected, actual); + } + + @Test + public void onBufferingUpdateProvidesAListWithASingleRange() { + eventCallbacks.onBufferingUpdate(10L); + + verify(mockEventSink).success(eventCaptor.capture()); + + Map actual = eventCaptor.getValue(); + Map expected = new HashMap<>(); + expected.put("event", "bufferingUpdate"); + expected.put("values", Collections.singletonList(Arrays.asList(0, 10L))); + assertEquals(expected, actual); + } + + @Test + public void onBufferingEnd() { + eventCallbacks.onBufferingEnd(); + + verify(mockEventSink).success(eventCaptor.capture()); + + Map actual = eventCaptor.getValue(); + Map expected = new HashMap<>(); + expected.put("event", "bufferingEnd"); + assertEquals(expected, actual); + } + + @Test + public void onCompleted() { + eventCallbacks.onCompleted(); + + verify(mockEventSink).success(eventCaptor.capture()); + + Map actual = eventCaptor.getValue(); + Map expected = new HashMap<>(); + expected.put("event", "completed"); + assertEquals(expected, actual); + } + + @Test + public void onError() { + eventCallbacks.onError("code", "message", "details"); + + verify(mockEventSink).error(eq("code"), eq("message"), eq("details")); + } + + @Test + public void onIsPlayingStateUpdate() { + eventCallbacks.onIsPlayingStateUpdate(true); + + verify(mockEventSink).success(eventCaptor.capture()); + + Map actual = eventCaptor.getValue(); + Map expected = new HashMap<>(); + expected.put("event", "isPlayingStateUpdate"); + expected.put("isPlaying", true); + assertEquals(expected, actual); + } +} diff --git a/packages/video_player_android/android/src/test/java/io/flutter/plugins/videoplayer/VideoPlayerPluginTest.java b/packages/video_player_android/android/src/test/java/io/flutter/plugins/videoplayer/VideoPlayerPluginTest.java new file mode 100644 index 0000000..4a5e913 --- /dev/null +++ b/packages/video_player_android/android/src/test/java/io/flutter/plugins/videoplayer/VideoPlayerPluginTest.java @@ -0,0 +1,116 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.videoplayer; + +import static org.junit.Assert.*; +import static org.mockito.Mockito.*; + +import android.content.Context; +import android.util.LongSparseArray; +import io.flutter.embedding.engine.plugins.FlutterPlugin; +import io.flutter.plugin.platform.PlatformViewRegistry; +import io.flutter.plugins.videoplayer.Messages.CreateMessage; +import io.flutter.plugins.videoplayer.Messages.PlatformVideoViewType; +import io.flutter.plugins.videoplayer.platformview.PlatformVideoViewFactory; +import io.flutter.plugins.videoplayer.platformview.PlatformViewVideoPlayer; +import io.flutter.plugins.videoplayer.texture.TextureVideoPlayer; +import io.flutter.view.TextureRegistry; +import java.lang.reflect.Field; +import java.util.HashMap; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.MockedStatic; +import org.mockito.MockitoAnnotations; +import org.robolectric.RobolectricTestRunner; + +@RunWith(RobolectricTestRunner.class) +public class VideoPlayerPluginTest { + @Mock private TextureRegistry mockTextureRegistry; + @Mock private TextureRegistry.SurfaceProducer mockSurfaceProducer; + @Mock private PlatformViewRegistry mockPlatformViewRegistry; + private VideoPlayerPlugin plugin; + + @Before + public void setUp() { + MockitoAnnotations.openMocks(this); + when(mockTextureRegistry.createSurfaceProducer()).thenReturn(mockSurfaceProducer); + + FlutterPlugin.FlutterPluginBinding binding = mock(FlutterPlugin.FlutterPluginBinding.class); + when(binding.getApplicationContext()).thenReturn(mock(Context.class)); + when(binding.getTextureRegistry()).thenReturn(mockTextureRegistry); + when(binding.getBinaryMessenger()) + .thenReturn(mock(io.flutter.plugin.common.BinaryMessenger.class)); + when(binding.getPlatformViewRegistry()).thenReturn(mockPlatformViewRegistry); + + plugin = new VideoPlayerPlugin(); + plugin.onAttachedToEngine(binding); + } + + @SuppressWarnings("unchecked") + private LongSparseArray getVideoPlayers() throws Exception { + final Field field = VideoPlayerPlugin.class.getDeclaredField("videoPlayers"); + field.setAccessible(true); + return (LongSparseArray) field.get(plugin); + } + + // This is only a placeholder test and doesn't actually initialize the plugin. + @Test + public void initPluginDoesNotThrow() { + final VideoPlayerPlugin plugin = new VideoPlayerPlugin(); + } + + @Test + public void registersPlatformVideoViewFactory() { + verify(mockPlatformViewRegistry) + .registerViewFactory( + eq("plugins.flutter.dev/video_player_android"), any(PlatformVideoViewFactory.class)); + } + + @Test + public void createsPlatformViewVideoPlayer() throws Exception { + try (MockedStatic mockedPlatformViewVideoPlayerStatic = + mockStatic(PlatformViewVideoPlayer.class)) { + mockedPlatformViewVideoPlayerStatic + .when(() -> PlatformViewVideoPlayer.create(any(), any(), any(), any())) + .thenReturn(mock(PlatformViewVideoPlayer.class)); + + final CreateMessage createMessage = + new CreateMessage.Builder() + .setViewType(PlatformVideoViewType.PLATFORM_VIEW) + .setUri("https://flutter.github.io/assets-for-api-docs/assets/videos/bee.mp4") + .setHttpHeaders(new HashMap<>()) + .build(); + + final long playerId = plugin.create(createMessage); + + final LongSparseArray videoPlayers = getVideoPlayers(); + assertNotNull(videoPlayers.get(playerId)); + } + } + + @Test + public void createsTextureVideoPlayer() throws Exception { + try (MockedStatic mockedTextureVideoPlayerStatic = + mockStatic(TextureVideoPlayer.class)) { + mockedTextureVideoPlayerStatic + .when(() -> TextureVideoPlayer.create(any(), any(), any(), any(), any())) + .thenReturn(mock(TextureVideoPlayer.class)); + + final CreateMessage createMessage = + new CreateMessage.Builder() + .setViewType(PlatformVideoViewType.TEXTURE_VIEW) + .setUri("https://flutter.github.io/assets-for-api-docs/assets/videos/bee.mp4") + .setHttpHeaders(new HashMap<>()) + .build(); + + final long playerId = plugin.create(createMessage); + + final LongSparseArray videoPlayers = getVideoPlayers(); + assertTrue(videoPlayers.get(playerId) instanceof TextureVideoPlayer); + } + } +} diff --git a/packages/video_player_android/android/src/test/java/io/flutter/plugins/videoplayer/VideoPlayerTest.java b/packages/video_player_android/android/src/test/java/io/flutter/plugins/videoplayer/VideoPlayerTest.java new file mode 100644 index 0000000..0b663b1 --- /dev/null +++ b/packages/video_player_android/android/src/test/java/io/flutter/plugins/videoplayer/VideoPlayerTest.java @@ -0,0 +1,216 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.videoplayer; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.*; + +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import androidx.media3.common.AudioAttributes; +import androidx.media3.common.C; +import androidx.media3.common.Format; +import androidx.media3.common.MediaItem; +import androidx.media3.common.PlaybackParameters; +import androidx.media3.common.Player; +import androidx.media3.exoplayer.ExoPlayer; +import io.flutter.plugins.videoplayer.platformview.PlatformViewExoPlayerEventListener; +import io.flutter.view.TextureRegistry.SurfaceProducer; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnit; +import org.mockito.junit.MockitoRule; +import org.robolectric.RobolectricTestRunner; + +/** + * Unit tests for {@link VideoPlayer}. + * + *

This test suite narrowly verifies that {@link VideoPlayer} interfaces with the {@link + * ExoPlayer} interface exactly as it did when the test suite was created. That is, if the + * behavior changes, this test will need to change. However, this suite should catch bugs related to + * "this is a safe refactor with no behavior changes". + * + *

It's hypothetically possible to write better tests using {@link + * androidx.media3.test.utils.FakeMediaSource}, but you really need a PhD in the Android media APIs + * in order to figure out how to set everything up so the player "works". + */ +@RunWith(RobolectricTestRunner.class) +public final class VideoPlayerTest { + private static final String FAKE_ASSET_URL = "https://flutter.dev/movie.mp4"; + private FakeVideoAsset fakeVideoAsset; + + @Mock private VideoPlayerCallbacks mockEvents; + @Mock private ExoPlayer mockExoPlayer; + @Captor private ArgumentCaptor attributesCaptor; + @Captor private ArgumentCaptor listenerCaptor; + + @Rule public MockitoRule initRule = MockitoJUnit.rule(); + + /** A test subclass of {@link VideoPlayer} that exposes the abstract class for testing. */ + private final class TestVideoPlayer extends VideoPlayer { + private TestVideoPlayer( + @NonNull VideoPlayerCallbacks events, + @NonNull MediaItem mediaItem, + @NonNull VideoPlayerOptions options, + @Nullable SurfaceProducer surfaceProducer, + @NonNull ExoPlayerProvider exoPlayerProvider) { + super(events, mediaItem, options, surfaceProducer, exoPlayerProvider); + } + + @NonNull + @Override + protected ExoPlayerEventListener createExoPlayerEventListener( + @NonNull ExoPlayer exoPlayer, @Nullable SurfaceProducer surfaceProducer) { + // Use platform view implementation for testing. + return new PlatformViewExoPlayerEventListener(exoPlayer, mockEvents); + } + } + + @Before + public void setUp() { + fakeVideoAsset = new FakeVideoAsset(FAKE_ASSET_URL); + } + + private VideoPlayer createVideoPlayer() { + return createVideoPlayer(new VideoPlayerOptions()); + } + + private VideoPlayer createVideoPlayer(VideoPlayerOptions options) { + return new TestVideoPlayer( + mockEvents, fakeVideoAsset.getMediaItem(), options, null, () -> mockExoPlayer); + } + + @Test + public void loadsAndPreparesProvidedMediaEnablesAudioFocusByDefault() { + VideoPlayer videoPlayer = createVideoPlayer(); + + verify(mockExoPlayer).setMediaItem(fakeVideoAsset.getMediaItem()); + verify(mockExoPlayer).prepare(); + + verify(mockExoPlayer).setAudioAttributes(attributesCaptor.capture(), eq(true)); + assertEquals(attributesCaptor.getValue().contentType, C.AUDIO_CONTENT_TYPE_MOVIE); + + videoPlayer.dispose(); + } + + @Test + public void loadsAndPreparesProvidedMediaDisablesAudioFocusWhenMixModeSet() { + VideoPlayerOptions options = new VideoPlayerOptions(); + options.mixWithOthers = true; + + VideoPlayer videoPlayer = createVideoPlayer(options); + + verify(mockExoPlayer).setAudioAttributes(attributesCaptor.capture(), eq(false)); + assertEquals(attributesCaptor.getValue().contentType, C.AUDIO_CONTENT_TYPE_MOVIE); + + videoPlayer.dispose(); + } + + @Test + public void playsAndPausesProvidedMedia() { + VideoPlayer videoPlayer = createVideoPlayer(); + + videoPlayer.play(); + verify(mockExoPlayer).play(); + + videoPlayer.pause(); + verify(mockExoPlayer).pause(); + + videoPlayer.dispose(); + } + + @Test + public void sendsBufferingUpdatesOnDemand() { + VideoPlayer videoPlayer = createVideoPlayer(); + + when(mockExoPlayer.getBufferedPosition()).thenReturn(10L); + videoPlayer.sendBufferingUpdate(); + verify(mockEvents).onBufferingUpdate(10L); + + videoPlayer.dispose(); + } + + @Test + public void togglesLoopingEnablesAndDisablesRepeatMode() { + VideoPlayer videoPlayer = createVideoPlayer(); + + videoPlayer.setLooping(true); + verify(mockExoPlayer).setRepeatMode(Player.REPEAT_MODE_ALL); + + videoPlayer.setLooping(false); + verify(mockExoPlayer).setRepeatMode(Player.REPEAT_MODE_OFF); + + videoPlayer.dispose(); + } + + @Test + public void setVolumeIsClampedBetween0and1() { + VideoPlayer videoPlayer = createVideoPlayer(); + + videoPlayer.setVolume(-1.0); + verify(mockExoPlayer).setVolume(0f); + + videoPlayer.setVolume(2.0); + verify(mockExoPlayer).setVolume(1f); + + videoPlayer.setVolume(0.5); + verify(mockExoPlayer).setVolume(0.5f); + + videoPlayer.dispose(); + } + + @Test + public void setPlaybackSpeedSetsPlaybackParametersWithValue() { + VideoPlayer videoPlayer = createVideoPlayer(); + + videoPlayer.setPlaybackSpeed(2.5); + verify(mockExoPlayer).setPlaybackParameters(new PlaybackParameters(2.5f)); + + videoPlayer.dispose(); + } + + @Test + public void seekAndGetPosition() { + VideoPlayer videoPlayer = createVideoPlayer(); + + videoPlayer.seekTo(10); + verify(mockExoPlayer).seekTo(10); + + when(mockExoPlayer.getCurrentPosition()).thenReturn(20L); + assertEquals(20L, videoPlayer.getPosition()); + } + + @Test + public void onInitializedCalledWhenVideoPlayerInitiallyAvailable() { + VideoPlayer videoPlayer = createVideoPlayer(); + + // Pretend we have a video, and capture the registered event listener. + when(mockExoPlayer.getVideoFormat()) + .thenReturn( + new Format.Builder().setWidth(300).setHeight(200).setRotationDegrees(0).build()); + verify(mockExoPlayer).addListener(listenerCaptor.capture()); + Player.Listener listener = listenerCaptor.getValue(); + + // Trigger an event that would trigger onInitialized. + listener.onPlaybackStateChanged(Player.STATE_READY); + verify(mockEvents).onInitialized(anyInt(), anyInt(), anyLong(), anyInt()); + + videoPlayer.dispose(); + } + + @Test + public void disposeReleasesExoPlayer() { + VideoPlayer videoPlayer = createVideoPlayer(); + + videoPlayer.dispose(); + + verify(mockExoPlayer).release(); + } +} diff --git a/packages/video_player_android/lib/src/android_video_player.dart b/packages/video_player_android/lib/src/android_video_player.dart new file mode 100644 index 0000000..2df0a0e --- /dev/null +++ b/packages/video_player_android/lib/src/android_video_player.dart @@ -0,0 +1,252 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'dart:async'; + +import 'package:flutter/services.dart'; +import 'package:flutter/widgets.dart'; +import 'package:video_player_platform_interface/video_player_platform_interface.dart'; + +import 'messages.g.dart'; +import 'platform_view_player.dart'; + +/// An Android implementation of [VideoPlayerPlatform] that uses the +/// Pigeon-generated [VideoPlayerApi]. +class AndroidVideoPlayer extends VideoPlayerPlatform { + final AndroidVideoPlayerApi _api = AndroidVideoPlayerApi(); + + /// A map that associates player ID with a view state. + /// This is used to determine which view type to use when building a view. + final Map _playerViewStates = + {}; + + /// Registers this class as the default instance of [PathProviderPlatform]. + static void registerWith() { + VideoPlayerPlatform.instance = AndroidVideoPlayer(); + } + + @override + Future init() { + return _api.initialize(); + } + + @override + Future dispose(int playerId) async { + await _api.dispose(playerId); + _playerViewStates.remove(playerId); + } + + @override + Future create(DataSource dataSource) { + return createWithOptions( + VideoCreationOptions( + dataSource: dataSource, + // Compatibility; "create" is always a textureView (createWithOptions + // allows selecting). + viewType: VideoViewType.textureView, + ), + ); + } + + @override + Future createWithOptions(VideoCreationOptions options) async { + final DataSource dataSource = options.dataSource; + + String? asset; + String? packageName; + String? uri; + String? formatHint; + Map httpHeaders = {}; + switch (dataSource.sourceType) { + case DataSourceType.asset: + asset = dataSource.asset; + packageName = dataSource.package; + case DataSourceType.network: + uri = dataSource.uri; + formatHint = _videoFormatStringMap[dataSource.formatHint]; + httpHeaders = dataSource.httpHeaders; + case DataSourceType.file: + uri = dataSource.uri; + httpHeaders = dataSource.httpHeaders; + case DataSourceType.contentUri: + uri = dataSource.uri; + } + final CreateMessage message = CreateMessage( + asset: asset, + packageName: packageName, + uri: uri, + httpHeaders: httpHeaders, + formatHint: formatHint, + viewType: _platformVideoViewTypeFromVideoViewType(options.viewType), + ); + + final int playerId = await _api.create(message); + _playerViewStates[playerId] = switch (options.viewType) { + // playerId is also the textureId when using texture view. + VideoViewType.textureView => + _VideoPlayerTextureViewState(textureId: playerId), + VideoViewType.platformView => const _VideoPlayerPlatformViewState(), + }; + + return playerId; + } + + @override + Future setLooping(int playerId, bool looping) { + return _api.setLooping(playerId, looping); + } + + @override + Future play(int playerId) { + return _api.play(playerId); + } + + @override + Future pause(int playerId) { + return _api.pause(playerId); + } + + @override + Future setVolume(int playerId, double volume) { + return _api.setVolume(playerId, volume); + } + + @override + Future setPlaybackSpeed(int playerId, double speed) { + assert(speed > 0); + + return _api.setPlaybackSpeed(playerId, speed); + } + + @override + Future seekTo(int playerId, Duration position) { + return _api.seekTo(playerId, position.inMilliseconds); + } + + @override + Future getPosition(int playerId) async { + final int position = await _api.position(playerId); + return Duration(milliseconds: position); + } + + @override + Stream videoEventsFor(int playerId) { + return _eventChannelFor(playerId) + .receiveBroadcastStream() + .map((dynamic event) { + final Map map = event as Map; + switch (map['event']) { + case 'initialized': + return VideoEvent( + eventType: VideoEventType.initialized, + duration: Duration(milliseconds: map['duration'] as int), + size: Size((map['width'] as num?)?.toDouble() ?? 0.0, + (map['height'] as num?)?.toDouble() ?? 0.0), + rotationCorrection: map['rotationCorrection'] as int? ?? 0, + ); + case 'completed': + return VideoEvent( + eventType: VideoEventType.completed, + ); + case 'bufferingUpdate': + final List values = map['values'] as List; + + return VideoEvent( + buffered: values.map(_toDurationRange).toList(), + eventType: VideoEventType.bufferingUpdate, + ); + case 'bufferingStart': + return VideoEvent(eventType: VideoEventType.bufferingStart); + case 'bufferingEnd': + return VideoEvent(eventType: VideoEventType.bufferingEnd); + case 'isPlayingStateUpdate': + return VideoEvent( + eventType: VideoEventType.isPlayingStateUpdate, + isPlaying: map['isPlaying'] as bool, + ); + default: + return VideoEvent(eventType: VideoEventType.unknown); + } + }); + } + + @override + Widget buildView(int playerId) { + return buildViewWithOptions( + VideoViewOptions(playerId: playerId), + ); + } + + @override + Widget buildViewWithOptions(VideoViewOptions options) { + final int playerId = options.playerId; + final _VideoPlayerViewState? viewState = _playerViewStates[playerId]; + + return switch (viewState) { + _VideoPlayerTextureViewState(:final int textureId) => + Texture(textureId: textureId), + _VideoPlayerPlatformViewState() => PlatformViewPlayer(playerId: playerId), + null => throw Exception( + 'Could not find corresponding view type for playerId: $playerId', + ), + }; + } + + @override + Future setMixWithOthers(bool mixWithOthers) { + return _api.setMixWithOthers(mixWithOthers); + } + + EventChannel _eventChannelFor(int playerId) { + return EventChannel('flutter.io/videoPlayer/videoEvents$playerId'); + } + + static const Map _videoFormatStringMap = + { + VideoFormat.ss: 'ss', + VideoFormat.hls: 'hls', + VideoFormat.dash: 'dash', + VideoFormat.other: 'other', + }; + + DurationRange _toDurationRange(dynamic value) { + final List pair = value as List; + return DurationRange( + Duration(milliseconds: pair[0] as int), + Duration(milliseconds: pair[1] as int), + ); + } +} + +PlatformVideoViewType _platformVideoViewTypeFromVideoViewType( + VideoViewType viewType, +) { + return switch (viewType) { + VideoViewType.textureView => PlatformVideoViewType.textureView, + VideoViewType.platformView => PlatformVideoViewType.platformView, + }; +} + +/// Base class representing the state of a video player view. +@immutable +sealed class _VideoPlayerViewState { + const _VideoPlayerViewState(); +} + +/// Represents the state of a video player view that uses a texture. +final class _VideoPlayerTextureViewState extends _VideoPlayerViewState { + /// Creates a new instance of [_VideoPlayerTextureViewState]. + const _VideoPlayerTextureViewState({ + required this.textureId, + }); + + /// The ID of the texture used by the video player. + final int textureId; +} + +/// Represents the state of a video player view that uses a platform view. +final class _VideoPlayerPlatformViewState extends _VideoPlayerViewState { + /// Creates a new instance of [_VideoPlayerPlatformViewState]. + const _VideoPlayerPlatformViewState(); +} diff --git a/packages/video_player_android/lib/src/messages.g.dart b/packages/video_player_android/lib/src/messages.g.dart new file mode 100644 index 0000000..717e8e0 --- /dev/null +++ b/packages/video_player_android/lib/src/messages.g.dart @@ -0,0 +1,432 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. +// Autogenerated from Pigeon (v22.6.1), do not edit directly. +// See also: https://pub.dev/packages/pigeon +// ignore_for_file: public_member_api_docs, non_constant_identifier_names, avoid_as, unused_import, unnecessary_parenthesis, prefer_null_aware_operators, omit_local_variable_types, unused_shown_name, unnecessary_import, no_leading_underscores_for_local_identifiers + +import 'dart:async'; +import 'dart:typed_data' show Float64List, Int32List, Int64List, Uint8List; + +import 'package:flutter/foundation.dart' show ReadBuffer, WriteBuffer; +import 'package:flutter/services.dart'; + +PlatformException _createConnectionError(String channelName) { + return PlatformException( + code: 'channel-error', + message: 'Unable to establish connection on channel: "$channelName".', + ); +} + +List wrapResponse( + {Object? result, PlatformException? error, bool empty = false}) { + if (empty) { + return []; + } + if (error == null) { + return [result]; + } + return [error.code, error.message, error.details]; +} + +/// Pigeon equivalent of VideoViewType. +enum PlatformVideoViewType { + textureView, + platformView, +} + +/// Information passed to the platform view creation. +class PlatformVideoViewCreationParams { + PlatformVideoViewCreationParams({ + required this.playerId, + }); + + int playerId; + + Object encode() { + return [ + playerId, + ]; + } + + static PlatformVideoViewCreationParams decode(Object result) { + result as List; + return PlatformVideoViewCreationParams( + playerId: result[0]! as int, + ); + } +} + +class CreateMessage { + CreateMessage({ + this.asset, + this.uri, + this.packageName, + this.formatHint, + required this.httpHeaders, + this.viewType, + }); + + String? asset; + + String? uri; + + String? packageName; + + String? formatHint; + + Map httpHeaders; + + PlatformVideoViewType? viewType; + + Object encode() { + return [ + asset, + uri, + packageName, + formatHint, + httpHeaders, + viewType, + ]; + } + + static CreateMessage decode(Object result) { + result as List; + return CreateMessage( + asset: result[0] as String?, + uri: result[1] as String?, + packageName: result[2] as String?, + formatHint: result[3] as String?, + httpHeaders: + (result[4] as Map?)!.cast(), + viewType: result[5] as PlatformVideoViewType?, + ); + } +} + +class _PigeonCodec extends StandardMessageCodec { + const _PigeonCodec(); + @override + void writeValue(WriteBuffer buffer, Object? value) { + if (value is int) { + buffer.putUint8(4); + buffer.putInt64(value); + } else if (value is PlatformVideoViewType) { + buffer.putUint8(129); + writeValue(buffer, value.index); + } else if (value is PlatformVideoViewCreationParams) { + buffer.putUint8(130); + writeValue(buffer, value.encode()); + } else if (value is CreateMessage) { + buffer.putUint8(131); + writeValue(buffer, value.encode()); + } else { + super.writeValue(buffer, value); + } + } + + @override + Object? readValueOfType(int type, ReadBuffer buffer) { + switch (type) { + case 129: + final int? value = readValue(buffer) as int?; + return value == null ? null : PlatformVideoViewType.values[value]; + case 130: + return PlatformVideoViewCreationParams.decode(readValue(buffer)!); + case 131: + return CreateMessage.decode(readValue(buffer)!); + default: + return super.readValueOfType(type, buffer); + } + } +} + +class AndroidVideoPlayerApi { + /// Constructor for [AndroidVideoPlayerApi]. The [binaryMessenger] named argument is + /// available for dependency injection. If it is left null, the default + /// BinaryMessenger will be used which routes to the host platform. + AndroidVideoPlayerApi( + {BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) + : pigeonVar_binaryMessenger = binaryMessenger, + pigeonVar_messageChannelSuffix = + messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; + final BinaryMessenger? pigeonVar_binaryMessenger; + + static const MessageCodec pigeonChannelCodec = _PigeonCodec(); + + final String pigeonVar_messageChannelSuffix; + + Future initialize() async { + final String pigeonVar_channelName = + 'dev.flutter.pigeon.video_player_android.AndroidVideoPlayerApi.initialize$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final List? pigeonVar_replyList = + await pigeonVar_channel.send(null) as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else { + return; + } + } + + Future create(CreateMessage msg) async { + final String pigeonVar_channelName = + 'dev.flutter.pigeon.video_player_android.AndroidVideoPlayerApi.create$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final List? pigeonVar_replyList = + await pigeonVar_channel.send([msg]) as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else if (pigeonVar_replyList[0] == null) { + throw PlatformException( + code: 'null-error', + message: 'Host platform returned null value for non-null return value.', + ); + } else { + return (pigeonVar_replyList[0] as int?)!; + } + } + + Future dispose(int playerId) async { + final String pigeonVar_channelName = + 'dev.flutter.pigeon.video_player_android.AndroidVideoPlayerApi.dispose$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final List? pigeonVar_replyList = + await pigeonVar_channel.send([playerId]) as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else { + return; + } + } + + Future setLooping(int playerId, bool looping) async { + final String pigeonVar_channelName = + 'dev.flutter.pigeon.video_player_android.AndroidVideoPlayerApi.setLooping$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final List? pigeonVar_replyList = await pigeonVar_channel + .send([playerId, looping]) as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else { + return; + } + } + + Future setVolume(int playerId, double volume) async { + final String pigeonVar_channelName = + 'dev.flutter.pigeon.video_player_android.AndroidVideoPlayerApi.setVolume$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final List? pigeonVar_replyList = await pigeonVar_channel + .send([playerId, volume]) as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else { + return; + } + } + + Future setPlaybackSpeed(int playerId, double speed) async { + final String pigeonVar_channelName = + 'dev.flutter.pigeon.video_player_android.AndroidVideoPlayerApi.setPlaybackSpeed$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final List? pigeonVar_replyList = await pigeonVar_channel + .send([playerId, speed]) as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else { + return; + } + } + + Future play(int playerId) async { + final String pigeonVar_channelName = + 'dev.flutter.pigeon.video_player_android.AndroidVideoPlayerApi.play$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final List? pigeonVar_replyList = + await pigeonVar_channel.send([playerId]) as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else { + return; + } + } + + Future position(int playerId) async { + final String pigeonVar_channelName = + 'dev.flutter.pigeon.video_player_android.AndroidVideoPlayerApi.position$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final List? pigeonVar_replyList = + await pigeonVar_channel.send([playerId]) as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else if (pigeonVar_replyList[0] == null) { + throw PlatformException( + code: 'null-error', + message: 'Host platform returned null value for non-null return value.', + ); + } else { + return (pigeonVar_replyList[0] as int?)!; + } + } + + Future seekTo(int playerId, int position) async { + final String pigeonVar_channelName = + 'dev.flutter.pigeon.video_player_android.AndroidVideoPlayerApi.seekTo$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final List? pigeonVar_replyList = await pigeonVar_channel + .send([playerId, position]) as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else { + return; + } + } + + Future pause(int playerId) async { + final String pigeonVar_channelName = + 'dev.flutter.pigeon.video_player_android.AndroidVideoPlayerApi.pause$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final List? pigeonVar_replyList = + await pigeonVar_channel.send([playerId]) as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else { + return; + } + } + + Future setMixWithOthers(bool mixWithOthers) async { + final String pigeonVar_channelName = + 'dev.flutter.pigeon.video_player_android.AndroidVideoPlayerApi.setMixWithOthers$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final List? pigeonVar_replyList = await pigeonVar_channel + .send([mixWithOthers]) as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else { + return; + } + } +} diff --git a/packages/video_player_android/lib/src/platform_view_player.dart b/packages/video_player_android/lib/src/platform_view_player.dart new file mode 100644 index 0000000..0411b10 --- /dev/null +++ b/packages/video_player_android/lib/src/platform_view_player.dart @@ -0,0 +1,60 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'package:flutter/foundation.dart'; +import 'package:flutter/gestures.dart'; +import 'package:flutter/rendering.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter/widgets.dart'; + +import 'messages.g.dart'; + +/// A widget that displays a video player using a platform view. +class PlatformViewPlayer extends StatelessWidget { + /// Creates a new instance of [PlatformViewPlayer]. + const PlatformViewPlayer({ + super.key, + required this.playerId, + }); + + /// The ID of the player. + final int playerId; + + @override + Widget build(BuildContext context) { + const String viewType = 'plugins.flutter.dev/video_player_android'; + final PlatformVideoViewCreationParams creationParams = + PlatformVideoViewCreationParams(playerId: playerId); + + // IgnorePointer so that GestureDetector can be used above the platform view. + return IgnorePointer( + child: PlatformViewLink( + viewType: viewType, + surfaceFactory: ( + BuildContext context, + PlatformViewController controller, + ) { + return AndroidViewSurface( + controller: controller as AndroidViewController, + gestureRecognizers: const >{}, + hitTestBehavior: PlatformViewHitTestBehavior.opaque, + ); + }, + onCreatePlatformView: (PlatformViewCreationParams params) { + return PlatformViewsService.initSurfaceAndroidView( + id: params.id, + viewType: viewType, + layoutDirection: + Directionality.maybeOf(context) ?? TextDirection.ltr, + creationParams: creationParams, + creationParamsCodec: AndroidVideoPlayerApi.pigeonChannelCodec, + onFocus: () => params.onFocusChanged(true), + ) + ..addOnPlatformViewCreatedListener(params.onPlatformViewCreated) + ..create(); + }, + ), + ); + } +} diff --git a/packages/video_player_android/lib/video_player_android.dart b/packages/video_player_android/lib/video_player_android.dart new file mode 100644 index 0000000..4e06756 --- /dev/null +++ b/packages/video_player_android/lib/video_player_android.dart @@ -0,0 +1,5 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +export 'src/android_video_player.dart'; diff --git a/packages/video_player_android/pubspec.yaml b/packages/video_player_android/pubspec.yaml new file mode 100644 index 0000000..7d2e1d7 --- /dev/null +++ b/packages/video_player_android/pubspec.yaml @@ -0,0 +1,32 @@ +name: video_player_android +description: Android implementation of the video_player plugin. +repository: https://github.com/flutter/packages/tree/main/packages/video_player/video_player_android +issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+video_player%22 +version: 2.8.4 + +environment: + sdk: ^3.6.0 + flutter: ">=3.27.0" + +flutter: + plugin: + implements: video_player + platforms: + android: + dartPluginClass: AndroidVideoPlayer + package: io.flutter.plugins.videoplayer + pluginClass: VideoPlayerPlugin + +dependencies: + flutter: + sdk: flutter + video_player_platform_interface: ^6.3.0 + +dev_dependencies: + flutter_test: + sdk: flutter + pigeon: ^22.4.2 + +topics: + - video + - video-player diff --git a/pubspec.lock b/pubspec.lock index 4584241..cd32cfc 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -5,56 +5,56 @@ packages: dependency: transitive description: name: _fe_analyzer_shared - sha256: da0d9209ca76bde579f2da330aeb9df62b6319c834fa7baae052021b0462401f - url: "https://pub.dev" + sha256: "0b2f2bd91ba804e53a61d757b986f89f1f9eaed5b11e4b2f5a2468d86d6c9fc7" + url: "https://pub.flutter-io.cn" source: hosted - version: "85.0.0" + version: "67.0.0" analyzer: dependency: transitive description: name: analyzer - sha256: "974859dc0ff5f37bc4313244b3218c791810d03ab3470a579580279ba971a48d" - url: "https://pub.dev" + sha256: "37577842a27e4338429a1cbc32679d508836510b056f1eedf0c8d20e39c1383d" + url: "https://pub.flutter-io.cn" source: hosted - version: "7.7.1" + version: "6.4.1" archive: dependency: transitive description: name: archive - sha256: ace891da0862b0e4cabbb064ee3fd87b2728b898949fdb366d83fe98342c9f19 - url: "https://pub.dev" + sha256: cb6a278ef2dbb298455e1a713bda08524a175630ec643a242c399c932a0a1f7d + url: "https://pub.flutter-io.cn" source: hosted - version: "4.2.0" + version: "3.6.1" args: dependency: transitive description: name: args - sha256: d0481093c50b1da8910eb0bb301626d4d8eb7284aa739614d2b394ee09e3ea04 - url: "https://pub.dev" + sha256: bf9f5caeea8d8fe6721a9c358dd8a5c1947b27f1cfaa18b39c301273594919e6 + url: "https://pub.flutter-io.cn" source: hosted - version: "2.7.0" + version: "2.6.0" async: dependency: transitive description: name: async sha256: "947bfcf187f74dbc5e146c9eb9c0f10c9f8b30743e341481c1e2ed3ecc18c20c" - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "2.11.0" audio_session: dependency: "direct main" description: name: audio_session - sha256: "2b7fff16a552486d078bfc09a8cde19f426dc6d6329262b684182597bec5b1ac" - url: "https://pub.dev" + sha256: "343e83bc7809fbda2591a49e525d6b63213ade10c76f15813be9aed6657b3261" + url: "https://pub.flutter-io.cn" source: hosted - version: "0.1.25" + version: "0.1.21" audioplayers: dependency: "direct main" description: name: audioplayers sha256: c346ba5a39dc208f1bab55fc239855f573d69b0e832402114bf0b793622adc4d - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "6.1.0" audioplayers_android: @@ -62,55 +62,55 @@ packages: description: name: audioplayers_android sha256: "5a09cf83ac1a1a8e4392eafa5f66ddc21fc435a605d37542dd9c2f838d516e26" - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "5.0.2" audioplayers_darwin: dependency: transitive description: name: audioplayers_darwin - sha256: c994b3bb3a921e4904ac40e013fbc94488e824fd7c1de6326f549943b0b44a91 - url: "https://pub.dev" + sha256: "34e1fb3a88ba02566615c6ca7173aa93b39cf61a38a05a729b60ba14c4899169" + url: "https://pub.flutter-io.cn" source: hosted - version: "6.4.0" + version: "6.1.0" audioplayers_linux: dependency: transitive description: name: audioplayers_linux - sha256: f75bce1ce864170ef5e6a2c6a61cd3339e1a17ce11e99a25bae4474ea491d001 - url: "https://pub.dev" + sha256: ce8383c1ff0db1ba93b5b0b8ef5b260ec2d0ce2598ad37dc8b946b773dd2c5fa + url: "https://pub.flutter-io.cn" source: hosted - version: "4.2.1" + version: "4.1.0" audioplayers_platform_interface: dependency: transitive description: name: audioplayers_platform_interface - sha256: "0e2f6a919ab56d0fec272e801abc07b26ae7f31980f912f24af4748763e5a656" - url: "https://pub.dev" + sha256: "6834dd48dfb7bc6c2404998ebdd161f79cd3774a7e6779e1348d54a3bfdcfaa5" + url: "https://pub.flutter-io.cn" source: hosted - version: "7.1.1" + version: "7.0.0" audioplayers_web: dependency: transitive description: name: audioplayers_web - sha256: faa8fa6587f996a6f604433b53af44c57a1407d4fe8dff5766cf63d6875e8de9 - url: "https://pub.dev" + sha256: "3609bdf0e05e66a3d9750ee40b1e37f2a622c4edb796cc600b53a90a30a2ace4" + url: "https://pub.flutter-io.cn" source: hosted - version: "5.2.0" + version: "5.0.1" audioplayers_windows: dependency: transitive description: name: audioplayers_windows - sha256: bafff2b38b6f6d331887558ba6e0a01c9c208d9dbb3ad0005234db065122a734 - url: "https://pub.dev" + sha256: "52b57c706a20fc85daa911be67381b3a5c9d03f8e27cb9fdb226de5bddf293b1" + url: "https://pub.flutter-io.cn" source: hosted - version: "4.3.0" + version: "4.1.0" bloc: dependency: transitive description: name: bloc sha256: "106842ad6569f0b60297619e9e0b1885c2fb9bf84812935490e6c5275777804e" - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "8.1.4" boolean_selector: @@ -118,103 +118,103 @@ packages: description: name: boolean_selector sha256: "6cfb5af12253eaf2b368f07bacc5a80d1301a071c73360d746b7f2e32d762c66" - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "2.1.1" build: dependency: transitive description: name: build - sha256: cef23f1eda9b57566c81e2133d196f8e3df48f244b317368d65c5943d91148f0 - url: "https://pub.dev" + sha256: "80184af8b6cb3e5c1c4ec6d8544d27711700bc3e6d2efad04238c7b5290889f0" + url: "https://pub.flutter-io.cn" source: hosted - version: "2.4.2" + version: "2.4.1" build_config: dependency: transitive description: name: build_config - sha256: "4ae2de3e1e67ea270081eaee972e1bd8f027d459f249e0f1186730784c2e7e33" - url: "https://pub.dev" + sha256: bf80fcfb46a29945b423bd9aad884590fb1dc69b330a4d4700cac476af1708d1 + url: "https://pub.flutter-io.cn" source: hosted - version: "1.1.2" + version: "1.1.1" build_daemon: dependency: transitive description: name: build_daemon - sha256: "8e928697a82be082206edb0b9c99c5a4ad6bc31c9e9b8b2f291ae65cd4a25daa" - url: "https://pub.dev" + sha256: "0343061a33da9c5810b2d6cee51945127d8f4c060b7fbdd9d54917f0a3feaaa1" + url: "https://pub.flutter-io.cn" source: hosted - version: "4.0.4" + version: "4.0.1" build_resolvers: dependency: transitive description: name: build_resolvers - sha256: b9e4fda21d846e192628e7a4f6deda6888c36b5b69ba02ff291a01fd529140f0 - url: "https://pub.dev" + sha256: "339086358431fa15d7eca8b6a36e5d783728cf025e559b834f4609a1fcfb7b0a" + url: "https://pub.flutter-io.cn" source: hosted - version: "2.4.4" + version: "2.4.2" build_runner: dependency: "direct dev" description: name: build_runner - sha256: "058fe9dce1de7d69c4b84fada934df3e0153dd000758c4d65964d0166779aa99" - url: "https://pub.dev" + sha256: "3ac61a79bfb6f6cc11f693591063a7f19a7af628dc52f141743edac5c16e8c22" + url: "https://pub.flutter-io.cn" source: hosted - version: "2.4.15" + version: "2.4.9" build_runner_core: dependency: transitive description: name: build_runner_core - sha256: "22e3aa1c80e0ada3722fe5b63fd43d9c8990759d0a2cf489c8c5d7b2bdebc021" - url: "https://pub.dev" + sha256: "4ae8ffe5ac758da294ecf1802f2aff01558d8b1b00616aa7538ea9a8a5d50799" + url: "https://pub.flutter-io.cn" source: hosted - version: "8.0.0" + version: "7.3.0" built_collection: dependency: transitive description: name: built_collection sha256: "376e3dd27b51ea877c28d525560790aee2e6fbb5f20e2f85d5081027d94e2100" - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "5.1.1" built_value: dependency: transitive description: name: built_value - sha256: f87ea98192116f7093cb214551ce1929caae0681fdba282b3d8b4462adee7bb7 - url: "https://pub.dev" + sha256: "8b158ab94ec6913e480dc3f752418348b5ae099eb75868b5f4775f0572999c61" + url: "https://pub.flutter-io.cn" source: hosted - version: "8.13.0" + version: "8.9.4" cached_network_image: dependency: "direct main" description: name: cached_network_image - sha256: "7c1183e361e5c8b0a0f21a28401eecdbde252441106a9816400dd4c2b2424916" - url: "https://pub.dev" + sha256: "28ea9690a8207179c319965c13cd8df184d5ee721ae2ce60f398ced1219cea1f" + url: "https://pub.flutter-io.cn" source: hosted - version: "3.4.1" + version: "3.3.1" cached_network_image_platform_interface: dependency: transitive description: name: cached_network_image_platform_interface - sha256: "35814b016e37fbdc91f7ae18c8caf49ba5c88501813f73ce8a07027a395e2829" - url: "https://pub.dev" + sha256: "9e90e78ae72caa874a323d78fa6301b3fb8fa7ea76a8f96dc5b5bf79f283bf2f" + url: "https://pub.flutter-io.cn" source: hosted - version: "4.1.1" + version: "4.0.0" cached_network_image_web: dependency: transitive description: name: cached_network_image_web - sha256: "980842f4e8e2535b8dbd3d5ca0b1f0ba66bf61d14cc3a17a9b4788a3685ba062" - url: "https://pub.dev" + sha256: "205d6a9f1862de34b93184f22b9d2d94586b2f05c581d546695e3d8f6a805cd7" + url: "https://pub.flutter-io.cn" source: hosted - version: "1.3.1" + version: "1.2.0" card_swiper: dependency: "direct main" description: name: card_swiper sha256: "0c94c538f47be1dab52d018d4900a7046b4cb0700dc7f95b8628da89d1212b35" - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "2.0.4" characters: @@ -222,7 +222,7 @@ packages: description: name: characters sha256: "04a925763edad70e8443c99234dc3328f442e811f1d8fd1a72f1c8ad0f69a605" - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "1.3.0" checked_yaml: @@ -230,7 +230,7 @@ packages: description: name: checked_yaml sha256: feb6bed21949061731a7a75fc5d2aa727cf160b91af9a3e464c5e3a32e28b5ff - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "2.0.3" chewie: @@ -238,7 +238,7 @@ packages: description: name: chewie sha256: "8bc4ac4cf3f316e50a25958c0f5eb9bb12cf7e8308bb1d74a43b230da2cfc144" - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "1.7.5" chivox_aiengine: @@ -253,23 +253,23 @@ packages: description: name: clock sha256: cb6d7f03e1de671e34607e909a7213e31d7752be4fb66a86d29fe1eb14bfb5cf - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "1.1.1" code_builder: dependency: transitive description: name: code_builder - sha256: "0ec10bf4a89e4c613960bf1e8b42c64127021740fb21640c29c909826a5eea3e" - url: "https://pub.dev" + sha256: f692079e25e7869c14132d39f223f8eec9830eb76131925143b2129c4bb01b37 + url: "https://pub.flutter-io.cn" source: hosted - version: "4.10.1" + version: "4.10.0" collection: dependency: transitive description: name: collection sha256: a1ace0a119f20aabc852d165077c036cd864315bd99b7eaa10a60100341941bf - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "1.19.0" common_utils: @@ -277,7 +277,7 @@ packages: description: name: common_utils sha256: c26884339b13ff99b0739e56f4b02090c84054ed9dd3a045435cd24e7b99c2c1 - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "2.1.0" connectivity_plus: @@ -285,7 +285,7 @@ packages: description: name: connectivity_plus sha256: "77a180d6938f78ca7d2382d2240eb626c0f6a735d0bfdce227d8ffb80f95c48b" - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "4.0.2" connectivity_plus_platform_interface: @@ -293,39 +293,39 @@ packages: description: name: connectivity_plus_platform_interface sha256: cf1d1c28f4416f8c654d7dc3cd638ec586076255d407cef3ddbdaf178272a71a - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "1.2.4" convert: dependency: transitive description: name: convert - sha256: b30acd5944035672bc15c6b7a8b47d773e41e2f17de064350988c5d02adb1c68 - url: "https://pub.dev" + sha256: "0f08b14755d163f6e2134cb58222dd25ea2a2ee8a195e53983d57c075324d592" + url: "https://pub.flutter-io.cn" source: hosted - version: "3.1.2" + version: "3.1.1" cross_file: dependency: transitive description: name: cross_file sha256: "7caf6a750a0c04effbb52a676dce9a4a592e10ad35c34d6d2d0e4811160d5670" - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "0.3.4+2" crypto: dependency: transitive description: name: crypto - sha256: c8ea0233063ba03258fbcf2ca4d6dadfefe14f02fab57702265467a19f27fadf - url: "https://pub.dev" + sha256: ff625774173754681d66daaf4a448684fb04b78f902da9cb3d308c19cc5e8bab + url: "https://pub.flutter-io.cn" source: hosted - version: "3.0.7" + version: "3.0.3" csslib: dependency: transitive description: name: csslib sha256: "09bad715f418841f976c77db72d5398dc1253c21fb9c0c7f0b0b985860b2d58e" - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "1.0.2" cupertino_icons: @@ -333,31 +333,31 @@ packages: description: name: cupertino_icons sha256: ba631d1c7f7bef6b729a622b7b752645a2d076dba9976925b8f25725a30e1ee6 - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "1.0.8" dart_style: dependency: transitive description: name: dart_style - sha256: "27eb0ae77836989a3bc541ce55595e8ceee0992807f14511552a898ddd0d88ac" - url: "https://pub.dev" + sha256: "99e066ce75c89d6b29903d788a7bb9369cf754f7b24bf70bf4b6d6d6b26853b9" + url: "https://pub.flutter-io.cn" source: hosted - version: "3.0.1" + version: "2.3.6" dbus: dependency: transitive description: name: dbus - sha256: d0c98dcd4f5169878b6cf8f6e0a52403a9dff371a3e2f019697accbf6f44a270 - url: "https://pub.dev" + sha256: "79e0c23480ff85dc68de79e2cd6334add97e48f7f4865d17686dd6ea81a47e8c" + url: "https://pub.flutter-io.cn" source: hosted - version: "0.7.12" + version: "0.7.11" decimal: dependency: "direct main" description: name: decimal sha256: "24a261d5d5c87e86c7651c417a5dbdf8bcd7080dd592533910e8d0505a279f21" - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "2.3.3" device_info_plus: @@ -365,7 +365,7 @@ packages: description: name: device_info_plus sha256: "77f757b789ff68e4eaf9c56d1752309bd9f7ad557cb105b938a7f8eb89e59110" - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "9.1.2" device_info_plus_platform_interface: @@ -373,39 +373,39 @@ packages: description: name: device_info_plus_platform_interface sha256: "0b04e02b30791224b31969eb1b50d723498f402971bff3630bca2ba839bd1ed2" - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "7.0.2" dio: dependency: "direct main" description: name: dio - sha256: "852ec3b48cc431ac04fff978413c541502b67ffc3e26921e74e3d994694192c1" - url: "https://pub.dev" + sha256: "253a18bbd4851fecba42f7343a1df3a9a4c1d31a2c1b37e221086b4fa8c8dbc9" + url: "https://pub.flutter-io.cn" source: hosted - version: "5.11.1" + version: "5.8.0+1" dio_web_adapter: dependency: transitive description: name: dio_web_adapter - sha256: "3a1b2cd7be71086f38504956e3ebcd2837288d231ff454bafa78021244102bfc" - url: "https://pub.dev" + sha256: "7586e476d70caecaf1686d21eee7247ea43ef5c345eab9e0cc3583ff13378d78" + url: "https://pub.flutter-io.cn" source: hosted - version: "2.2.2" + version: "2.1.1" equatable: dependency: "direct main" description: name: equatable - sha256: "3bce007a596ff8b3119c45d68aaef631272537c03d30e5d4534dd24bf4c5eaa2" - url: "https://pub.dev" + sha256: "567c64b3cb4cf82397aac55f4f0cbd3ca20d77c6c03bedbc4ceaddc08904aef7" + url: "https://pub.flutter-io.cn" source: hosted - version: "2.1.0" + version: "2.0.7" extended_text: dependency: "direct main" description: name: extended_text sha256: "32119a9447888fe97f506df6c87e23744ea2dbdf25a75fd713030cc7bc055c3a" - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "11.2.0" extended_text_library: @@ -413,7 +413,7 @@ packages: description: name: extended_text_library sha256: f6ae456324ff6ba3f9fe560a5c12f51ec02c5f463ef5a02bf165b678f049d547 - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "11.1.0" fake_async: @@ -421,7 +421,7 @@ packages: description: name: fake_async sha256: "511392330127add0b769b75a987850d136345d9227c6b94c96a04cf4a391bf78" - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "1.3.1" ffi: @@ -429,55 +429,55 @@ packages: description: name: ffi sha256: "16ed7b077ef01ad6170a3d0c57caa4a112a38d7a2ed5602e0aca9ca6f3d98da6" - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "2.1.3" file: dependency: transitive description: name: file - sha256: a3b4f84adafef897088c160faf7dfffb7696046cb13ae90b508c2cbc95d3b8d4 - url: "https://pub.dev" + sha256: "1b92bec4fc2a72f59a8e15af5f52cd441e4a7860b49499d69dfa817af20e925d" + url: "https://pub.flutter-io.cn" source: hosted - version: "7.0.1" + version: "6.1.4" file_selector_linux: dependency: transitive description: name: file_selector_linux sha256: "54cbbd957e1156d29548c7d9b9ec0c0ebb6de0a90452198683a7d23aed617a33" - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "0.9.3+2" file_selector_macos: dependency: transitive description: name: file_selector_macos - sha256: "8c9250b2bd2d8d4268e39c82543bacbaca0fda7d29e0728c3c4bbb7c820fd711" - url: "https://pub.dev" + sha256: "271ab9986df0c135d45c3cdb6bd0faa5db6f4976d3e4b437cf7d0f258d941bfc" + url: "https://pub.flutter-io.cn" source: hosted - version: "0.9.4+3" + version: "0.9.4+2" file_selector_platform_interface: dependency: transitive description: name: file_selector_platform_interface sha256: a3994c26f10378a039faa11de174d7b78eb8f79e4dd0af2a451410c1a5c3f66b - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "2.6.2" file_selector_windows: dependency: transitive description: name: file_selector_windows - sha256: "320fcfb6f33caa90f0b58380489fc5ac05d99ee94b61aa96ec2bff0ba81d3c2b" - url: "https://pub.dev" + sha256: "8f5d2f6590d51ecd9179ba39c64f722edc15226cc93dcc8698466ad36a4a85a4" + url: "https://pub.flutter-io.cn" source: hosted - version: "0.9.3+4" + version: "0.9.3+3" fixnum: dependency: transitive description: name: fixnum sha256: b6dc7065e46c974bc7c5f143080a6764ec7a4be6da1285ececdc37be96de53be - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "1.1.1" flutter: @@ -489,32 +489,32 @@ packages: dependency: "direct main" description: name: flutter_app_update - sha256: "336a87c9b8f5c2f040ac314939f61a567e812a3ec3c066d8c99a524d95171d81" - url: "https://pub.dev" + sha256: "09290240949c4651581cd6fc535e52d019e189e694d6019c56b5a56c2e69ba65" + url: "https://pub.flutter-io.cn" source: hosted - version: "3.2.4" + version: "3.2.2" flutter_bloc: dependency: "direct main" description: name: flutter_bloc sha256: b594505eac31a0518bdcb4b5b79573b8d9117b193cc80cc12e17d639b10aa27a - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "8.1.6" flutter_cache_manager: dependency: transitive description: name: flutter_cache_manager - sha256: "400b6592f16a4409a7f2bb929a9a7e38c72cceb8ffb99ee57bbf2cb2cecf8386" - url: "https://pub.dev" + sha256: "8207f27539deb83732fdda03e259349046a39a4c767269285f449ade355d54ba" + url: "https://pub.flutter-io.cn" source: hosted - version: "3.4.1" + version: "3.3.1" flutter_easyloading: dependency: "direct main" description: name: flutter_easyloading sha256: ba21a3c883544e582f9cc455a4a0907556714e1e9cf0eababfcb600da191d17c - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "3.0.5" flutter_inappwebview: @@ -522,63 +522,63 @@ packages: description: name: flutter_inappwebview sha256: "3e9a443a18ecef966fb930c3a76ca5ab6a7aafc0c7b5e14a4a850cf107b09959" - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "6.0.0" flutter_inappwebview_android: dependency: transitive description: name: flutter_inappwebview_android - sha256: "62557c15a5c2db5d195cb3892aab74fcaec266d7b86d59a6f0027abd672cddba" - url: "https://pub.dev" + sha256: d247f6ed417f1f8c364612fa05a2ecba7f775c8d0c044c1d3b9ee33a6515c421 + url: "https://pub.flutter-io.cn" source: hosted - version: "1.1.3" + version: "1.0.13" flutter_inappwebview_internal_annotations: dependency: transitive description: name: flutter_inappwebview_internal_annotations sha256: "787171d43f8af67864740b6f04166c13190aa74a1468a1f1f1e9ee5b90c359cd" - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "1.2.0" flutter_inappwebview_ios: dependency: transitive description: name: flutter_inappwebview_ios - sha256: "5818cf9b26cf0cbb0f62ff50772217d41ea8d3d9cc00279c45f8aabaa1b4025d" - url: "https://pub.dev" + sha256: f363577208b97b10b319cd0c428555cd8493e88b468019a8c5635a0e4312bd0f + url: "https://pub.flutter-io.cn" source: hosted - version: "1.1.2" + version: "1.0.13" flutter_inappwebview_macos: dependency: transitive description: name: flutter_inappwebview_macos - sha256: c1fbb86af1a3738e3541364d7d1866315ffb0468a1a77e34198c9be571287da1 - url: "https://pub.dev" + sha256: b55b9e506c549ce88e26580351d2c71d54f4825901666bd6cfa4be9415bb2636 + url: "https://pub.flutter-io.cn" source: hosted - version: "1.1.2" + version: "1.0.11" flutter_inappwebview_platform_interface: dependency: transitive description: name: flutter_inappwebview_platform_interface - sha256: cf5323e194096b6ede7a1ca808c3e0a078e4b33cc3f6338977d75b4024ba2500 - url: "https://pub.dev" + sha256: "545fd4c25a07d2775f7d5af05a979b2cac4fbf79393b0a7f5d33ba39ba4f6187" + url: "https://pub.flutter-io.cn" source: hosted - version: "1.3.0+1" + version: "1.0.10" flutter_inappwebview_web: dependency: transitive description: name: flutter_inappwebview_web - sha256: "55f89c83b0a0d3b7893306b3bb545ba4770a4df018204917148ebb42dc14a598" - url: "https://pub.dev" + sha256: d8c680abfb6fec71609a700199635d38a744df0febd5544c5a020bd73de8ee07 + url: "https://pub.flutter-io.cn" source: hosted - version: "1.1.2" + version: "1.0.8" flutter_lints: dependency: "direct dev" description: name: flutter_lints sha256: a25a15ebbdfc33ab1cd26c63a6ee519df92338a9c10f122adda92938253bef04 - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "2.0.3" flutter_oss_aliyun: @@ -586,57 +586,57 @@ packages: description: name: flutter_oss_aliyun sha256: "8280c1e8dfb792dec6449d1e6052e1d3492b3b3a1dfee456cc41d3f31b4cbc26" - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "6.4.2" flutter_plugin_android_lifecycle: dependency: transitive description: name: flutter_plugin_android_lifecycle - sha256: "6382ce712ff69b0f719640ce957559dde459e55ecd433c767e06d139ddf16cab" - url: "https://pub.dev" + sha256: "8cf40eebf5dec866a6d1956ad7b4f7016e6c0cc69847ab946833b7d43743809f" + url: "https://pub.flutter-io.cn" source: hosted - version: "2.0.29" + version: "2.0.19" flutter_screenutil: dependency: "direct main" description: name: flutter_screenutil sha256: "8239210dd68bee6b0577aa4a090890342d04a136ce1c81f98ee513fc0ce891de" - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "5.9.3" flutter_sound: dependency: "direct main" description: name: flutter_sound - sha256: ef89477f6e8ce2fa395158ebc4a8b11982e3ada440b4021c06fd97a4e771554b - url: "https://pub.dev" + sha256: "1f40b26b92907a433afe877c927cd48f5a2e4d0f7188e5d39eb5756008aa51ab" + url: "https://pub.flutter-io.cn" source: hosted - version: "9.28.0" + version: "9.6.0" flutter_sound_platform_interface: dependency: transitive description: name: flutter_sound_platform_interface - sha256: "3394d7e664a09796818014ff85a81db0dec397f4c286cbe52f8783886fa5a497" - url: "https://pub.dev" + sha256: "2e218521d8187b9a4c65063ad9c79bfe88119531ff68047a2eaa6b027cb276bb" + url: "https://pub.flutter-io.cn" source: hosted - version: "9.28.0" + version: "9.6.0" flutter_sound_web: dependency: transitive description: name: flutter_sound_web - sha256: "4e10c94a8574bd93bb8668af59bf76f5312a890bccd3778d73168a7133217dc5" - url: "https://pub.dev" + sha256: "5013a15e4e69a4bdc8badd729130eef43c3305e30ba8e6933f863436ce969932" + url: "https://pub.flutter-io.cn" source: hosted - version: "9.28.0" + version: "9.6.0" flutter_spinkit: dependency: transitive description: name: flutter_spinkit - sha256: "77850df57c00dc218bfe96071d576a8babec24cf58b2ed121c83cca4a2fdce7f" - url: "https://pub.dev" + sha256: d2696eed13732831414595b98863260e33e8882fc069ee80ec35d4ac9ddb0472 + url: "https://pub.flutter-io.cn" source: hosted - version: "5.2.2" + version: "5.2.1" flutter_test: dependency: "direct dev" description: flutter @@ -651,16 +651,16 @@ packages: dependency: "direct main" description: name: fluttertoast - sha256: "90778fe0497fe3a09166e8cf2e0867310ff434b794526589e77ec03cf08ba8e8" - url: "https://pub.dev" + sha256: "95f349437aeebe524ef7d6c9bde3e6b4772717cf46a0eb6a3ceaddc740b297cc" + url: "https://pub.flutter-io.cn" source: hosted - version: "8.2.14" + version: "8.2.8" fluwx: dependency: "direct main" description: name: fluwx sha256: d25c26a12a1fa280833105869ea255a5877695e03dc1190f0d2c027a7c989ef3 - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "4.6.3" frontend_server_client: @@ -668,47 +668,47 @@ packages: description: name: frontend_server_client sha256: f64a0333a82f30b0cca061bc3d143813a486dc086b574bfb233b7c1372427694 - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "4.0.0" glob: dependency: transitive description: name: glob - sha256: "218aeb56050c714f62a3182775320dfa04602b55074873e24e31bbd39bda96fb" - url: "https://pub.dev" + sha256: c3f1ee72c96f8f78935e18aa8cecced9ab132419e8625dc187e1c2408efc20de + url: "https://pub.flutter-io.cn" source: hosted - version: "2.2.0" + version: "2.1.3" google_fonts: dependency: "direct main" description: name: google_fonts sha256: "2776c66b3e97c6cdd58d1bd3281548b074b64f1fd5c8f82391f7456e38849567" - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "4.0.5" graphs: dependency: transitive description: name: graphs - sha256: "741bbf84165310a68ff28fe9e727332eef1407342fca52759cb21ad8177bb8d0" - url: "https://pub.dev" + sha256: aedc5a15e78fc65a6e23bcd927f24c64dd995062bcd1ca6eda65a3cff92a4d19 + url: "https://pub.flutter-io.cn" source: hosted - version: "2.3.2" + version: "2.3.1" html: dependency: transitive description: name: html - sha256: "43b67b8f43321ab066817dfac5619596c98bb1b61624e77203bb4351785f9699" - url: "https://pub.dev" + sha256: "1fc58edeaec4307368c60d59b7e15b9d658b57d7f3125098b6294153c75337ec" + url: "https://pub.flutter-io.cn" source: hosted - version: "0.15.7" + version: "0.15.5" http: dependency: "direct overridden" description: name: http sha256: "5895291c13fa8a3bd82e76d5627f69e0d85ca6a30dcac95c4ea19a5d555879c2" - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "0.13.6" http_multi_server: @@ -716,111 +716,111 @@ packages: description: name: http_multi_server sha256: aa6199f908078bb1c5efb8d8638d4ae191aac11b311132c3ef48ce352fb52ef8 - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "3.2.2" http_parser: dependency: transitive description: name: http_parser - sha256: "178d74305e7866013777bab2c3d8726205dc5a4dd935297175b19a23a2e66571" - url: "https://pub.dev" + sha256: "2aa08ce0341cc9b354a498388e30986515406668dbcc4f7c950c3e715496693b" + url: "https://pub.flutter-io.cn" source: hosted - version: "4.1.2" + version: "4.0.2" image: dependency: "direct main" description: name: image - sha256: "1976370a4df3091bb0f72409c187ad1f9132a818bc6b95ca59c0bae1c75c688e" - url: "https://pub.dev" + sha256: f31d52537dc417fdcde36088fdf11d191026fd5e4fae742491ebd40e5a8bea7d + url: "https://pub.flutter-io.cn" source: hosted - version: "4.9.2" + version: "4.3.0" image_picker: dependency: "direct main" description: name: image_picker sha256: b6951e25b795d053a6ba03af5f710069c99349de9341af95155d52665cb4607c - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "0.8.9" image_picker_android: dependency: transitive description: name: image_picker_android - sha256: e83b2b05141469c5e19d77e1dfa11096b6b1567d09065b2265d7c6904560050c - url: "https://pub.dev" + sha256: "0f57fee1e8bfadf8cc41818bbcd7f72e53bb768a54d9496355d5e8a5681a19f1" + url: "https://pub.flutter-io.cn" source: hosted - version: "0.8.13" + version: "0.8.12+1" image_picker_for_web: dependency: transitive description: name: image_picker_for_web sha256: "869fe8a64771b7afbc99fc433a5f7be2fea4d1cb3d7c11a48b6b579eb9c797f0" - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "2.2.0" image_picker_ios: dependency: transitive description: name: image_picker_ios - sha256: eb06fe30bab4c4497bad449b66448f50edcc695f1c59408e78aa3a8059eb8f0e - url: "https://pub.dev" + sha256: "4f0568120c6fcc0aaa04511cb9f9f4d29fc3d0139884b1d06be88dcec7641d6b" + url: "https://pub.flutter-io.cn" source: hosted - version: "0.8.13" + version: "0.8.12+1" image_picker_linux: dependency: transitive description: name: image_picker_linux - sha256: "1f81c5f2046b9ab724f85523e4af65be1d47b038160a8c8deed909762c308ed4" - url: "https://pub.dev" + sha256: "4ed1d9bb36f7cd60aa6e6cd479779cc56a4cb4e4de8f49d487b1aaad831300fa" + url: "https://pub.flutter-io.cn" source: hosted - version: "0.2.2" + version: "0.2.1+1" image_picker_macos: dependency: transitive description: name: image_picker_macos - sha256: d58cd9d67793d52beefd6585b12050af0a7663c0c2a6ece0fb110a35d6955e04 - url: "https://pub.dev" + sha256: "3f5ad1e8112a9a6111c46d0b57a7be2286a9a07fc6e1976fdf5be2bd31d4ff62" + url: "https://pub.flutter-io.cn" source: hosted - version: "0.2.2" + version: "0.2.1+1" image_picker_platform_interface: dependency: transitive description: name: image_picker_platform_interface - sha256: "9f143b0dba3e459553209e20cc425c9801af48e6dfa4f01a0fcf927be3f41665" - url: "https://pub.dev" + sha256: "9ec26d410ff46f483c5519c29c02ef0e02e13a543f882b152d4bfd2f06802f80" + url: "https://pub.flutter-io.cn" source: hosted - version: "2.11.0" + version: "2.10.0" image_picker_windows: dependency: transitive description: name: image_picker_windows - sha256: d248c86554a72b5495a31c56f060cf73a41c7ff541689327b1a7dbccc33adfae - url: "https://pub.dev" + sha256: "6ad07afc4eb1bc25f3a01084d28520496c4a3bb0cb13685435838167c9dcedeb" + url: "https://pub.flutter-io.cn" source: hosted - version: "0.2.2" + version: "0.2.1+1" intl: dependency: "direct main" description: name: intl sha256: d6f56758b7d3014a48af9701c085700aac781a92a87a62b1333b46d8879661cf - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "0.19.0" io: dependency: transitive description: name: io - sha256: "2635216ca6a737e60de577ffa1a48a0bec76ca8a62917cfc1bb88c14c570646f" - url: "https://pub.dev" + sha256: "2ec25704aba361659e10e3e5f5d672068d332fc8ac516421d483a11e5cbd061e" + url: "https://pub.flutter-io.cn" source: hosted - version: "1.1.0" + version: "1.0.4" js: dependency: transitive description: name: js sha256: f2c445dce49627136094980615a031419f7f3eb393237e4ecd97ac15dea343f3 - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "0.6.7" json_annotation: @@ -828,23 +828,23 @@ packages: description: name: json_annotation sha256: "1ce844379ca14835a50d2f019a3099f419082cfdd231cd86a142af94dd5c6bb1" - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "4.9.0" json_serializable: dependency: "direct dev" description: name: json_serializable - sha256: c50ef5fc083d5b5e12eef489503ba3bf5ccc899e487d691584699b4bdefeea8c - url: "https://pub.dev" + sha256: ea1432d167339ea9b5bb153f0571d0039607a873d6e04e0117af043f14a1fd4b + url: "https://pub.flutter-io.cn" source: hosted - version: "6.9.5" + version: "6.8.0" leak_tracker: dependency: transitive description: name: leak_tracker sha256: "7bb2830ebd849694d1ec25bf1f44582d6ac531a57a365a803a6034ff751d2d06" - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "10.0.7" leak_tracker_flutter_testing: @@ -852,7 +852,7 @@ packages: description: name: leak_tracker_flutter_testing sha256: "9491a714cca3667b60b5c420da8217e6de0d1ba7a5ec322fab01758f6998f379" - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "3.0.8" leak_tracker_testing: @@ -860,7 +860,7 @@ packages: description: name: leak_tracker_testing sha256: "6ba465d5d76e67ddf503e1161d1f4a6bc42306f9d66ca1e8f079a47290fb06d3" - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "3.0.1" limiting_direction_csx: @@ -868,7 +868,7 @@ packages: description: name: limiting_direction_csx sha256: "283a846809a076ad641924ba830e3e39ff5385b9fb9bab7ecd322200948a89bd" - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "0.2.0+5" lints: @@ -876,39 +876,39 @@ packages: description: name: lints sha256: "0a217c6c989d21039f1498c3ed9f3ed71b354e69873f13a8dfc3c9fe76f1b452" - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "2.1.1" logger: dependency: transitive description: name: logger - sha256: "2a0dc097e7b01d942475bdd552356db2d0f768b05540bd4b2b53f1840f2239a7" - url: "https://pub.dev" + sha256: be4b23575aac7ebf01f225a241eb7f6b5641eeaf43c6a8613510fc2f8cf187d1 + url: "https://pub.flutter-io.cn" source: hosted - version: "2.8.0" + version: "2.5.0" logging: dependency: transitive description: name: logging - sha256: c8245ada5f1717ed44271ed1c26b8ce85ca3228fd2ffdb75468ab01979309d61 - url: "https://pub.dev" + sha256: "623a88c9594aa774443aa3eb2d41807a48486b5613e67599fb4c41c0ad47c340" + url: "https://pub.flutter-io.cn" source: hosted - version: "1.3.0" + version: "1.2.0" lottie: dependency: "direct main" description: name: lottie - sha256: c5fa04a80a620066c15cf19cc44773e19e9b38e989ff23ea32e5903ef1015950 - url: "https://pub.dev" + sha256: "7afc60865a2429d994144f7d66ced2ae4305fe35d82890b8766e3359872d872c" + url: "https://pub.flutter-io.cn" source: hosted - version: "3.3.1" + version: "3.1.3" matcher: dependency: transitive description: name: matcher sha256: d2323aa2060500f906aa31a895b4030b6da3ebdcc5619d14ce1aada65cd161cb - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "0.12.16+1" material_color_utilities: @@ -916,7 +916,7 @@ packages: description: name: material_color_utilities sha256: f7142bb1154231d7ea5f96bc7bde4bda2a0945d2806bb11670e30b850d56bdec - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "0.11.1" meta: @@ -924,7 +924,7 @@ packages: description: name: meta sha256: bdb68674043280c3428e9ec998512fb681678676b3c54e773629ffe74419f8c7 - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "1.15.0" mime: @@ -932,7 +932,7 @@ packages: description: name: mime sha256: "801fd0b26f14a4a58ccb09d5892c3fbdeff209594300a542492cf13fba9d247a" - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "1.0.6" nested: @@ -940,7 +940,7 @@ packages: description: name: nested sha256: "03bac4c528c64c95c722ec99280375a6f2fc708eec17c7b3f07253b626cd2a20" - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "1.0.0" nested_scroll_views: @@ -948,7 +948,7 @@ packages: description: name: nested_scroll_views sha256: "37d0f35682441a4cdf5f50bd5767a53b7192780a085c9dc728fc273df8a3443a" - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "0.0.12" nm: @@ -956,7 +956,7 @@ packages: description: name: nm sha256: "2c9aae4127bdc8993206464fcc063611e0e36e72018696cd9631023a31b24254" - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "0.5.0" octo_image: @@ -964,23 +964,23 @@ packages: description: name: octo_image sha256: "34faa6639a78c7e3cbe79be6f9f96535867e879748ade7d17c9b1ae7536293bd" - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "2.1.0" package_config: dependency: transitive description: name: package_config - sha256: f096c55ebb7deb7e384101542bfba8c52696c1b56fca2eb62827989ef2353bbc - url: "https://pub.dev" + sha256: "1c5b77ccc91e4823a5af61ee74e6b972db1ef98c2ff5a18d3161c982a55448bd" + url: "https://pub.flutter-io.cn" source: hosted - version: "2.2.0" + version: "2.1.0" package_info_plus: dependency: "direct main" description: name: package_info_plus sha256: "7e76fad405b3e4016cd39d08f455a4eb5199723cf594cd1b8916d47140d93017" - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "4.2.0" package_info_plus_platform_interface: @@ -988,7 +988,7 @@ packages: description: name: package_info_plus_platform_interface sha256: "9bc8ba46813a4cc42c66ab781470711781940780fd8beddd0c3da62506d3a6c6" - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "2.0.1" path: @@ -996,31 +996,31 @@ packages: description: name: path sha256: "087ce49c3f0dc39180befefc60fdb4acd8f8620e5682fe2476afd0b3688bb4af" - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "1.9.0" path_provider: dependency: "direct main" description: name: path_provider - sha256: "50c5dd5b6e1aaf6fb3a78b33f6aa3afca52bf903a8a5298f53101fdaee55bbcd" - url: "https://pub.dev" + sha256: fec0d61223fba3154d87759e3cc27fe2c8dc498f6386c6d6fc80d1afdd1bf378 + url: "https://pub.flutter-io.cn" source: hosted - version: "2.1.5" + version: "2.1.4" path_provider_android: dependency: transitive description: name: path_provider_android - sha256: d0d310befe2c8ab9e7f393288ccbb11b60c019c6b5afc21973eeee4dda2b35e9 - url: "https://pub.dev" + sha256: a248d8146ee5983446bf03ed5ea8f6533129a12b11f12057ad1b4a67a2b3b41d + url: "https://pub.flutter-io.cn" source: hosted - version: "2.2.17" + version: "2.2.4" path_provider_foundation: dependency: transitive description: name: path_provider_foundation sha256: "4843174df4d288f5e29185bd6e72a6fbdf5a4a4602717eed565497429f179942" - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "2.4.1" path_provider_linux: @@ -1028,7 +1028,7 @@ packages: description: name: path_provider_linux sha256: f7a1fe3a634fe7734c8d3f2766ad746ae2a2884abe22e241a8b301bf5cac3279 - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "2.2.1" path_provider_platform_interface: @@ -1036,7 +1036,7 @@ packages: description: name: path_provider_platform_interface sha256: "88f5779f72ba699763fa3a3b06aa4bf6de76c8e5de842cf6f29e2e06476c2334" - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "2.1.2" path_provider_windows: @@ -1044,23 +1044,23 @@ packages: description: name: path_provider_windows sha256: bd6f00dbd873bfb70d0761682da2b3a2c2fccc2b9e84c495821639601d81afe7 - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "2.3.0" percent_indicator: dependency: "direct main" description: name: percent_indicator - sha256: "157d29133bbc6ecb11f923d36e7960a96a3f28837549a20b65e5135729f0f9fd" - url: "https://pub.dev" + sha256: "0d77d5c6fa9b7f60202cedf748b568ba9ba38d3f30405d6ceae4da76f5185462" + url: "https://pub.flutter-io.cn" source: hosted - version: "4.2.5" + version: "4.2.4" permission_handler: dependency: "direct main" description: name: permission_handler sha256: bc56bfe9d3f44c3c612d8d393bd9b174eb796d706759f9b495ac254e4294baa5 - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "10.4.5" permission_handler_android: @@ -1068,7 +1068,7 @@ packages: description: name: permission_handler_android sha256: "59c6322171c29df93a22d150ad95f3aa19ed86542eaec409ab2691b8f35f9a47" - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "10.3.6" permission_handler_apple: @@ -1076,7 +1076,7 @@ packages: description: name: permission_handler_apple sha256: "99e220bce3f8877c78e4ace901082fb29fa1b4ebde529ad0932d8d664b34f3f5" - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "9.1.4" permission_handler_platform_interface: @@ -1084,7 +1084,7 @@ packages: description: name: permission_handler_platform_interface sha256: "6760eb5ef34589224771010805bea6054ad28453906936f843a8cc4d3a55c4a4" - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "3.12.0" permission_handler_windows: @@ -1092,7 +1092,7 @@ packages: description: name: permission_handler_windows sha256: cc074aace208760f1eee6aa4fae766b45d947df85bc831cde77009cdb4720098 - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "0.1.3" petitparser: @@ -1100,7 +1100,7 @@ packages: description: name: petitparser sha256: c15605cd28af66339f8eb6fbe0e541bfe2d1b72d5825efc6598f3e0a31b9ad27 - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "6.0.2" platform: @@ -1108,7 +1108,7 @@ packages: description: name: platform sha256: "5d6b1b0036a5f331ebc77c850ebc8506cbc1e9416c27e59b439f917a902a4984" - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "3.1.6" plugin_platform_interface: @@ -1116,63 +1116,55 @@ packages: description: name: plugin_platform_interface sha256: "4820fbfdb9478b1ebae27888254d445073732dae3d6ea81f0b7e06d5dedc3f02" - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "2.1.8" pool: dependency: transitive description: name: pool - sha256: "4177f68c237ea2128d1bee66ac17b2ce05ba3dbaafcbdd54c5d40a39d0b6b11c" - url: "https://pub.dev" - source: hosted - version: "1.5.3" - posix: - dependency: transitive - description: - name: posix - sha256: bc1bad54ad2b735816e31f8d4600cfde6c7839975085ddfbca48b6c9f7c4044e - url: "https://pub.dev" + sha256: "20fe868b6314b322ea036ba325e6fc0711a22948856475e2c2b6306e8ab39c2a" + url: "https://pub.flutter-io.cn" source: hosted - version: "6.5.2" + version: "1.5.1" pretty_dio_logger: dependency: "direct main" description: name: pretty_dio_logger sha256: "36f2101299786d567869493e2f5731de61ce130faa14679473b26905a92b6407" - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "1.4.0" provider: dependency: transitive description: name: provider - sha256: "4e82183fa20e5ca25703ead7e05de9e4cceed1fbd1eadc1ac3cb6f565a09f272" - url: "https://pub.dev" + sha256: c8a055ee5ce3fd98d6fc872478b03823ffdb448699c6ebdbbc71d59b596fd48c + url: "https://pub.flutter-io.cn" source: hosted - version: "6.1.5+1" + version: "6.1.2" pub_semver: dependency: transitive description: name: pub_semver - sha256: "261236774e8b1d69cfc6b9eabbc96c40f25e7a2d6b171f3385d4f65d5734fb24" - url: "https://pub.dev" + sha256: "40d3ab1bbd474c4c2328c91e3a7df8c6dd629b79ece4c4bd04bee496a224fb0c" + url: "https://pub.flutter-io.cn" source: hosted - version: "2.2.1" + version: "2.1.4" pubspec_parse: dependency: transitive description: name: pubspec_parse - sha256: "0560ba233314abbed0a48a2956f7f022cce7c3e1e73df540277da7544cad4082" - url: "https://pub.dev" + sha256: "81876843eb50dc2e1e5b151792c9a985c5ed2536914115ed04e9c8528f6647b0" + url: "https://pub.flutter-io.cn" source: hosted - version: "1.5.0" + version: "1.4.0" pull_to_refresh: dependency: "direct main" description: name: pull_to_refresh sha256: bbadd5a931837b57739cf08736bea63167e284e71fb23b218c8c9a6e042aad12 - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "2.0.0" rational: @@ -1180,55 +1172,63 @@ packages: description: name: rational sha256: cb808fb6f1a839e6fc5f7d8cb3b0a10e1db48b3be102de73938c627f0b636336 - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "2.2.3" + recase: + dependency: transitive + description: + name: recase + sha256: e4eb4ec2dcdee52dcf99cb4ceabaffc631d7424ee55e56f280bc039737f89213 + url: "https://pub.flutter-io.cn" + source: hosted + version: "4.1.0" responsive_framework: dependency: "direct main" description: name: responsive_framework sha256: a8e1c13d4ba980c60cbf6fa1e9907cd60662bf2585184d7c96ca46c43de91552 - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "1.5.1" rxdart: dependency: transitive description: name: rxdart - sha256: "5c3004a4a8dbb94bd4bf5412a4def4acdaa12e12f269737a5751369e12d1a962" - url: "https://pub.dev" + sha256: "0c7c0cedd93788d996e33041ffecda924cc54389199cde4e6a34b440f50044cb" + url: "https://pub.flutter-io.cn" source: hosted - version: "0.28.0" + version: "0.27.7" shared_preferences: dependency: "direct main" description: name: shared_preferences - sha256: "6e8bf70b7fef813df4e9a36f658ac46d107db4b4cfe1048b477d4e453a8159f5" - url: "https://pub.dev" + sha256: d3bbe5553a986e83980916ded2f0b435ef2e1893dfaa29d5a7a790d0eca12180 + url: "https://pub.flutter-io.cn" source: hosted - version: "2.5.3" + version: "2.2.3" shared_preferences_android: dependency: transitive description: name: shared_preferences_android - sha256: "5bcf0772a761b04f8c6bf814721713de6f3e5d9d89caf8d3fe031b02a342379e" - url: "https://pub.dev" + sha256: "1ee8bf911094a1b592de7ab29add6f826a7331fb854273d55918693d5364a1f2" + url: "https://pub.flutter-io.cn" source: hosted - version: "2.4.11" + version: "2.2.2" shared_preferences_foundation: dependency: transitive description: name: shared_preferences_foundation - sha256: "6a52cfcdaeac77cad8c97b539ff688ccfc458c007b4db12be584fbe5c0e49e03" - url: "https://pub.dev" + sha256: "07e050c7cd39bad516f8d64c455f04508d09df104be326d8c02551590a0d513d" + url: "https://pub.flutter-io.cn" source: hosted - version: "2.5.4" + version: "2.5.3" shared_preferences_linux: dependency: transitive description: name: shared_preferences_linux sha256: "580abfd40f415611503cae30adf626e6656dfb2f0cee8f465ece7b6defb40f2f" - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "2.4.1" shared_preferences_platform_interface: @@ -1236,41 +1236,41 @@ packages: description: name: shared_preferences_platform_interface sha256: "57cbf196c486bc2cf1f02b85784932c6094376284b3ad5779d1b1c6c6a816b80" - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "2.4.1" shared_preferences_web: dependency: transitive description: name: shared_preferences_web - sha256: c49bd060261c9a3f0ff445892695d6212ff603ef3115edbb448509d407600019 - url: "https://pub.dev" + sha256: "59dc807b94d29d52ddbb1b3c0d3b9d0a67fc535a64e62a5542c8db0513fcb6c2" + url: "https://pub.flutter-io.cn" source: hosted - version: "2.4.3" + version: "2.4.1" shared_preferences_windows: dependency: transitive description: name: shared_preferences_windows sha256: "94ef0f72b2d71bc3e700e025db3710911bd51a71cefb65cc609dd0d9a982e3c1" - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "2.4.1" shelf: dependency: transitive description: name: shelf - sha256: e7dd780a7ffb623c57850b33f43309312fc863fb6aa3d276a754bb299839ef12 - url: "https://pub.dev" + sha256: ad29c505aee705f41a4d8963641f91ac4cee3c8fad5947e033390a7bd8180fa4 + url: "https://pub.flutter-io.cn" source: hosted - version: "1.4.2" + version: "1.4.1" shelf_web_socket: dependency: transitive description: name: shelf_web_socket - sha256: "3632775c8e90d6c9712f883e633716432a27758216dfb61bd86a8321c0580925" - url: "https://pub.dev" + sha256: "9ca081be41c60190ebcb4766b2486a7d50261db7bd0f5d9615f2d653637a84c1" + url: "https://pub.flutter-io.cn" source: hosted - version: "3.0.0" + version: "1.0.4" sky_engine: dependency: transitive description: flutter @@ -1280,72 +1280,56 @@ packages: dependency: transitive description: name: source_gen - sha256: "35c8150ece9e8c8d263337a265153c3329667640850b9304861faea59fc98f6b" - url: "https://pub.dev" + sha256: "14658ba5f669685cd3d63701d01b31ea748310f7ab854e471962670abcf57832" + url: "https://pub.flutter-io.cn" source: hosted - version: "2.0.0" + version: "1.5.0" source_helper: dependency: transitive description: name: source_helper - sha256: a447acb083d3a5ef17f983dd36201aeea33fedadb3228fa831f2f0c92f0f3aca - url: "https://pub.dev" + sha256: "6adebc0006c37dd63fe05bca0a929b99f06402fc95aa35bf36d67f5c06de01fd" + url: "https://pub.flutter-io.cn" source: hosted - version: "1.3.7" + version: "1.3.4" source_span: dependency: transitive description: name: source_span sha256: "53e943d4206a5e30df338fd4c6e7a077e02254531b138a15aec3bd143c1a8b3c" - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "1.10.0" + sprintf: + dependency: transitive + description: + name: sprintf + sha256: "1fc9ffe69d4df602376b52949af107d8f5703b77cda567c4d7d86a0693120f23" + url: "https://pub.flutter-io.cn" + source: hosted + version: "7.0.0" sqflite: dependency: "direct main" description: name: sqflite - sha256: "2d7299468485dca85efeeadf5d38986909c5eb0cd71fd3db2c2f000e6c9454bb" - url: "https://pub.dev" - source: hosted - version: "2.4.1" - sqflite_android: - dependency: transitive - description: - name: sqflite_android - sha256: "78f489aab276260cdd26676d2169446c7ecd3484bbd5fead4ca14f3ed4dd9ee3" - url: "https://pub.dev" + sha256: a43e5a27235518c03ca238e7b4732cf35eabe863a369ceba6cbefa537a66f16d + url: "https://pub.flutter-io.cn" source: hosted - version: "2.4.0" + version: "2.3.3+1" sqflite_common: dependency: transitive description: name: sqflite_common - sha256: "761b9740ecbd4d3e66b8916d784e581861fd3c3553eda85e167bc49fdb68f709" - url: "https://pub.dev" + sha256: "3da423ce7baf868be70e2c0976c28a1bb2f73644268b7ffa7d2e08eab71f16a4" + url: "https://pub.flutter-io.cn" source: hosted - version: "2.5.4+6" - sqflite_darwin: - dependency: transitive - description: - name: sqflite_darwin - sha256: "22adfd9a2c7d634041e96d6241e6e1c8138ca6817018afc5d443fef91dcefa9c" - url: "https://pub.dev" - source: hosted - version: "2.4.1+1" - sqflite_platform_interface: - dependency: transitive - description: - name: sqflite_platform_interface - sha256: "8dd4515c7bdcae0a785b0062859336de775e8c65db81ae33dd5445f35be61920" - url: "https://pub.dev" - source: hosted - version: "2.4.0" + version: "2.5.4" stack_trace: dependency: transitive description: name: stack_trace sha256: "9f47fd3630d76be3ab26f0ee06d213679aa425996925ff3feffdec504931c377" - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "1.12.0" stream_channel: @@ -1353,39 +1337,39 @@ packages: description: name: stream_channel sha256: ba2aa5d8cc609d96bbb2899c28934f9e1af5cddbd60a827822ea467161eb54e7 - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "2.1.2" stream_transform: dependency: transitive description: name: stream_transform - sha256: a00e5f18bffc764f923e7dec1038527f7fe7a1791361a7117f0358193f13d53a - url: "https://pub.dev" + sha256: ad47125e588cfd37a9a7f86c7d6356dde8dfe89d071d293f80ca9e9273a33871 + url: "https://pub.flutter-io.cn" source: hosted - version: "2.1.2" + version: "2.1.1" string_scanner: dependency: transitive description: name: string_scanner sha256: "688af5ed3402a4bde5b3a6c15fd768dbf2621a614950b17f04626c431ab3c4c3" - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "1.3.0" synchronized: dependency: transitive description: name: synchronized - sha256: "69fe30f3a8b04a0be0c15ae6490fc859a78ef4c43ae2dd5e8a623d45bfcf9225" - url: "https://pub.dev" + sha256: "539ef412b170d65ecdafd780f924e5be3f60032a1128df156adad6c5b373d558" + url: "https://pub.flutter-io.cn" source: hosted - version: "3.3.0+3" + version: "3.1.0+1" term_glyph: dependency: transitive description: name: term_glyph sha256: a29248a84fbb7c79282b40b8c72a1209db169a2e0542bce341da992fe1bc7e84 - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "1.2.1" test_api: @@ -1393,79 +1377,79 @@ packages: description: name: test_api sha256: "664d3a9a64782fcdeb83ce9c6b39e78fd2971d4e37827b9b06c3aa1edc5e760c" - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "0.7.3" timing: dependency: transitive description: name: timing - sha256: "62ee18aca144e4a9f29d212f5a4c6a053be252b895ab14b5821996cff4ed90fe" - url: "https://pub.dev" + sha256: "70a3b636575d4163c477e6de42f247a23b315ae20e86442bebe32d3cabf61c32" + url: "https://pub.flutter-io.cn" source: hosted - version: "1.0.2" + version: "1.0.1" tobias: dependency: "direct main" description: name: tobias sha256: "32836a9dae348d1c3f5f4247ed0a6a409fd5b9ddf490b06966a0fad2fd02cb7a" - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "3.3.2" typed_data: dependency: transitive description: name: typed_data - sha256: f9049c039ebfeb4cf7a7104a675823cd72dba8297f264b6637062516699fa006 - url: "https://pub.dev" + sha256: facc8d6582f16042dd49f2463ff1bd6e2c9ef9f3d5da3d9b087e244a7b564b3c + url: "https://pub.flutter-io.cn" source: hosted - version: "1.4.0" + version: "1.3.2" umeng_apm_sdk: dependency: "direct main" description: name: umeng_apm_sdk - sha256: "37f61a30ad84c06d89bedbcf00ca4f09347468a2186975c4c121aee1db3a2083" - url: "https://pub.dev" + sha256: a1d1afa3fbcc71079fec2acdf9189a24c9d5350c30f3048b17b729c169ff0e0f + url: "https://pub.flutter-io.cn" source: hosted - version: "2.3.7" + version: "2.3.5" umeng_common_sdk: dependency: "direct main" description: name: umeng_common_sdk sha256: "203ae013220ffd00c677a164636239a2c9722ba533b6f25e00e7a4929a91aecd" - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "1.3.1" url_launcher: dependency: "direct main" description: name: url_launcher - sha256: f6a7e5c4835bb4e3026a04793a4199ca2d14c739ec378fdfe23fc8075d0439f8 - url: "https://pub.dev" + sha256: "9d06212b1362abc2f0f0d78e6f09f726608c74e3b9462e8368bb03314aa8d603" + url: "https://pub.flutter-io.cn" source: hosted - version: "6.3.2" + version: "6.3.1" url_launcher_android: dependency: transitive description: name: url_launcher_android - sha256: "0aedad096a85b49df2e4725fa32118f9fa580f3b14af7a2d2221896a02cd5656" - url: "https://pub.dev" + sha256: "17cd5e205ea615e2c6ea7a77323a11712dffa0720a8a90540db57a01347f9ad9" + url: "https://pub.flutter-io.cn" source: hosted - version: "6.3.17" + version: "6.3.2" url_launcher_ios: dependency: transitive description: name: url_launcher_ios - sha256: "7f2022359d4c099eea7df3fdf739f7d3d3b9faf3166fb1dd390775176e0b76cb" - url: "https://pub.dev" + sha256: "16a513b6c12bb419304e72ea0ae2ab4fed569920d1c7cb850263fe3acc824626" + url: "https://pub.flutter-io.cn" source: hosted - version: "6.3.3" + version: "6.3.2" url_launcher_linux: dependency: transitive description: name: url_launcher_linux sha256: "4e9ba368772369e3e08f231d2301b4ef72b9ff87c31192ef471b380ef29a4935" - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "3.2.1" url_launcher_macos: @@ -1473,7 +1457,7 @@ packages: description: name: url_launcher_macos sha256: "17ba2000b847f334f16626a574c702b196723af2a289e7a93ffcb79acff855c2" - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "3.2.2" url_launcher_platform_interface: @@ -1481,63 +1465,62 @@ packages: description: name: url_launcher_platform_interface sha256: "552f8a1e663569be95a8190206a38187b531910283c3e982193e4f2733f01029" - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "2.3.2" url_launcher_web: dependency: transitive description: name: url_launcher_web - sha256: "4bd2b7b4dc4d4d0b94e5babfffbca8eac1a126c7f3d6ecbc1a11013faa3abba2" - url: "https://pub.dev" + sha256: "772638d3b34c779ede05ba3d38af34657a05ac55b06279ea6edd409e323dca8e" + url: "https://pub.flutter-io.cn" source: hosted - version: "2.4.1" + version: "2.3.3" url_launcher_windows: dependency: transitive description: name: url_launcher_windows - sha256: "3284b6d2ac454cf34f114e1d3319866fdd1e19cdc329999057e44ffe936cfa77" - url: "https://pub.dev" + sha256: "44cf3aabcedde30f2dba119a9dea3b0f2672fbe6fa96e85536251d678216b3c4" + url: "https://pub.flutter-io.cn" source: hosted - version: "3.1.4" + version: "3.1.3" uuid: dependency: transitive description: name: uuid - sha256: "9b129329f58692f6e6578329498a8fe9fbe98f090beb764ffbb8ee2eadd01dcd" - url: "https://pub.dev" + sha256: a5be9ef6618a7ac1e964353ef476418026db906c4facdedaa299b7a2e71690ff + url: "https://pub.flutter-io.cn" source: hosted - version: "4.6.0" + version: "4.5.1" vector_math: dependency: transitive description: name: vector_math sha256: "80b3257d1492ce4d091729e3a67a60407d227c27241d6927be0130c98e741803" - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "2.1.4" video_player: dependency: "direct main" description: name: video_player - sha256: "4a8c3492d734f7c39c2588a3206707a05ee80cef52e8c7f3b2078d430c84bc17" - url: "https://pub.dev" + sha256: "0d55b1f1a31e5ad4c4967bfaa8ade0240b07d20ee4af1dfef5f531056512961a" + url: "https://pub.flutter-io.cn" source: hosted - version: "2.9.2" + version: "2.10.0" video_player_android: - dependency: transitive + dependency: "direct overridden" description: - name: video_player_android - sha256: "28dcc4122079f40f93a0965b3679aff1a5f4251cf79611bd8011f937eb6b69de" - url: "https://pub.dev" - source: hosted + path: "packages/video_player_android" + relative: true + source: path version: "2.8.4" video_player_avfoundation: dependency: transitive description: name: video_player_avfoundation sha256: f9a780aac57802b2892f93787e5ea53b5f43cc57dc107bee9436458365be71cd - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "2.8.4" video_player_platform_interface: @@ -1545,23 +1528,23 @@ packages: description: name: video_player_platform_interface sha256: cf2a1d29a284db648fd66cbd18aacc157f9862d77d2cc790f6f9678a46c1db5a - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "6.4.0" video_player_web: dependency: transitive description: name: video_player_web - sha256: "9f3c00be2ef9b76a95d94ac5119fb843dca6f2c69e6c9968f6f2b6c9e7afbdeb" - url: "https://pub.dev" + sha256: "6dcdd298136523eaf7dfc31abaf0dfba9aa8a8dbc96670e87e9d42b6f2caf774" + url: "https://pub.flutter-io.cn" source: hosted - version: "2.4.0" + version: "2.3.2" vm_service: dependency: transitive description: name: vm_service sha256: f6be3ed8bd01289b34d679c2b62226f63c0e69f9fd2e50a6b3c1c729a961041b - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "14.3.0" wakelock_plus: @@ -1569,7 +1552,7 @@ packages: description: name: wakelock_plus sha256: f268ca2116db22e57577fb99d52515a24bdc1d570f12ac18bb762361d43b043d - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "1.1.4" wakelock_plus_platform_interface: @@ -1577,63 +1560,55 @@ packages: description: name: wakelock_plus_platform_interface sha256: "036deb14cd62f558ca3b73006d52ce049fabcdcb2eddfe0bf0fe4e8a943b5cf2" - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "1.3.0" watcher: dependency: transitive description: name: watcher - sha256: "1398c9f081a753f9226febe8900fce8f7d0a67163334e1c94a2438339d79d635" - url: "https://pub.dev" + sha256: "69da27e49efa56a15f8afe8f4438c4ec02eff0a117df1b22ea4aad194fe1c104" + url: "https://pub.flutter-io.cn" source: hosted - version: "1.2.1" + version: "1.1.1" web: dependency: transitive description: name: web - sha256: "868d88a33d8a87b18ffc05f9f030ba328ffefba92d6c127917a2ba740f9cfe4a" - url: "https://pub.dev" - source: hosted - version: "1.1.1" - web_socket: - dependency: transitive - description: - name: web_socket - sha256: "34d64019aa8e36bf9842ac014bb5d2f5586ca73df5e4d9bf5c936975cae6982c" - url: "https://pub.dev" + sha256: "97da13628db363c635202ad97068d47c5b8aa555808e7a9411963c533b449b27" + url: "https://pub.flutter-io.cn" source: hosted - version: "1.0.1" + version: "0.5.1" web_socket_channel: dependency: transitive description: name: web_socket_channel - sha256: d645757fb0f4773d602444000a8131ff5d48c9e47adfe9772652dd1a4f2d45c8 - url: "https://pub.dev" + sha256: d88238e5eac9a42bb43ca4e721edba3c08c6354d4a53063afaa568516217621b + url: "https://pub.flutter-io.cn" source: hosted - version: "3.0.3" + version: "2.4.0" win32: dependency: transitive description: name: win32 sha256: daf97c9d80197ed7b619040e86c8ab9a9dad285e7671ee7390f9180cc828a51e - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "5.10.1" win32_registry: dependency: transitive description: name: win32_registry - sha256: "21ec76dfc731550fd3e2ce7a33a9ea90b828fdf19a5c3bcf556fa992cfa99852" - url: "https://pub.dev" + sha256: "10589e0d7f4e053f2c61023a31c9ce01146656a70b7b7f0828c0b46d7da2a9bb" + url: "https://pub.flutter-io.cn" source: hosted - version: "1.1.5" + version: "1.1.3" xdg_directories: dependency: transitive description: name: xdg_directories sha256: "7a3f37b05d989967cdddcbb571f1ea834867ae2faa29725fd085180e0883aa15" - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "1.1.0" xml: @@ -1641,17 +1616,17 @@ packages: description: name: xml sha256: b015a8ad1c488f66851d762d3090a21c600e479dc75e68328c52774040cf9226 - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "6.5.0" yaml: dependency: transitive description: name: yaml - sha256: f67cdd8e07d3c6329146aaef1ba043542b3134c12489f553ca9a7435d1068aea - url: "https://pub.dev" + sha256: "75769501ea3489fca56601ff33454fe45507ea3bfb014161abc3b43ae25989d5" + url: "https://pub.flutter-io.cn" source: hosted - version: "3.1.4" + version: "3.1.2" sdks: dart: ">=3.6.0 <4.0.0" flutter: ">=3.27.0" diff --git a/pubspec.yaml b/pubspec.yaml index 925a210..0a24d6d 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -16,7 +16,7 @@ publish_to: 'none' # Remove this line if you wish to publish to pub.dev # https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html # In Windows, build-name is used as the major, minor, and patch parts # of the product and file versions while build-number is used as the build suffix. -version: 1.0.14+14 +version: 1.0.17+17 environment: sdk: '>=3.6.0 <4.0.0' @@ -95,7 +95,7 @@ dependencies: # 富文本插件 https://pub.dev/packages/extended_text extended_text: ^11.0.1 # 视频播放 https://pub.dev/packages/video_player - video_player: 2.9.2 + video_player: 2.10.0 # 视频播放器控制层 https://pub.dev/packages/chewie chewie: 1.7.5 # 驰声语音评测 SDK(官方离线包裁剪为当前支持架构) @@ -135,6 +135,9 @@ dependencies: dependency_overrides: # lottie 3.1.2 depends on http ^1.0.0 umeng_apm_sdk >=2.0.1 depends on http ^0.13.1 http: ^0.13.3 + # 开启 Media3 解码器初始化失败后的备用解码器回退。 + video_player_android: + path: packages/video_player_android dev_dependencies: build_runner: ^2.4.4