USB 摄像头+远程遥控+中英的适配+topic的集成和状态的使用到相应页面

This commit is contained in:
2026-10-20 17:03:37 +08:00
parent 178cd2533c
commit 582242e9aa
144 changed files with 15759 additions and 406 deletions

View File

@@ -0,0 +1,68 @@
# Below is a list of people and organizations that have contributed
# to the Flutter project. Names should be added to the list like so:
#
# Name/Organization <email address>
Google Inc.
The Chromium Authors
German Saprykin <saprykin.h@gmail.com>
Benjamin Sauer <sauer.benjamin@gmail.com>
larsenthomasj@gmail.com
Ali Bitek <alibitek@protonmail.ch>
Pol Batlló <pol.batllo@gmail.com>
Anatoly Pulyaevskiy
Hayden Flinner <haydenflinner@gmail.com>
Stefano Rodriguez <hlsroddy@gmail.com>
Salvatore Giordano <salvatoregiordanoo@gmail.com>
Brian Armstrong <brian@flutter.institute>
Paul DeMarco <paulmdemarco@gmail.com>
Fabricio Nogueira <feufeu@gmail.com>
Simon Lightfoot <simon@devangels.london>
Ashton Thomas <ashton@acrinta.com>
Thomas Danner <thmsdnnr@gmail.com>
Diego Velásquez <diego.velasquez.lopez@gmail.com>
Hajime Nakamura <nkmrhj@gmail.com>
Tuyển Vũ Xuân <netsoft1985@gmail.com>
Miguel Ruivo <miguel@miguelruivo.com>
Sarthak Verma <sarthak@artiosys.com>
Mike Diarmid <mike@invertase.io>
Invertase <oss@invertase.io>
Elliot Hesp <elliot@invertase.io>
Vince Varga <vince.varga@smaho.com>
Aawaz Gyawali <awazgyawali@gmail.com>
EUI Limited <ian.evans3@admiralgroup.co.uk>
Katarina Sheremet <katarina@sheremet.ch>
Thomas Stockx <thomas@stockxit.com>
Sarbagya Dhaubanjar <sarbagyastha@gmail.com>
Ozkan Eksi <ozeksi@gmail.com>
Rishab Nayak <rishab@bu.edu>
ko2ic <ko2ic.dev@gmail.com>
Jonathan Younger <jonathan@daikini.com>
Jose Sanchez <josesm82@gmail.com>
Debkanchan Samadder <debu.samadder@gmail.com>
Audrius Karosevicius <audrius.karosevicius@gmail.com>
Lukasz Piliszczuk <lukasz@intheloup.io>
SoundReply Solutions GmbH <ch@soundreply.com>
Rafal Wachol <rwachol@gmail.com>
Pau Picas <pau.picas@gmail.com>
Christian Weder <chrstian.weder@yapeal.ch>
Alexandru Tuca <salexandru.tuca@outlook.com>
Christian Weder <chrstian.weder@yapeal.ch>
Rhodes Davis Jr. <rody.davis.jr@gmail.com>
Luigi Agosti <luigi@tengio.com>
Quentin Le Guennec <quentin@tengio.com>
Koushik Ravikumar <koushik@tengio.com>
Nissim Dsilva <nissim@tengio.com>
Giancarlo Rocha <giancarloiff@gmail.com>
Ryo Miyake <ryo@miyake.id>
Théo Champion <contact.theochampion@gmail.com>
Kazuki Yamaguchi <y.kazuki0614n@gmail.com>
Eitan Schwartz <eshvartz@gmail.com>
Chris Rutkowski <chrisrutkowski89@gmail.com>
Juan Alvarez <juan.alvarez@resideo.com>
Aleksandr Yurkovskiy <sanekyy@gmail.com>
Anton Borries <mail@antonborri.es>
Alex Li <google@alexv525.com>
Rahul Raj <64.rahulraj@gmail.com>
Márton Matuz <matuzmarci@gmail.com>
André Sousa <andrelvsousa@gmail.com>

View File

