From d2b3433a2d12f8f35595f035e4db392b324c1cdd Mon Sep 17 00:00:00 2001 From: wuqifeng <540416539@qq.com> Date: Mon, 28 Sep 2026 18:54:33 +0800 Subject: [PATCH] fix: 修复部分安卓设备视频持续加载 --- lib/pages/video/zone/video_zone_player_page.dart | 11 ++++++++--- packages/video_player_android/LICENSE | 25 +++++++++++++++++++++++++ packages/video_player_android/android/build.gradle | 72 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ packages/video_player_android/android/settings.gradle | 1 + packages/video_player_android/android/src/main/AndroidManifest.xml | 3 +++ packages/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/ExoPlayerEventListener.java | 107 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ packages/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/ExoPlayerState.java | 71 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ packages/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/HttpVideoAsset.java | 98 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ packages/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/LocalVideoAsset.java | 29 +++++++++++++++++++++++++++++ packages/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/Messages.java | 698 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ packages/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/QueuingEventSink.java | 85 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ packages/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/RtspVideoAsset.java | 32 ++++++++++++++++++++++++++++++++ packages/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/VideoAsset.java | 98 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ packages/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/VideoPlayer.java | 123 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ packages/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/VideoPlayerCallbacks.java | 33 +++++++++++++++++++++++++++++++++ packages/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/VideoPlayerEventCallbacks.java | 104 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ packages/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/VideoPlayerOptions.java | 9 +++++++++ packages/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/VideoPlayerPlugin.java | 262 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ packages/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/platformview/PlatformVideoView.java | 94 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ packages/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/platformview/PlatformVideoViewFactory.java | 68 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ packages/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/platformview/PlatformViewExoPlayerEventListener.java | 52 ++++++++++++++++++++++++++++++++++++++++++++++++++++ packages/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/platformview/PlatformViewVideoPlayer.java | 72 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ packages/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/texture/TextureExoPlayerEventListener.java | 103 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ packages/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/texture/TextureVideoPlayer.java | 129 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ packages/video_player_android/android/src/test/java/io/flutter/plugins/videoplayer/ExoPlayerEventListenerTest.java | 148 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ packages/video_player_android/android/src/test/java/io/flutter/plugins/videoplayer/FakeVideoAsset.java | 37 +++++++++++++++++++++++++++++++++++++ packages/video_player_android/android/src/test/java/io/flutter/plugins/videoplayer/PlatformVideoViewFactoryTest.java | 40 ++++++++++++++++++++++++++++++++++++++++ packages/video_player_android/android/src/test/java/io/flutter/plugins/videoplayer/PlatformVideoViewTest.java | 33 +++++++++++++++++++++++++++++++++ packages/video_player_android/android/src/test/java/io/flutter/plugins/videoplayer/PlatformViewExoPlayerEventListenerTest.java | 80 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ packages/video_player_android/android/src/test/java/io/flutter/plugins/videoplayer/TextureExoPlayerEventListenerTest.java | 188 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ packages/video_player_android/android/src/test/java/io/flutter/plugins/videoplayer/TextureVideoPlayerTest.java | 233 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ packages/video_player_android/android/src/test/java/io/flutter/plugins/videoplayer/VideoAssetTest.java | 154 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ packages/video_player_android/android/src/test/java/io/flutter/plugins/videoplayer/VideoPlayerEventCallbacksTest.java | 151 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ packages/video_player_android/android/src/test/java/io/flutter/plugins/videoplayer/VideoPlayerPluginTest.java | 116 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ packages/video_player_android/android/src/test/java/io/flutter/plugins/videoplayer/VideoPlayerTest.java | 216 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ packages/video_player_android/lib/src/android_video_player.dart | 252 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ packages/video_player_android/lib/src/messages.g.dart | 432 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ packages/video_player_android/lib/src/platform_view_player.dart | 60 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ packages/video_player_android/lib/video_player_android.dart | 5 +++++ packages/video_player_android/pubspec.yaml | 32 ++++++++++++++++++++++++++++++++ pubspec.lock | 9 ++++----- pubspec.yaml | 3 +++ 42 files changed, 4560 insertions(+), 8 deletions(-) create mode 100644 packages/video_player_android/LICENSE create mode 100644 packages/video_player_android/android/build.gradle create mode 100644 packages/video_player_android/android/settings.gradle create mode 100644 packages/video_player_android/android/src/main/AndroidManifest.xml create mode 100644 packages/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/ExoPlayerEventListener.java create mode 100644 packages/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/ExoPlayerState.java create mode 100644 packages/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/HttpVideoAsset.java create mode 100644 packages/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/LocalVideoAsset.java create mode 100644 packages/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/Messages.java create mode 100644 packages/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/QueuingEventSink.java create mode 100644 packages/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/RtspVideoAsset.java create mode 100644 packages/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/VideoAsset.java create mode 100644 packages/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/VideoPlayer.java create mode 100644 packages/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/VideoPlayerCallbacks.java create mode 100644 packages/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/VideoPlayerEventCallbacks.java create mode 100644 packages/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/VideoPlayerOptions.java create mode 100644 packages/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/VideoPlayerPlugin.java create mode 100644 packages/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/platformview/PlatformVideoView.java create mode 100644 packages/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/platformview/PlatformVideoViewFactory.java create mode 100644 packages/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/platformview/PlatformViewExoPlayerEventListener.java create mode 100644 packages/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/platformview/PlatformViewVideoPlayer.java create mode 100644 packages/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/texture/TextureExoPlayerEventListener.java create mode 100644 packages/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/texture/TextureVideoPlayer.java create mode 100644 packages/video_player_android/android/src/test/java/io/flutter/plugins/videoplayer/ExoPlayerEventListenerTest.java create mode 100644 packages/video_player_android/android/src/test/java/io/flutter/plugins/videoplayer/FakeVideoAsset.java create mode 100644 packages/video_player_android/android/src/test/java/io/flutter/plugins/videoplayer/PlatformVideoViewFactoryTest.java create mode 100644 packages/video_player_android/android/src/test/java/io/flutter/plugins/videoplayer/PlatformVideoViewTest.java create mode 100644 packages/video_player_android/android/src/test/java/io/flutter/plugins/videoplayer/PlatformViewExoPlayerEventListenerTest.java create mode 100644 packages/video_player_android/android/src/test/java/io/flutter/plugins/videoplayer/TextureExoPlayerEventListenerTest.java create mode 100644 packages/video_player_android/android/src/test/java/io/flutter/plugins/videoplayer/TextureVideoPlayerTest.java create mode 100644 packages/video_player_android/android/src/test/java/io/flutter/plugins/videoplayer/VideoAssetTest.java create mode 100644 packages/video_player_android/android/src/test/java/io/flutter/plugins/videoplayer/VideoPlayerEventCallbacksTest.java create mode 100644 packages/video_player_android/android/src/test/java/io/flutter/plugins/videoplayer/VideoPlayerPluginTest.java create mode 100644 packages/video_player_android/android/src/test/java/io/flutter/plugins/videoplayer/VideoPlayerTest.java create mode 100644 packages/video_player_android/lib/src/android_video_player.dart create mode 100644 packages/video_player_android/lib/src/messages.g.dart create mode 100644 packages/video_player_android/lib/src/platform_view_player.dart create mode 100644 packages/video_player_android/lib/video_player_android.dart create mode 100644 packages/video_player_android/pubspec.yaml diff --git a/lib/pages/video/zone/video_zone_player_page.dart b/lib/pages/video/zone/video_zone_player_page.dart index 18e52a7..c43d01d 100644 --- a/lib/pages/video/zone/video_zone_player_page.dart +++ b/lib/pages/video/zone/video_zone_player_page.dart @@ -65,9 +65,7 @@ class _VideoZonePlayerPageState extends State _lastIsPlaying = null; final controller = VideoPlayerController.networkUrl( Uri.parse(_currentItem.videoUrl), - viewType: defaultTargetPlatform == TargetPlatform.android - ? VideoViewType.platformView - : VideoViewType.textureView, + viewType: VideoViewType.textureView, ); _controller = controller; _chewieController = null; @@ -144,6 +142,7 @@ class _VideoZonePlayerPageState extends State setState(() {}); } catch (error) { if (mounted && controller == _controller) { + debugPrint('视频初始化失败(videoId=${_currentItem.id}): $error'); setState(() => _loadError = error); } } @@ -152,6 +151,12 @@ class _VideoZonePlayerPageState extends State void _onVideoChanged() { final controller = _controller; if (!mounted || controller == null) return; + if (controller.value.hasError && _loadError == null) { + final error = controller.value.errorDescription ?? '未知播放器错误'; + debugPrint('视频播放失败(videoId=${_currentItem.id}): $error'); + setState(() => _loadError = error); + return; + } final isPlaying = controller.value.isPlaying; if (_lastIsPlaying != null && _lastIsPlaying != isPlaying) { unawaited(_cacheCurrentProgress()); 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 b4d59f9..cd32cfc 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -1509,12 +1509,11 @@ packages: source: hosted version: "2.10.0" video_player_android: - dependency: transitive + dependency: "direct overridden" description: - name: video_player_android - sha256: "28dcc4122079f40f93a0965b3679aff1a5f4251cf79611bd8011f937eb6b69de" - url: "https://pub.flutter-io.cn" - source: hosted + path: "packages/video_player_android" + relative: true + source: path version: "2.8.4" video_player_avfoundation: dependency: transitive diff --git a/pubspec.yaml b/pubspec.yaml index c28daf1..b84b924 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -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 -- libgit2 0.22.2