本地视频延迟优化+视频的获取链路播放

This commit is contained in:
2026-10-13 12:40:16 +08:00
parent 9671798f29
commit e4f7cc7a90
25 changed files with 6438 additions and 0 deletions

View File

@@ -0,0 +1,3 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="io.flutter.plugins.videoplayer">
</manifest>

View File

@@ -0,0 +1,24 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="io.flutter.plugins.videoplayerexample">
<application
android:icon="@mipmap/ic_launcher"
android:label="video_player_example"
android:networkSecurityConfig="@xml/network_security_config">
<activity
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection"
android:exported="true"
android:hardwareAccelerated="true"
android:name="io.flutter.embedding.android.FlutterActivity"
android:theme="@style/LaunchTheme"
android:windowSoftInputMode="adjustResize">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<meta-data android:name="flutterEmbedding" android:value="2"/>
</application>
<uses-permission android:name="android.permission.INTERNET"/>
</manifest>

View File

@@ -0,0 +1,24 @@
// 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.
import 'package:flutter_driver/driver_extension.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
import 'package:video_player_example/main.dart' as app;
/// Entry point for integration tests that require espresso.
@pragma('vm:entry-point')
void integrationTestMain() {
enableFlutterDriverExtension();
app.main();
}
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
// Since this file is lacking integration tests, this test ensures the example
// app can be launched on an emulator/device.
testWidgets('Launch Test', (WidgetTester tester) async {});
}

View File

@@ -0,0 +1,169 @@
// 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.
import 'dart:io';
import 'dart:typed_data';
import 'package:flutter/services.dart' show rootBundle;
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
import 'package:path_provider/path_provider.dart';
import 'package:video_player_android/video_player_android.dart';
import 'package:video_player_platform_interface/video_player_platform_interface.dart';
const Duration _playDuration = Duration(seconds: 1);
const String _videoAssetKey = 'assets/Butterfly-209.mp4';
// Returns the URL to load an asset from this example app as a network source.
//
// TODO(stuartmorgan): Convert this to a local `HttpServer` that vends the
// assets directly, https://github.com/flutter/flutter/issues/95420
String getUrlForAssetAsNetworkSource(String assetKey) {
return 'https://github.com/flutter/packages/blob/'
// This hash can be rolled forward to pick up newly-added assets.
'2e1673307ff7454aff40b47024eaed49a9e77e81'
'/packages/video_player/video_player/example/'
'$assetKey'
'?raw=true';
}
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
late AndroidVideoPlayer player;
setUp(() async {
player = AndroidVideoPlayer();
await player.init();
});
testWidgets('registers expected implementation', (_) async {
AndroidVideoPlayer.registerWith();
expect(VideoPlayerPlatform.instance, isA<AndroidVideoPlayer>());
});
testWidgets('initializes at the start', (_) async {
final int playerId = (await player.create(
DataSource(sourceType: DataSourceType.asset, asset: _videoAssetKey),
))!;
expect(
await _getDuration(player, playerId),
const Duration(seconds: 7, milliseconds: 540),
);
await player.dispose(playerId);
});
testWidgets('can be played', (WidgetTester tester) async {
final int playerId = (await player.create(
DataSource(sourceType: DataSourceType.asset, asset: _videoAssetKey),
))!;
await player.play(playerId);
await tester.pumpAndSettle(_playDuration);
expect(await player.getPosition(playerId), greaterThan(Duration.zero));
await player.dispose(playerId);
});
testWidgets('can seek', (WidgetTester tester) async {
final int playerId = (await player.create(
DataSource(sourceType: DataSourceType.asset, asset: _videoAssetKey),
))!;
await player.seekTo(playerId, const Duration(seconds: 3));
await tester.pumpAndSettle(_playDuration);
expect(
await player.getPosition(playerId),
greaterThanOrEqualTo(const Duration(seconds: 3)),
);
await player.dispose(playerId);
});
testWidgets('can pause', (WidgetTester tester) async {
final int playerId = (await player.create(
DataSource(sourceType: DataSourceType.asset, asset: _videoAssetKey),
))!;
await player.play(playerId);
await tester.pumpAndSettle(_playDuration);
await player.pause(playerId);
await tester.pumpAndSettle(_playDuration);
final Duration pausedDuration = await player.getPosition(playerId);
await tester.pumpAndSettle(_playDuration);
expect(await player.getPosition(playerId), pausedDuration);
await player.dispose(playerId);
});
testWidgets('can play a video from a file', (WidgetTester tester) async {
final Directory directory = await getTemporaryDirectory();
final file = File('${directory.path}/video.mp4');
await file.writeAsBytes(
Uint8List.fromList(
(await rootBundle.load(_videoAssetKey)).buffer.asUint8List(),
),
);
final int playerId = (await player.create(
DataSource(sourceType: DataSourceType.file, uri: file.path),
))!;
await player.play(playerId);
await tester.pumpAndSettle(_playDuration);
expect(await player.getPosition(playerId), greaterThan(Duration.zero));
await directory.delete(recursive: true);
await player.dispose(playerId);
});
testWidgets('can play a video from network', (WidgetTester tester) async {
final int playerId = (await player.create(
DataSource(
sourceType: DataSourceType.network,
uri: getUrlForAssetAsNetworkSource(_videoAssetKey),
),
))!;
await player.play(playerId);
await player.seekTo(playerId, const Duration(seconds: 5));
await tester.pumpAndSettle(_playDuration);
await player.pause(playerId);
expect(await player.getPosition(playerId), greaterThan(Duration.zero));
final DurationRange range = await _getBufferingRange(player, playerId);
expect(range.start, Duration.zero);
expect(range.end, greaterThan(Duration.zero));
await player.dispose(playerId);
});
}
Future<Duration> _getDuration(AndroidVideoPlayer player, int playerId) {
return player
.videoEventsFor(playerId)
.firstWhere((VideoEvent event) {
return event.eventType == VideoEventType.initialized;
})
.then((VideoEvent event) {
return event.duration!;
});
}
Future<DurationRange> _getBufferingRange(
AndroidVideoPlayer player,
int playerId,
) {
return player
.videoEventsFor(playerId)
.firstWhere((VideoEvent event) {
return event.eventType == VideoEventType.bufferingUpdate;
})
.then((VideoEvent event) {
return event.buffered!.first;
});
}

View File

@@ -0,0 +1,383 @@
// 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.
// ignore_for_file: public_member_api_docs
import 'package:flutter/material.dart';
import 'package:video_player_platform_interface/video_player_platform_interface.dart';
import 'mini_controller.dart';
void main() {
runApp(MaterialApp(home: _App()));
}
class _App extends StatelessWidget {
@override
Widget build(BuildContext context) {
return DefaultTabController(
length: 3,
child: Scaffold(
key: const ValueKey<String>('home_page'),
appBar: AppBar(
title: const Text('Video player example'),
bottom: const TabBar(
isScrollable: true,
tabs: <Widget>[
Tab(icon: Icon(Icons.cloud), text: 'Remote'),
Tab(icon: Icon(Icons.videocam), text: 'RTSP'),
Tab(icon: Icon(Icons.insert_drive_file), text: 'Asset'),
],
),
),
body: TabBarView(
children: <Widget>[
_ViewTypeTabBar(
builder: (VideoViewType viewType) =>
_BumbleBeeRemoteVideo(viewType),
),
_ViewTypeTabBar(
builder: (VideoViewType viewType) => _RtspRemoteVideo(viewType),
),
_ViewTypeTabBar(
builder: (VideoViewType viewType) =>
_ButterFlyAssetVideo(viewType),
),
],
),
),
);
}
}
class _ViewTypeTabBar extends StatefulWidget {
const _ViewTypeTabBar({required this.builder});
final Widget Function(VideoViewType) builder;
@override
State<_ViewTypeTabBar> createState() => _ViewTypeTabBarState();
}
class _ViewTypeTabBarState extends State<_ViewTypeTabBar>
with SingleTickerProviderStateMixin {
late final TabController _tabController;
@override
void initState() {
super.initState();
_tabController = TabController(length: 2, vsync: this);
}
@override
void dispose() {
_tabController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
TabBar(
controller: _tabController,
isScrollable: true,
tabs: const <Widget>[
Tab(icon: Icon(Icons.texture), text: 'Texture view'),
Tab(icon: Icon(Icons.construction), text: 'Platform view'),
],
),
Expanded(
child: TabBarView(
controller: _tabController,
children: <Widget>[
widget.builder(VideoViewType.textureView),
widget.builder(VideoViewType.platformView),
],
),
),
],
);
}
}
class _ButterFlyAssetVideo extends StatefulWidget {
const _ButterFlyAssetVideo(this.viewType);
final VideoViewType viewType;
@override
_ButterFlyAssetVideoState createState() => _ButterFlyAssetVideoState();
}
class _ButterFlyAssetVideoState extends State<_ButterFlyAssetVideo> {
late MiniController _controller;
@override
void initState() {
super.initState();
_controller = MiniController.asset(
'assets/Butterfly-209.mp4',
viewType: widget.viewType,
);
_controller.addListener(() {
setState(() {});
});
_controller.initialize().then((_) => _controller.play());
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return SingleChildScrollView(
child: Column(
children: <Widget>[
Container(padding: const EdgeInsets.only(top: 20.0)),
const Text('With assets mp4'),
Container(
padding: const EdgeInsets.all(20),
child: AspectRatio(
aspectRatio: _controller.value.aspectRatio,
child: Stack(
alignment: Alignment.bottomCenter,
children: <Widget>[
VideoPlayer(_controller),
_ControlsOverlay(controller: _controller),
VideoProgressIndicator(_controller),
],
),
),
),
],
),
);
}
}
class _BumbleBeeRemoteVideo extends StatefulWidget {
const _BumbleBeeRemoteVideo(this.viewType);
final VideoViewType viewType;
@override
_BumbleBeeRemoteVideoState createState() => _BumbleBeeRemoteVideoState();
}
class _BumbleBeeRemoteVideoState extends State<_BumbleBeeRemoteVideo> {
late MiniController _controller;
@override
void initState() {
super.initState();
_controller = MiniController.network(
'https://flutter.github.io/assets-for-api-docs/assets/videos/bee.mp4',
viewType: widget.viewType,
);
_controller.addListener(() {
setState(() {});
});
_controller.initialize();
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return SingleChildScrollView(
child: Column(
children: <Widget>[
Container(padding: const EdgeInsets.only(top: 20.0)),
const Text('With remote mp4'),
Container(
padding: const EdgeInsets.all(20),
child: AspectRatio(
aspectRatio: _controller.value.aspectRatio,
child: Stack(
alignment: Alignment.bottomCenter,
children: <Widget>[
VideoPlayer(_controller),
_ControlsOverlay(controller: _controller),
VideoProgressIndicator(_controller),
],
),
),
),
],
),
);
}
}
class _RtspRemoteVideo extends StatefulWidget {
const _RtspRemoteVideo(this.viewType);
final VideoViewType viewType;
@override
_RtspRemoteVideoState createState() => _RtspRemoteVideoState();
}
class _RtspRemoteVideoState extends State<_RtspRemoteVideo> {
MiniController? _controller;
@override
void dispose() {
_controller?.dispose();
super.dispose();
}
Future<void> changeUrl(String url) async {
if (_controller != null) {
await _controller!.dispose();
}
setState(() {
_controller = MiniController.network(url, viewType: widget.viewType);
});
_controller!.addListener(() {
setState(() {});
});
return _controller!.initialize();
}
String? _validateRtspUrl(String? value) {
if (value == null || !value.startsWith('rtsp://')) {
return 'Enter a valid RTSP URL';
}
return null;
}
@override
Widget build(BuildContext context) {
return SingleChildScrollView(
child: Column(
children: <Widget>[
Container(padding: const EdgeInsets.only(top: 20.0)),
const Text('With RTSP streaming'),
Padding(
padding: const EdgeInsets.all(20.0),
child: TextFormField(
autovalidateMode: AutovalidateMode.onUserInteraction,
decoration: const InputDecoration(label: Text('RTSP URL')),
validator: _validateRtspUrl,
textInputAction: TextInputAction.done,
onFieldSubmitted: (String value) {
if (_validateRtspUrl(value) == null) {
changeUrl(value);
} else {
setState(() {
_controller?.dispose();
_controller = null;
});
}
},
),
),
if (_controller != null)
Container(
padding: const EdgeInsets.all(20),
child: AspectRatio(
aspectRatio: _controller!.value.aspectRatio,
child: Stack(
alignment: Alignment.bottomCenter,
children: <Widget>[
VideoPlayer(_controller!),
_ControlsOverlay(controller: _controller!),
VideoProgressIndicator(_controller!),
],
),
),
),
],
),
);
}
}
class _ControlsOverlay extends StatelessWidget {
const _ControlsOverlay({required this.controller});
static const List<double> _examplePlaybackRates = <double>[
0.25,
0.5,
1.0,
1.5,
2.0,
3.0,
5.0,
10.0,
];
final MiniController controller;
@override
Widget build(BuildContext context) {
return Stack(
children: <Widget>[
AnimatedSwitcher(
duration: const Duration(milliseconds: 50),
reverseDuration: const Duration(milliseconds: 200),
child: controller.value.isPlaying
? const SizedBox.shrink()
: const ColoredBox(
color: Colors.black26,
child: Center(
child: Icon(
key: ValueKey<String>('Play'),
Icons.play_arrow,
color: Colors.white,
size: 100.0,
semanticLabel: 'Play',
),
),
),
),
GestureDetector(
onTap: () {
controller.value.isPlaying ? controller.pause() : controller.play();
},
),
Align(
alignment: Alignment.topRight,
child: PopupMenuButton<double>(
initialValue: controller.value.playbackSpeed,
tooltip: 'Playback speed',
onSelected: (double speed) {
controller.setPlaybackSpeed(speed);
},
itemBuilder: (BuildContext context) {
return <PopupMenuItem<double>>[
for (final double speed in _examplePlaybackRates)
PopupMenuItem<double>(value: speed, child: Text('${speed}x')),
];
},
child: Padding(
padding: const EdgeInsets.symmetric(
// Using less vertical padding as the text is also longer
// horizontally, so it feels like it would need more spacing
// horizontally (matching the aspect ratio of the video).
vertical: 12,
horizontal: 16,
),
child: Text('${controller.value.playbackSpeed}x'),
),
),
),
],
);
}
}