@@ -0,0 +1,391 @@
## 2.9.5
* Updates build files from Groovy to Kotlin.
## 2.9.4
* Updates `androidx.media3` to 1.9.2.
## 2.9.3
* Updates `androidx.media3` to 1.9.1.
## 2.9.2
* Bumps kotlin_version to 2.3.0.
## 2.9.1
* Updates to Pigeon 26.1.5.
## 2.9.0
* Implements `getAudioTracks()` and `selectAudioTrack()` methods for Android using ExoPlayer.
## 2.8.22
* Bumps kotlin_version to 2.2.21.
## 2.8.21
* Bumps com.android.tools.build:gradle from 8.12.1 to 8.13.1.
## 2.8.20
* Bumps `exoplayer_version` from 1.5.1 to 1.8.0.
## 2.8.19
* Updates to Pigeon 26.
## 2.8.18
* Removed mockito-inline and updated to mockito-core 5.17.0.
## 2.8.17
* Moves video event processing logic to Dart, and fixes an issue where buffer
range would not be updated for a paused video.
* Switches to Kotlin for Pigeon-generated code.
* Adopts type-safe event channels for internal communication.
## 2.8.16
* Updates Java compatibility version to 17 and minimum supported SDK version to Flutter 3.35/Dart 3.9.
## 2.8.15
* Resolves Gradle 9 deprecations.
## 2.8.14
* Restructures internal logic for player creation and tracking.
## 2.8.13
* Bumps com.android.tools.build:gradle to 8.12.1.
## 2.8.12
* Moves buffer position update event generation to Dart.
## 2.8.11
* Updates kotlin version to 2.2.0 to enable gradle 8.11 support.
## 2.8.10
* Restructures internal logic to move more code to Dart.
## 2.8.9
* Restructures the communication between Dart and Java code.
## 2.8.8
* * Updates Media3-ExoPlayer to 1.5.1.
## 2.8.7
* Adds note about known issue regarding platform views to the README.
## 2.8.6
* Fixes a [bug](https://github.com/flutter/flutter/issues/165149) where the `isBuffering` flag
always returns true after seeking to any position.
## 2.8.5
* Replaces deprecated `onSurfaceDestroyed` with `onSurfaceCleanup`.
* Restores background playback support.
## 2.8.4
* Fixes incorrect width/height swap ([bug](https://github.com/flutter/flutter/issues/166097)). The swap was originally required for the uncorrected width/height of `Format` but was mistakenly retained after [switching to `VideoSize`](https://github.com/flutter/packages/pull/6535), which already accounts for rotation.
* Fixes example app layout issue caused by `Transform.rotate` not affecting space calculation (following [#8685](https://github.com/flutter/packages/pull/8685)).
## 2.8.3
* Changes plugin to use `TextureRegistry.SurfaceProducer.handlesCropAndRotation` to detect
whether or not the video player rotation needs to be corrected.
## 2.8.2
* Fixes a [bug](https://github.com/flutter/flutter/issues/164689) that can cause video to
disappear after an app is suspended and resumed.
## 2.8.1
* Updates compileSdk 34 to flutter.compileSdkVersion.
## 2.8.0
* Adds support for platform views as an optional way of displaying a video.
* Suppresses deprecation and removal warnings for
`TextureRegistry.SurfaceProducer.onSurfaceDestroyed`.
## 2.7.17
* Replaces deprecated Android embedder APIs (`onSurfaceCreated` -> `onSurfaceAvailable`).
* Updates minimum supported SDK version to Flutter 3.22/Dart 3.4.
## 2.7.16
* Updates internal Pigeon API to use newer features.
## 2.7.15
* Changes the rotation correction calculation for Android API 29+ to use
the one that is reported by the video's format instead of the unapplied
rotation degrees that Exoplayer does not report on Android API 21+.
* Changes the rotation correction calculation for Android APIs 21-28 to 0
because the Impeller backend used on those API versions correctly rotates
the video being played automatically.
## 2.7.14
* Removes SSL workaround for API 19, which is no longer supported.
## 2.7.13
* When `AndroidVideoPlayer` attempts to operate on a `textureId` that is not
active (i.e. it was previously disposed or never created), the resulting
platform exception is more informative than a "NullPointerException".
## 2.7.12
* Fixes a [bug](https://github.com/flutter/flutter/issues/156451) where
additional harmless but annoying warnings in the form of native stack traces
would be printed when the app was backgrounded. There may be additional
warnings that are not yet fixed, but this should address the
most common case.
## 2.7.11
* Fixes a [bug](https://github.com/flutter/flutter/issues/156158) where a
harmless but annoying warning in the form of a native stack trace would be
printed when a previously disposed video player received a trim memory event
(i.e. by backgrounding).
## 2.7.10
* Fixes a [bug](https://github.com/flutter/flutter/issues/156158) where
disposing a video player (including implicitly by switching tabs or views
in a running app) would cause native stack traces.
## 2.7.9
* Updates Java compatibility version to 11.
## 2.7.8
* Updates Pigeon for non-nullable collection type support.
## 2.7.7
* Removes the flag to treat warnings as errors in client builds.
## 2.7.6
* Fixes a [bug](https://github.com/flutter/flutter/issues/154602) where
resuming a video player would cause a `Bad state: Future already completed`.
## 2.7.5
* Add a deprecation suppression in advance of a new `SurfaceProducer` API.
## 2.7.4
* Fixes a [bug](https://github.com/flutter/flutter/issues/154559) where
resuming (or using a plugin like `share_plus` that implicitly resumes the
activity where) a video player would cause a `DecoderInitializationException`.
## 2.7.3
* Updates Media3-ExoPlayer to 1.4.1.
## 2.7.2
* Updates minimum supported SDK version to Flutter 3.24/Dart 3.5.
* Re-adds Impeller support.
## 2.7.1
* Revert Impeller support.
## 2.7.0
* Re-adds [support for Impeller](https://docs.flutter.dev/release/breaking-changes/android-surface-plugins).
## 2.6.0
* Adds RTSP support.
## 2.5.4
* Updates Media3-ExoPlayer to 1.4.0.
## 2.5.3
* Updates lint checks to ignore NewerVersionAvailable.
## 2.5.2
* Updates Android Gradle plugin to 8.5.0.
## 2.5.1
* Removes additional references to the v1 Android embedding.
## 2.5.0
* Migrates ExoPlayer to Media3-ExoPlayer 1.3.1.
## 2.4.17
* Revert Impeller support.
## 2.4.16
* [Supports Impeller](https://docs.flutter.dev/release/breaking-changes/android-surface-plugins).
## 2.4.15
* Updates minimum supported SDK version to Flutter 3.22/Dart 3.4.
* Removes support for apps using the v1 Android embedding.
## 2.4.14
* Calls `onDestroy` instead of `initialize` in onDetachedFromEngine.
## 2.4.13
* Updates minSdkVersion to 19.
* Updates minimum supported SDK version to Flutter 3.16/Dart 3.2.
## 2.4.12
* Updates compileSdk version to 34.
* Adds error handling for `BehindLiveWindowException`, which may occur upon live-video playback failure.
## 2.4.11
* Updates minimum supported SDK version to Flutter 3.10/Dart 3.0.
* Fixes new lint warnings.
## 2.4.10
* Adds pub topics to package metadata.
* Updates minimum supported SDK version to Flutter 3.7/Dart 2.19.
## 2.4.9
* Bumps ExoPlayer version to 2.18.7.
## 2.4.8
* Bumps ExoPlayer version to 2.18.6.
## 2.4.7
* Fixes Java warnings.
## 2.4.6
* Fixes compatibility with AGP versions older than 4.2.
## 2.4.5
* Adds a namespace for compatibility with AGP 8.0.
## 2.4.4
* Synchronizes `VideoPlayerValue.isPlaying` with `ExoPlayer`.
* Updates minimum Flutter version to 3.3.
## 2.4.3
* Bumps ExoPlayer version to 2.18.5.
## 2.4.2
* Bumps ExoPlayer version to 2.18.4.
## 2.4.1
* Changes the severity of `javac` warnings so that they are treated as errors and fixes the violations.
## 2.4.0
* Allows setting the ExoPlayer user agent by passing a User-Agent HTTP header.
## 2.3.12
* Clarifies explanation of endorsement in README.
* Aligns Dart and Flutter SDK constraints.
* Updates compileSdkVersion to 33.
## 2.3.11
* Updates links for the merge of flutter/plugins into flutter/packages.
* Updates minimum Flutter version to 3.0.
## 2.3.10
* Adds compatibilty with version 6.0 of the platform interface.
* Fixes file URI construction in example.
* Updates code for new analysis options.
* Updates code for `no_leading_underscores_for_local_identifiers` lint.
* Updates minimum Flutter version to 2.10.
* Fixes violations of new analysis option use_named_constants.
* Removes an unnecessary override in example code.
## 2.3.9
* Updates ExoPlayer to 2.18.1.
* Fixes avoid_redundant_argument_values lint warnings and minor typos.
## 2.3.8
* Updates ExoPlayer to 2.18.0.
## 2.3.7
* Bumps gradle version to 7.2.1.
* Ignores unnecessary import warnings in preparation for [upcoming Flutter changes](https://github.com/flutter/flutter/pull/106316).
## 2.3.6
* Updates references to the obsolete master branch.
## 2.3.5
* Sets rotationCorrection for videos recorded in landscapeRight (https://github.com/flutter/flutter/issues/60327).
## 2.3.4
* Updates ExoPlayer to 2.17.1.
## 2.3.3
* Removes unnecessary imports.
* Fixes library_private_types_in_public_api, sort_child_properties_last and use_key_in_widget_constructors
lint warnings.
## 2.3.2
* Updates ExoPlayer to 2.17.0.
## 2.3.1
* Renames internal method channels to avoid potential confusion with the
default implementation's method channel.
* Updates Pigeon to 2.0.1.
## 2.3.0
* Updates Pigeon to ^1.0.16.
## 2.2.17
* Splits from `video_player` as a federated implementation.

View File

@@ -0,0 +1,25 @@
Copyright 2013 The Flutter Authors
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.

View File

@@ -0,0 +1,90 @@
import org.jetbrains.kotlin.gradle.dsl.JvmTarget
group = "io.flutter.plugins.videoplayer"
version = "1.0-SNAPSHOT"
buildscript {
val kotlinVersion = "2.3.0"
repositories {
google()
mavenCentral()
}
dependencies {
classpath("com.android.tools.build:gradle:8.13.1")
classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion")
}
}
allprojects {
repositories {
google()
mavenCentral()
}
}
plugins {
id("com.android.library")
id("kotlin-android")
}
kotlin {
compilerOptions {
jvmTarget = JvmTarget.fromTarget(JavaVersion.VERSION_17.toString())
}
}
android {
namespace = "io.flutter.plugins.videoplayer"
compileSdk = flutter.compileSdkVersion
defaultConfig {
minSdk = 24
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
}
lint {
checkAllWarnings = true
warningsAsErrors = true
disable.addAll(setOf("AndroidGradlePluginVersion", "InvalidPackage", "GradleDependency", "NewerVersionAvailable"))
baseline = file("lint-baseline.xml")
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
dependencies {
val exoplayerVersion = "1.9.2"
implementation("androidx.media3:media3-exoplayer:${exoplayerVersion}")
implementation("androidx.media3:media3-exoplayer-hls:${exoplayerVersion}")
implementation("androidx.media3:media3-exoplayer-dash:${exoplayerVersion}")
implementation("androidx.media3:media3-exoplayer-rtsp:${exoplayerVersion}")
implementation("androidx.media3:media3-exoplayer-smoothstreaming:${exoplayerVersion}")
testImplementation("junit:junit:4.13.2")
testImplementation("androidx.test:core:1.7.0")
testImplementation("org.mockito:mockito-core:5.23.0")
testImplementation("org.robolectric:robolectric:4.16")
testImplementation("androidx.media3:media3-test-utils:${exoplayerVersion}")
}
testOptions {
unitTests {
isIncludeAndroidResources = true
isReturnDefaultValues = true
all {
it.outputs.upToDateWhen { false }
it.testLogging {
events("passed", "skipped", "failed", "standardOut", "standardError")
showStandardStreams = true
}
// 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.
it.jvmArgs("-Xmx4G")
}
}
}
}

View File

@@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<issues format="6" by="lint 8.11.0" type="baseline" client="gradle" dependencies="false" name="AGP (8.11.0)" variant="all" version="8.11.0">
<issue
id="MemberExtensionConflict"
message="`containsKey` is defined both as a member in class `kotlin.collections.Map` and an extension in package `kotlin.collections`. The defined behavior for this is to use the member, but since the extension is explicitly imported into this file, there&apos;s a chance that this was not expected. (One common way this happens is for members to be added to a class after code was already written to use an extension)."
errorLine1=" a.all { (b as Map&lt;Any?, Any?>).containsKey(it.key) &amp;&amp; deepEquals(it.value, b[it.key]) }"
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="src/main/kotlin/io/flutter/plugins/videoplayer/Messages.kt"
line="58"
column="19"/>
</issue>
</issues>

View File

@@ -0,0 +1 @@
rootProject.name = "video_player_android"

View File

@@ -0,0 +1,124 @@
// Copyright 2013 The Flutter Authors
// 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.media3.common.C;
import androidx.media3.common.PlaybackException;
import androidx.media3.common.Player;
import androidx.media3.common.Tracks;
import androidx.media3.exoplayer.ExoPlayer;
public abstract class ExoPlayerEventListener implements Player.Listener {
private boolean isInitialized = false;
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) {
this.exoPlayer = exoPlayer;
this.events = events;
}
protected abstract void sendInitialized();
@Override
public void onPlaybackStateChanged(final int playbackState) {
PlatformPlaybackState platformState = PlatformPlaybackState.UNKNOWN;
switch (playbackState) {
case Player.STATE_BUFFERING:
platformState = PlatformPlaybackState.BUFFERING;
break;
case Player.STATE_READY:
platformState = PlatformPlaybackState.READY;
if (!isInitialized) {
isInitialized = true;
sendInitialized();
}
break;
case Player.STATE_ENDED:
platformState = PlatformPlaybackState.ENDED;
break;
case Player.STATE_IDLE:
platformState = PlatformPlaybackState.IDLE;
break;
}
events.onPlaybackStateChanged(platformState);
}
@Override
public void onPlayerError(@NonNull final PlaybackException error) {
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);
}
@Override
public void onTracksChanged(@NonNull Tracks tracks) {
// Find the currently selected audio track and notify
String selectedTrackId = findSelectedAudioTrackId(tracks);
events.onAudioTrackChanged(selectedTrackId);
}
/**
* Finds the ID of the currently selected audio track.
*
* @param tracks The current tracks
* @return The track ID in format "groupIndex_trackIndex", or null if no audio track is selected
*/
@Nullable
private String findSelectedAudioTrackId(@NonNull Tracks tracks) {
int groupIndex = 0;
for (Tracks.Group group : tracks.getGroups()) {
if (group.getType() == C.TRACK_TYPE_AUDIO && group.isSelected()) {
// Find the selected track within this group
for (int i = 0; i < group.length; i++) {
if (group.isTrackSelected(i)) {
return groupIndex + "_" + i;
}
}
}
groupIndex++;
}
return null;
}
}

View File

@@ -0,0 +1,94 @@
// Copyright 2013 The Flutter Authors
// 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 {
@NonNull private final StreamingFormat streamingFormat;
@NonNull private final Map<String, String> httpHeaders;
@Nullable private final String userAgent;
HttpVideoAsset(
@Nullable String assetUrl,
@NonNull StreamingFormat streamingFormat,
@NonNull Map<String, String> httpHeaders,
@Nullable String userAgent) {
super(assetUrl);
this.streamingFormat = streamingFormat;
this.httpHeaders = httpHeaders;
this.userAgent = userAgent;
}
@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.
*
* <p>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) {
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<String, String> httpHeaders,
@Nullable String userAgent) {
factory.setUserAgent(userAgent).setAllowCrossProtocolRedirects(true);
if (!httpHeaders.isEmpty()) {
factory.setDefaultRequestProperties(httpHeaders);
}
}
}

View File

@@ -0,0 +1,29 @@
// Copyright 2013 The Flutter Authors
// 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);
}
}

View File

@@ -0,0 +1,223 @@
// Copyright 2013 The Flutter Authors
// Use of this source code is governed by a BSD-style license that should be
// found in the LICENSE file.
package io.flutter.plugins.videoplayer;
import android.content.Context;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.media3.common.util.UnstableApi;
import androidx.media3.exoplayer.DefaultRenderersFactory;
import androidx.media3.exoplayer.mediacodec.MediaCodecInfo;
import androidx.media3.exoplayer.mediacodec.MediaCodecSelector;
import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 直播播放调参(本项目本地覆盖新增,用于花屏/延迟现场 A/B 试验)。
*
* <p>这些值由 App 侧在 {@code VideoPlayerController.initialize()} 之前通过 MethodChannel 下发,
* 播放器等创建时读取,因此**改动只对"下一次拉流"生效**,不需要重新编译。
*
* <p>字段保持默认值时,行为与未引入本类时一致(minBuffer 500 / maxBuffer 3000 / 起播 0 / UDP)。
*/
public final class PlaybackTuning {
private static final String TAG = "PlaybackTuning";
/** App 与插件约定的通道名。 */
public static final String CHANNEL = "plugins.flutter.dev/video_player_android/tuning";
/**
* RTSP 的 RTP 传输方式。{@code false} = UDP(Media3 默认,延迟低但空口丢包直接花屏); {@code true} =
* TCP interleaved(丢包由 TCP 重传兜住,画面完整,代价是弱链路下卡顿、延迟上升)。
*/
public static volatile boolean forceRtpTcp = false;
/**
* {@code DefaultLoadControl} 的 minBufferMs(= Loader 重新开始加载的水位)。 注意:Media3 内部有 500ms
* 硬下限({@code minBufferUs = max(minBufferUs, 500_000)}), 因此填小于 500 的值不会有任何效果。
*/
public static volatile int minBufferMs = 500;
/**
* {@code DefaultLoadControl} 的 maxBufferMs(= Loader 停止加载的水位,即稳态积压上限)。 加载水位在
* minBufferMs..maxBufferMs 之间锯齿,稳态平均积压约为两者中点, 所以这是"画面延迟"最直接的可调项。
*/
public static volatile int maxBufferMs = 3000;
/** 起播所需缓冲:直播保持 0,首帧到达即渲染。 */
public static volatile int bufferForPlaybackMs = 0;
/** rebuffer 后恢复播放所需缓冲:直播保持 0,避免每次卡完再攒一段。 */
public static volatile int bufferForPlaybackAfterRebufferMs = 0;
/**
* RtspMediaSource 的超时(毫秒)。0 = 使用 Media3 默认值。 它同时影响"UDP 无数据时改用 TCP 重试"以及"多久没收到数据判为流结束",
* 设得过小会在弱链路上误判断流。
*/
public static volatile int rtspTimeoutMs = 0;
/**
* {@code DefaultLoadControl.setTargetBufferBytes}:按字节封顶的加载上限。 0 = 不覆盖,用 Media3 默认(视频约 2MB)。
*
* <p>为什么直播也要管它:加载器是"时间水位到了<b>或</b>字节数到了"就停止加载。子码流下 2MB 相当于十几秒, 时间水位先撞上,字节上限无关;
* 但换主码流/高码率后 2MB 可能不到 1 秒,于是"看起来只缓冲了几百 ms 就不再加载" → 频繁 rebuffer。 高码率场景要把它调大(如 8~16MB)。
*/
public static volatile int targetBufferBytes = 0;
/** 解码方式:硬件优先(Media3 默认)。 */
public static final int DECODER_HARDWARE_PREFERRED = 0;
/** 解码方式:只用软件解码器。用于排查"硬解对损坏码流的容错差异",代价是功耗与高分辨率下跟不上。 */
public static final int DECODER_SOFTWARE_ONLY = 1;
/** 解码方式:硬件优先,初始化失败时回退软件解码。 */
public static final int DECODER_HARDWARE_WITH_FALLBACK = 2;
/**
* 解码方式(见上面三个常量)。Media3 不传 RenderersFactory 时就是 {@code DefaultRenderersFactory} + {@code
* MediaCodecSelector.DEFAULT},硬件优先,且硬解初始化失败<b>不会</b>自动回退软解。
*/
public static volatile int decoderMode = DECODER_HARDWARE_PREFERRED;
private PlaybackTuning() {}
/**
* 注册调参通道。由 {@link VideoPlayerPlugin#onAttachedToEngine} 调用。
*
* @param messenger 引擎的 BinaryMessenger。
*/
public static void setUp(@NonNull BinaryMessenger messenger) {
MethodChannel channel = new MethodChannel(messenger, CHANNEL);
channel.setMethodCallHandler(
(MethodCall call, MethodChannel.Result result) -> {
switch (call.method) {
case "set": {
applyArgs(call.arguments());
result.success(describe());
break;
}
case "get":
result.success(describe());
break;
case "reset":
resetDefaults();
result.success(describe());
break;
default:
result.notImplemented();
}
});
}
/** 注销通道(engine detach 时调用,避免残留 handler)。 */
public static void tearDown(@NonNull BinaryMessenger messenger) {
new MethodChannel(messenger, CHANNEL).setMethodCallHandler(null);
}
private static void resetDefaults() {
forceRtpTcp = false;
minBufferMs = 500;
maxBufferMs = 3000;
bufferForPlaybackMs = 0;
bufferForPlaybackAfterRebufferMs = 0;
rtspTimeoutMs = 0;
targetBufferBytes = 0;
decoderMode = DECODER_HARDWARE_PREFERRED;
}
@SuppressWarnings("unchecked")
private static void applyArgs(@Nullable Object rawArgs) {
if (!(rawArgs instanceof Map)) {
Log.w(TAG, "set 参数不是 Map,忽略:" + rawArgs);
return;
}
Map<Object, Object> args = (Map<Object, Object>) rawArgs;
if (args.containsKey("forceRtpTcp")) {
forceRtpTcp = Boolean.TRUE.equals(args.get("forceRtpTcp"));
}
minBufferMs = intArg(args, "minBufferMs", minBufferMs);
maxBufferMs = intArg(args, "maxBufferMs", maxBufferMs);
bufferForPlaybackMs = intArg(args, "bufferForPlaybackMs", bufferForPlaybackMs);
bufferForPlaybackAfterRebufferMs =
intArg(args, "bufferForPlaybackAfterRebufferMs", bufferForPlaybackAfterRebufferMs);
rtspTimeoutMs = intArg(args, "rtspTimeoutMs", rtspTimeoutMs);
targetBufferBytes = intArg(args, "targetBufferBytes", targetBufferBytes);
decoderMode = intArg(args, "decoderMode", decoderMode);
// Media3 构造函数里有 assertGreaterOrEqual(maxBufferMs, minBufferMs),
// 这里提前夹紧,避免 App 填出非法组合直接抛异常导致黑屏。
if (maxBufferMs < minBufferMs) {
maxBufferMs = minBufferMs;
}
Log.i(TAG, "已应用调参 -> " + describe());
}
private static int intArg(Map<Object, Object> args, String key, int fallback) {
Object v = args.get(key);
if (v instanceof Number) {
return ((Number) v).intValue();
}
return fallback;
}
/** 当前生效值,用于回显给 App 侧。 */
public static Map<String, Object> describe() {
Map<String, Object> out = new HashMap<>();
out.put("forceRtpTcp", forceRtpTcp);
out.put("minBufferMs", minBufferMs);
out.put("maxBufferMs", maxBufferMs);
out.put("bufferForPlaybackMs", bufferForPlaybackMs);
out.put("bufferForPlaybackAfterRebufferMs", bufferForPlaybackAfterRebufferMs);
out.put("rtspTimeoutMs", rtspTimeoutMs);
out.put("targetBufferBytes", targetBufferBytes);
out.put("decoderMode", decoderMode);
return out;
}
/**
* 按当前 {@link #decoderMode} 构造 RenderersFactory,供两处 ExoPlayer.Builder 共用。
*
* @param context application context。
* @return 配置好的 RenderersFactory。
*/
@UnstableApi
@NonNull
public static DefaultRenderersFactory buildRenderersFactory(@NonNull Context context) {
DefaultRenderersFactory factory = new DefaultRenderersFactory(context);
// 硬解初始化失败是否回退软解。Media3 默认 false:机型缺对应硬解时直接报错黑屏,
// 而不是慢慢软解。H265 在部分机型上只有软解,打开这一档能"播得上"但可能跟不上。
factory.setEnableDecoderFallback(decoderMode == DECODER_HARDWARE_WITH_FALLBACK);
if (decoderMode == DECODER_SOFTWARE_ONLY) {
factory.setMediaCodecSelector(SOFTWARE_ONLY_SELECTOR);
}
Log.i(TAG, "RenderersFactory: decoderMode=" + decoderMode);
return factory;
}
/** 只保留软件解码器;若过滤后为空(极少数 ROM 报不出软解)则退回原列表,保证不播不出画面。 */
private static final MediaCodecSelector SOFTWARE_ONLY_SELECTOR =
(String mimeType, boolean requiresSecureDecoder, boolean requiresTunnelingDecoder) -> {
List<MediaCodecInfo> all =
MediaCodecSelector.DEFAULT.getDecoderInfos(
mimeType, requiresSecureDecoder, requiresTunnelingDecoder);
List<MediaCodecInfo> software = new ArrayList<>();
for (MediaCodecInfo info : all) {
// 注意:Media3 1.x 的 softwareOnly / hardwareAccelerated 是字段,不是 getter。
if (info.softwareOnly) {
software.add(info);
}
}
Log.i(
TAG,
"软解筛选 " + mimeType + ": 候选" + all.size() + " 个,软解" + software.size() + " 个");
return software.isEmpty() ? all : software;
};
}

View File

@@ -0,0 +1,81 @@
// Copyright 2013 The Flutter Authors
// 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 java.util.ArrayList;
/**
* A wrapper for {@link PigeonEventSink} which can queue messages.
*
* <p>It delivers messages immediately when downstream is available, but it queues messages before
* the delegate event sink is set with setDelegate.
*
* <p>This class is not thread-safe. All calls must be done on the same thread or synchronized
* externally.
*/
final class QueuingEventSink {
private PigeonEventSink<PlatformVideoEvent> delegate;
private final ArrayList<Object> eventQueue = new ArrayList<>();
private boolean done = false;
public void setDelegate(PigeonEventSink<PlatformVideoEvent> delegate) {
this.delegate = delegate;
maybeFlush();
}
public void endOfStream() {
enqueue(new EndOfStreamEvent());
maybeFlush();
done = true;
}
public void error(String code, String message, Object details) {
enqueue(new ErrorEvent(code, message, details));
maybeFlush();
}
public void success(PlatformVideoEvent 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((PlatformVideoEvent) 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;
}
}
}

View File

@@ -0,0 +1,42 @@
// Copyright 2013 The Flutter Authors
// 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
@NonNull
public MediaSource.Factory getMediaSourceFactory(@NonNull Context context) {
RtspMediaSource.Factory factory = new RtspMediaSource.Factory();
// 本项目本地覆盖新增:两个策略可现场切换,默认值保持 Media3 原有行为。
// forceRtpTcp=false → UDP(Media3 默认):延迟低,但图传/空口丢包直接表现为花屏;
// forceRtpTcp=true → TCP interleaved:丢包由 TCP 重传兜住,画面完整,代价是卡顿与延迟上升。
factory.setForceUseRtpTcp(PlaybackTuning.forceRtpTcp);
// 0 表示不覆盖,用 Media3 默认超时;调小会加快“无数据→判流结束”,但弱链路易误判断流。
if (PlaybackTuning.rtspTimeoutMs > 0) {
factory.setTimeoutMs(PlaybackTuning.rtspTimeoutMs);
}
return factory;
}
}

View File

@@ -0,0 +1,99 @@
// Copyright 2013 The Flutter Authors
// 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<String, String> httpHeaders,
@Nullable String userAgent) {
return new HttpVideoAsset(remoteUrl, streamingFormat, new HashMap<>(httpHeaders), userAgent);
}
/**
* 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
}
}

View File

@@ -0,0 +1,242 @@
// Copyright 2013 The Flutter Authors
// 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.Format;
import androidx.media3.common.MediaItem;
import androidx.media3.common.PlaybackParameters;
import androidx.media3.common.TrackGroup;
import androidx.media3.common.TrackSelectionOverride;
import androidx.media3.common.Tracks;
import androidx.media3.common.util.UnstableApi;
import androidx.media3.exoplayer.ExoPlayer;
import androidx.media3.exoplayer.trackselection.DefaultTrackSelector;
import io.flutter.view.TextureRegistry.SurfaceProducer;
import java.util.ArrayList;
import java.util.List;
/**
* A class responsible for managing video playback using {@link ExoPlayer}.
*
* <p>It provides methods to control playback, adjust volume, and handle seeking.
*/
public abstract class VideoPlayer implements VideoPlayerInstanceApi {
@NonNull protected final VideoPlayerCallbacks videoPlayerEvents;
@Nullable protected final SurfaceProducer surfaceProducer;
@Nullable private DisposeHandler disposeHandler;
@NonNull protected ExoPlayer exoPlayer;
// TODO: Migrate to stable API, see https://github.com/flutter/flutter/issues/147039.
@UnstableApi @Nullable protected DefaultTrackSelector trackSelector;
/** 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();
}
/** A handler to run when dispose is called. */
public interface DisposeHandler {
void onDispose();
}
// TODO: Migrate to stable API, see https://github.com/flutter/flutter/issues/147039.
@UnstableApi
// Error thrown for this-escape warning on JDK 21+ due to https://bugs.openjdk.org/browse/JDK-8015831.
// Keeping behavior as-is and addressing the warning could cause a regression: https://github.com/flutter/packages/pull/10193
@SuppressWarnings("this-escape")
public VideoPlayer(
@NonNull VideoPlayerCallbacks events,
@NonNull MediaItem mediaItem,
@NonNull VideoPlayerOptions options,
@Nullable SurfaceProducer surfaceProducer,
@NonNull ExoPlayerProvider exoPlayerProvider) {
this.videoPlayerEvents = events;
this.surfaceProducer = surfaceProducer;
exoPlayer = exoPlayerProvider.get();
// Try to get the track selector from the ExoPlayer if it was built with one
if (exoPlayer.getTrackSelector() instanceof DefaultTrackSelector) {
trackSelector = (DefaultTrackSelector) exoPlayer.getTrackSelector();
}
exoPlayer.setMediaItem(mediaItem);
exoPlayer.prepare();
exoPlayer.addListener(createExoPlayerEventListener(exoPlayer, surfaceProducer));
setAudioAttributes(exoPlayer, options.mixWithOthers);
}
public void setDisposeHandler(@Nullable DisposeHandler handler) {
disposeHandler = handler;
}
@NonNull
protected abstract ExoPlayerEventListener createExoPlayerEventListener(
@NonNull ExoPlayer exoPlayer, @Nullable SurfaceProducer surfaceProducer);
private static void setAudioAttributes(ExoPlayer exoPlayer, boolean isMixMode) {
exoPlayer.setAudioAttributes(
new AudioAttributes.Builder().setContentType(C.AUDIO_CONTENT_TYPE_MOVIE).build(),
!isMixMode);
}
@Override
public void play() {
exoPlayer.play();
}
@Override
public void pause() {
exoPlayer.pause();
}
@Override
public void setLooping(boolean looping) {
exoPlayer.setRepeatMode(looping ? REPEAT_MODE_ALL : REPEAT_MODE_OFF);
}
@Override
public void setVolume(double volume) {
float bracketedValue = (float) Math.max(0.0, Math.min(1.0, volume));
exoPlayer.setVolume(bracketedValue);
}
@Override
public void setPlaybackSpeed(double speed) {
// 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) speed);
exoPlayer.setPlaybackParameters(playbackParameters);
}
@Override
public long getCurrentPosition() {
return exoPlayer.getCurrentPosition();
}
@Override
public long getBufferedPosition() {
return exoPlayer.getBufferedPosition();
}
@Override
public void seekTo(long position) {
exoPlayer.seekTo(position);
}
@NonNull
public ExoPlayer getExoPlayer() {
return exoPlayer;
}
// TODO: Migrate to stable API, see https://github.com/flutter/flutter/issues/147039.
@UnstableApi
@Override
public @NonNull NativeAudioTrackData getAudioTracks() {
List<ExoPlayerAudioTrackData> audioTracks = new ArrayList<>();
// Get the current tracks from ExoPlayer
Tracks tracks = exoPlayer.getCurrentTracks();
// Iterate through all track groups
for (int groupIndex = 0; groupIndex < tracks.getGroups().size(); groupIndex++) {
Tracks.Group group = tracks.getGroups().get(groupIndex);
// Only process audio tracks
if (group.getType() == C.TRACK_TYPE_AUDIO) {
for (int trackIndex = 0; trackIndex < group.length; trackIndex++) {
Format format = group.getTrackFormat(trackIndex);
boolean isSelected = group.isTrackSelected(trackIndex);
// Create audio track data with metadata
ExoPlayerAudioTrackData audioTrack =
new ExoPlayerAudioTrackData(
(long) groupIndex,
(long) trackIndex,
format.label,
format.language,
isSelected,
format.bitrate != Format.NO_VALUE ? (long) format.bitrate : null,
format.sampleRate != Format.NO_VALUE ? (long) format.sampleRate : null,
format.channelCount != Format.NO_VALUE ? (long) format.channelCount : null,
format.codecs != null ? format.codecs : null);
audioTracks.add(audioTrack);
}
}
}
return new NativeAudioTrackData(audioTracks);
}
// TODO: Migrate to stable API, see https://github.com/flutter/flutter/issues/147039.
@UnstableApi
@Override
public void selectAudioTrack(long groupIndex, long trackIndex) {
if (trackSelector == null) {
throw new IllegalStateException("Cannot select audio track: track selector is null");
}
// Get current tracks
Tracks tracks = exoPlayer.getCurrentTracks();
if (groupIndex < 0 || groupIndex >= tracks.getGroups().size()) {
throw new IllegalArgumentException(
"Cannot select audio track: groupIndex "
+ groupIndex
+ " is out of bounds (available groups: "
+ tracks.getGroups().size()
+ ")");
}
Tracks.Group group = tracks.getGroups().get((int) groupIndex);
// Verify it's an audio track
if (group.getType() != C.TRACK_TYPE_AUDIO) {
throw new IllegalArgumentException(
"Cannot select audio track: group at index "
+ groupIndex
+ " is not an audio track (type: "
+ group.getType()
+ ")");
}
// Verify the track index is valid
if (trackIndex < 0 || (int) trackIndex >= group.length) {
throw new IllegalArgumentException(
"Cannot select audio track: trackIndex "
+ trackIndex
+ " is out of bounds (available tracks in group: "
+ group.length
+ ")");
}
// Get the track group and create a selection override
TrackGroup trackGroup = group.getMediaTrackGroup();
TrackSelectionOverride override = new TrackSelectionOverride(trackGroup, (int) trackIndex);
// Apply the track selection override
trackSelector.setParameters(
trackSelector.buildUponParameters().setOverrideForType(override).build());
}
public void dispose() {
if (disposeHandler != null) {
disposeHandler.onDispose();
}
exoPlayer.release();
}
}

View File

@@ -0,0 +1,29 @@
// Copyright 2013 The Flutter Authors
// 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}.
*
* <p>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.
*
* <p>See {@link androidx.media3.common.Player.Listener} for details.
*/
public interface VideoPlayerCallbacks {
void onInitialized(int width, int height, long durationInMs, int rotationCorrectionInDegrees);
void onPlaybackStateChanged(@NonNull PlatformPlaybackState state);
void onError(@NonNull String code, @Nullable String message, @Nullable Object details);
void onIsPlayingStateUpdate(boolean isPlaying);
void onAudioTrackChanged(@Nullable String selectedTrackId);
}

View File

@@ -0,0 +1,71 @@
// Copyright 2013 The Flutter Authors
// 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.BinaryMessenger;
final class VideoPlayerEventCallbacks implements VideoPlayerCallbacks {
private final QueuingEventSink eventSink;
static VideoPlayerEventCallbacks bindTo(
@NonNull BinaryMessenger binaryMessenger, @NonNull String identifier) {
QueuingEventSink eventSink = new QueuingEventSink();
VideoEventsStreamHandler.Companion.register(
binaryMessenger,
new VideoEventsStreamHandler() {
@Override
public void onListen(
Object arguments, @NonNull PigeonEventSink<PlatformVideoEvent> events) {
eventSink.setDelegate(events);
}
@Override
public void onCancel(Object arguments) {
eventSink.setDelegate(null);
}
},
identifier);
return VideoPlayerEventCallbacks.withSink(eventSink);
}
@VisibleForTesting
static VideoPlayerEventCallbacks withSink(QueuingEventSink eventSink) {
return new VideoPlayerEventCallbacks(eventSink);
}
private VideoPlayerEventCallbacks(QueuingEventSink eventSink) {
this.eventSink = eventSink;
}
@Override
public void onInitialized(
int width, int height, long durationInMs, int rotationCorrectionInDegrees) {
eventSink.success(
new InitializationEvent(durationInMs, width, height, rotationCorrectionInDegrees));
}
@Override
public void onPlaybackStateChanged(@NonNull PlatformPlaybackState state) {
eventSink.success(new PlaybackStateChangeEvent(state));
}
@Override
public void onError(@NonNull String code, @Nullable String message, @Nullable Object details) {
eventSink.error(code, message, details);
}
@Override
public void onIsPlayingStateUpdate(boolean isPlaying) {
eventSink.success(new IsPlayingStateEvent(isPlaying));
}
@Override
public void onAudioTrackChanged(@Nullable String selectedTrackId) {
eventSink.success(new AudioTrackChangedEvent(selectedTrackId));
}
}

View File

@@ -0,0 +1,9 @@
// Copyright 2013 The Flutter Authors
// 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;
}

View File

@@ -0,0 +1,234 @@
// Copyright 2013 The Flutter Authors
// 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 androidx.annotation.Nullable;
import androidx.annotation.OptIn;
import androidx.media3.common.util.UnstableApi;
import io.flutter.FlutterInjector;
import io.flutter.Log;
import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.plugin.common.BinaryMessenger;
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<VideoPlayer> videoPlayers = new LongSparseArray<>();
private FlutterState flutterState;
private final VideoPlayerOptions sharedOptions = new VideoPlayerOptions();
private long nextPlayerIdentifier = 1;
/** 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());
// 本项目本地覆盖新增:注册直播调参通道(RTSP 传输方式 / LoadControl 水位),供 App 现场 A/B。
PlaybackTuning.setUp(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());
PlaybackTuning.tearDown(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();
}
@OptIn(markerClass = UnstableApi.class)
@Override
public long createForPlatformView(@NonNull CreationOptions options) {
final VideoAsset videoAsset = videoAssetWithOptions(options);
long id = nextPlayerIdentifier++;
final String streamInstance = Long.toString(id);
VideoPlayer videoPlayer =
PlatformViewVideoPlayer.create(
flutterState.applicationContext,
VideoPlayerEventCallbacks.bindTo(flutterState.binaryMessenger, streamInstance),
videoAsset,
sharedOptions);
registerPlayerInstance(videoPlayer, id);
return id;
}
@OptIn(markerClass = UnstableApi.class)
@Override
public @NonNull TexturePlayerIds createForTextureView(@NonNull CreationOptions options) {
final VideoAsset videoAsset = videoAssetWithOptions(options);
long id = nextPlayerIdentifier++;
final String streamInstance = Long.toString(id);
TextureRegistry.SurfaceProducer handle = flutterState.textureRegistry.createSurfaceProducer();
VideoPlayer videoPlayer =
TextureVideoPlayer.create(
flutterState.applicationContext,
VideoPlayerEventCallbacks.bindTo(flutterState.binaryMessenger, streamInstance),
handle,
videoAsset,
sharedOptions);
registerPlayerInstance(videoPlayer, id);
return new TexturePlayerIds(id, handle.id());
}
private @NonNull VideoAsset videoAssetWithOptions(@NonNull CreationOptions options) {
final @NonNull String uri = options.getUri();
if (uri.startsWith("asset:")) {
return VideoAsset.fromAssetUrl(uri);
} else if (uri.startsWith("rtsp:")) {
return VideoAsset.fromRtspUrl(uri);
} else {
VideoAsset.StreamingFormat streamingFormat = VideoAsset.StreamingFormat.UNKNOWN;
PlatformVideoFormat formatHint = options.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;
}
}
return VideoAsset.fromRemoteUrl(
uri, streamingFormat, options.getHttpHeaders(), options.getUserAgent());
}
}
private void registerPlayerInstance(VideoPlayer player, long id) {
// Set up the instance-specific API handler, and make sure it is removed when the player is
// disposed.
BinaryMessenger messenger = flutterState.binaryMessenger;
final String channelSuffix = Long.toString(id);
VideoPlayerInstanceApi.Companion.setUp(messenger, player, channelSuffix);
player.setDisposeHandler(
() -> VideoPlayerInstanceApi.Companion.setUp(messenger, null, channelSuffix));
videoPlayers.put(id, player);
}
@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(long playerId) {
VideoPlayer player = getPlayer(playerId);
player.dispose();
videoPlayers.remove(playerId);
}
@Override
public void setMixWithOthers(boolean mixWithOthers) {
sharedOptions.mixWithOthers = mixWithOthers;
}
@Override
public @NonNull String getLookupKeyForAsset(@NonNull String asset, @Nullable String packageName) {
return packageName == null
? flutterState.keyForAsset.get(asset)
: flutterState.keyForAssetAndPackageName.get(asset, packageName);
}
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.Companion.setUp(messenger, methodCallHandler);
}
void stopListening(BinaryMessenger messenger) {
AndroidVideoPlayerApi.Companion.setUp(messenger, null);
}
}
}

View File

@@ -0,0 +1,94 @@
// Copyright 2013 The Flutter Authors
// 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();
}
}

View File

@@ -0,0 +1,69 @@
// Copyright 2013 The Flutter Authors
// 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.AndroidVideoPlayerApi;
import io.flutter.plugins.videoplayer.PlatformVideoViewCreationParams;
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(AndroidVideoPlayerApi.Companion.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 PlatformVideoViewCreationParams params =
Objects.requireNonNull((PlatformVideoViewCreationParams) args);
final Long playerId = params.getPlayerId();
final VideoPlayer player = videoPlayerProvider.getVideoPlayer(playerId);
final ExoPlayer exoPlayer = player.getExoPlayer();
return new PlatformVideoView(context, exoPlayer);
}
}

View File

@@ -0,0 +1,45 @@
// Copyright 2013 The Flutter Authors
// 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.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 {
public PlatformViewExoPlayerEventListener(
@NonNull ExoPlayer exoPlayer, @NonNull VideoPlayerCallbacks events) {
super(exoPlayer, events);
}
@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());
}
}

View File

@@ -0,0 +1,95 @@
// Copyright 2013 The Flutter Authors
// 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.common.util.UnstableApi;
import androidx.media3.exoplayer.DefaultLoadControl;
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 {
// TODO: Migrate to stable API, see https://github.com/flutter/flutter/issues/147039.
@UnstableApi
@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.
*/
// TODO: Migrate to stable API, see https://github.com/flutter/flutter/issues/147039.
@UnstableApi
@NonNull
public static PlatformViewVideoPlayer create(
@NonNull Context context,
@NonNull VideoPlayerCallbacks events,
@NonNull VideoAsset asset,
@NonNull VideoPlayerOptions options) {
return new PlatformViewVideoPlayer(
events,
asset.getMediaItem(),
options,
() -> {
androidx.media3.exoplayer.trackselection.DefaultTrackSelector trackSelector =
new androidx.media3.exoplayer.trackselection.DefaultTrackSelector(context);
// 直播低延迟:四个水位参数由 App 侧通过 PlaybackTuning 下发(默认 500/3000/0/0)。
// 与 TextureVideoPlayer 保持一致:maxBufferMs 是稳态积压上限,
// 平均积压约为 (minBufferMs + maxBufferMs) / 2;bufferForPlaybackMs=0 保证首帧即渲染。
DefaultLoadControl loadControl =
new DefaultLoadControl.Builder()
.setBufferDurationsMs(
/* minBufferMs= */ io.flutter.plugins.videoplayer.PlaybackTuning.minBufferMs,
/* maxBufferMs= */ io.flutter.plugins.videoplayer.PlaybackTuning.maxBufferMs,
/* bufferForPlaybackMs= */
io.flutter.plugins.videoplayer.PlaybackTuning.bufferForPlaybackMs,
/* bufferForPlaybackAfterRebufferMs= */
io.flutter.plugins.videoplayer.PlaybackTuning.bufferForPlaybackAfterRebufferMs)
.setTargetBufferBytes(
io.flutter.plugins.videoplayer.PlaybackTuning.targetBufferBytes)
.build();
ExoPlayer.Builder builder =
new ExoPlayer.Builder(context)
.setTrackSelector(trackSelector)
// 与 TextureVideoPlayer 一致:解码方式运行时可调。
.setRenderersFactory(
io.flutter.plugins.videoplayer.PlaybackTuning.buildRenderersFactory(context))
.setMediaSourceFactory(asset.getMediaSourceFactory(context))
.setLoadControl(loadControl);
return builder.build();
});
}
@NonNull
@Override
protected ExoPlayerEventListener createExoPlayerEventListener(
@NonNull ExoPlayer exoPlayer, @Nullable SurfaceProducer surfaceProducer) {
return new PlatformViewExoPlayerEventListener(exoPlayer, videoPlayerEvents);
}
}

View File

@@ -0,0 +1,62 @@
// Copyright 2013 The Flutter Authors
// 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 androidx.annotation.NonNull;
import androidx.annotation.OptIn;
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 final boolean surfaceProducerHandlesCropAndRotation;
public TextureExoPlayerEventListener(
@NonNull ExoPlayer exoPlayer,
@NonNull VideoPlayerCallbacks events,
boolean surfaceProducerHandlesCropAndRotation) {
super(exoPlayer, events);
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) {
// When the SurfaceTexture backend for Impeller is used, the preview should already
// be correctly rotated.
if (!surfaceProducerHandlesCropAndRotation) {
// 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());
}
@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;
}
}

View File

@@ -0,0 +1,148 @@
// Copyright 2013 The Flutter Authors
// 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 android.view.Surface;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RestrictTo;
import androidx.annotation.VisibleForTesting;
import androidx.media3.common.MediaItem;
import androidx.media3.common.util.UnstableApi;
import androidx.media3.exoplayer.DefaultLoadControl;
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 texture view as a way of
* displaying the video in the app.
*
* <p>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 {
// True when the ExoPlayer instance has a null surface.
private boolean needsSurface = true;
/**
* 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.
*/
// TODO: Migrate to stable API, see https://github.com/flutter/flutter/issues/147039.
@UnstableApi
@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,
() -> {
androidx.media3.exoplayer.trackselection.DefaultTrackSelector trackSelector =
new androidx.media3.exoplayer.trackselection.DefaultTrackSelector(context);
// 直播低延迟:四个水位参数由 App 侧通过 PlaybackTuning 下发(默认 500/3000/0/0)。
// 依据 Media3 DefaultLoadControl 源码:
// - minBufferUs 有 500ms 硬下限,填更小不会生效;
// - Loader 在 minBufferMs..maxBufferMs 之间锯齿,maxBufferMs 是稳态积压上限,
// 平均积压约为 (minBufferMs + maxBufferMs) / 2;
// - bufferForPlaybackMs=0 才是“首帧到达即渲染”的关键。
// - targetBufferBytes 是另一条停止加载的条件(字节上限),0 = 用 Media3 默认;
// 主码流/高码率时默认约 2MB 会先于时间水位撞上,需调大。
DefaultLoadControl loadControl =
new DefaultLoadControl.Builder()
.setBufferDurationsMs(
/* minBufferMs= */ io.flutter.plugins.videoplayer.PlaybackTuning.minBufferMs,
/* maxBufferMs= */ io.flutter.plugins.videoplayer.PlaybackTuning.maxBufferMs,
/* bufferForPlaybackMs= */
io.flutter.plugins.videoplayer.PlaybackTuning.bufferForPlaybackMs,
/* bufferForPlaybackAfterRebufferMs= */
io.flutter.plugins.videoplayer.PlaybackTuning.bufferForPlaybackAfterRebufferMs)
.setTargetBufferBytes(
io.flutter.plugins.videoplayer.PlaybackTuning.targetBufferBytes)
.build();
ExoPlayer.Builder builder =
new ExoPlayer.Builder(context)
.setTrackSelector(trackSelector)
// 解码方式(硬解/软解/失败回退)也改成运行时可调,默认保持 Media3 原生行为。
.setRenderersFactory(
io.flutter.plugins.videoplayer.PlaybackTuning.buildRenderersFactory(context))
.setMediaSourceFactory(asset.getMediaSourceFactory(context))
.setLoadControl(loadControl);
return builder.build();
});
}
// TODO: Migrate to stable API, see https://github.com/flutter/flutter/issues/147039.
@UnstableApi
@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);
Surface surface = surfaceProducer.getSurface();
this.exoPlayer.setVideoSurface(surface);
needsSurface = surface == null;
}
@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);
}
@RestrictTo(RestrictTo.Scope.LIBRARY)
public void onSurfaceAvailable() {
if (needsSurface) {
// TextureVideoPlayer must always set a surfaceProducer.
assert surfaceProducer != null;
exoPlayer.setVideoSurface(surfaceProducer.getSurface());
needsSurface = false;
}
}
@RestrictTo(RestrictTo.Scope.LIBRARY)
public void onSurfaceCleanup() {
exoPlayer.setVideoSurface(null);
needsSurface = true;
}
public void dispose() {
// Super must be called first to ensure the player is released before the surface.
super.dispose();
// TextureVideoPlayer must always set a surfaceProducer.
assert surfaceProducer != null;
surfaceProducer.release();
}
}

