-
Notifications
You must be signed in to change notification settings - Fork 1k
/
Copy pathchewie_player.dart
689 lines (585 loc) · 22.1 KB
/
chewie_player.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
import 'dart:async';
import 'package:chewie/src/chewie_progress_colors.dart';
import 'package:chewie/src/models/option_item.dart';
import 'package:chewie/src/models/options_translation.dart';
import 'package:chewie/src/models/subtitle_model.dart';
import 'package:chewie/src/notifiers/player_notifier.dart';
import 'package:chewie/src/player_with_controls.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import 'package:video_player/video_player.dart';
import 'package:wakelock_plus/wakelock_plus.dart';
typedef ChewieRoutePageBuilder = Widget Function(
BuildContext context,
Animation<double> animation,
Animation<double> secondaryAnimation,
ChewieControllerProvider controllerProvider,
);
/// A Video Player with Material and Cupertino skins.
///
/// `video_player` is pretty low level. Chewie wraps it in a friendly skin to
/// make it easy to use!
class Chewie extends StatefulWidget {
const Chewie({
super.key,
required this.controller,
});
/// The [ChewieController]
final ChewieController controller;
@override
ChewieState createState() {
return ChewieState();
}
}
class ChewieState extends State<Chewie> {
bool _isFullScreen = false;
bool get isControllerFullScreen => widget.controller.isFullScreen;
late PlayerNotifier notifier;
@override
void initState() {
super.initState();
widget.controller.addListener(listener);
notifier = PlayerNotifier.init();
}
@override
void dispose() {
widget.controller.removeListener(listener);
notifier.dispose();
super.dispose();
}
@override
void didUpdateWidget(Chewie oldWidget) {
if (oldWidget.controller != widget.controller) {
widget.controller.addListener(listener);
}
super.didUpdateWidget(oldWidget);
if (_isFullScreen != isControllerFullScreen) {
widget.controller._isFullScreen = _isFullScreen;
}
}
Future<void> listener() async {
if (isControllerFullScreen && !_isFullScreen) {
_isFullScreen = isControllerFullScreen;
await _pushFullScreenWidget(context);
} else if (_isFullScreen) {
Navigator.of(
context,
rootNavigator: widget.controller.useRootNavigator,
).pop();
_isFullScreen = false;
}
}
@override
Widget build(BuildContext context) {
return ChewieControllerProvider(
controller: widget.controller,
child: ChangeNotifierProvider<PlayerNotifier>.value(
value: notifier,
builder: (context, w) => const PlayerWithControls(),
),
);
}
Widget _buildFullScreenVideo(
BuildContext context,
Animation<double> animation,
ChewieControllerProvider controllerProvider,
) {
return Scaffold(
resizeToAvoidBottomInset: false,
body: Container(
alignment: Alignment.center,
color: Colors.black,
child: controllerProvider,
),
);
}
AnimatedWidget _defaultRoutePageBuilder(
BuildContext context,
Animation<double> animation,
Animation<double> secondaryAnimation,
ChewieControllerProvider controllerProvider,
) {
return AnimatedBuilder(
animation: animation,
builder: (BuildContext context, Widget? child) {
return _buildFullScreenVideo(context, animation, controllerProvider);
},
);
}
Widget _fullScreenRoutePageBuilder(
BuildContext context,
Animation<double> animation,
Animation<double> secondaryAnimation,
) {
final controllerProvider = ChewieControllerProvider(
controller: widget.controller,
child: ChangeNotifierProvider<PlayerNotifier>.value(
value: notifier,
builder: (context, w) => const PlayerWithControls(),
),
);
if (widget.controller.routePageBuilder == null) {
return _defaultRoutePageBuilder(
context,
animation,
secondaryAnimation,
controllerProvider,
);
}
return widget.controller.routePageBuilder!(
context,
animation,
secondaryAnimation,
controllerProvider,
);
}
Future<dynamic> _pushFullScreenWidget(BuildContext context) async {
final TransitionRoute<void> route = PageRouteBuilder<void>(
pageBuilder: _fullScreenRoutePageBuilder,
);
onEnterFullScreen();
if (!widget.controller.allowedScreenSleep) {
WakelockPlus.enable();
}
await Navigator.of(
context,
rootNavigator: widget.controller.useRootNavigator,
).push(route);
if (kIsWeb) {
_reInitializeControllers();
}
_isFullScreen = false;
widget.controller.exitFullScreen();
if (!widget.controller.allowedScreenSleep) {
WakelockPlus.disable();
}
SystemChrome.setEnabledSystemUIMode(
SystemUiMode.manual,
overlays: widget.controller.systemOverlaysAfterFullScreen,
);
SystemChrome.setPreferredOrientations(
widget.controller.deviceOrientationsAfterFullScreen,
);
}
void onEnterFullScreen() {
final videoWidth = widget.controller.videoPlayerController.value.size.width;
final videoHeight =
widget.controller.videoPlayerController.value.size.height;
SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual, overlays: []);
// if (widget.controller.systemOverlaysOnEnterFullScreen != null) {
// /// Optional user preferred settings
// SystemChrome.setEnabledSystemUIMode(
// SystemUiMode.manual,
// overlays: widget.controller.systemOverlaysOnEnterFullScreen,
// );
// } else {
// /// Default behavior
// SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual, overlays: SystemUiOverlay.values);
// }
if (widget.controller.deviceOrientationsOnEnterFullScreen != null) {
/// Optional user preferred settings
SystemChrome.setPreferredOrientations(
widget.controller.deviceOrientationsOnEnterFullScreen!,
);
} else {
final isLandscapeVideo = videoWidth > videoHeight;
final isPortraitVideo = videoWidth < videoHeight;
/// Default behavior
/// Video w > h means we force landscape
if (isLandscapeVideo) {
SystemChrome.setPreferredOrientations([
DeviceOrientation.landscapeLeft,
DeviceOrientation.landscapeRight,
]);
}
/// Video h > w means we force portrait
else if (isPortraitVideo) {
SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
DeviceOrientation.portraitDown,
]);
}
/// Otherwise if h == w (square video)
else {
SystemChrome.setPreferredOrientations(DeviceOrientation.values);
}
}
}
///When viewing full screen on web, returning from full screen causes original video to lose the picture.
///We re initialise controllers for web only when returning from full screen
void _reInitializeControllers() {
final prevPosition = widget.controller.videoPlayerController.value.position;
widget.controller.videoPlayerController.initialize().then((_) async {
widget.controller._initialize();
widget.controller.videoPlayerController.seekTo(prevPosition);
await widget.controller.videoPlayerController.play();
widget.controller.videoPlayerController.pause();
});
}
}
/// The ChewieController is used to configure and drive the Chewie Player
/// Widgets. It provides methods to control playback, such as [pause] and
/// [play], as well as methods that control the visual appearance of the player,
/// such as [enterFullScreen] or [exitFullScreen].
///
/// In addition, you can listen to the ChewieController for presentational
/// changes, such as entering and exiting full screen mode. To listen for
/// changes to the playback, such as a change to the seek position of the
/// player, please use the standard information provided by the
/// `VideoPlayerController`.
class ChewieController extends ChangeNotifier {
ChewieController({
required this.videoPlayerController,
this.optionsTranslation,
this.aspectRatio,
this.autoInitialize = false,
this.autoPlay = false,
this.draggableProgressBar = true,
this.startAt,
this.looping = false,
this.fullScreenByDefault = false,
this.cupertinoProgressColors,
this.materialProgressColors,
this.materialSeekButtonFadeDuration = const Duration(milliseconds: 300),
this.materialSeekButtonSize = 26,
this.placeholder,
this.overlay,
this.showControlsOnInitialize = true,
this.showOptions = true,
this.optionsBuilder,
this.additionalOptions,
this.showControls = true,
this.transformationController,
this.zoomAndPan = false,
this.maxScale = 2.5,
this.subtitle,
this.showSubtitles = false,
this.subtitleBuilder,
this.customControls,
this.errorBuilder,
this.bufferingBuilder,
this.allowedScreenSleep = true,
this.isLive = false,
this.allowFullScreen = true,
this.allowMuting = true,
this.allowPlaybackSpeedChanging = true,
this.useRootNavigator = true,
this.playbackSpeeds = const [0.25, 0.5, 0.75, 1, 1.25, 1.5, 1.75, 2],
this.systemOverlaysOnEnterFullScreen,
this.deviceOrientationsOnEnterFullScreen,
this.systemOverlaysAfterFullScreen = SystemUiOverlay.values,
this.deviceOrientationsAfterFullScreen = DeviceOrientation.values,
this.routePageBuilder,
this.progressIndicatorDelay,
this.hideControlsTimer = defaultHideControlsTimer,
this.controlsSafeAreaMinimum = EdgeInsets.zero,
}) : assert(
playbackSpeeds.every((speed) => speed > 0),
'The playbackSpeeds values must all be greater than 0',
) {
_initialize();
}
ChewieController copyWith({
VideoPlayerController? videoPlayerController,
OptionsTranslation? optionsTranslation,
double? aspectRatio,
bool? autoInitialize,
bool? autoPlay,
bool? draggableProgressBar,
Duration? startAt,
bool? looping,
bool? fullScreenByDefault,
ChewieProgressColors? cupertinoProgressColors,
ChewieProgressColors? materialProgressColors,
Duration? materialSeekButtonFadeDuration,
double? materialSeekButtonSize,
Widget? placeholder,
Widget? overlay,
bool? showControlsOnInitialize,
bool? showOptions,
Future<void> Function(BuildContext, List<OptionItem>)? optionsBuilder,
List<OptionItem> Function(BuildContext)? additionalOptions,
bool? showControls,
TransformationController? transformationController,
bool? zoomAndPan,
double? maxScale,
Subtitles? subtitle,
bool? showSubtitles,
Widget Function(BuildContext, dynamic)? subtitleBuilder,
Widget? customControls,
WidgetBuilder? bufferingBuilder,
Widget Function(BuildContext, String)? errorBuilder,
bool? allowedScreenSleep,
bool? isLive,
bool? allowFullScreen,
bool? allowMuting,
bool? allowPlaybackSpeedChanging,
bool? useRootNavigator,
Duration? hideControlsTimer,
EdgeInsets? controlsSafeAreaMinimum,
List<double>? playbackSpeeds,
List<SystemUiOverlay>? systemOverlaysOnEnterFullScreen,
List<DeviceOrientation>? deviceOrientationsOnEnterFullScreen,
List<SystemUiOverlay>? systemOverlaysAfterFullScreen,
List<DeviceOrientation>? deviceOrientationsAfterFullScreen,
Duration? progressIndicatorDelay,
Widget Function(
BuildContext,
Animation<double>,
Animation<double>,
ChewieControllerProvider,
)? routePageBuilder,
}) {
return ChewieController(
draggableProgressBar: draggableProgressBar ?? this.draggableProgressBar,
videoPlayerController:
videoPlayerController ?? this.videoPlayerController,
optionsTranslation: optionsTranslation ?? this.optionsTranslation,
aspectRatio: aspectRatio ?? this.aspectRatio,
autoInitialize: autoInitialize ?? this.autoInitialize,
autoPlay: autoPlay ?? this.autoPlay,
startAt: startAt ?? this.startAt,
looping: looping ?? this.looping,
fullScreenByDefault: fullScreenByDefault ?? this.fullScreenByDefault,
cupertinoProgressColors:
cupertinoProgressColors ?? this.cupertinoProgressColors,
materialProgressColors:
materialProgressColors ?? this.materialProgressColors,
materialSeekButtonFadeDuration:
materialSeekButtonFadeDuration ?? this.materialSeekButtonFadeDuration,
materialSeekButtonSize:
materialSeekButtonSize ?? this.materialSeekButtonSize,
placeholder: placeholder ?? this.placeholder,
overlay: overlay ?? this.overlay,
showControlsOnInitialize:
showControlsOnInitialize ?? this.showControlsOnInitialize,
showOptions: showOptions ?? this.showOptions,
optionsBuilder: optionsBuilder ?? this.optionsBuilder,
additionalOptions: additionalOptions ?? this.additionalOptions,
showControls: showControls ?? this.showControls,
showSubtitles: showSubtitles ?? this.showSubtitles,
subtitle: subtitle ?? this.subtitle,
subtitleBuilder: subtitleBuilder ?? this.subtitleBuilder,
customControls: customControls ?? this.customControls,
errorBuilder: errorBuilder ?? this.errorBuilder,
bufferingBuilder: bufferingBuilder ?? this.bufferingBuilder,
allowedScreenSleep: allowedScreenSleep ?? this.allowedScreenSleep,
isLive: isLive ?? this.isLive,
allowFullScreen: allowFullScreen ?? this.allowFullScreen,
allowMuting: allowMuting ?? this.allowMuting,
allowPlaybackSpeedChanging:
allowPlaybackSpeedChanging ?? this.allowPlaybackSpeedChanging,
useRootNavigator: useRootNavigator ?? this.useRootNavigator,
playbackSpeeds: playbackSpeeds ?? this.playbackSpeeds,
systemOverlaysOnEnterFullScreen: systemOverlaysOnEnterFullScreen ??
this.systemOverlaysOnEnterFullScreen,
deviceOrientationsOnEnterFullScreen:
deviceOrientationsOnEnterFullScreen ??
this.deviceOrientationsOnEnterFullScreen,
systemOverlaysAfterFullScreen:
systemOverlaysAfterFullScreen ?? this.systemOverlaysAfterFullScreen,
deviceOrientationsAfterFullScreen: deviceOrientationsAfterFullScreen ??
this.deviceOrientationsAfterFullScreen,
routePageBuilder: routePageBuilder ?? this.routePageBuilder,
hideControlsTimer: hideControlsTimer ?? this.hideControlsTimer,
progressIndicatorDelay:
progressIndicatorDelay ?? this.progressIndicatorDelay,
);
}
static const defaultHideControlsTimer = Duration(seconds: 3);
/// If false, the options button in MaterialUI and MaterialDesktopUI
/// won't be shown.
final bool showOptions;
/// Pass your translations for the options like:
/// - PlaybackSpeed
/// - Subtitles
/// - Cancel
///
/// Buttons
///
/// These are required for the default `OptionItem`'s
final OptionsTranslation? optionsTranslation;
/// Build your own options with default chewieOptions shiped through
/// the builder method. Just add your own options to the Widget
/// you'll build. If you want to hide the chewieOptions, just leave them
/// out from your Widget.
final Future<void> Function(
BuildContext context,
List<OptionItem> chewieOptions,
)? optionsBuilder;
/// Add your own additional options on top of chewie options
final List<OptionItem> Function(BuildContext context)? additionalOptions;
/// Define here your own Widget on how your n'th subtitle will look like
Widget Function(BuildContext context, dynamic subtitle)? subtitleBuilder;
/// Add a List of Subtitles here in `Subtitles.subtitle`
Subtitles? subtitle;
/// Determines whether subtitles should be shown by default when the video starts.
///
/// If set to `true`, subtitles will be displayed automatically when the video
/// begins playing. If set to `false`, subtitles will be hidden by default.
bool showSubtitles;
/// The controller for the video you want to play
final VideoPlayerController videoPlayerController;
/// Initialize the Video on Startup. This will prep the video for playback.
final bool autoInitialize;
/// Play the video as soon as it's displayed
final bool autoPlay;
/// Non-Draggable Progress Bar
final bool draggableProgressBar;
/// Start video at a certain position
final Duration? startAt;
/// Whether or not the video should loop
final bool looping;
/// Wether or not to show the controls when initializing the widget.
final bool showControlsOnInitialize;
/// Whether or not to show the controls at all
final bool showControls;
/// Controller to pass into the [InteractiveViewer] component
final TransformationController? transformationController;
/// Whether or not to allow zooming and panning
final bool zoomAndPan;
/// Max scale when zooming
final double maxScale;
/// Defines customised controls. Check [MaterialControls] or
/// [CupertinoControls] for reference.
final Widget? customControls;
/// When the video playback runs into an error, you can build a custom
/// error message.
final Widget Function(BuildContext context, String errorMessage)?
errorBuilder;
/// When the video is buffering, you can build a custom widget.
final WidgetBuilder? bufferingBuilder;
/// The Aspect Ratio of the Video. Important to get the correct size of the
/// video!
///
/// Will fallback to fitting within the space allowed.
final double? aspectRatio;
/// The colors to use for controls on iOS. By default, the iOS player uses
/// colors sampled from the original iOS 11 designs.
final ChewieProgressColors? cupertinoProgressColors;
/// The colors to use for the Material Progress Bar. By default, the Material
/// player uses the colors from your Theme.
final ChewieProgressColors? materialProgressColors;
// The duration of the fade animation for the seek button (Material Player only)
final Duration materialSeekButtonFadeDuration;
// The size of the seek button for the Material Player only
final double materialSeekButtonSize;
/// The placeholder is displayed underneath the Video before it is initialized
/// or played.
final Widget? placeholder;
/// A widget which is placed between the video and the controls
final Widget? overlay;
/// Defines if the player will start in fullscreen when play is pressed
final bool fullScreenByDefault;
/// Defines if the player will sleep in fullscreen or not
final bool allowedScreenSleep;
/// Defines if the controls should be shown for live stream video
final bool isLive;
/// Defines if the fullscreen control should be shown
final bool allowFullScreen;
/// Defines if the mute control should be shown
final bool allowMuting;
/// Defines if the playback speed control should be shown
final bool allowPlaybackSpeedChanging;
/// Defines if push/pop navigations use the rootNavigator
final bool useRootNavigator;
/// Defines the [Duration] before the video controls are hidden. By default, this is set to three seconds.
final Duration hideControlsTimer;
/// Defines the set of allowed playback speeds user can change
final List<double> playbackSpeeds;
/// Defines the system overlays visible on entering fullscreen
final List<SystemUiOverlay>? systemOverlaysOnEnterFullScreen;
/// Defines the set of allowed device orientations on entering fullscreen
final List<DeviceOrientation>? deviceOrientationsOnEnterFullScreen;
/// Defines the system overlays visible after exiting fullscreen
final List<SystemUiOverlay> systemOverlaysAfterFullScreen;
/// Defines the set of allowed device orientations after exiting fullscreen
final List<DeviceOrientation> deviceOrientationsAfterFullScreen;
/// Defines a custom RoutePageBuilder for the fullscreen
final ChewieRoutePageBuilder? routePageBuilder;
/// Defines a delay in milliseconds between entering buffering state and displaying the loading spinner. Set null (default) to disable it.
final Duration? progressIndicatorDelay;
/// Adds additional padding to the controls' [SafeArea] as desired.
/// Defaults to [EdgeInsets.zero].
final EdgeInsets controlsSafeAreaMinimum;
static ChewieController of(BuildContext context) {
final chewieControllerProvider =
context.dependOnInheritedWidgetOfExactType<ChewieControllerProvider>()!;
return chewieControllerProvider.controller;
}
bool _isFullScreen = false;
bool get isFullScreen => _isFullScreen;
bool get isPlaying => videoPlayerController.value.isPlaying;
Future<dynamic> _initialize() async {
await videoPlayerController.setLooping(looping);
if ((autoInitialize || autoPlay) &&
!videoPlayerController.value.isInitialized) {
await videoPlayerController.initialize();
}
if (autoPlay) {
if (fullScreenByDefault) {
enterFullScreen();
}
await videoPlayerController.play();
}
if (startAt != null) {
await videoPlayerController.seekTo(startAt!);
}
if (fullScreenByDefault) {
videoPlayerController.addListener(_fullScreenListener);
}
}
Future<void> _fullScreenListener() async {
if (videoPlayerController.value.isPlaying && !_isFullScreen) {
enterFullScreen();
videoPlayerController.removeListener(_fullScreenListener);
}
}
void enterFullScreen() {
_isFullScreen = true;
notifyListeners();
}
void exitFullScreen() {
_isFullScreen = false;
notifyListeners();
}
void toggleFullScreen() {
_isFullScreen = !_isFullScreen;
notifyListeners();
}
void togglePause() {
isPlaying ? pause() : play();
}
Future<void> play() async {
await videoPlayerController.play();
}
// ignore: avoid_positional_boolean_parameters
Future<void> setLooping(bool looping) async {
await videoPlayerController.setLooping(looping);
}
Future<void> pause() async {
await videoPlayerController.pause();
}
Future<void> seekTo(Duration moment) async {
await videoPlayerController.seekTo(moment);
}
Future<void> setVolume(double volume) async {
await videoPlayerController.setVolume(volume);
}
void setSubtitle(List<Subtitle> newSubtitle) {
subtitle = Subtitles(newSubtitle);
}
}
class ChewieControllerProvider extends InheritedWidget {
const ChewieControllerProvider({
super.key,
required this.controller,
required super.child,
});
final ChewieController controller;
@override
bool updateShouldNotify(ChewieControllerProvider oldWidget) =>
controller != oldWidget.controller;
}