View File

@@ -0,0 +1,591 @@
// 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.
// TODO(stuartmorgan): Consider extracting this to a shared local (path-based)
// package for use in all implementation packages.
import 'dart:async';
import 'dart:io';
import 'dart:math' as math show max;
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:video_player_platform_interface/video_player_platform_interface.dart';
VideoPlayerPlatform? _cachedPlatform;
VideoPlayerPlatform get _platform {
if (_cachedPlatform == null) {
_cachedPlatform = VideoPlayerPlatform.instance;
_cachedPlatform!.init();
}
return _cachedPlatform!;
}
/// The duration, current position, buffering state, error state and settings
/// of a [MiniController].
@immutable
class VideoPlayerValue {
/// Constructs a video with the given values. Only [duration] is required. The
/// rest will initialize with default values when unset.
const VideoPlayerValue({
required this.duration,
this.size = Size.zero,
this.position = Duration.zero,
this.buffered = const <DurationRange>[],
this.isInitialized = false,
this.isPlaying = false,
this.isBuffering = false,
this.playbackSpeed = 1.0,
this.errorDescription,
this.rotationCorrection = 0,
});
/// Returns an instance for a video that hasn't been loaded.
const VideoPlayerValue.uninitialized()
: this(duration: Duration.zero, isInitialized: false);
/// Returns an instance with the given [errorDescription].
const VideoPlayerValue.erroneous(String errorDescription)
: this(
duration: Duration.zero,
isInitialized: false,
errorDescription: errorDescription,
);
/// The total duration of the video.
///
/// The duration is [Duration.zero] if the video hasn't been initialized.
final Duration duration;
/// The current playback position.
final Duration position;
/// The currently buffered ranges.
final List<DurationRange> buffered;
/// True if the video is playing. False if it's paused.
final bool isPlaying;
/// True if the video is currently buffering.
final bool isBuffering;
/// The current speed of the playback.
final double playbackSpeed;
/// A description of the error if present.
///
/// If [hasError] is false this is `null`.
final String? errorDescription;
/// The [size] of the currently loaded video.
final Size size;
/// Indicates whether or not the video has been loaded and is ready to play.
final bool isInitialized;
/// Degrees to rotate the video (clockwise) so it is displayed correctly.
final int rotationCorrection;
/// Indicates whether or not the video is in an error state. If this is true
/// [errorDescription] should have information about the problem.
bool get hasError => errorDescription != null;
/// Returns [size.width] / [size.height].
///
/// Will return `1.0` if:
/// * [isInitialized] is `false`
/// * [size.width], or [size.height] is equal to `0.0`
/// * aspect ratio would be less than or equal to `0.0`
double get aspectRatio {
if (!isInitialized || size.width == 0 || size.height == 0) {
return 1.0;
}
final double aspectRatio = size.width / size.height;
if (aspectRatio <= 0) {
return 1.0;
}
return aspectRatio;
}
/// Returns a new instance that has the same values as this current instance,
/// except for any overrides passed in as arguments to [copyWidth].
VideoPlayerValue copyWith({
Duration? duration,
Size? size,
Duration? position,
List<DurationRange>? buffered,
bool? isInitialized,
bool? isPlaying,
bool? isBuffering,
double? playbackSpeed,
String? errorDescription,
int? rotationCorrection,
}) {
return VideoPlayerValue(
duration: duration ?? this.duration,
size: size ?? this.size,
position: position ?? this.position,
buffered: buffered ?? this.buffered,
isInitialized: isInitialized ?? this.isInitialized,
isPlaying: isPlaying ?? this.isPlaying,
isBuffering: isBuffering ?? this.isBuffering,
playbackSpeed: playbackSpeed ?? this.playbackSpeed,
errorDescription: errorDescription ?? this.errorDescription,
rotationCorrection: rotationCorrection ?? this.rotationCorrection,
);
}
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is VideoPlayerValue &&
runtimeType == other.runtimeType &&
duration == other.duration &&
position == other.position &&
listEquals(buffered, other.buffered) &&
isPlaying == other.isPlaying &&
isBuffering == other.isBuffering &&
playbackSpeed == other.playbackSpeed &&
errorDescription == other.errorDescription &&
size == other.size &&
isInitialized == other.isInitialized &&
rotationCorrection == other.rotationCorrection;
@override
int get hashCode => Object.hash(
duration,
position,
buffered,
isPlaying,
isBuffering,
playbackSpeed,
errorDescription,
size,
isInitialized,
rotationCorrection,
);
}
/// A very minimal version of `VideoPlayerController` for running the example
/// without relying on `video_player`.
class MiniController extends ValueNotifier<VideoPlayerValue> {
/// Constructs a [MiniController] playing a video from an asset.
///
/// The name of the asset is given by the [dataSource] argument and must not be
/// null. The [package] argument must be non-null when the asset comes from a
/// package and null otherwise.
MiniController.asset(
this.dataSource, {
this.package,
this.viewType = VideoViewType.textureView,
}) : dataSourceType = DataSourceType.asset,
super(const VideoPlayerValue(duration: Duration.zero));
/// Constructs a [MiniController] playing a video from obtained from
/// the network.
MiniController.network(
this.dataSource, {
this.viewType = VideoViewType.textureView,
}) : dataSourceType = DataSourceType.network,
package = null,
super(const VideoPlayerValue(duration: Duration.zero));
/// Constructs a [MiniController] playing a video from obtained from a file.
MiniController.file(File file, {this.viewType = VideoViewType.textureView})
: dataSource = Uri.file(file.absolute.path).toString(),
dataSourceType = DataSourceType.file,
package = null,
super(const VideoPlayerValue(duration: Duration.zero));
/// The URI to the video file. This will be in different formats depending on
/// the [DataSourceType] of the original video.
final String dataSource;
/// Describes the type of data source this [MiniController]
/// is constructed with.
final DataSourceType dataSourceType;
/// Only set for [asset] videos. The package that the asset was loaded from.
final String? package;
/// The type of view used to display the video.
final VideoViewType viewType;
Timer? _timer;
Completer<void>? _creatingCompleter;
StreamSubscription<dynamic>? _eventSubscription;
/// The id of a player that hasn't been initialized.
@visibleForTesting
static const int kUninitializedPlayerId = -1;
int _playerId = kUninitializedPlayerId;
/// This is just exposed for testing. It shouldn't be used by anyone depending
/// on the plugin.
@visibleForTesting
int get playerId => _playerId;
/// Attempts to open the given [dataSource] and load metadata about the video.
Future<void> initialize() async {
_creatingCompleter = Completer<void>();
late DataSource dataSourceDescription;
switch (dataSourceType) {
case DataSourceType.asset:
dataSourceDescription = DataSource(
sourceType: DataSourceType.asset,
asset: dataSource,
package: package,
);
case DataSourceType.network:
dataSourceDescription = DataSource(
sourceType: DataSourceType.network,
uri: dataSource,
);
case DataSourceType.file:
dataSourceDescription = DataSource(
sourceType: DataSourceType.file,
uri: dataSource,
);
case DataSourceType.contentUri:
dataSourceDescription = DataSource(
sourceType: DataSourceType.contentUri,
uri: dataSource,
);
}
final creationOptions = VideoCreationOptions(
dataSource: dataSourceDescription,
viewType: viewType,
);
_playerId =
(await _platform.createWithOptions(creationOptions)) ??
kUninitializedPlayerId;
_creatingCompleter!.complete(null);
final initializingCompleter = Completer<void>();
void eventListener(VideoEvent event) {
switch (event.eventType) {
case VideoEventType.initialized:
value = value.copyWith(
duration: event.duration,
rotationCorrection: event.rotationCorrection,
size: event.size,
isInitialized: event.duration != null,
);
initializingCompleter.complete(null);
_platform.setVolume(_playerId, 1.0);
_platform.setLooping(_playerId, true);
_applyPlayPause();
case VideoEventType.completed:
pause().then((void pauseResult) => seekTo(value.duration));
case VideoEventType.bufferingUpdate:
value = value.copyWith(buffered: event.buffered);
case VideoEventType.bufferingStart:
value = value.copyWith(isBuffering: true);
case VideoEventType.bufferingEnd:
value = value.copyWith(isBuffering: false);
case VideoEventType.isPlayingStateUpdate:
value = value.copyWith(isPlaying: event.isPlaying);
case VideoEventType.unknown:
break;
}
}
void errorListener(Object obj) {
final e = obj as PlatformException;
value = VideoPlayerValue.erroneous(e.message!);
_timer?.cancel();
if (!initializingCompleter.isCompleted) {
initializingCompleter.completeError(obj);
}
}
_eventSubscription = _platform
.videoEventsFor(_playerId)
.listen(eventListener, onError: errorListener);
return initializingCompleter.future;
}
@override
Future<void> dispose() async {
if (_creatingCompleter != null) {
await _creatingCompleter!.future;
_timer?.cancel();
await _eventSubscription?.cancel();
await _platform.dispose(_playerId);
}
super.dispose();
}
/// Starts playing the video.
Future<void> play() async {
value = value.copyWith(isPlaying: true);
await _applyPlayPause();
}
/// Pauses the video.
Future<void> pause() async {
value = value.copyWith(isPlaying: false);
await _applyPlayPause();
}
Future<void> _applyPlayPause() async {
_timer?.cancel();
if (value.isPlaying) {
await _platform.play(_playerId);
_timer = Timer.periodic(const Duration(milliseconds: 500), (
Timer timer,
) async {
final Duration? newPosition = await position;
if (newPosition == null) {
return;
}
_updatePosition(newPosition);
});
await _applyPlaybackSpeed();
} else {
await _platform.pause(_playerId);
}
}
Future<void> _applyPlaybackSpeed() async {
if (value.isPlaying) {
await _platform.setPlaybackSpeed(_playerId, value.playbackSpeed);
}
}
/// The position in the current video.
Future<Duration?> get position async {
return _platform.getPosition(_playerId);
}
/// Sets the video's current timestamp to be at [position].
Future<void> seekTo(Duration position) async {
if (position > value.duration) {
position = value.duration;
} else if (position < Duration.zero) {
position = Duration.zero;
}
await _platform.seekTo(_playerId, position);
_updatePosition(position);
}
/// Sets the playback speed.
Future<void> setPlaybackSpeed(double speed) async {
value = value.copyWith(playbackSpeed: speed);
await _applyPlaybackSpeed();
}
void _updatePosition(Duration position) {
value = value.copyWith(position: position);
}
}
/// Widget that displays the video controlled by [controller].
class VideoPlayer extends StatefulWidget {
/// Uses the given [controller] for all video rendered in this widget.
const VideoPlayer(this.controller, {super.key});
/// The [MiniController] responsible for the video being rendered in
/// this widget.
final MiniController controller;
@override
State<VideoPlayer> createState() => _VideoPlayerState();
}
class _VideoPlayerState extends State<VideoPlayer> {
_VideoPlayerState() {
_listener = () {
final int newPlayerId = widget.controller.playerId;
if (newPlayerId != _playerId) {
setState(() {
_playerId = newPlayerId;
});
}
};
}
late VoidCallback _listener;
late int _playerId;
@override
void initState() {
super.initState();
_playerId = widget.controller.playerId;
// Need to listen for initialization events since the actual player ID
// becomes available after asynchronous initialization finishes.
widget.controller.addListener(_listener);
}
@override
void didUpdateWidget(VideoPlayer oldWidget) {
super.didUpdateWidget(oldWidget);
oldWidget.controller.removeListener(_listener);
_playerId = widget.controller.playerId;
widget.controller.addListener(_listener);
}
@override
void dispose() {
widget.controller.removeListener(_listener);
super.dispose();
}
@override
Widget build(BuildContext context) {
return _playerId == MiniController.kUninitializedPlayerId
? Container()
: _VideoPlayerWithRotation(
rotation: widget.controller.value.rotationCorrection,
child: _platform.buildViewWithOptions(
VideoViewOptions(playerId: _playerId),
),
);
}
}
class _VideoPlayerWithRotation extends StatelessWidget {
const _VideoPlayerWithRotation({required this.rotation, required this.child});
final int rotation;
final Widget child;
@override
Widget build(BuildContext context) {
if (rotation == 0) {
return child;
}
return RotatedBox(quarterTurns: rotation ~/ 90, child: child);
}
}
class _VideoScrubber extends StatefulWidget {
const _VideoScrubber({required this.child, required this.controller});
final Widget child;
final MiniController controller;
@override
_VideoScrubberState createState() => _VideoScrubberState();
}
class _VideoScrubberState extends State<_VideoScrubber> {
MiniController get controller => widget.controller;
@override
Widget build(BuildContext context) {
void seekToRelativePosition(Offset globalPosition) {
final box = context.findRenderObject()! as RenderBox;
final Offset tapPos = box.globalToLocal(globalPosition);
final double relative = tapPos.dx / box.size.width;
final Duration position = controller.value.duration * relative;
controller.seekTo(position);
}
return GestureDetector(
behavior: HitTestBehavior.opaque,
child: widget.child,
onTapDown: (TapDownDetails details) {
if (controller.value.isInitialized) {
seekToRelativePosition(details.globalPosition);
}
},
);
}
}
/// Displays the play/buffering status of the video controlled by [controller].
class VideoProgressIndicator extends StatefulWidget {
/// Construct an instance that displays the play/buffering status of the video
/// controlled by [controller].
const VideoProgressIndicator(this.controller, {super.key});
/// The [MiniController] that actually associates a video with this
/// widget.
final MiniController controller;
@override
State<VideoProgressIndicator> createState() => _VideoProgressIndicatorState();
}
class _VideoProgressIndicatorState extends State<VideoProgressIndicator> {
_VideoProgressIndicatorState() {
listener = () {
if (mounted) {
setState(() {});
}
};
}
late VoidCallback listener;
MiniController get controller => widget.controller;
@override
void initState() {
super.initState();
controller.addListener(listener);
}
@override
void dispose() {
controller.removeListener(listener);
super.dispose();
}
@override
Widget build(BuildContext context) {
const playedColor = Color.fromRGBO(255, 0, 0, 0.7);
const bufferedColor = Color.fromRGBO(50, 50, 200, 0.2);
const backgroundColor = Color.fromRGBO(200, 200, 200, 0.5);
final Widget progressIndicator;
if (controller.value.isInitialized) {
final int duration = controller.value.duration.inMilliseconds;
final int position = controller.value.position.inMilliseconds;
final double maxBuffering = duration == 0.0
? 0.0
: controller.value.buffered
.map((DurationRange range) => range.end.inMilliseconds)
.fold(0, math.max) /
duration;
progressIndicator = Stack(
fit: StackFit.passthrough,
children: <Widget>[
LinearProgressIndicator(
value: maxBuffering,
valueColor: const AlwaysStoppedAnimation<Color>(bufferedColor),
backgroundColor: backgroundColor,
),
LinearProgressIndicator(
value: duration == 0.0 ? 0.0 : position / duration,
valueColor: const AlwaysStoppedAnimation<Color>(playedColor),
backgroundColor: Colors.transparent,
),
],
);
} else {
progressIndicator = const LinearProgressIndicator(
valueColor: AlwaysStoppedAnimation<Color>(playedColor),
backgroundColor: backgroundColor,
);
}
return _VideoScrubber(
controller: controller,
child: Padding(
padding: const EdgeInsets.only(top: 5.0),
child: progressIndicator,
),
);
}
}