View File

@@ -0,0 +1,115 @@
// Copyright 2013 The Flutter Authors
// 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.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.verifyNoMoreInteractions;
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}.
*
* <p>This test suite <em>narrowly verifies</em> 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 TestExoPlayerEventListener 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 {
private boolean calledSendInitialized = false;
public TestExoPlayerEventListener(ExoPlayer exoPlayer, VideoPlayerCallbacks callbacks) {
super(exoPlayer, callbacks);
}
@Override
protected void sendInitialized() {
calledSendInitialized = true;
}
boolean calledSendInitialized() {
return calledSendInitialized;
}
}
@Before
public void setUp() {
eventListener = new TestExoPlayerEventListener(mockExoPlayer, mockCallbacks);
}
@Test
public void onPlaybackStateChangedBufferingSendsBuffering() {
eventListener.onPlaybackStateChanged(Player.STATE_BUFFERING);
verify(mockCallbacks).onPlaybackStateChanged(PlatformPlaybackState.BUFFERING);
verifyNoMoreInteractions(mockCallbacks);
}
@Test
public void onPlaybackStateChangedEndedSendsEnded() {
eventListener.onPlaybackStateChanged(Player.STATE_ENDED);
verify(mockCallbacks).onPlaybackStateChanged(PlatformPlaybackState.ENDED);
verifyNoMoreInteractions(mockCallbacks);
}
@Test
public void onPlaybackStateChangedIdleSendsIdle() {
eventListener.onPlaybackStateChanged(Player.STATE_IDLE);
verify(mockCallbacks).onPlaybackStateChanged(PlatformPlaybackState.IDLE);
verifyNoMoreInteractions(mockCallbacks);
}
@Test
public void onPlaybackStateChangedReadySendsInitializedAndReady() {
eventListener.onPlaybackStateChanged(Player.STATE_READY);
verify(mockCallbacks).onPlaybackStateChanged(PlatformPlaybackState.READY);
verifyNoMoreInteractions(mockCallbacks);
assertTrue(eventListener.calledSendInitialized());
}
@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);
}
}