View File

@@ -0,0 +1,7 @@
// 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.
import 'package:integration_test/integration_test_driver.dart';
Future<void> main() => integrationDriver();

View File

@@ -0,0 +1,524 @@
// 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.
import 'dart:async';
import 'package:flutter/widgets.dart';
import 'package:video_player_platform_interface/video_player_platform_interface.dart';
import 'messages.g.dart' hide videoEvents;
import 'messages.g.dart' as pigeon show videoEvents;
import 'platform_view_player.dart';
/// The non-test implementation of `_apiProvider`.
VideoPlayerInstanceApi _productionApiProvider(int playerId) {
return VideoPlayerInstanceApi(messageChannelSuffix: playerId.toString());
}
/// The non-test implementation of `_videoEventStreamProvider`.
Stream<PlatformVideoEvent> _productionVideoEventStreamProvider(
String streamIdentifier,
) {
return pigeon.videoEvents(instanceName: streamIdentifier);
}
/// An Android implementation of [VideoPlayerPlatform] that uses the
/// Pigeon-generated [VideoPlayerApi].
class AndroidVideoPlayer extends VideoPlayerPlatform {
/// Creates a new Android video player implementation instance.
AndroidVideoPlayer({
@visibleForTesting AndroidVideoPlayerApi? pluginApi,
@visibleForTesting
VideoPlayerInstanceApi Function(int playerId)? playerApiProvider,
Stream<PlatformVideoEvent> Function(String streamIdentifier)?
videoEventStreamProvider,
}) : _api = pluginApi ?? AndroidVideoPlayerApi(),
_playerApiProvider = playerApiProvider ?? _productionApiProvider,
_videoEventStreamProvider =
videoEventStreamProvider ?? _productionVideoEventStreamProvider;
final AndroidVideoPlayerApi _api;
// A method to create VideoPlayerInstanceApi instances, which can be
// overridden for testing.
final VideoPlayerInstanceApi Function(int playerId) _playerApiProvider;
// A method to create video event stream instances, which can be
// overridden for testing.
final Stream<PlatformVideoEvent> Function(String streamIdentifier)
_videoEventStreamProvider;
final Map<int, _PlayerInstance> _players = <int, _PlayerInstance>{};
/// Registers this class as the default instance of [PathProviderPlatform].
static void registerWith() {
VideoPlayerPlatform.instance = AndroidVideoPlayer();
}
@override
Future<void> init() {
return _api.initialize();
}
@override
Future<void> dispose(int playerId) async {
final _PlayerInstance? player = _players.remove(playerId);
await player?.dispose();
await _api.dispose(playerId);
}
@override
Future<int?> create(DataSource dataSource) {
return createWithOptions(
VideoCreationOptions(
dataSource: dataSource,
// Compatibility; "create" is always a textureView (createWithOptions
// allows selecting).
viewType: VideoViewType.textureView,
),
);
}
@override
Future<int?> createWithOptions(VideoCreationOptions options) async {
final DataSource dataSource = options.dataSource;
String? uri;
PlatformVideoFormat? formatHint;
final Map<String, String> httpHeaders = dataSource.httpHeaders;
final String? userAgent = _userAgentFromHeaders(httpHeaders);
switch (dataSource.sourceType) {
case DataSourceType.asset:
final String? asset = dataSource.asset;
if (asset == null) {
throw ArgumentError(
'"asset" must be non-null for an asset data source',
);
}
final String key = await _api.getLookupKeyForAsset(
asset,
dataSource.package,
);
uri = 'asset:///$key';
case DataSourceType.network:
uri = dataSource.uri;
formatHint = _platformVideoFormatFromVideoFormat(dataSource.formatHint);
case DataSourceType.file:
case DataSourceType.contentUri:
uri = dataSource.uri;
}
if (uri == null) {
throw ArgumentError('Unable to construct a video asset from $options');
}
final pigeonCreationOptions = CreationOptions(
uri: uri,
httpHeaders: httpHeaders,
userAgent: userAgent,
formatHint: formatHint,
);
final int playerId;
final VideoPlayerViewState state;
switch (options.viewType) {
case VideoViewType.textureView:
final TexturePlayerIds ids = await _api.createForTextureView(
pigeonCreationOptions,
);
playerId = ids.playerId;
state = VideoPlayerTextureViewState(textureId: ids.textureId);
case VideoViewType.platformView:
playerId = await _api.createForPlatformView(pigeonCreationOptions);
state = const VideoPlayerPlatformViewState();
}
ensurePlayerInitialized(playerId, state);
return playerId;
}
// Returns the user agent to use with ExoPlayer for the given headers.
String? _userAgentFromHeaders(Map<String, String> httpHeaders) {
// TODO(stuartmorgan): HTTP headers are case-insensitive, so this should be
// adjusted to find any entry where the key has a case-insensitive match.
const userAgentKey = 'User-Agent';
// TODO(stuartmorgan): Investigate removing this. The use of a hard-coded
// default agent dates back to the original ExoPlayer implementation of the
// plugin, but it's not clear why the default isn't null, which would let
// ExoPlayer use its own default value.
const defaultUserAgent = 'ExoPlayer';
return httpHeaders[userAgentKey] ?? defaultUserAgent;
}
/// Returns the player instance for [playerId], creating it if it doesn't
/// already exist.
@visibleForTesting
void ensurePlayerInitialized(int playerId, VideoPlayerViewState viewState) {
_players.putIfAbsent(playerId, () {
return _PlayerInstance(
_playerApiProvider(playerId),
viewState,
videoEventStream: _videoEventStreamProvider(playerId.toString()),
);
});
}
@override
Future<void> setLooping(int playerId, bool looping) {
return _playerWith(id: playerId).setLooping(looping);
}
@override
Future<void> play(int playerId) {
return _playerWith(id: playerId).play();
}
@override
Future<void> pause(int playerId) {
return _playerWith(id: playerId).pause();
}
@override
Future<void> setVolume(int playerId, double volume) {
return _playerWith(id: playerId).setVolume(volume);
}
@override
Future<void> setPlaybackSpeed(int playerId, double speed) {
assert(speed > 0);
return _playerWith(id: playerId).setPlaybackSpeed(speed);
}
@override
Future<void> seekTo(int playerId, Duration position) {
return _playerWith(id: playerId).seekTo(position);
}
@override
Future<Duration> getPosition(int playerId) async {
return _playerWith(id: playerId).getPosition();
}
@override
Stream<VideoEvent> videoEventsFor(int playerId) {
return _playerWith(id: playerId).videoEvents();
}
@override
Widget buildView(int playerId) {
return buildViewWithOptions(VideoViewOptions(playerId: playerId));
}
@override
Widget buildViewWithOptions(VideoViewOptions options) {
final int playerId = options.playerId;
final VideoPlayerViewState viewState = _playerWith(id: playerId).viewState;
return switch (viewState) {
VideoPlayerTextureViewState(:final int textureId) => Texture(
textureId: textureId,
),
VideoPlayerPlatformViewState() => PlatformViewPlayer(playerId: playerId),
};
}
@override
Future<void> setMixWithOthers(bool mixWithOthers) {
return _api.setMixWithOthers(mixWithOthers);
}
@override
Future<List<VideoAudioTrack>> getAudioTracks(int playerId) async {
final NativeAudioTrackData nativeData = await _playerWith(
id: playerId,
).getAudioTracks();
final tracks = <VideoAudioTrack>[];
// Convert ExoPlayer tracks to VideoAudioTrack
if (nativeData.exoPlayerTracks != null) {
for (final ExoPlayerAudioTrackData track in nativeData.exoPlayerTracks!) {
// Construct a string ID from groupIndex and trackIndex for compatibility
final trackId = '${track.groupIndex}_${track.trackIndex}';
tracks.add(
VideoAudioTrack(
id: trackId,
label: track.label,
language: track.language,
isSelected: track.isSelected,
bitrate: track.bitrate,
sampleRate: track.sampleRate,
channelCount: track.channelCount,
codec: track.codec,
),
);
}
}
return tracks;
}
@override
Future<void> selectAudioTrack(int playerId, String trackId) {
return _playerWith(id: playerId).selectAudioTrack(trackId);
}
@override
bool isAudioTrackSupportAvailable() {
// Android with ExoPlayer supports audio track selection
return true;
}
_PlayerInstance _playerWith({required int id}) {
final _PlayerInstance? player = _players[id];
return player ?? (throw StateError('No active player with ID $id.'));
}
PlatformVideoFormat? _platformVideoFormatFromVideoFormat(
VideoFormat? format,
) {
return switch (format) {
VideoFormat.dash => PlatformVideoFormat.dash,
VideoFormat.hls => PlatformVideoFormat.hls,
VideoFormat.ss => PlatformVideoFormat.ss,
VideoFormat.other => null,
// Include a catch-all, since the enum comes from another package, so
// this code must handle the possibility of a new enum value.
_ => null,
};
}
}
/// An instance of a video player, corresponding to a single player ID in
/// [AndroidVideoPlayer].
class _PlayerInstance {
/// Creates a new instance of [_PlayerInstance] corresponding to the given
/// API instance.
_PlayerInstance(
this._api,
this.viewState, {
required Stream<PlatformVideoEvent> videoEventStream,
}) {
_eventSubscription = videoEventStream.listen(
_onStreamEvent,
onError: (Object e) {
_setBuffering(false);
_eventStreamController.addError(e);
},
);
}
final VideoPlayerInstanceApi _api;
final StreamController<VideoEvent> _eventStreamController =
StreamController<VideoEvent>();
late final StreamSubscription<dynamic> _eventSubscription;
bool _isDisposed = false;
Timer? _bufferPollingTimer;
int _lastBufferPosition = -1;
bool _isBuffering = false;
Completer<void>? _audioTrackSelectionCompleter;
final VideoPlayerViewState viewState;
Future<void> setLooping(bool looping) {
return _api.setLooping(looping);
}
Future<void> play() {
return _api.play();
}
Future<void> pause() {
return _api.pause();
}
Future<void> setVolume(double volume) {
return _api.setVolume(volume);
}
Future<void> setPlaybackSpeed(double speed) {
return _api.setPlaybackSpeed(speed);
}
Future<void> seekTo(Duration position) {
return _api.seekTo(position.inMilliseconds);
}
Future<Duration> getPosition() async {
return Duration(milliseconds: await _api.getCurrentPosition());
}
Stream<VideoEvent> videoEvents() {
return _eventStreamController.stream;
}
Future<NativeAudioTrackData> getAudioTracks() {
return _api.getAudioTracks();
}
Future<void> selectAudioTrack(String trackId) async {
// Parse the trackId to get groupIndex and trackIndex
final List<String> parts = trackId.split('_');
if (parts.length != 2) {
throw ArgumentError(
'Invalid trackId format: "$trackId". Expected format: "groupIndex_trackIndex"',
);
}
final int groupIndex = int.parse(parts[0]);
final int trackIndex = int.parse(parts[1]);
// Create a completer to wait for the track selection to complete
_audioTrackSelectionCompleter = Completer<void>();
try {
await _api.selectAudioTrack(groupIndex, trackIndex);
// Wait for the onTracksChanged event from ExoPlayer with a timeout
await _audioTrackSelectionCompleter!.future.timeout(
const Duration(seconds: 5),
onTimeout: () {
// If we timeout, just continue - the track may still have been selected
// This is a fallback in case the event doesn't arrive for some reason
},
);
} finally {
_audioTrackSelectionCompleter = null;
}
}
Future<void> dispose() async {
_isDisposed = true;
_bufferPollingTimer?.cancel();
await _eventSubscription.cancel();
}
void _setBuffering(bool buffering) {
if (buffering != _isBuffering) {
_isBuffering = buffering;
_eventStreamController.add(
VideoEvent(
eventType: buffering
? VideoEventType.bufferingStart
: VideoEventType.bufferingEnd,
),
);
// Trigger an extra buffer position check, so that clients have an
// accurate reporting of the current buffering state.
_api.getBufferedPosition().then((int position) {
if (!_isDisposed) {
_updateBufferPosition(position);
}
});
}
}
/// Sends a buffering update if the buffer position has changed since the
/// last check.
void _updateBufferPosition(int bufferPosition) {
if (bufferPosition != _lastBufferPosition) {
_lastBufferPosition = bufferPosition;
_eventStreamController.add(
VideoEvent(
eventType: VideoEventType.bufferingUpdate,
buffered: _bufferRangeForPosition(bufferPosition),
),
);
}
}
void _onStreamEvent(PlatformVideoEvent event) {
switch (event) {
case InitializationEvent _:
_eventStreamController.add(
VideoEvent(
eventType: VideoEventType.initialized,
duration: Duration(milliseconds: event.duration),
size: Size(event.width.toDouble(), event.height.toDouble()),
rotationCorrection: event.rotationCorrection,
),
);
// Start polling for buffer position, since there is no buffer position
// event to listen to.
_bufferPollingTimer = Timer.periodic(const Duration(seconds: 1), (
Timer timer,
) async {
final int position = await _api.getBufferedPosition();
if (!_isDisposed) {
_updateBufferPosition(position);
}
});
case IsPlayingStateEvent _:
_eventStreamController.add(
VideoEvent(
eventType: VideoEventType.isPlayingStateUpdate,
isPlaying: event.isPlaying,
),
);
case PlaybackStateChangeEvent _:
switch (event.state) {
case PlatformPlaybackState.idle:
// This is currently only used for buffering below.
break;
case PlatformPlaybackState.buffering:
_setBuffering(true);
case PlatformPlaybackState.ready:
// On the Dart side, this is only used for buffering below. On the
// native side it drives the 'initialized' event; that can't
// currently be moved here since gathering the initialization state
// should be synchronous with the state change.
break;
case PlatformPlaybackState.ended:
_eventStreamController.add(
VideoEvent(eventType: VideoEventType.completed),
);
case PlatformPlaybackState.unknown:
// Ignore unknown states. This isn't an error since the media
// framework could add new states in the future.
break;
}
// Any state other than buffering should end the buffering state.
if (event.state != PlatformPlaybackState.buffering) {
_setBuffering(false);
}
case AudioTrackChangedEvent _:
// Complete the audio track selection completer if it exists
// This signals that the track selection has completed
if (_audioTrackSelectionCompleter != null &&
!_audioTrackSelectionCompleter!.isCompleted) {
_audioTrackSelectionCompleter!.complete();
}
}
}
// Turns a single buffer position, which is what ExoPlayer reports, into the
// DurationRange array expected by [VideoEventType.bufferingUpdate].
List<DurationRange> _bufferRangeForPosition(int milliseconds) {
return <DurationRange>[
DurationRange(Duration.zero, Duration(milliseconds: milliseconds)),
];
}
}
/// Base class representing the state of a video player view.
@visibleForTesting
@immutable
sealed class VideoPlayerViewState {
const VideoPlayerViewState();
}
/// Represents the state of a video player view that uses a texture.
@visibleForTesting
final class VideoPlayerTextureViewState extends VideoPlayerViewState {
/// Creates a new instance of [VideoPlayerTextureViewState].
const VideoPlayerTextureViewState({required this.textureId});
/// The ID of the texture used by the video player.
final int textureId;
}
/// Represents the state of a video player view that uses a platform view.
@visibleForTesting
final class VideoPlayerPlatformViewState extends VideoPlayerViewState {
/// Creates a new instance of [VideoPlayerPlatformViewState].
const VideoPlayerPlatformViewState();
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,55 @@
// 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.
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'messages.g.dart';
/// A widget that displays a video player using a platform view.
class PlatformViewPlayer extends StatelessWidget {
/// Creates a new instance of [PlatformViewPlayer].
const PlatformViewPlayer({super.key, required this.playerId});
/// The ID of the player.
final int playerId;
@override
Widget build(BuildContext context) {
const viewType = 'plugins.flutter.dev/video_player_android';
final creationParams = PlatformVideoViewCreationParams(playerId: playerId);
// IgnorePointer so that GestureDetector can be used above the platform view.
return IgnorePointer(
child: PlatformViewLink(
viewType: viewType,
surfaceFactory:
(BuildContext context, PlatformViewController controller) {
return AndroidViewSurface(
controller: controller as AndroidViewController,
gestureRecognizers:
const <Factory<OneSequenceGestureRecognizer>>{},
hitTestBehavior: PlatformViewHitTestBehavior.opaque,
);
},
onCreatePlatformView: (PlatformViewCreationParams params) {
return PlatformViewsService.initSurfaceAndroidView(
id: params.id,
viewType: viewType,
layoutDirection:
Directionality.maybeOf(context) ?? TextDirection.ltr,
creationParams: creationParams,
creationParamsCodec: AndroidVideoPlayerApi.pigeonChannelCodec,
onFocus: () => params.onFocusChanged(true),
)
..addOnPlatformViewCreatedListener(params.onPlatformViewCreated)
..create();
},
),
);
}
}

View File

@@ -0,0 +1,5 @@
// 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.
export 'src/android_video_player.dart';

View File

@@ -0,0 +1,200 @@
// 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.
import 'package:pigeon/pigeon.dart';
@ConfigurePigeon(
PigeonOptions(
dartOut: 'lib/src/messages.g.dart',
kotlinOut:
'android/src/main/kotlin/io/flutter/plugins/videoplayer/Messages.kt',
kotlinOptions: KotlinOptions(package: 'io.flutter.plugins.videoplayer'),
copyrightHeader: 'pigeons/copyright.txt',
),
)
/// Pigeon equivalent of video_platform_interface's VideoFormat.
enum PlatformVideoFormat { dash, hls, ss }
/// Pigeon equivalent of Player's playback state.
/// https://developer.android.com/media/media3/exoplayer/listening-to-player-events#playback-state
enum PlatformPlaybackState { idle, buffering, ready, ended, unknown }
sealed class PlatformVideoEvent {}
/// Sent when the video is initialized and ready to play.
class InitializationEvent extends PlatformVideoEvent {
/// The video duration in milliseconds.
late final int duration;
/// The width of the video in pixels.
late final int width;
/// The height of the video in pixels.
late final int height;
/// The rotation that should be applied during playback.
late final int rotationCorrection;
}
/// Sent when the video state changes.
///
/// Corresponds to ExoPlayer's onPlaybackStateChanged.
class PlaybackStateChangeEvent extends PlatformVideoEvent {
late final PlatformPlaybackState state;
}
/// Sent when the video starts or stops playing.
///
/// Corresponds to ExoPlayer's onIsPlayingChanged.
class IsPlayingStateEvent extends PlatformVideoEvent {
late final bool isPlaying;
}
/// Sent when audio tracks change.
///
/// This includes when the selected audio track changes after calling selectAudioTrack.
/// Corresponds to ExoPlayer's onTracksChanged.
class AudioTrackChangedEvent extends PlatformVideoEvent {
/// The ID of the newly selected audio track, if any.
late final String? selectedTrackId;
}
/// Information passed to the platform view creation.
class PlatformVideoViewCreationParams {
const PlatformVideoViewCreationParams({required this.playerId});
final int playerId;
}
class CreationOptions {
CreationOptions({required this.uri, required this.httpHeaders});
String uri;
PlatformVideoFormat? formatHint;
Map<String, String> httpHeaders;
String? userAgent;
}
class TexturePlayerIds {
TexturePlayerIds({required this.playerId, required this.textureId});
final int playerId;
final int textureId;
}
class PlaybackState {
PlaybackState({required this.playPosition, required this.bufferPosition});
/// The current playback position, in milliseconds.
final int playPosition;
/// The current buffer position, in milliseconds.
final int bufferPosition;
}
/// Represents an audio track in a video.
class AudioTrackMessage {
AudioTrackMessage({
required this.id,
required this.label,
required this.language,
required this.isSelected,
this.bitrate,
this.sampleRate,
this.channelCount,
this.codec,
});
String id;
String label;
String language;
bool isSelected;
int? bitrate;
int? sampleRate;
int? channelCount;
String? codec;
}
/// Raw audio track data from ExoPlayer Format objects.
class ExoPlayerAudioTrackData {
ExoPlayerAudioTrackData({
required this.groupIndex,
required this.trackIndex,
this.label,
this.language,
required this.isSelected,
this.bitrate,
this.sampleRate,
this.channelCount,
this.codec,
});
int groupIndex;
int trackIndex;
String? label;
String? language;
bool isSelected;
int? bitrate;
int? sampleRate;
int? channelCount;
String? codec;
}
/// Container for raw audio track data from Android ExoPlayer.
class NativeAudioTrackData {
NativeAudioTrackData({this.exoPlayerTracks});
/// ExoPlayer-based tracks
List<ExoPlayerAudioTrackData>? exoPlayerTracks;
}
@HostApi()
abstract class AndroidVideoPlayerApi {
void initialize();
// Creates a new player using a platform view for rendering and returns its
// ID.
int createForPlatformView(CreationOptions options);
// Creates a new player using a texture for rendering and returns its IDs.
TexturePlayerIds createForTextureView(CreationOptions options);
void dispose(int playerId);
void setMixWithOthers(bool mixWithOthers);
String getLookupKeyForAsset(String asset, String? packageName);
}
@HostApi()
abstract class VideoPlayerInstanceApi {
/// Sets whether to automatically loop playback of the video.
void setLooping(bool looping);
/// Sets the volume, with 0.0 being muted and 1.0 being full volume.
void setVolume(double volume);
/// Sets the playback speed as a multiple of normal speed.
void setPlaybackSpeed(double speed);
/// Begins playback if the video is not currently playing.
void play();
/// Pauses playback if the video is currently playing.
void pause();
/// Seeks to the given playback position, in milliseconds.
void seekTo(int position);
/// Returns the current playback position, in milliseconds.
int getCurrentPosition();
/// Returns the current buffer position, in milliseconds.
int getBufferedPosition();
/// Gets the available audio tracks for the video.
NativeAudioTrackData getAudioTracks();
/// Selects which audio track is chosen for playback from its [groupIndex] and [trackIndex]
void selectAudioTrack(int groupIndex, int trackIndex);
}
@EventChannelApi()
abstract class VideoEventChannel {
PlatformVideoEvent videoEvents();
}

View File

@@ -0,0 +1,954 @@
// 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.
import 'dart:async';
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import 'package:video_player_android/src/messages.g.dart';
import 'package:video_player_android/src/platform_view_player.dart';
import 'package:video_player_android/video_player_android.dart';
import 'package:video_player_platform_interface/video_player_platform_interface.dart';
import 'android_video_player_test.mocks.dart';
@GenerateNiceMocks(<MockSpec<Object>>[
MockSpec<AndroidVideoPlayerApi>(),
MockSpec<VideoPlayerInstanceApi>(),
])
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
// Provide dummy values for audio track types
provideDummy<NativeAudioTrackData>(
NativeAudioTrackData(exoPlayerTracks: <ExoPlayerAudioTrackData>[]),
);
provideDummy<Future<NativeAudioTrackData>>(
Future<NativeAudioTrackData>.value(
NativeAudioTrackData(exoPlayerTracks: <ExoPlayerAudioTrackData>[]),
),
);
provideDummy<Future<void>>(Future<void>.value());
(AndroidVideoPlayer, MockAndroidVideoPlayerApi, MockVideoPlayerInstanceApi)
setUpMockPlayer({required int playerId, int? textureId}) {
final pluginApi = MockAndroidVideoPlayerApi();
final instanceApi = MockVideoPlayerInstanceApi();
final player = AndroidVideoPlayer(
pluginApi: pluginApi,
playerApiProvider: (_) => instanceApi,
);
player.ensurePlayerInitialized(
playerId,
textureId == null
? const VideoPlayerPlatformViewState()
: VideoPlayerTextureViewState(textureId: textureId),
);
return (player, pluginApi, instanceApi);
}
(
AndroidVideoPlayer,
MockAndroidVideoPlayerApi,
MockVideoPlayerInstanceApi,
StreamController<PlatformVideoEvent>,
)
setUpMockPlayerWithStream({required int playerId, int? textureId}) {
final pluginApi = MockAndroidVideoPlayerApi();
final instanceApi = MockVideoPlayerInstanceApi();
final streamController = StreamController<PlatformVideoEvent>();
final player = AndroidVideoPlayer(
pluginApi: pluginApi,
playerApiProvider: (_) => instanceApi,
videoEventStreamProvider: (_) =>
streamController.stream.asBroadcastStream(),
);
player.ensurePlayerInitialized(
playerId,
textureId == null
? const VideoPlayerPlatformViewState()
: VideoPlayerTextureViewState(textureId: textureId),
);
return (player, pluginApi, instanceApi, streamController);
}
test('registration', () async {
AndroidVideoPlayer.registerWith();
expect(VideoPlayerPlatform.instance, isA<AndroidVideoPlayer>());
});
group('AndroidVideoPlayer', () {
test('init', () async {
final (AndroidVideoPlayer player, MockAndroidVideoPlayerApi api, _) =
setUpMockPlayer(playerId: 1);
await player.init();
verify(api.initialize());
});
test('dispose', () async {
final (AndroidVideoPlayer player, MockAndroidVideoPlayerApi api, _) =
setUpMockPlayer(playerId: 1);
await player.dispose(1);
verify(api.dispose(1));
});
test('create with asset', () async {
final (AndroidVideoPlayer player, MockAndroidVideoPlayerApi api, _) =
setUpMockPlayer(playerId: 1, textureId: 100);
const newPlayerId = 2;
when(api.createForTextureView(any)).thenAnswer(
(_) async => TexturePlayerIds(playerId: newPlayerId, textureId: 100),
);
const asset = 'someAsset';
const package = 'somePackage';
const assetKey = 'resultingAssetKey';
when(
api.getLookupKeyForAsset(asset, package),
).thenAnswer((_) async => assetKey);
final int? playerId = await player.create(
DataSource(
sourceType: DataSourceType.asset,
asset: asset,
package: package,
),
);
final VerificationResult verification = verify(
api.createForTextureView(captureAny),
);
final creationOptions = verification.captured[0] as CreationOptions;
expect(creationOptions.uri, 'asset:///$assetKey');
expect(playerId, newPlayerId);
expect(
player.buildViewWithOptions(VideoViewOptions(playerId: playerId!)),
isA<Texture>(),
);
});
test('create with network', () async {
final (AndroidVideoPlayer player, MockAndroidVideoPlayerApi api, _) =
setUpMockPlayer(playerId: 1, textureId: 100);
const newPlayerId = 2;
when(api.createForTextureView(any)).thenAnswer(
(_) async => TexturePlayerIds(playerId: newPlayerId, textureId: 100),
);
const uri = 'https://example.com';
final int? playerId = await player.create(
DataSource(
sourceType: DataSourceType.network,
uri: uri,
formatHint: VideoFormat.dash,
),
);
final VerificationResult verification = verify(
api.createForTextureView(captureAny),
);
final creationOptions = verification.captured[0] as CreationOptions;
expect(creationOptions.uri, uri);
expect(creationOptions.formatHint, PlatformVideoFormat.dash);
expect(creationOptions.httpHeaders, <String, String>{});
expect(playerId, newPlayerId);
expect(
player.buildViewWithOptions(VideoViewOptions(playerId: playerId!)),
isA<Texture>(),
);
});
test('create with network passes headers', () async {
final (AndroidVideoPlayer player, MockAndroidVideoPlayerApi api, _) =
setUpMockPlayer(playerId: 1, textureId: 100);
when(
api.createForTextureView(any),
).thenAnswer((_) async => TexturePlayerIds(playerId: 2, textureId: 100));
const headers = <String, String>{'Authorization': 'Bearer token'};
await player.create(
DataSource(
sourceType: DataSourceType.network,
uri: 'https://example.com',
httpHeaders: headers,
),
);
final VerificationResult verification = verify(
api.createForTextureView(captureAny),
);
final creationOptions = verification.captured[0] as CreationOptions;
expect(creationOptions.httpHeaders, headers);
});
test('create with network sets a default user agent', () async {
final (AndroidVideoPlayer player, MockAndroidVideoPlayerApi api, _) =
setUpMockPlayer(playerId: 1, textureId: 100);
when(
api.createForTextureView(any),
).thenAnswer((_) async => TexturePlayerIds(playerId: 2, textureId: 100));
await player.create(
DataSource(
sourceType: DataSourceType.network,
uri: 'https://example.com',
httpHeaders: <String, String>{},
),
);
final VerificationResult verification = verify(
api.createForTextureView(captureAny),
);
final creationOptions = verification.captured[0] as CreationOptions;
expect(creationOptions.userAgent, 'ExoPlayer');
});
test('create with network uses user agent from headers', () async {
final (AndroidVideoPlayer player, MockAndroidVideoPlayerApi api, _) =
setUpMockPlayer(playerId: 1, textureId: 100);
when(
api.createForTextureView(any),
).thenAnswer((_) async => TexturePlayerIds(playerId: 2, textureId: 100));
const userAgent = 'Test User Agent';
const headers = <String, String>{'User-Agent': userAgent};
await player.create(
DataSource(
sourceType: DataSourceType.network,
uri: 'https://example.com',
httpHeaders: headers,
),
);
final VerificationResult verification = verify(
api.createForTextureView(captureAny),
);
final creationOptions = verification.captured[0] as CreationOptions;
expect(creationOptions.userAgent, userAgent);
});
test('create with file', () async {
final (AndroidVideoPlayer player, MockAndroidVideoPlayerApi api, _) =
setUpMockPlayer(playerId: 1, textureId: 100);
when(
api.createForTextureView(any),
).thenAnswer((_) async => TexturePlayerIds(playerId: 2, textureId: 100));
const fileUri = 'file:///foo/bar';
final int? playerId = await player.create(
DataSource(sourceType: DataSourceType.file, uri: fileUri),
);
final VerificationResult verification = verify(
api.createForTextureView(captureAny),
);
final creationOptions = verification.captured[0] as CreationOptions;
expect(creationOptions.uri, fileUri);
expect(
player.buildViewWithOptions(VideoViewOptions(playerId: playerId!)),
isA<Texture>(),
);
});
test('create with file passes headers', () async {
final (AndroidVideoPlayer player, MockAndroidVideoPlayerApi api, _) =
setUpMockPlayer(playerId: 1, textureId: 100);
when(
api.createForTextureView(any),
).thenAnswer((_) async => TexturePlayerIds(playerId: 2, textureId: 100));
const fileUri = 'file:///foo/bar';
const headers = <String, String>{'Authorization': 'Bearer token'};
await player.create(
DataSource(
sourceType: DataSourceType.file,
uri: fileUri,
httpHeaders: headers,
),
);
final VerificationResult verification = verify(
api.createForTextureView(captureAny),
);
final creationOptions = verification.captured[0] as CreationOptions;
expect(creationOptions.httpHeaders, headers);
});
test('createWithOptions with asset', () async {
final (AndroidVideoPlayer player, MockAndroidVideoPlayerApi api, _) =
setUpMockPlayer(playerId: 1, textureId: 100);
const newPlayerId = 2;
when(api.createForTextureView(any)).thenAnswer(
(_) async => TexturePlayerIds(playerId: newPlayerId, textureId: 100),
);
const asset = 'someAsset';
const package = 'somePackage';
const assetKey = 'resultingAssetKey';
when(
api.getLookupKeyForAsset(asset, package),
).thenAnswer((_) async => assetKey);
final int? playerId = await player.createWithOptions(
VideoCreationOptions(
dataSource: DataSource(
sourceType: DataSourceType.asset,
asset: asset,
package: package,
),
viewType: VideoViewType.textureView,
),
);
final VerificationResult verification = verify(
api.createForTextureView(captureAny),
);
final creationOptions = verification.captured[0] as CreationOptions;
expect(creationOptions.uri, 'asset:///$assetKey');
expect(playerId, newPlayerId);
expect(
player.buildViewWithOptions(VideoViewOptions(playerId: playerId!)),
isA<Texture>(),
);
});
test('createWithOptions with network', () async {
final (AndroidVideoPlayer player, MockAndroidVideoPlayerApi api, _) =
setUpMockPlayer(playerId: 1, textureId: 100);
const newPlayerId = 2;
when(api.createForTextureView(any)).thenAnswer(
(_) async => TexturePlayerIds(playerId: newPlayerId, textureId: 100),
);
const uri = 'https://example.com';
final int? playerId = await player.createWithOptions(
VideoCreationOptions(
dataSource: DataSource(
sourceType: DataSourceType.network,
uri: uri,
formatHint: VideoFormat.dash,
),
viewType: VideoViewType.textureView,
),
);
final VerificationResult verification = verify(
api.createForTextureView(captureAny),
);
final creationOptions = verification.captured[0] as CreationOptions;
expect(creationOptions.uri, uri);
expect(creationOptions.formatHint, PlatformVideoFormat.dash);
expect(creationOptions.httpHeaders, <String, String>{});
expect(playerId, newPlayerId);
expect(
player.buildViewWithOptions(VideoViewOptions(playerId: playerId!)),
isA<Texture>(),
);
});
test('createWithOptions with network passes headers', () async {
final (AndroidVideoPlayer player, MockAndroidVideoPlayerApi api, _) =
setUpMockPlayer(playerId: 1, textureId: 100);
const newPlayerId = 2;
when(api.createForTextureView(any)).thenAnswer(
(_) async => TexturePlayerIds(playerId: newPlayerId, textureId: 100),
);
const headers = <String, String>{'Authorization': 'Bearer token'};
final int? playerId = await player.createWithOptions(
VideoCreationOptions(
dataSource: DataSource(
sourceType: DataSourceType.network,
uri: 'https://example.com',
httpHeaders: headers,
),
viewType: VideoViewType.textureView,
),
);
final VerificationResult verification = verify(
api.createForTextureView(captureAny),
);
final creationOptions = verification.captured[0] as CreationOptions;
expect(creationOptions.httpHeaders, headers);
expect(playerId, newPlayerId);
});
test('createWithOptions with file', () async {
final (AndroidVideoPlayer player, MockAndroidVideoPlayerApi api, _) =
setUpMockPlayer(playerId: 1, textureId: 100);
const newPlayerId = 2;
when(api.createForTextureView(any)).thenAnswer(
(_) async => TexturePlayerIds(playerId: newPlayerId, textureId: 100),
);
const fileUri = 'file:///foo/bar';
final int? playerId = await player.createWithOptions(
VideoCreationOptions(
dataSource: DataSource(sourceType: DataSourceType.file, uri: fileUri),
viewType: VideoViewType.textureView,
),
);
final VerificationResult verification = verify(
api.createForTextureView(captureAny),
);
final creationOptions = verification.captured[0] as CreationOptions;
expect(creationOptions.uri, fileUri);
expect(playerId, newPlayerId);
expect(
player.buildViewWithOptions(VideoViewOptions(playerId: playerId!)),
isA<Texture>(),
);
});
test('createWithOptions with file passes headers', () async {
final (AndroidVideoPlayer player, MockAndroidVideoPlayerApi api, _) =
setUpMockPlayer(playerId: 1, textureId: 100);
when(
api.createForTextureView(any),
).thenAnswer((_) async => TexturePlayerIds(playerId: 2, textureId: 100));
const fileUri = 'file:///foo/bar';
const headers = <String, String>{'Authorization': 'Bearer token'};
await player.createWithOptions(
VideoCreationOptions(
dataSource: DataSource(
sourceType: DataSourceType.file,
uri: fileUri,
httpHeaders: headers,
),
viewType: VideoViewType.textureView,
),
);
final VerificationResult verification = verify(
api.createForTextureView(captureAny),
);
final creationOptions = verification.captured[0] as CreationOptions;
expect(creationOptions.httpHeaders, headers);
});
test('createWithOptions with platform view', () async {
final (AndroidVideoPlayer player, MockAndroidVideoPlayerApi api, _) =
setUpMockPlayer(playerId: 1);
const newPlayerId = 2;
when(api.createForPlatformView(any)).thenAnswer((_) async => newPlayerId);
const uri = 'file:///foo/bar';
final int? playerId = await player.createWithOptions(
VideoCreationOptions(
dataSource: DataSource(sourceType: DataSourceType.file, uri: uri),
viewType: VideoViewType.platformView,
),
);
final VerificationResult verification = verify(
api.createForPlatformView(captureAny),
);
final creationOptions = verification.captured[0] as CreationOptions;
expect(creationOptions.uri, uri);
expect(playerId, newPlayerId);
expect(
player.buildViewWithOptions(VideoViewOptions(playerId: playerId!)),
isA<PlatformViewPlayer>(),
);
});
test('setLooping', () async {
final (
AndroidVideoPlayer player,
_,
MockVideoPlayerInstanceApi playerApi,
) = setUpMockPlayer(
playerId: 1,
);
await player.setLooping(1, true);
verify(playerApi.setLooping(true));
});
test('play', () async {
final (
AndroidVideoPlayer player,
_,
MockVideoPlayerInstanceApi playerApi,
) = setUpMockPlayer(
playerId: 1,
);
await player.play(1);
verify(playerApi.play());
});
test('pause', () async {
final (
AndroidVideoPlayer player,
_,
MockVideoPlayerInstanceApi playerApi,
) = setUpMockPlayer(
playerId: 1,
);
await player.pause(1);
verify(playerApi.pause());
});
group('setMixWithOthers', () {
test('passes true', () async {
final (AndroidVideoPlayer player, MockAndroidVideoPlayerApi api, _) =
setUpMockPlayer(playerId: 1);
await player.setMixWithOthers(true);
verify(api.setMixWithOthers(true));
});
test('passes false', () async {
final (AndroidVideoPlayer player, MockAndroidVideoPlayerApi api, _) =
setUpMockPlayer(playerId: 1);
await player.setMixWithOthers(false);
verify(api.setMixWithOthers(false));
});
});
test('setVolume', () async {
final (
AndroidVideoPlayer player,
_,
MockVideoPlayerInstanceApi playerApi,
) = setUpMockPlayer(
playerId: 1,
);
const volume = 0.7;
await player.setVolume(1, volume);
verify(playerApi.setVolume(volume));
});
test('setPlaybackSpeed', () async {
final (
AndroidVideoPlayer player,
_,
MockVideoPlayerInstanceApi playerApi,
) = setUpMockPlayer(
playerId: 1,
);
const speed = 1.5;
await player.setPlaybackSpeed(1, speed);
verify(playerApi.setPlaybackSpeed(speed));
});
test('seekTo', () async {
final (
AndroidVideoPlayer player,
_,
MockVideoPlayerInstanceApi playerApi,
) = setUpMockPlayer(
playerId: 1,
);
const positionMilliseconds = 12345;
await player.seekTo(
1,
const Duration(milliseconds: positionMilliseconds),
);
verify(playerApi.seekTo(positionMilliseconds));
});
test('getPosition', () async {
final (
AndroidVideoPlayer player,
_,
MockVideoPlayerInstanceApi playerApi,
) = setUpMockPlayer(
playerId: 1,
);
const positionMilliseconds = 12345;
when(
playerApi.getCurrentPosition(),
).thenAnswer((_) async => positionMilliseconds);
final Duration position = await player.getPosition(1);
expect(position, const Duration(milliseconds: positionMilliseconds));
});
group('video events', () {
// Sets up a mock player that emits the given event structure as a success
// callback on the internal platform channel event stream, and returns
// the player's videoEventsFor(...) stream.
Stream<VideoEvent> mockPlayerEmitingEvents(
List<PlatformVideoEvent> events,
) {
const playerId = 1;
final (
AndroidVideoPlayer player,
_,
_,
StreamController<PlatformVideoEvent> streamController,
) = setUpMockPlayerWithStream(
playerId: playerId,
);
events.forEach(streamController.add);
return player.videoEventsFor(playerId);
}
test('initialize', () async {
final Stream<VideoEvent> eventStream =
mockPlayerEmitingEvents(<PlatformVideoEvent>[
InitializationEvent(
duration: 98765,
width: 1920,
height: 1080,
rotationCorrection: 90,
),
]);
expect(
eventStream,
emitsInOrder(<dynamic>[
VideoEvent(
eventType: VideoEventType.initialized,
duration: const Duration(milliseconds: 98765),
size: const Size(1920, 1080),
rotationCorrection: 90,
),
]),
);
});
test('initialization triggers buffer update polling', () async {
final Stream<VideoEvent> eventStream =
mockPlayerEmitingEvents(<PlatformVideoEvent>[
InitializationEvent(
duration: 98765,
width: 1920,
height: 1080,
rotationCorrection: 90,
),
]);
expect(
eventStream,
emitsInOrder(<dynamic>[
VideoEvent(
eventType: VideoEventType.initialized,
duration: const Duration(milliseconds: 98765),
size: const Size(1920, 1080),
rotationCorrection: 90,
),
VideoEvent(
eventType: VideoEventType.bufferingUpdate,
buffered: <DurationRange>[
DurationRange(Duration.zero, Duration.zero),
],
),
]),
);
});
test('completed', () async {
final Stream<VideoEvent> eventStream = mockPlayerEmitingEvents(
<PlatformVideoEvent>[
PlaybackStateChangeEvent(state: PlatformPlaybackState.ended),
],
);
expect(
eventStream,
emitsInOrder(<dynamic>[
VideoEvent(eventType: VideoEventType.completed),
]),
);
});
test('buffering start', () async {
final Stream<VideoEvent> eventStream = mockPlayerEmitingEvents(
<PlatformVideoEvent>[
PlaybackStateChangeEvent(state: PlatformPlaybackState.buffering),
],
);
expect(
eventStream,
emitsInOrder(<dynamic>[
VideoEvent(eventType: VideoEventType.bufferingStart),
// A buffer start should trigger a buffer update as well.
VideoEvent(
eventType: VideoEventType.bufferingUpdate,
buffered: <DurationRange>[
DurationRange(Duration.zero, Duration.zero),
],
),
]),
);
});
test('buffering end for ready', () async {
final Stream<VideoEvent> eventStream = mockPlayerEmitingEvents(
<PlatformVideoEvent>[
// Trigger a start first, since end is only emitted if it's
// started.
PlaybackStateChangeEvent(state: PlatformPlaybackState.buffering),
PlaybackStateChangeEvent(state: PlatformPlaybackState.ready),
],
);
expect(
eventStream,
emitsInOrder(<dynamic>[
// Emitted by buffering.
VideoEvent(eventType: VideoEventType.bufferingStart),
VideoEvent(
eventType: VideoEventType.bufferingUpdate,
buffered: <DurationRange>[
DurationRange(Duration.zero, Duration.zero),
],
),
// Emitted by ready.
VideoEvent(eventType: VideoEventType.bufferingEnd),
]),
);
});
test('buffering end for idle', () async {
final Stream<VideoEvent> eventStream = mockPlayerEmitingEvents(
<PlatformVideoEvent>[
// Trigger a start first, since end is only emitted if it's
// started.
PlaybackStateChangeEvent(state: PlatformPlaybackState.buffering),
PlaybackStateChangeEvent(state: PlatformPlaybackState.idle),
],
);
expect(
eventStream,
emitsInOrder(<dynamic>[
// Emitted by buffering.
VideoEvent(eventType: VideoEventType.bufferingStart),
VideoEvent(
eventType: VideoEventType.bufferingUpdate,
buffered: <DurationRange>[
DurationRange(Duration.zero, Duration.zero),
],
),
// Emitted by ready.
VideoEvent(eventType: VideoEventType.bufferingEnd),
]),
);
});
test('buffering end for ended', () async {
final Stream<VideoEvent> eventStream = mockPlayerEmitingEvents(
<PlatformVideoEvent>[
// Trigger a start first, since end is only emitted if it's
// started.
PlaybackStateChangeEvent(state: PlatformPlaybackState.buffering),
PlaybackStateChangeEvent(state: PlatformPlaybackState.ended),
],
);
expect(
eventStream,
emitsInOrder(<dynamic>[
// Emitted by buffering.
VideoEvent(eventType: VideoEventType.bufferingStart),
VideoEvent(
eventType: VideoEventType.bufferingUpdate,
buffered: <DurationRange>[
DurationRange(Duration.zero, Duration.zero),
],
),
// Emitted by ended.
VideoEvent(eventType: VideoEventType.completed),
VideoEvent(eventType: VideoEventType.bufferingEnd),
]),
);
});
test('playback start', () async {
final Stream<VideoEvent> eventStream = mockPlayerEmitingEvents(
<PlatformVideoEvent>[IsPlayingStateEvent(isPlaying: true)],
);
expect(
eventStream,
emitsInOrder(<dynamic>[
VideoEvent(
eventType: VideoEventType.isPlayingStateUpdate,
isPlaying: true,
),
]),
);
});
test('playback stop', () async {
final Stream<VideoEvent> eventStream = mockPlayerEmitingEvents(
<PlatformVideoEvent>[IsPlayingStateEvent(isPlaying: false)],
);
expect(
eventStream,
emitsInOrder(<dynamic>[
VideoEvent(
eventType: VideoEventType.isPlayingStateUpdate,
isPlaying: false,
),
]),
);
});
});
group('audio tracks', () {
test('isAudioTrackSupportAvailable returns true', () {
final (AndroidVideoPlayer player, _, _) = setUpMockPlayer(playerId: 1);
expect(player.isAudioTrackSupportAvailable(), true);
});
test('getAudioTracks returns empty list when no tracks', () async {
final (AndroidVideoPlayer player, _, MockVideoPlayerInstanceApi api) =
setUpMockPlayer(playerId: 1);
when(api.getAudioTracks()).thenAnswer(
(_) async => NativeAudioTrackData(
exoPlayerTracks: <ExoPlayerAudioTrackData>[],
),
);
final List<VideoAudioTrack> tracks = await player.getAudioTracks(1);
expect(tracks, isEmpty);
verify(api.getAudioTracks());
});
test(
'getAudioTracks converts native tracks to VideoAudioTrack',
() async {
final (AndroidVideoPlayer player, _, MockVideoPlayerInstanceApi api) =
setUpMockPlayer(playerId: 1);
when(api.getAudioTracks()).thenAnswer(
(_) async => NativeAudioTrackData(
exoPlayerTracks: <ExoPlayerAudioTrackData>[
ExoPlayerAudioTrackData(
groupIndex: 0,
trackIndex: 1,
label: 'English',
language: 'en',
isSelected: true,
bitrate: 128000,
sampleRate: 44100,
channelCount: 2,
codec: 'mp4a.40.2',
),
ExoPlayerAudioTrackData(
groupIndex: 0,
trackIndex: 2,
label: 'Spanish',
language: 'es',
isSelected: false,
bitrate: 128000,
sampleRate: 44100,
channelCount: 2,
codec: 'mp4a.40.2',
),
],
),
);
final List<VideoAudioTrack> tracks = await player.getAudioTracks(1);
expect(tracks.length, 2);
expect(tracks[0].id, '0_1');
expect(tracks[0].label, 'English');
expect(tracks[0].language, 'en');
expect(tracks[0].isSelected, true);
expect(tracks[0].bitrate, 128000);
expect(tracks[0].sampleRate, 44100);
expect(tracks[0].channelCount, 2);
expect(tracks[0].codec, 'mp4a.40.2');
expect(tracks[1].id, '0_2');
expect(tracks[1].label, 'Spanish');
expect(tracks[1].language, 'es');
expect(tracks[1].isSelected, false);
},
);
test('getAudioTracks handles null exoPlayerTracks', () async {
final (AndroidVideoPlayer player, _, MockVideoPlayerInstanceApi api) =
setUpMockPlayer(playerId: 1);
when(
api.getAudioTracks(),
).thenAnswer((_) async => NativeAudioTrackData());
final List<VideoAudioTrack> tracks = await player.getAudioTracks(1);
expect(tracks, isEmpty);
});
test('selectAudioTrack parses trackId and calls API', () async {
final (
AndroidVideoPlayer player,
_,
MockVideoPlayerInstanceApi api,
StreamController<PlatformVideoEvent> streamController,
) = setUpMockPlayerWithStream(
playerId: 1,
);
when(api.selectAudioTrack(2, 3)).thenAnswer((_) async {});
// Start the selection and immediately send the track changed event
final Future<void> selectionFuture = player.selectAudioTrack(1, '2_3');
streamController.add(AudioTrackChangedEvent());
await selectionFuture;
verify(api.selectAudioTrack(2, 3));
});
test('selectAudioTrack throws on invalid trackId format', () async {
final (AndroidVideoPlayer player, _, _) = setUpMockPlayer(playerId: 1);
expect(
() => player.selectAudioTrack(1, 'invalid'),
throwsA(isA<ArgumentError>()),
);
});
test('selectAudioTrack throws on trackId with too many parts', () async {
final (AndroidVideoPlayer player, _, _) = setUpMockPlayer(playerId: 1);
expect(
() => player.selectAudioTrack(1, '1_2_3'),
throwsA(isA<ArgumentError>()),
);
});
test('selectAudioTrack completes on AudioTrackChangedEvent', () async {
final (
AndroidVideoPlayer player,
_,
MockVideoPlayerInstanceApi api,
StreamController<PlatformVideoEvent> streamController,
) = setUpMockPlayerWithStream(
playerId: 1,
);
when(api.selectAudioTrack(0, 1)).thenAnswer((_) async {});
// Start selection
final Future<void> selectionFuture = player.selectAudioTrack(1, '0_1');
// Simulate the track changed event from ExoPlayer
streamController.add(AudioTrackChangedEvent());
// Should complete without timeout
await selectionFuture;
verify(api.selectAudioTrack(0, 1));
});
});
});
}