View File

@@ -0,0 +1,37 @@
// Copyright 2013 The Flutter Authors
// 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;
}
}

View File

@@ -0,0 +1,45 @@
// Copyright 2013 The Flutter Authors
// 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 androidx.test.core.app.ApplicationProvider;
import io.flutter.plugin.platform.PlatformView;
import io.flutter.plugins.videoplayer.platformview.PlatformVideoView;
import io.flutter.plugins.videoplayer.platformview.PlatformVideoViewFactory;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
@RunWith(RobolectricTestRunner.class)
public class PlatformVideoViewFactoryTest {
@Test
public void createsPlatformVideoViewBasedOnSuppliedArguments() {
final PlatformVideoViewFactory.VideoPlayerProvider videoPlayerProvider =
mock(PlatformVideoViewFactory.VideoPlayerProvider.class);
final VideoPlayer videoPlayer = mock(VideoPlayer.class);
final Context context = ApplicationProvider.getApplicationContext();
final ExoPlayer exoPlayer = new ExoPlayer.Builder(context).build();
final long playerId = 1L;
when(videoPlayerProvider.getVideoPlayer(playerId)).thenReturn(videoPlayer);
when(videoPlayer.getExoPlayer()).thenReturn(exoPlayer);
final PlatformVideoViewFactory factory = new PlatformVideoViewFactory(videoPlayerProvider);
final PlatformVideoViewCreationParams args = new PlatformVideoViewCreationParams(playerId);
final PlatformView view = factory.create(context, 0, args);
assertTrue(view instanceof PlatformVideoView);
verify(videoPlayerProvider).getVideoPlayer(playerId);
verify(videoPlayer).getExoPlayer();
exoPlayer.release();
}
}

View File

@@ -0,0 +1,39 @@
// Copyright 2013 The Flutter Authors
// 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 androidx.test.core.app.ApplicationProvider;
import io.flutter.plugins.videoplayer.platformview.PlatformVideoView;
import java.lang.reflect.Field;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
/** Unit tests for {@link PlatformVideoViewTest}. */
@RunWith(RobolectricTestRunner.class)
public class PlatformVideoViewTest {
@Test
public void createsSurfaceViewAndSetsItForExoPlayer() throws Exception {
final Context context = ApplicationProvider.getApplicationContext();
final ExoPlayer exoPlayer = spy(new ExoPlayer.Builder(context).build());
final PlatformVideoView view = new PlatformVideoView(context, exoPlayer);
final Field field = PlatformVideoView.class.getDeclaredField("surfaceView");
field.setAccessible(true);
final SurfaceView surfaceView = (SurfaceView) field.get(view);
assertNotNull(surfaceView);
verify(exoPlayer).setVideoSurfaceView(surfaceView);
exoPlayer.release();
}
}

View File

@@ -0,0 +1,80 @@
// Copyright 2013 The Flutter Authors
// 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}.
*
* <p>This test suite <em>narrowly verifies</em> 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);
}
}

View File

@@ -0,0 +1,127 @@
// Copyright 2013 The Flutter Authors
// 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;
/**
* Unit tests for {@link TextureExoPlayerEventListener}.
*
* <p>This test suite <em>narrowly verifies</em> 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
public void
onPlaybackStateChangedReadySendInitialized_whenSurfaceProducerHandlesCropAndRotation() {
TextureExoPlayerEventListener eventListener =
new TextureExoPlayerEventListener(mockExoPlayer, mockCallbacks, true);
VideoSize size = new VideoSize(800, 400, 0);
when(mockExoPlayer.getVideoSize()).thenReturn(size);
when(mockExoPlayer.getDuration()).thenReturn(10L);
eventListener.onPlaybackStateChanged(Player.STATE_READY);
verify(mockCallbacks).onInitialized(800, 400, 10L, 0);
}
@Test
public void
onPlaybackStateChangedReadySendInitializedWithRotationCorrectionAndWidthAndHeightSwap_whenSurfaceProducerDoesNotHandleCropAndRotation() {
TextureExoPlayerEventListener eventListener =
new TextureExoPlayerEventListener(mockExoPlayer, mockCallbacks, false);
VideoSize size = new VideoSize(800, 400, 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
public void
onPlaybackStateChangedReadyInPortraitMode90DegreesDoesNotSwapWidthAndHeight_whenSurfaceProducerHandlesCropAndRotation() {
TextureExoPlayerEventListener eventListener =
new TextureExoPlayerEventListener(mockExoPlayer, mockCallbacks, true);
VideoSize size = new VideoSize(800, 400, 0);
when(mockExoPlayer.getVideoSize()).thenReturn(size);
when(mockExoPlayer.getDuration()).thenReturn(10L);
eventListener.onPlaybackStateChanged(Player.STATE_READY);
verify(mockCallbacks).onInitialized(800, 400, 10L, 0);
}
@Test
public void
onPlaybackStateChangedReadyInPortraitMode90DegreesSwapWidthAndHeight_whenSurfaceProducerDoesNotHandleCropAndRotation() {
TextureExoPlayerEventListener eventListener =
new TextureExoPlayerEventListener(mockExoPlayer, mockCallbacks, false);
VideoSize size = new VideoSize(800, 400, 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
public void
onPlaybackStateChangedReadyInPortraitMode270DegreesDoesNotSwapWidthAndHeight_whenSurfaceProducerHandlesCropAndRotation() {
TextureExoPlayerEventListener eventListener =
new TextureExoPlayerEventListener(mockExoPlayer, mockCallbacks, true);
VideoSize size = new VideoSize(800, 400, 0);
when(mockExoPlayer.getVideoSize()).thenReturn(size);
when(mockExoPlayer.getDuration()).thenReturn(10L);
eventListener.onPlaybackStateChanged(Player.STATE_READY);
verify(mockCallbacks).onInitialized(800, 400, 10L, 0);
}
@Test
public void
onPlaybackStateChangedReadyInPortraitMode270DegreesDoesNotSwapWidthAndHeight_whenSurfaceProducerDoesNotHandleCropAndRotation() {
TextureExoPlayerEventListener eventListener =
new TextureExoPlayerEventListener(mockExoPlayer, mockCallbacks, false);
VideoSize size = new VideoSize(800, 400, 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);
}
}

View File

@@ -0,0 +1,203 @@
// Copyright 2013 The Flutter Authors
// 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}.
*
* <p>This test suite <em>narrowly verifies</em> that {@link TextureVideoPlayer} interfaces with the
* {@link ExoPlayer} interface <em>exactly</em> 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 <em>"this is a safe refactor with no behavior changes"</em>.
*/
@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<AudioAttributes> attributesCaptor;
@Captor private ArgumentCaptor<TextureRegistry.SurfaceProducer.Callback> callbackCaptor;
@Captor private ArgumentCaptor<Player.Listener> 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(C.AUDIO_CONTENT_TYPE_MOVIE, attributesCaptor.getValue().contentType);
videoPlayer.dispose();
}
@Test
public void onSurfaceProducerCleanupAndAvailableRemovesAndRestoresSurface() {
VideoPlayer videoPlayer = createVideoPlayer();
verify(mockProducer).setCallback(callbackCaptor.capture());
verify(mockExoPlayer).setVideoSurface(notNull());
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();
producerLifecycle.onSurfaceCleanup();
verify(mockExoPlayer).setVideoSurface(null);
reset(mockExoPlayer);
producerLifecycle.onSurfaceAvailable();
verify(mockExoPlayer).setVideoSurface(notNull());
videoPlayer.dispose();
}
@Test
public void onSurfaceProducerCleanupDoesNotStopOrPauseVideo() {
VideoPlayer videoPlayer = createVideoPlayer();
verify(mockProducer).setCallback(callbackCaptor.capture());
TextureRegistry.SurfaceProducer.Callback producerLifecycle = callbackCaptor.getValue();
producerLifecycle.onSurfaceCleanup();
verify(mockExoPlayer, never()).stop();
verify(mockExoPlayer, never()).pause();
verify(mockExoPlayer, never()).setPlayWhenReady(anyBoolean());
videoPlayer.dispose();
}
@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 onSurfaceAvailable/Cleanup.
verify(mockProducer).setCallback(callbackCaptor.capture());
TextureRegistry.SurfaceProducer.Callback producerLifecycle = callbackCaptor.getValue();
verify(mockExoPlayer).addListener(listenerCaptor.capture());
Player.Listener listener = listenerCaptor.getValue();
// Trigger ready state, which should trigger initialization.
listener.onPlaybackStateChanged(Player.STATE_READY);
verify(mockEvents).onInitialized(anyInt(), anyInt(), anyLong(), anyInt());
// Trigger cleanup/available.
producerLifecycle.onSurfaceCleanup();
producerLifecycle.onSurfaceAvailable();
// It should still only have been called the one time.
verify(mockEvents).onInitialized(anyInt(), anyInt(), anyLong(), anyInt());
videoPlayer.dispose();
}
@Test
public void onSurfaceAvailableWithoutCleanupDoesNotRecreate() {
// 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/Cleanup.
verify(mockProducer).setCallback(callbackCaptor.capture());
TextureRegistry.SurfaceProducer.Callback producerLifecycle = callbackCaptor.getValue();
// Calling onSurfaceAvailable does not do anything, since the surface was never cleaned up.
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();
}
}