View File

@@ -0,0 +1,255 @@
// Mocks generated by Mockito 5.4.6 from annotations
// in video_player_android/test/android_video_player_test.dart.
// Do not manually edit this file.
// ignore_for_file: no_leading_underscores_for_library_prefixes
import 'dart:async' as _i4;
import 'package:mockito/mockito.dart' as _i1;
import 'package:mockito/src/dummies.dart' as _i3;
import 'package:video_player_android/src/messages.g.dart' as _i2;
// ignore_for_file: type=lint
// ignore_for_file: avoid_redundant_argument_values
// ignore_for_file: avoid_setters_without_getters
// ignore_for_file: comment_references
// ignore_for_file: deprecated_member_use
// ignore_for_file: deprecated_member_use_from_same_package
// ignore_for_file: implementation_imports
// ignore_for_file: invalid_use_of_visible_for_testing_member
// ignore_for_file: must_be_immutable
// ignore_for_file: prefer_const_constructors
// ignore_for_file: unnecessary_parenthesis
// ignore_for_file: camel_case_types
// ignore_for_file: subtype_of_sealed_class
class _FakeTexturePlayerIds_0 extends _i1.SmartFake
implements _i2.TexturePlayerIds {
_FakeTexturePlayerIds_0(Object parent, Invocation parentInvocation)
: super(parent, parentInvocation);
}
class _FakeNativeAudioTrackData_1 extends _i1.SmartFake
implements _i2.NativeAudioTrackData {
_FakeNativeAudioTrackData_1(Object parent, Invocation parentInvocation)
: super(parent, parentInvocation);
}
/// A class which mocks [AndroidVideoPlayerApi].
///
/// See the documentation for Mockito's code generation for more information.
class MockAndroidVideoPlayerApi extends _i1.Mock
implements _i2.AndroidVideoPlayerApi {
@override
String get pigeonVar_messageChannelSuffix =>
(super.noSuchMethod(
Invocation.getter(#pigeonVar_messageChannelSuffix),
returnValue: _i3.dummyValue<String>(
this,
Invocation.getter(#pigeonVar_messageChannelSuffix),
),
returnValueForMissingStub: _i3.dummyValue<String>(
this,
Invocation.getter(#pigeonVar_messageChannelSuffix),
),
)
as String);
@override
_i4.Future<void> initialize() =>
(super.noSuchMethod(
Invocation.method(#initialize, []),
returnValue: _i4.Future<void>.value(),
returnValueForMissingStub: _i4.Future<void>.value(),
)
as _i4.Future<void>);
@override
_i4.Future<int> createForPlatformView(_i2.CreationOptions? options) =>
(super.noSuchMethod(
Invocation.method(#createForPlatformView, [options]),
returnValue: _i4.Future<int>.value(0),
returnValueForMissingStub: _i4.Future<int>.value(0),
)
as _i4.Future<int>);
@override
_i4.Future<_i2.TexturePlayerIds> createForTextureView(
_i2.CreationOptions? options,
) =>
(super.noSuchMethod(
Invocation.method(#createForTextureView, [options]),
returnValue: _i4.Future<_i2.TexturePlayerIds>.value(
_FakeTexturePlayerIds_0(
this,
Invocation.method(#createForTextureView, [options]),
),
),
returnValueForMissingStub: _i4.Future<_i2.TexturePlayerIds>.value(
_FakeTexturePlayerIds_0(
this,
Invocation.method(#createForTextureView, [options]),
),
),
)
as _i4.Future<_i2.TexturePlayerIds>);
@override
_i4.Future<void> dispose(int? playerId) =>
(super.noSuchMethod(
Invocation.method(#dispose, [playerId]),
returnValue: _i4.Future<void>.value(),
returnValueForMissingStub: _i4.Future<void>.value(),
)
as _i4.Future<void>);
@override
_i4.Future<void> setMixWithOthers(bool? mixWithOthers) =>
(super.noSuchMethod(
Invocation.method(#setMixWithOthers, [mixWithOthers]),
returnValue: _i4.Future<void>.value(),
returnValueForMissingStub: _i4.Future<void>.value(),
)
as _i4.Future<void>);
@override
_i4.Future<String> getLookupKeyForAsset(String? asset, String? packageName) =>
(super.noSuchMethod(
Invocation.method(#getLookupKeyForAsset, [asset, packageName]),
returnValue: _i4.Future<String>.value(
_i3.dummyValue<String>(
this,
Invocation.method(#getLookupKeyForAsset, [asset, packageName]),
),
),
returnValueForMissingStub: _i4.Future<String>.value(
_i3.dummyValue<String>(
this,
Invocation.method(#getLookupKeyForAsset, [asset, packageName]),
),
),
)
as _i4.Future<String>);
}
/// A class which mocks [VideoPlayerInstanceApi].
///
/// See the documentation for Mockito's code generation for more information.
class MockVideoPlayerInstanceApi extends _i1.Mock
implements _i2.VideoPlayerInstanceApi {
@override
String get pigeonVar_messageChannelSuffix =>
(super.noSuchMethod(
Invocation.getter(#pigeonVar_messageChannelSuffix),
returnValue: _i3.dummyValue<String>(
this,
Invocation.getter(#pigeonVar_messageChannelSuffix),
),
returnValueForMissingStub: _i3.dummyValue<String>(
this,
Invocation.getter(#pigeonVar_messageChannelSuffix),
),
)
as String);
@override
_i4.Future<void> setLooping(bool? looping) =>
(super.noSuchMethod(
Invocation.method(#setLooping, [looping]),
returnValue: _i4.Future<void>.value(),
returnValueForMissingStub: _i4.Future<void>.value(),
)
as _i4.Future<void>);
@override
_i4.Future<void> setVolume(double? volume) =>
(super.noSuchMethod(
Invocation.method(#setVolume, [volume]),
returnValue: _i4.Future<void>.value(),
returnValueForMissingStub: _i4.Future<void>.value(),
)
as _i4.Future<void>);
@override
_i4.Future<void> setPlaybackSpeed(double? speed) =>
(super.noSuchMethod(
Invocation.method(#setPlaybackSpeed, [speed]),
returnValue: _i4.Future<void>.value(),
returnValueForMissingStub: _i4.Future<void>.value(),
)
as _i4.Future<void>);
@override
_i4.Future<void> play() =>
(super.noSuchMethod(
Invocation.method(#play, []),
returnValue: _i4.Future<void>.value(),
returnValueForMissingStub: _i4.Future<void>.value(),
)
as _i4.Future<void>);
@override
_i4.Future<void> pause() =>
(super.noSuchMethod(
Invocation.method(#pause, []),
returnValue: _i4.Future<void>.value(),
returnValueForMissingStub: _i4.Future<void>.value(),
)
as _i4.Future<void>);
@override
_i4.Future<void> seekTo(int? position) =>
(super.noSuchMethod(
Invocation.method(#seekTo, [position]),
returnValue: _i4.Future<void>.value(),
returnValueForMissingStub: _i4.Future<void>.value(),
)
as _i4.Future<void>);
@override
_i4.Future<int> getCurrentPosition() =>
(super.noSuchMethod(
Invocation.method(#getCurrentPosition, []),
returnValue: _i4.Future<int>.value(0),
returnValueForMissingStub: _i4.Future<int>.value(0),
)
as _i4.Future<int>);
@override
_i4.Future<int> getBufferedPosition() =>
(super.noSuchMethod(
Invocation.method(#getBufferedPosition, []),
returnValue: _i4.Future<int>.value(0),
returnValueForMissingStub: _i4.Future<int>.value(0),
)
as _i4.Future<int>);
@override
_i4.Future<_i2.NativeAudioTrackData> getAudioTracks() =>
(super.noSuchMethod(
Invocation.method(#getAudioTracks, []),
returnValue: _i4.Future<_i2.NativeAudioTrackData>.value(
_FakeNativeAudioTrackData_1(
this,
Invocation.method(#getAudioTracks, []),
),
),
returnValueForMissingStub:
_i4.Future<_i2.NativeAudioTrackData>.value(
_FakeNativeAudioTrackData_1(
this,
Invocation.method(#getAudioTracks, []),
),
),
)
as _i4.Future<_i2.NativeAudioTrackData>);
@override
_i4.Future<void> selectAudioTrack(int? groupIndex, int? trackIndex) =>
(super.noSuchMethod(
Invocation.method(#selectAudioTrack, [groupIndex, trackIndex]),
returnValue: _i4.Future<void>.value(),
returnValueForMissingStub: _i4.Future<void>.value(),
)
as _i4.Future<void>);
}