View File

@@ -0,0 +1,140 @@
// Copyright 2013 The Flutter Authors
// 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.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyMap;
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}.
*
* <p>This test suite <em>narrowly verifies</em> that the {@link VideoAsset} factory methods, {@link
* VideoAsset#fromRemoteUrl(String, VideoAsset.StreamingFormat, Map)} and {@link
* VideoAsset#fromAssetUrl(String)} follow the contract they have documented.
*
* <p>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(any())).thenReturn(httpFactory);
when(httpFactory.setAllowCrossProtocolRedirects(anyBoolean())).thenReturn(httpFactory);
when(httpFactory.setDefaultRequestProperties(anyMap())).thenReturn(httpFactory);
return httpFactory;
}
@Test
public void remoteVideoSetsUserAgentAndCrossProtocolRedirects() {
final String userAgent = "A User Agent";
VideoAsset asset =
VideoAsset.fromRemoteUrl(
"https://flutter.dev/video.mp4",
VideoAsset.StreamingFormat.UNKNOWN,
new HashMap<>(),
userAgent);
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(userAgent);
verify(mockFactory).setAllowCrossProtocolRedirects(true);
verify(mockFactory, never()).setDefaultRequestProperties(anyMap());
}
// 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<>(),
null);
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<String, String> headers = new HashMap<>();
headers.put("X-Cache-Forever", "true");
VideoAsset asset =
VideoAsset.fromRemoteUrl(
"https://flutter.dev/video.mp4", VideoAsset.StreamingFormat.UNKNOWN, headers, null);
DefaultHttpDataSource.Factory mockFactory = mockHttpFactory();
// Cast to HttpVideoAsset to call a testing-only method to intercept calls.
((HttpVideoAsset) asset)
.getMediaSourceFactory(ApplicationProvider.getApplicationContext(), mockFactory);
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"));
}
}

View File

@@ -0,0 +1,91 @@
// Copyright 2013 The Flutter Authors
// 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.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}.
*
* <p>This test suite <em>narrowly verifies</em> that calling the provided event callbacks, such as
* {@link VideoPlayerEventCallbacks#onPlaybackStateChanged(PlatformPlaybackState)}, produces the
* expected data as an encoded {@link Map}.
*
* <p>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<PlatformVideoEvent> eventCaptor;
@Rule public MockitoRule initRule = MockitoJUnit.rule();
@Before
public void setUp() {
eventCallbacks = VideoPlayerEventCallbacks.withSink(mockEventSink);
}
@Test
public void onInitializedSendsExpectedArguments() {
final int width = 800;
final int height = 600;
final long duration = 10L;
final int rotation = 180;
eventCallbacks.onInitialized(width, height, duration, rotation);
verify(mockEventSink).success(eventCaptor.capture());
PlatformVideoEvent actual = eventCaptor.getValue();
InitializationEvent expected = new InitializationEvent(duration, width, height, rotation);
assertEquals(expected, actual);
}
@Test
public void onPlaybackStateChanged() {
PlatformPlaybackState state = PlatformPlaybackState.READY;
eventCallbacks.onPlaybackStateChanged(state);
verify(mockEventSink).success(eventCaptor.capture());
PlatformVideoEvent actual = eventCaptor.getValue();
PlaybackStateChangeEvent expected = new PlaybackStateChangeEvent(state);
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());
PlatformVideoEvent actual = eventCaptor.getValue();
IsPlayingStateEvent expected = new IsPlayingStateEvent(true);
assertEquals(expected, actual);
}
}

View File

@@ -0,0 +1,114 @@
// Copyright 2013 The Flutter Authors
// 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.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<VideoPlayer> getVideoPlayers() throws Exception {
final Field field = VideoPlayerPlugin.class.getDeclaredField("videoPlayers");
field.setAccessible(true);
return (LongSparseArray<VideoPlayer>) 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<PlatformViewVideoPlayer> mockedPlatformViewVideoPlayerStatic =
mockStatic(PlatformViewVideoPlayer.class)) {
mockedPlatformViewVideoPlayerStatic
.when(() -> PlatformViewVideoPlayer.create(any(), any(), any(), any()))
.thenReturn(mock(PlatformViewVideoPlayer.class));
final CreationOptions options =
new CreationOptions(
"https://flutter.github.io/assets-for-api-docs/assets/videos/bee.mp4",
null,
new HashMap<>(),
null);
final long playerId = plugin.createForPlatformView(options);
final LongSparseArray<VideoPlayer> videoPlayers = getVideoPlayers();
assertTrue(videoPlayers.get(playerId) instanceof PlatformViewVideoPlayer);
}
}
@Test
public void createsTextureVideoPlayer() throws Exception {
try (MockedStatic<TextureVideoPlayer> mockedTextureVideoPlayerStatic =
mockStatic(TextureVideoPlayer.class)) {
mockedTextureVideoPlayerStatic
.when(() -> TextureVideoPlayer.create(any(), any(), any(), any(), any()))
.thenReturn(mock(TextureVideoPlayer.class));
final CreationOptions options =
new CreationOptions(
"https://flutter.github.io/assets-for-api-docs/assets/videos/bee.mp4",
null,
new HashMap<>(),
null);
final TexturePlayerIds ids = plugin.createForTextureView(options);
final LongSparseArray<VideoPlayer> videoPlayers = getVideoPlayers();
assertTrue(videoPlayers.get(ids.getPlayerId()) instanceof TextureVideoPlayer);
}
}
}

View File

@@ -0,0 +1,623 @@
// Copyright 2013 The Flutter Authors
// 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.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
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.common.TrackGroup;
import androidx.media3.common.TrackSelectionOverride;
import androidx.media3.common.Tracks;
import androidx.media3.exoplayer.ExoPlayer;
import androidx.media3.exoplayer.trackselection.DefaultTrackSelector;
import com.google.common.collect.ImmutableList;
import io.flutter.plugins.videoplayer.platformview.PlatformViewExoPlayerEventListener;
import io.flutter.view.TextureRegistry.SurfaceProducer;
import java.lang.reflect.Field;
import java.util.List;
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}.
*
* <p>This test suite <em>narrowly verifies</em> that {@link VideoPlayer} interfaces with the {@link
* ExoPlayer} interface <em>exactly</em> 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
* <em>"this is a safe refactor with no behavior changes"</em>.
*
* <p>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<AudioAttributes> attributesCaptor;
@Captor private ArgumentCaptor<Player.Listener> 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(C.AUDIO_CONTENT_TYPE_MOVIE, attributesCaptor.getValue().contentType);
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(C.AUDIO_CONTENT_TYPE_MOVIE, attributesCaptor.getValue().contentType);
videoPlayer.dispose();
}
@Test
public void playsAndPausesProvidedMedia() {
VideoPlayer videoPlayer = createVideoPlayer();
videoPlayer.play();
verify(mockExoPlayer).play();
videoPlayer.pause();
verify(mockExoPlayer).pause();
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 seekTo() {
VideoPlayer videoPlayer = createVideoPlayer();
videoPlayer.seekTo(10L);
verify(mockExoPlayer).seekTo(10);
videoPlayer.dispose();
}
@Test
public void getCurrentPosition() {
VideoPlayer videoPlayer = createVideoPlayer();
final long playbackPosition = 20L;
when(mockExoPlayer.getCurrentPosition()).thenReturn(playbackPosition);
final Long position = videoPlayer.getCurrentPosition();
assertEquals(playbackPosition, position.longValue());
videoPlayer.dispose();
}
@Test
public void getBufferedPosition() {
VideoPlayer videoPlayer = createVideoPlayer();
final long bufferedPosition = 10L;
when(mockExoPlayer.getBufferedPosition()).thenReturn(bufferedPosition);
final Long position = videoPlayer.getBufferedPosition();
assertEquals(bufferedPosition, position.longValue());
videoPlayer.dispose();
}
@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();
}
// Helper method to set the length field on a mocked Tracks.Group
private void setGroupLength(Tracks.Group group, int length) {
try {
Field lengthField = group.getClass().getDeclaredField("length");
lengthField.setAccessible(true);
lengthField.setInt(group, length);
} catch (Exception e) {
throw new RuntimeException("Failed to set length field", e);
}
}
@Test
public void testGetAudioTracks_withMultipleAudioTracks() {
Tracks mockTracks = mock(Tracks.class);
Tracks.Group mockAudioGroup1 = mock(Tracks.Group.class);
Tracks.Group mockAudioGroup2 = mock(Tracks.Group.class);
Tracks.Group mockVideoGroup = mock(Tracks.Group.class);
// Create mock formats for audio tracks
Format audioFormat1 =
new Format.Builder()
.setId("audio_track_1")
.setLabel("English")
.setLanguage("en")
.setAverageBitrate(128000)
.setSampleRate(48000)
.setChannelCount(2)
.setCodecs("mp4a.40.2")
.build();
Format audioFormat2 =
new Format.Builder()
.setId("audio_track_2")
.setLabel("Español")
.setLanguage("es")
.setAverageBitrate(96000)
.setSampleRate(44100)
.setChannelCount(2)
.setCodecs("mp4a.40.2")
.build();
// Mock audio groups and set length field
setGroupLength(mockAudioGroup1, 1);
setGroupLength(mockAudioGroup2, 1);
when(mockAudioGroup1.getType()).thenReturn(C.TRACK_TYPE_AUDIO);
when(mockAudioGroup1.getTrackFormat(0)).thenReturn(audioFormat1);
when(mockAudioGroup1.isTrackSelected(0)).thenReturn(true);
when(mockAudioGroup2.getType()).thenReturn(C.TRACK_TYPE_AUDIO);
when(mockAudioGroup2.getTrackFormat(0)).thenReturn(audioFormat2);
when(mockAudioGroup2.isTrackSelected(0)).thenReturn(false);
when(mockVideoGroup.getType()).thenReturn(C.TRACK_TYPE_VIDEO);
// Mock tracks
ImmutableList<Tracks.Group> groups =
ImmutableList.of(mockAudioGroup1, mockAudioGroup2, mockVideoGroup);
when(mockTracks.getGroups()).thenReturn(groups);
when(mockExoPlayer.getCurrentTracks()).thenReturn(mockTracks);
VideoPlayer videoPlayer = createVideoPlayer();
// Test the method
NativeAudioTrackData nativeData = videoPlayer.getAudioTracks();
List<ExoPlayerAudioTrackData> result = nativeData.getExoPlayerTracks();
// Verify results
assertNotNull(result);
assertEquals(2, result.size());
// Verify first track
ExoPlayerAudioTrackData track1 = result.get(0);
assertEquals(0L, track1.getGroupIndex());
assertEquals(0L, track1.getTrackIndex());
assertEquals("English", track1.getLabel());
assertEquals("en", track1.getLanguage());
assertTrue(track1.isSelected());
assertEquals(Long.valueOf(128000), track1.getBitrate());
assertEquals(Long.valueOf(48000), track1.getSampleRate());
assertEquals(Long.valueOf(2), track1.getChannelCount());
assertEquals("mp4a.40.2", track1.getCodec());
// Verify second track
ExoPlayerAudioTrackData track2 = result.get(1);
assertEquals(1L, track2.getGroupIndex());
assertEquals(0L, track2.getTrackIndex());
assertEquals("Español", track2.getLabel());
assertEquals("es", track2.getLanguage());
assertFalse(track2.isSelected());
assertEquals(Long.valueOf(96000), track2.getBitrate());
assertEquals(Long.valueOf(44100), track2.getSampleRate());
assertEquals(Long.valueOf(2), track2.getChannelCount());
assertEquals("mp4a.40.2", track2.getCodec());
videoPlayer.dispose();
}
@Test
public void testGetAudioTracks_withNoAudioTracks() {
Tracks mockTracks = mock(Tracks.class);
Tracks.Group mockVideoGroup = mock(Tracks.Group.class);
// Mock video group only (no audio tracks)
when(mockVideoGroup.getType()).thenReturn(C.TRACK_TYPE_VIDEO);
ImmutableList<Tracks.Group> groups = ImmutableList.of(mockVideoGroup);
when(mockTracks.getGroups()).thenReturn(groups);
when(mockExoPlayer.getCurrentTracks()).thenReturn(mockTracks);
VideoPlayer videoPlayer = createVideoPlayer();
// Test the method
NativeAudioTrackData nativeData = videoPlayer.getAudioTracks();
List<ExoPlayerAudioTrackData> result = nativeData.getExoPlayerTracks();
// Verify results
assertNotNull(result);
assertEquals(0, result.size());
videoPlayer.dispose();
}
@Test
public void testGetAudioTracks_withNullValues() {
Tracks mockTracks = mock(Tracks.class);
Tracks.Group mockAudioGroup1 = mock(Tracks.Group.class);
// Create format with null/missing values
Format audioFormat =
new Format.Builder()
.setId("audio_track_null")
.setLabel(null) // Null label
.setLanguage(null) // Null language
.setAverageBitrate(Format.NO_VALUE) // No bitrate
.setSampleRate(Format.NO_VALUE) // No sample rate
.setChannelCount(Format.NO_VALUE) // No channel count
.setCodecs(null) // Null codec
.build();
// Mock audio group and set length field
setGroupLength(mockAudioGroup1, 1);
when(mockAudioGroup1.getType()).thenReturn(C.TRACK_TYPE_AUDIO);
when(mockAudioGroup1.getTrackFormat(0)).thenReturn(audioFormat);
when(mockAudioGroup1.isTrackSelected(0)).thenReturn(false);
ImmutableList<Tracks.Group> groups = ImmutableList.of(mockAudioGroup1);
when(mockTracks.getGroups()).thenReturn(groups);
when(mockExoPlayer.getCurrentTracks()).thenReturn(mockTracks);
VideoPlayer videoPlayer = createVideoPlayer();
// Test the method
NativeAudioTrackData nativeData = videoPlayer.getAudioTracks();
List<ExoPlayerAudioTrackData> result = nativeData.getExoPlayerTracks();
// Verify results
assertNotNull(result);
assertEquals(1, result.size());
ExoPlayerAudioTrackData track = result.get(0);
assertEquals(0L, track.getGroupIndex());
assertEquals(0L, track.getTrackIndex());
assertNull(track.getLabel()); // Null values should be preserved
assertNull(track.getLanguage()); // Null values should be preserved
assertFalse(track.isSelected());
assertNull(track.getBitrate());
assertNull(track.getSampleRate());
assertNull(track.getChannelCount());
assertNull(track.getCodec());
videoPlayer.dispose();
}
@Test
public void testGetAudioTracks_withMultipleTracksInSameGroup() {
Tracks mockTracks = mock(Tracks.class);
Tracks.Group mockAudioGroup1 = mock(Tracks.Group.class);
// Create format for group with multiple tracks
Format audioFormat1 =
new Format.Builder()
.setId("audio_track_1")
.setLabel("Track 1")
.setLanguage("en")
.setAverageBitrate(128000)
.build();
Format audioFormat2 =
new Format.Builder()
.setId("audio_track_2")
.setLabel("Track 2")
.setLanguage("en")
.setAverageBitrate(192000)
.build();
// Mock audio group with multiple tracks
setGroupLength(mockAudioGroup1, 2);
when(mockAudioGroup1.getType()).thenReturn(C.TRACK_TYPE_AUDIO);
when(mockAudioGroup1.getTrackFormat(0)).thenReturn(audioFormat1);
when(mockAudioGroup1.getTrackFormat(1)).thenReturn(audioFormat2);
when(mockAudioGroup1.isTrackSelected(0)).thenReturn(true);
when(mockAudioGroup1.isTrackSelected(1)).thenReturn(false);
ImmutableList<Tracks.Group> groups = ImmutableList.of(mockAudioGroup1);
when(mockTracks.getGroups()).thenReturn(groups);
when(mockExoPlayer.getCurrentTracks()).thenReturn(mockTracks);
VideoPlayer videoPlayer = createVideoPlayer();
// Test the method
NativeAudioTrackData nativeData = videoPlayer.getAudioTracks();
List<ExoPlayerAudioTrackData> result = nativeData.getExoPlayerTracks();
// Verify results
assertNotNull(result);
assertEquals(2, result.size());
// Verify track indices are correct
ExoPlayerAudioTrackData track1 = result.get(0);
ExoPlayerAudioTrackData track2 = result.get(1);
assertEquals(0L, track1.getGroupIndex());
assertEquals(0L, track1.getTrackIndex());
assertEquals(0L, track2.getGroupIndex());
assertEquals(1L, track2.getTrackIndex());
// Tracks have same group but different track indices
assertEquals(track1.getGroupIndex(), track2.getGroupIndex());
assertNotEquals(track1.getTrackIndex(), track2.getTrackIndex());
videoPlayer.dispose();
}
@Test
public void testSelectAudioTrack_validIndices() {
DefaultTrackSelector mockTrackSelector = mock(DefaultTrackSelector.class);
DefaultTrackSelector.Parameters mockParameters = mock(DefaultTrackSelector.Parameters.class);
DefaultTrackSelector.Parameters.Builder mockBuilder =
mock(DefaultTrackSelector.Parameters.Builder.class);
Tracks mockTracks = mock(Tracks.class);
Tracks.Group mockAudioGroup = mock(Tracks.Group.class);
Format audioFormat =
new Format.Builder().setId("audio_track_1").setLabel("English").setLanguage("en").build();
// Create a real TrackGroup with the format
TrackGroup trackGroup = new TrackGroup(audioFormat);
// Mock audio group with 2 tracks
setGroupLength(mockAudioGroup, 2);
when(mockAudioGroup.getType()).thenReturn(C.TRACK_TYPE_AUDIO);
when(mockAudioGroup.getMediaTrackGroup()).thenReturn(trackGroup);
ImmutableList<Tracks.Group> groups = ImmutableList.of(mockAudioGroup);
when(mockTracks.getGroups()).thenReturn(groups);
// Set up track selector BEFORE creating VideoPlayer
when(mockExoPlayer.getTrackSelector()).thenReturn(mockTrackSelector);
when(mockExoPlayer.getCurrentTracks()).thenReturn(mockTracks);
when(mockTrackSelector.buildUponParameters()).thenReturn(mockBuilder);
when(mockBuilder.setOverrideForType(any(TrackSelectionOverride.class))).thenReturn(mockBuilder);
when(mockBuilder.build()).thenReturn(mockParameters);
VideoPlayer videoPlayer = createVideoPlayer();
// Test selecting a valid audio track
videoPlayer.selectAudioTrack(0, 0);
// Verify track selector was called
verify(mockTrackSelector).buildUponParameters();
verify(mockBuilder).setOverrideForType(any(TrackSelectionOverride.class));
verify(mockBuilder).build();
verify(mockTrackSelector).setParameters(mockParameters);
videoPlayer.dispose();
}
@Test
public void testSelectAudioTrack_nullTrackSelector() {
// Track selector is null by default in mock
VideoPlayer videoPlayer = createVideoPlayer();
assertThrows(IllegalStateException.class, () -> videoPlayer.selectAudioTrack(0, 0));
videoPlayer.dispose();
}
@Test
public void testSelectAudioTrack_invalidGroupIndex() {
DefaultTrackSelector mockTrackSelector = mock(DefaultTrackSelector.class);
Tracks mockTracks = mock(Tracks.class);
Tracks.Group mockAudioGroup = mock(Tracks.Group.class);
Format audioFormat =
new Format.Builder().setId("audio_track_1").setLabel("English").setLanguage("en").build();
ImmutableList<Tracks.Group> groups = ImmutableList.of(mockAudioGroup);
when(mockTracks.getGroups()).thenReturn(groups);
when(mockExoPlayer.getCurrentTracks()).thenReturn(mockTracks);
when(mockExoPlayer.getTrackSelector()).thenReturn(mockTrackSelector);
VideoPlayer videoPlayer = createVideoPlayer();
// Test with invalid group index (only 1 group exists at index 0)
assertThrows(IllegalArgumentException.class, () -> videoPlayer.selectAudioTrack(5, 0));
videoPlayer.dispose();
}
@Test
public void testSelectAudioTrack_invalidTrackIndex() {
DefaultTrackSelector mockTrackSelector = mock(DefaultTrackSelector.class);
Tracks mockTracks = mock(Tracks.class);
Tracks.Group mockAudioGroup = mock(Tracks.Group.class);
Format audioFormat =
new Format.Builder().setId("audio_track_1").setLabel("English").setLanguage("en").build();
// Mock audio group with only 1 track
setGroupLength(mockAudioGroup, 1);
when(mockAudioGroup.getType()).thenReturn(C.TRACK_TYPE_AUDIO);
ImmutableList<Tracks.Group> groups = ImmutableList.of(mockAudioGroup);
when(mockTracks.getGroups()).thenReturn(groups);
when(mockExoPlayer.getCurrentTracks()).thenReturn(mockTracks);
when(mockExoPlayer.getTrackSelector()).thenReturn(mockTrackSelector);
VideoPlayer videoPlayer = createVideoPlayer();
// Test with invalid track index (only 1 track exists at index 0)
assertThrows(IllegalArgumentException.class, () -> videoPlayer.selectAudioTrack(0, 5));
videoPlayer.dispose();
}
@Test
public void testSelectAudioTrack_nonAudioGroup() {
DefaultTrackSelector mockTrackSelector = mock(DefaultTrackSelector.class);
Tracks mockTracks = mock(Tracks.class);
Tracks.Group mockVideoGroup = mock(Tracks.Group.class);
// Mock video group (not audio)
setGroupLength(mockVideoGroup, 1);
when(mockVideoGroup.getType()).thenReturn(C.TRACK_TYPE_VIDEO);
ImmutableList<Tracks.Group> groups = ImmutableList.of(mockVideoGroup);
when(mockTracks.getGroups()).thenReturn(groups);
when(mockExoPlayer.getCurrentTracks()).thenReturn(mockTracks);
when(mockExoPlayer.getTrackSelector()).thenReturn(mockTrackSelector);
VideoPlayer videoPlayer = createVideoPlayer();
// Test selecting from a non-audio group
assertThrows(IllegalArgumentException.class, () -> videoPlayer.selectAudioTrack(0, 0));
videoPlayer.dispose();
}
@Test
public void testSelectAudioTrack_negativeIndices() {
DefaultTrackSelector mockTrackSelector = mock(DefaultTrackSelector.class);
Tracks mockTracks = mock(Tracks.class);
Tracks.Group mockAudioGroup = mock(Tracks.Group.class);
Format audioFormat =
new Format.Builder().setId("audio_track_1").setLabel("English").setLanguage("en").build();
ImmutableList<Tracks.Group> groups = ImmutableList.of(mockAudioGroup);
when(mockTracks.getGroups()).thenReturn(groups);
when(mockExoPlayer.getCurrentTracks()).thenReturn(mockTracks);
when(mockExoPlayer.getTrackSelector()).thenReturn(mockTrackSelector);
VideoPlayer videoPlayer = createVideoPlayer();
// Test with negative indices - should be caught by bounds checking
assertThrows(IllegalArgumentException.class, () -> videoPlayer.selectAudioTrack(-1, 0));
videoPlayer.dispose();
}
}

View File

@@ -0,0 +1,69 @@
plugins {
id "com.android.application"
id "org.jetbrains.kotlin.android"
id "dev.flutter.flutter-gradle-plugin"
}
def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
localPropertiesFile.withReader('UTF-8') { reader ->
localProperties.load(reader)
}
}
def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
flutterVersionCode = '1'
}
def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
flutterVersionName = '1.0'
}
android {
namespace = "io.flutter.plugins.videoplayerexample"
compileSdk = flutter.compileSdkVersion
compileOptions {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
defaultConfig {
applicationId "io.flutter.plugins.videoplayerexample"
minSdkVersion flutter.minSdkVersion
targetSdkVersion flutter.targetSdkVersion
versionCode flutterVersionCode.toInteger()
versionName flutterVersionName
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
// TODO: Add your own signing config for the release build.
// Signing with the debug keys for now, so `flutter run --release` works.
signingConfig = signingConfigs.debug
}
}
lint {
disable 'InvalidPackage'
}
}
flutter {
source = '../..'
}
dependencies {
testImplementation("androidx.test.ext:junit:1.2.1")
testImplementation("com.google.truth:truth:1.1.3")
testImplementation("junit:junit:4.13")
testImplementation("org.robolectric:robolectric:4.16")
testImplementation("org.mockito:mockito-core:5.17.0")
androidTestImplementation("androidx.test:runner:1.1.1")
androidTestImplementation("androidx.test.espresso:espresso-core:3.1.1")
implementation(project(':espresso'))
api("androidx.test:core:1.2.0")
}

View File

@@ -0,0 +1,6 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-9.3.0-all.zip
networkTimeout=10000
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

View File

@@ -0,0 +1,21 @@
// Copyright 2013 The Flutter Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/*
* Annotation to aid repository tooling in determining if a test is
* a native java unit test or a java class with a dart integration.
*
* See: https://github.com/flutter/flutter/blob/master/docs/ecosystem/testing/Plugin-Tests.md#enabling-android-ui-tests
* for more information.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface DartIntegrationTest {}

View File

@@ -0,0 +1,19 @@
// Copyright 2013 The Flutter Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.videoplayerexample;
import androidx.test.rule.ActivityTestRule;
import dev.flutter.plugins.integration_test.FlutterTestRunner;
import io.flutter.embedding.android.FlutterActivity;
import io.flutter.plugins.DartIntegrationTest;
import org.junit.Rule;
import org.junit.runner.RunWith;
@DartIntegrationTest
@RunWith(FlutterTestRunner.class)
public class FlutterActivityTest {
@Rule
public ActivityTestRule<FlutterActivity> rule = new ActivityTestRule<>(FlutterActivity.class);
}

View File

@@ -0,0 +1,73 @@
// Copyright 2013 The Flutter Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.videoplayerexample;
import static androidx.test.espresso.flutter.EspressoFlutter.WidgetInteraction;
import static androidx.test.espresso.flutter.EspressoFlutter.onFlutterWidget;
import static androidx.test.espresso.flutter.action.FlutterActions.click;
import static androidx.test.espresso.flutter.assertion.FlutterAssertions.matches;
import static androidx.test.espresso.flutter.matcher.FlutterMatchers.isExisting;
import static androidx.test.espresso.flutter.matcher.FlutterMatchers.withText;
import static androidx.test.espresso.flutter.matcher.FlutterMatchers.withValueKey;
import androidx.test.ext.junit.rules.ActivityScenarioRule;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
@RunWith(AndroidJUnit4.class)
public class VideoPlayerUITest {
@Rule
public ActivityScenarioRule<DriverExtensionActivity> activityRule =
new ActivityScenarioRule<>(DriverExtensionActivity.class);
@Test
@Ignore("Doesn't run in Firebase Test Lab: https://github.com/flutter/flutter/issues/94748")
public void playVideo() {
WidgetInteraction remoteTab = onFlutterWidget(withText("Remote"));
remoteTab.check(matches(isExisting()));
for (String tabName : new String[] {"Platform view", "Texture view"}) {
WidgetInteraction viewTypeTab = onFlutterWidget(withText(tabName));
viewTypeTab.check(matches(isExisting()));
viewTypeTab.perform(click());
WidgetInteraction playButton = onFlutterWidget(withValueKey("Play"));
playButton.check(matches(isExisting()));
playButton.perform(click());
WidgetInteraction playbackSpeed1x = onFlutterWidget(withText("1.0x"));
playbackSpeed1x.check(matches(isExisting()));
playbackSpeed1x.perform(click());
WidgetInteraction playbackSpeed5xButton = onFlutterWidget(withText("5.0x"));
playbackSpeed5xButton.check(matches(isExisting()));
playbackSpeed5xButton.perform(click());
WidgetInteraction playbackSpeed5x = onFlutterWidget(withText("5.0x"));
playbackSpeed5x.check(matches(isExisting()));
}
for (String[] tabData :
new String[][] {{"Asset", "With assets mp4"}, {"Remote", "With remote mp4"}}) {
String tabName = tabData[0];
String videoDescription = tabData[1];
WidgetInteraction tab = onFlutterWidget(withText(tabName));
WidgetInteraction tabDescription = onFlutterWidget(withText(videoDescription));
tab.check(matches(isExisting()));
// TODO(FirentisTFW): Assert that testDescription is not visible before we tap on tab.
// This should be done once the Espresso API allows us to perform such an assertion. See
// https://github.com/flutter/flutter/issues/160599
tab.perform(click());
tab.check(matches(isExisting()));
tabDescription.check(matches(isExisting()));
}
}
}

View File

@@ -0,0 +1,10 @@
// Copyright 2013 The Flutter Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.videoplayerexample;
import io.flutter.embedding.android.FlutterActivity;
/** Test Activity that sets the name of the Dart method entrypoint in the manifest. */
public class DriverExtensionActivity extends FlutterActivity {}

View File

@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Modify this file to customize your launch splash screen -->
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@android:color/white" />
<!-- You can insert your own image assets here -->
<!-- <item>
<bitmap
android:gravity="center"
android:src="@mipmap/launch_image" />
</item> -->
</layer-list>

Binary file not shown.

After

Width:  |  Height:  |  Size: 544 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 442 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 721 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="LaunchTheme" parent="@android:style/Theme.Black.NoTitleBar">
<item name="android:windowBackground">@drawable/launch_background</item>
</style>
</resources>

View File

@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<domain-config cleartextTrafficPermitted="true">
<domain includeSubdomains="true">www.sample-videos.com</domain>
<domain includeSubdomains="true">184.72.239.149</domain>
<!-- Needed for Espresso integration test -->
<domain includeSubdomains="true">127.0.0.1</domain>
</domain-config>
</network-security-config>

View File

@@ -0,0 +1,56 @@
// Copyright 2013 The Flutter Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.videoplayerexample;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import android.content.Context;
import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugin.platform.PlatformViewRegistry;
import io.flutter.plugins.videoplayer.VideoPlayerPlugin;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
@RunWith(RobolectricTestRunner.class)
@Config(manifest = Config.NONE)
public class FlutterActivityTest {
AutoCloseable mockCloseable;
@Mock FlutterPlugin.FlutterPluginBinding flutterPluginBinding;
@Before
public void before() {
mockCloseable = MockitoAnnotations.openMocks(this);
}
@After
public void tearDown() throws Exception {
mockCloseable.close();
}
@Test
public void disposeAllPlayers() {
when(flutterPluginBinding.getApplicationContext()).thenReturn(mock(Context.class));
when(flutterPluginBinding.getBinaryMessenger()).thenReturn(mock(BinaryMessenger.class));
when(flutterPluginBinding.getPlatformViewRegistry())
.thenReturn(mock(PlatformViewRegistry.class));
VideoPlayerPlugin videoPlayerPlugin = spy(new VideoPlayerPlugin());
videoPlayerPlugin.onAttachedToEngine(flutterPluginBinding);
videoPlayerPlugin.onDetachedFromEngine(flutterPluginBinding);
verify(videoPlayerPlugin, times(1)).onDestroy();
}
}

View File

@@ -0,0 +1,59 @@
allprojects {
repositories {
// See https://github.com/flutter/flutter/blob/master/docs/ecosystem/Plugins-and-Packages-repository-structure.md#gradle-structure for more info.
def artifactRepoKey = 'ARTIFACT_HUB_REPOSITORY'
if (System.getenv().containsKey(artifactRepoKey)) {
println "Using artifact hub"
maven { url System.getenv(artifactRepoKey) }
}
google()
mavenCentral()
}
}
rootProject.buildDir = '../build'
subprojects {
project.buildDir = "${rootProject.buildDir}/${project.name}"
}
subprojects {
project.evaluationDependsOn(':app')
}
tasks.register("clean", Delete) {
delete rootProject.buildDir
}
// Build the plugin project with warnings enabled. This is here rather than
// in the plugin itself to avoid breaking clients that have different
// warnings (e.g., deprecation warnings from a newer SDK than this project
// builds with).
gradle.projectsEvaluated {
project(":video_player_android") {
tasks.withType(JavaCompile) {
options.compilerArgs << "-Xlint:all" << "-Werror"
// Workaround for several warnings when building
// that the above turns into errors, coming from
// org.checkerframework.checker.nullness.qual and
// com.google.errorprone.annotations:
//
// warning: Cannot find annotation method 'value()' in type
// 'EnsuresNonNull': class file for
// org.checkerframework.checker.nullness.qual.EnsuresNonNull not found
//
// warning: Cannot find annotation method 'replacement()' in type
// 'InlineMe': class file for
// com.google.errorprone.annotations.InlineMe not found
//
// The dependency version are taken from:
// https://github.com/google/ExoPlayer/blob/r2.18.1/constants.gradle
//
// For future reference the dependencies are excluded here:
// https://github.com/google/ExoPlayer/blob/r2.18.1/library/common/build.gradle#L33-L34
dependencies {
implementation("org.checkerframework:checker-qual:3.13.0")
implementation("com.google.errorprone:error_prone_annotations:2.10.0")
}
}
}
}

View File

@@ -0,0 +1,2 @@
org.gradle.jvmargs=-Xmx4G
android.useAndroidX=true

View File

@@ -0,0 +1,7 @@
#Fri Jun 23 08:50:38 CEST 2017
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.13-all.zip

View File

@@ -0,0 +1,27 @@
pluginManagement {
def flutterSdkPath = {
def properties = new Properties()
file("local.properties").withInputStream { properties.load(it) }
def flutterSdkPath = properties.getProperty("flutter.sdk")
assert flutterSdkPath != null, "flutter.sdk not set in local.properties"
return flutterSdkPath
}()
includeBuild("$flutterSdkPath/packages/flutter_tools/gradle")
repositories {
google()
mavenCentral()
gradlePluginPortal()
}
}
// See https://github.com/flutter/flutter/blob/master/docs/ecosystem/Plugins-and-Packages-repository-structure.md#gradle-structure for more info.
plugins {
id "dev.flutter.flutter-plugin-loader" version "1.0.0"
id "com.android.application" version "8.11.1" apply false
id "org.jetbrains.kotlin.android" version "2.2.20" apply false
id "com.google.cloud.artifactregistry.gradle-plugin" version "2.2.1"
}
include ":app"

Binary file not shown.

After

Width:  |  Height:  |  Size: 482 B

View File

@@ -0,0 +1,36 @@
name: video_player_example
description: Demonstrates how to use the video_player plugin.
publish_to: none
environment:
sdk: ^3.9.0
flutter: ">=3.35.0"
dependencies:
flutter:
sdk: flutter
flutter_driver:
sdk: flutter
video_player_android:
# When depending on this package from a real application you should use:
# video_player_android: ^x.y.z
# See https://dart.dev/tools/pub/dependencies#version-constraints
# The example app is bundled with the plugin so we use a path dependency on
# the parent directory to use the current plugin's version.
path: ../
video_player_platform_interface: ^6.6.0
dev_dependencies:
espresso: ^0.4.0
flutter_test:
sdk: flutter
integration_test:
sdk: flutter
path_provider: ^2.0.6
test: any
flutter:
uses-material-design: true
assets:
- assets/flutter-mark-square-64.png
- assets/Butterfly-209.mp4

View File

@@ -0,0 +1,3 @@
Copyright 2013 The Flutter Authors
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.

View File

@@ -0,0 +1,34 @@
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.9.5
environment:
sdk: ^3.9.0
flutter: ">=3.35.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.6.0
dev_dependencies:
build_runner: ^2.3.3
flutter_test:
sdk: flutter
mockito: ^5.4.4
pigeon: ^26.1.5
topics:
- video
- video-player