π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
[mobile][photos] add race-safe double-tap video seeking
r4khul49b6708cde7e
diff --git a/mobile/apps/photos/lib/ui/viewer/file/native_video_player_controls/seek_bar.dart b/mobile/apps/photos/lib/ui/viewer/file/native_video_player_controls/seek_bar.dartindex 888cf88ad1..5e606fdb9a 100644--- a/mobile/apps/photos/lib/ui/viewer/file/native_video_player_controls/seek_bar.dart+++ b/mobile/apps/photos/lib/ui/viewer/file/native_video_player_controls/seek_bar.dart@@ -7,16 +7,17 @@ import "package:photos/core/event_bus.dart";import "package:photos/events/seekbar_triggered_event.dart";import "package:photos/theme/colors.dart";import "package:photos/ui/viewer/file/video_control/gallery_video_controls.dart";+import "package:photos/ui/viewer/file/video_seek_controller.dart";class NativeVideoProgressControls extends StatefulWidget {final NativeVideoPlayerController controller;final int? duration;- final ValueNotifier<bool> isSeeking;+ final VideoSeekController seekController;const NativeVideoProgressControls(this.controller,this.duration,- this.isSeeking, {+ this.seekController, {super.key,});@@ -30,10 +31,6 @@ class _NativeVideoProgressControlsStatewith SingleTickerProviderStateMixin {late final AnimationController _animationController;int _elapsedMilliseconds = 0;- final _debouncer = Debouncer(- const Duration(milliseconds: 100),- executionInterval: const Duration(milliseconds: 325),- );StreamSubscription<void>? _eventsSubscription;StreamSubscription<SeekbarTriggeredEvent>? _seekbarSubscription;@@ -59,6 +56,7 @@ class _NativeVideoProgressControlsState});_eventsSubscription = widget.controller.events.listen(_listen);+ widget.seekController.addListener(_onSeekStateChanged);_startMovingSeekbar();}@@ -67,8 +65,8 @@ class _NativeVideoProgressControlsStatevoid dispose() {_seekbarSubscription?.cancel();_eventsSubscription?.cancel();+ widget.seekController.removeListener(_onSeekStateChanged);_animationController.dispose();- _debouncer.cancelDebounceTimer();super.dispose();}@@ -77,6 +75,7 @@ class _NativeVideoProgressControlsStatereturn AnimatedBuilder(animation: _animationController,builder: (_, _) {+ final canSeek = widget.seekController.canSeek;final seekBar = SliderTheme(data: SliderTheme.of(context).copyWith(trackHeight: 3.0,@@ -94,21 +93,30 @@ class _NativeVideoProgressControlsStatemin: 0.0,max: 1.0,value: _animationController.value,- onChangeStart: (value) {- widget.isSeeking.value = true;- },- onChanged: (value) {- _elapsedMilliseconds = _positionInMilliseconds(value) ?? 0;- _animationController.value = value;- _seekTo(value);- },+ onChangeStart: canSeek+ ? (value) => widget.seekController.beginSliderInteraction()+ : null,+ onChanged: canSeek+ ? (value) {+ final position = _positionInMilliseconds(value);+ if (position != null) {+ widget.seekController.updateSliderTarget(+ Duration(milliseconds: position),+ );+ }+ }+ : null,divisions: 4500,- onChangeEnd: (value) {- _elapsedMilliseconds = _positionInMilliseconds(value) ?? 0;- _animationController.value = value;- _seekTo(value);- widget.isSeeking.value = false;- },+ onChangeEnd: canSeek+ ? (value) {+ final position = _positionInMilliseconds(value);+ widget.seekController.endSliderInteraction(+ position == null+ ? widget.seekController.position+ : Duration(milliseconds: position),+ );+ }+ : null,allowedInteraction: SliderInteraction.tapAndSlide,),);@@ -123,18 +131,12 @@ class _NativeVideoProgressControlsState);}- void _seekTo(double value) {- _debouncer.run(() async {- final position = _positionInMilliseconds(value);- if (position == null) return;- unawaited(widget.controller.seekTo(Duration(milliseconds: position)));- });- }-void _startMovingSeekbar() {// Start the seek animation after delayed video playback begins.Future.delayed(const Duration(milliseconds: 700), () {- if (!mounted) {+ if (!mounted ||+ widget.seekController.state.phase != VideoSeekPhase.idle ||+ widget.controller.playbackStatus != PlaybackStatus.playing) {return;}final nudge = _durationNudge();@@ -168,35 +170,41 @@ class _NativeVideoProgressControlsState}}- void _onPlaybackPositionChanged() async {- if (widget.controller.playbackStatus == PlaybackStatus.paused ||- (widget.controller.playbackStatus == PlaybackStatus.stopped &&- widget.controller.playbackPosition.inSeconds != 0)) {- return;- }+ void _onPlaybackPositionChanged() {final target = widget.controller.playbackPosition.inMilliseconds;+ final duration = _effectiveDurationInMilliseconds();+ widget.seekController.onPlayerPosition(+ Duration(milliseconds: target),+ duration: duration == null ? null : Duration(milliseconds: duration),+ );+ }++ void _onSeekStateChanged() => _syncFromController();- // The position event after zero arrives about 350 ms late.- if (target == 0) {- await Future.delayed(const Duration(milliseconds: 450));+ void _syncFromController() {+ if (!mounted) return;+ final duration = _effectiveDurationInMilliseconds();+ final elapsed = widget.seekController.position.inMilliseconds;+ if (_elapsedMilliseconds != elapsed) {+ setState(() {+ _elapsedMilliseconds = elapsed;+ });}- if (!mounted) {- return;+ if (duration != null && duration > 0) {+ final fraction = (elapsed / duration).clamp(0.0, 1.0);+ if (widget.seekController.state.phase == VideoSeekPhase.idle &&+ widget.controller.playbackStatus == PlaybackStatus.playing) {+ unawaited(+ _animationController.animateTo(+ (fraction + _durationNudge()).clamp(0.0, 1.0),+ duration: const Duration(seconds: 1),+ ),+ );+ } else {+ _animationController.stop();+ _animationController.value = fraction;+ }}-- _elapsedMilliseconds = target;- final duration = widget.controller.videoInfo?.durationInMilliseconds;- final double fractionTarget = duration == null || duration <= 0- ? 0- : target / duration;-- final nudge = _durationNudge();- unawaited(- _animationController.animateTo(- (fractionTarget + nudge).clamp(0.0, 1.0),- duration: const Duration(seconds: 1),- ),- );}int? _effectiveDurationInMilliseconds() {diff --git a/mobile/apps/photos/lib/ui/viewer/file/video_double_tap_seek.dart b/mobile/apps/photos/lib/ui/viewer/file/video_double_tap_seek.dartnew file mode 100644index 0000000000..fdadf23486--- /dev/null+++ b/mobile/apps/photos/lib/ui/viewer/file/video_double_tap_seek.dart@@ -0,0 +1,193 @@+import "dart:async";++import "package:flutter/material.dart";+import "package:hugeicons/hugeicons.dart";+import "package:photos/theme/colors.dart";+import "package:photos/theme/ente_theme.dart";++const kDefaultSeekDuration = Duration(seconds: 5);++class DoubleTapSeekOverlay extends StatefulWidget {+ final bool Function() enabled;+ final Duration Function() position;+ final Duration Function() duration;+ final Duration Function(Duration) seekBy;+ final VoidCallback? onSingleTap;+ final VoidCallback? onSeekInteraction;+ final GestureLongPressCallback? onLongPress;+ final GestureLongPressUpCallback? onLongPressUp;++ const DoubleTapSeekOverlay({+ required this.enabled,+ required this.position,+ required this.duration,+ required this.seekBy,+ this.onSeekInteraction,+ this.onSingleTap,+ this.onLongPress,+ this.onLongPressUp,+ super.key,+ });++ @override+ State<DoubleTapSeekOverlay> createState() => _DoubleTapSeekOverlayState();+}++class _DoubleTapSeekOverlayState extends State<DoubleTapSeekOverlay>+ with SingleTickerProviderStateMixin {+ Timer? _badgeHideTimer;+ bool _showBadge = false;+ bool _badgeForward = true;+ int _accumulatedSeconds = 0;+ DateTime? _lastDoubleTapTime;+ bool? _lastDirection;+ TapDownDetails? _doubleTapDetails;+ int _seekGeneration = 0;+ late final AnimationController _badgeAnimation;++ @override+ void initState() {+ super.initState();+ _badgeAnimation = AnimationController(+ vsync: this,+ duration: const Duration(milliseconds: 180),+ );+ }++ @override+ void dispose() {+ _badgeHideTimer?.cancel();+ _badgeAnimation.dispose();+ super.dispose();+ }++ void _handleDoubleTap(TapDownDetails details) {+ if (!widget.enabled()) return;++ final renderBox = context.findRenderObject() as RenderBox?;+ final width = renderBox?.size.width ?? MediaQuery.of(context).size.width;+ final isForward = details.localPosition.dx >= width / 2;++ if (widget.duration() <= Duration.zero) return;++ final now = DateTime.now();+ final isFastSequence =+ _lastDoubleTapTime != null &&+ now.difference(_lastDoubleTapTime!).inMilliseconds <= 750 &&+ _lastDirection == isForward;++ final position = widget.position();+ final target = widget.seekBy(+ isForward ? kDefaultSeekDuration : -kDefaultSeekDuration,+ );+ final applied = (target - position).abs();+ if (applied == Duration.zero) return;+ final appliedSeconds = (applied.inMilliseconds / 1000).ceil();++ if (isFastSequence) {+ _accumulatedSeconds += appliedSeconds;+ } else {+ _accumulatedSeconds = appliedSeconds;+ _lastDirection = isForward;+ }+ _lastDoubleTapTime = now;+ _seekGeneration++;++ widget.onSeekInteraction?.call();+ _showSeekBadge(isForward);+ }++ void _showSeekBadge(bool forward) {+ _badgeHideTimer?.cancel();+ final generation = _seekGeneration;+ setState(() {+ _badgeForward = forward;+ _showBadge = true;+ });+ _badgeAnimation.forward(from: 0);+ _badgeHideTimer = Timer(const Duration(milliseconds: 750), () {+ if (!mounted || generation != _seekGeneration) return;+ setState(() {+ _showBadge = false;+ _lastDoubleTapTime = null;+ });+ });+ }++ @override+ Widget build(BuildContext context) {+ return Stack(+ fit: StackFit.expand,+ children: [+ GestureDetector(+ behavior: HitTestBehavior.translucent,+ onTap: widget.onSingleTap,+ onDoubleTapDown: (details) => _doubleTapDetails = details,+ onDoubleTapCancel: () => _doubleTapDetails = null,+ onDoubleTap: () {+ if (_doubleTapDetails != null) {+ _handleDoubleTap(_doubleTapDetails!);+ _doubleTapDetails = null;+ }+ },+ onLongPress: widget.onLongPress,+ onLongPressUp: widget.onLongPressUp,+ child: Container(constraints: const BoxConstraints.expand()),+ ),+ SafeArea(+ top: false,+ bottom: false,+ child: Align(+ alignment: _badgeForward+ ? Alignment.centerRight+ : Alignment.centerLeft,+ child: Padding(+ padding: const EdgeInsets.symmetric(horizontal: 24),+ child: IgnorePointer(+ child: AnimatedOpacity(+ opacity: _showBadge ? 1 : 0,+ duration: const Duration(milliseconds: 180),+ child: ScaleTransition(+ scale: Tween<double>(begin: 0.8, end: 1).animate(+ CurvedAnimation(+ parent: _badgeAnimation,+ curve: Curves.easeOutQuad,+ ),+ ),+ child: Container(+ width: 64,+ height: 64,+ decoration: BoxDecoration(+ color: Colors.black.withValues(alpha: 0.3),+ shape: BoxShape.circle,+ border: Border.all(color: strokeFaintDark, width: 1),+ ),+ child: Column(+ mainAxisAlignment: MainAxisAlignment.center,+ children: [+ HugeIcon(+ icon: _badgeForward+ ? HugeIcons.strokeRoundedArrowRightDouble+ : HugeIcons.strokeRoundedArrowLeftDouble,+ size: 22,+ color: textBaseDark,+ ),+ Text(+ "${_accumulatedSeconds}s",+ style: getEnteTextTheme(+ context,+ ).tiny.copyWith(color: textBaseDark),+ ),+ ],+ ),+ ),+ ),+ ),+ ),+ ),+ ),+ ),+ ],+ );+ }+}diff --git a/mobile/apps/photos/lib/ui/viewer/file/video_seek_controller.dart b/mobile/apps/photos/lib/ui/viewer/file/video_seek_controller.dartnew file mode 100644index 0000000000..45bed8f2cf--- /dev/null+++ b/mobile/apps/photos/lib/ui/viewer/file/video_seek_controller.dart@@ -0,0 +1,300 @@+import "dart:async";++import "package:flutter/foundation.dart";++enum VideoSeekPhase { idle, dragging, settling }++class VideoSeekState {+ final Duration position;+ final Duration? duration;+ final VideoSeekPhase phase;+ final int requestId;++ const VideoSeekState({+ required this.position,+ required this.duration,+ required this.phase,+ required this.requestId,+ });++ bool get isInteracting => phase != VideoSeekPhase.idle;++ @override+ bool operator ==(Object other) =>+ other is VideoSeekState &&+ other.position == position &&+ other.duration == duration &&+ other.phase == phase &&+ other.requestId == requestId;++ @override+ int get hashCode => Object.hash(position, duration, phase, requestId);++ VideoSeekState copyWith({+ Duration? position,+ Duration? duration,+ VideoSeekPhase? phase,+ int? requestId,+ }) {+ return VideoSeekState(+ position: position ?? this.position,+ duration: duration ?? this.duration,+ phase: phase ?? this.phase,+ requestId: requestId ?? this.requestId,+ );+ }+}++class VideoSeekController extends ChangeNotifier {+ static const _seekCommandTimeout = Duration(seconds: 2);+ static const _positionTolerance = Duration(milliseconds: 750);+ static const _reconciliationTimeout = Duration(seconds: 2);+ static const _sliderSeekInterval = Duration(milliseconds: 300);++ final Future<void> Function(Duration target) _seek;+ final Duration Function() _readPosition;+ final Duration? Function() _readDuration;+ final void Function(Object error, StackTrace stackTrace)? _onSeekError;++ VideoSeekState _state = const VideoSeekState(+ position: Duration.zero,+ duration: null,+ phase: VideoSeekPhase.idle,+ requestId: 0,+ );+ Duration _confirmedPosition = Duration.zero;+ Duration? _expectedPosition;+ Duration? _queuedTarget;+ bool _commandInFlight = false;+ bool _disposed = false;+ int _sessionId = 0;+ Timer? _reconciliationTimer;+ Timer? _sliderSeekTimer;++ VideoSeekController({+ required Future<void> Function(Duration target) seek,+ required Duration Function() readPosition,+ required Duration? Function() readDuration,+ void Function(Object error, StackTrace stackTrace)? onSeekError,+ }) : _seek = seek,+ _readPosition = readPosition,+ _readDuration = readDuration,+ _onSeekError = onSeekError;++ VideoSeekState get state => _state;++ Duration get position => _state.position;++ Duration? get duration => _state.duration ?? _readDuration();++ bool get canSeek {+ final duration = this.duration;+ return duration != null && duration > Duration.zero;+ }++ void updateDuration(Duration? duration) {+ if (_disposed || _state.duration == duration) return;+ _setState(_state.copyWith(duration: duration));+ }++ void beginSliderInteraction() {+ if (_disposed || !canSeek) return;+ _sliderSeekTimer?.cancel();+ _sliderSeekTimer = null;+ _setState(_state.copyWith(phase: VideoSeekPhase.dragging));+ }++ void updateSliderTarget(Duration target) {+ if (_disposed || _state.phase != VideoSeekPhase.dragging) return;+ _setOptimisticTarget(target, VideoSeekPhase.dragging);+ if (_sliderSeekTimer?.isActive ?? false) return;+ _sliderSeekTimer = Timer(_sliderSeekInterval, () {+ _sliderSeekTimer = null;+ _startCommandDrain();+ });+ }++ void endSliderInteraction(Duration target) {+ if (_disposed || _state.phase != VideoSeekPhase.dragging) return;+ _sliderSeekTimer?.cancel();+ _sliderSeekTimer = null;+ _setOptimisticTarget(target, VideoSeekPhase.settling);+ _startCommandDrain();+ }++ Duration seekBy(Duration delta) {+ if (_disposed) return _state.position;+ _sliderSeekTimer?.cancel();+ _sliderSeekTimer = null;+ final target = _clamp(_state.position + delta);+ if (target == _state.position) return target;+ _setOptimisticTarget(target, VideoSeekPhase.settling);+ _startCommandDrain();+ return _state.position;+ }++ void onPlayerPosition(Duration position, {Duration? duration}) {+ if (_disposed) return;+ if (duration != null) updateDuration(duration);++ if (_state.phase == VideoSeekPhase.dragging) return;++ final expected = _expectedPosition;+ if (expected != null) {+ if ((position - expected).abs() > _positionTolerance) {+ return;+ }+ _clearReconciliation();+ }++ _confirmedPosition = position;+ _setState(+ _state.copyWith(+ position: position,+ phase: _commandInFlight || _queuedTarget != null+ ? VideoSeekPhase.settling+ : VideoSeekPhase.idle,+ ),+ );+ }++ void reset({Duration position = Duration.zero, Duration? duration}) {+ if (_disposed) return;+ _sessionId++;+ _sliderSeekTimer?.cancel();+ _sliderSeekTimer = null;+ _queuedTarget = null;+ _clearReconciliation();+ _commandInFlight = false;+ _confirmedPosition = position;+ _setState(+ VideoSeekState(+ position: position,+ duration: duration,+ phase: VideoSeekPhase.idle,+ requestId: _state.requestId + 1,+ ),+ );+ }++ void _setOptimisticTarget(Duration target, VideoSeekPhase phase) {+ final clampedTarget = _clamp(target);+ final requestId = _state.requestId + 1;+ _reconciliationTimer?.cancel();+ _reconciliationTimer = null;+ _queuedTarget = clampedTarget;+ _expectedPosition = clampedTarget;+ _setState(+ _state.copyWith(+ position: clampedTarget,+ phase: phase,+ requestId: requestId,+ ),+ );+ }++ Duration _clamp(Duration target) {+ final duration = this.duration;+ if (duration == null || duration <= Duration.zero) {+ return target < Duration.zero ? Duration.zero : target;+ }+ if (target < Duration.zero) return Duration.zero;+ if (target > duration) return duration;+ return target;+ }++ void _startCommandDrain() {+ if (_commandInFlight || _disposed) return;+ unawaited(_drainCommands());+ }++ Future<void> _drainCommands() async {+ _commandInFlight = true;+ final sessionId = _sessionId;+ try {+ while (!_disposed && sessionId == _sessionId) {+ final target = _queuedTarget;+ if (target == null) break;+ final requestId = _state.requestId;+ _queuedTarget = null;+ try {+ await _seek(target).timeout(_seekCommandTimeout);+ if (!_disposed &&+ sessionId == _sessionId &&+ requestId == _state.requestId &&+ _queuedTarget == null &&+ _expectedPosition != null) {+ _scheduleReconciliation(sessionId, requestId);+ }+ } catch (error, stackTrace) {+ if (_disposed || sessionId != _sessionId) return;+ if (_state.requestId != requestId || _queuedTarget != null) {+ continue;+ }+ _clearReconciliation();+ _queuedTarget = null;+ _setState(+ _state.copyWith(+ position: _confirmedPosition,+ phase: VideoSeekPhase.idle,+ ),+ );+ _onSeekError?.call(error, stackTrace);+ return;+ }+ }+ } finally {+ if (!_disposed && sessionId == _sessionId) {+ _commandInFlight = false;+ if (_queuedTarget != null) {+ _startCommandDrain();+ } else if (_expectedPosition == null &&+ _state.phase != VideoSeekPhase.dragging) {+ _setState(_state.copyWith(phase: VideoSeekPhase.idle));+ }+ }+ }+ }++ void _scheduleReconciliation(int sessionId, int requestId) {+ _reconciliationTimer?.cancel();+ _reconciliationTimer = Timer(_reconciliationTimeout, () {+ if (_disposed ||+ sessionId != _sessionId ||+ requestId != _state.requestId ||+ _expectedPosition == null ||+ _commandInFlight ||+ _state.phase == VideoSeekPhase.dragging ||+ _queuedTarget != null) {+ return;+ }+ final position = _clamp(_readPosition());+ _clearReconciliation();+ _confirmedPosition = position;+ _setState(+ _state.copyWith(position: position, phase: VideoSeekPhase.idle),+ );+ });+ }++ void _clearReconciliation() {+ _reconciliationTimer?.cancel();+ _reconciliationTimer = null;+ _expectedPosition = null;+ }++ void _setState(VideoSeekState state) {+ if (_disposed || _state == state) return;+ _state = state;+ notifyListeners();+ }++ @override+ void dispose() {+ _disposed = true;+ _sessionId++;+ _reconciliationTimer?.cancel();+ _sliderSeekTimer?.cancel();+ super.dispose();+ }+}diff --git a/mobile/apps/photos/lib/ui/viewer/file/video_widget_media_kit_common.dart b/mobile/apps/photos/lib/ui/viewer/file/video_widget_media_kit_common.dartindex c717e4e485..d539641696 100644--- a/mobile/apps/photos/lib/ui/viewer/file/video_widget_media_kit_common.dart+++ b/mobile/apps/photos/lib/ui/viewer/file/video_widget_media_kit_common.dart@@ -4,11 +4,14 @@ import "package:ente_pure_utils/ente_pure_utils.dart";import "package:ente_ui/components/loading_widget.dart";import "package:flutter/material.dart";import "package:hugeicons/hugeicons.dart";+import "package:logging/logging.dart";import "package:media_kit_video/media_kit_video.dart";import "package:photos/models/file/file.dart";import "package:photos/states/detail_page_state.dart";import "package:photos/theme/colors.dart";import "package:photos/ui/viewer/file/video_control/gallery_video_controls.dart";+import "package:photos/ui/viewer/file/video_double_tap_seek.dart";+import "package:photos/ui/viewer/file/video_seek_controller.dart";import "package:photos/ui/viewer/file/video_stream_change.dart";import "package:photos/ui/viewer/file/zoomable_video_viewer.dart";@@ -42,19 +45,33 @@ class VideoWidget extends StatefulWidget {}class _VideoWidgetState extends State<VideoWidget> {+ final _logger = Logger("VideoWidget");final showControlsNotifier = ValueNotifier<bool>(true);final _hideControlsDebouncer = Debouncer(const Duration(milliseconds: 2000));- final _isSeekingNotifier = ValueNotifier<bool>(false);+ late final VideoSeekController _seekController;+ bool _isSeekInteractionActive = false;late final StreamSubscription<bool> _isPlayingStreamSubscription;+ late final StreamSubscription<bool> _completedStreamSubscription;@overridevoid initState() {super.initState();widget.playbackSpeed.addListener(_onPlaybackSpeedChanged);widget.controller.player.setRate(widget.playbackSpeed.value);+ _seekController = VideoSeekController(+ seek: widget.controller.player.seek,+ readPosition: () => widget.controller.player.state.position,+ readDuration: () => widget.controller.player.state.duration,+ onSeekError: (error, stackTrace) {+ _logger.warning("Could not seek video", error, stackTrace);+ },+ );+ _seekController.addListener(_onSeekInteractionChanged);_isPlayingStreamSubscription = widget.controller.player.stream.playing.listen((isPlaying) {- if (isPlaying && !_isSeekingNotifier.value) {+ if (!isPlaying) {+ _hideControlsDebouncer.cancelDebounceTimer();+ } else if (!_seekController.state.isInteracting) {_hideControlsDebouncer.run(() async {showControlsNotifier.value = false;widget.playbackCallback?.call(@@ -64,8 +81,15 @@ class _VideoWidgetState extends State<VideoWidget> {});}});-- _isSeekingNotifier.addListener(isSeekingListener);+ _completedStreamSubscription = widget.controller.player.stream.completed+ .listen((isCompleted) {+ if (isCompleted) {+ _seekController.reset(+ position: widget.controller.player.state.position,+ duration: widget.controller.player.state.duration,+ );+ }+ });}@override@@ -73,9 +97,10 @@ class _VideoWidgetState extends State<VideoWidget> {widget.playbackSpeed.removeListener(_onPlaybackSpeedChanged);showControlsNotifier.dispose();_isPlayingStreamSubscription.cancel();+ _completedStreamSubscription.cancel();_hideControlsDebouncer.cancelDebounceTimer();- _isSeekingNotifier.removeListener(isSeekingListener);- _isSeekingNotifier.dispose();+ _seekController.removeListener(_onSeekInteractionChanged);+ _seekController.dispose();super.dispose();}@@ -83,8 +108,11 @@ class _VideoWidgetState extends State<VideoWidget> {widget.controller.player.setRate(widget.playbackSpeed.value);}- void isSeekingListener() {- if (_isSeekingNotifier.value) {+ void _onSeekInteractionChanged() {+ final isInteracting = _seekController.state.isInteracting;+ if (_isSeekInteractionActive == isInteracting) return;+ _isSeekInteractionActive = isInteracting;+ if (isInteracting) {_hideControlsDebouncer.cancelDebounceTimer();} else {if (widget.controller.player.state.playing) {@@ -116,6 +144,48 @@ class _VideoWidgetState extends State<VideoWidget> {child: videoWidget,): videoWidget,+ DoubleTapSeekOverlay(+ enabled: () => !widget.isFromMemories,+ position: () => _seekController.position,+ duration: () => widget.controller.player.state.duration,+ seekBy: _seekController.seekBy,+ onSeekInteraction: () {+ showControlsNotifier.value = true;+ },+ onSingleTap: widget.isFromMemories+ ? null+ : () {+ showControlsNotifier.value = !showControlsNotifier.value;+ if (widget.playbackCallback != null) {+ widget.playbackCallback!(+ !showControlsNotifier.value,+ FullScreenRequestReason.userInteraction,+ );+ }+ },+ onLongPress: widget.isFromMemories+ ? () {+ widget.playbackCallback?.call(+ false,+ FullScreenRequestReason.userInteraction,+ );+ if (widget.controller.player.state.playing) {+ widget.controller.player.pause();+ }+ }+ : null,+ onLongPressUp: widget.isFromMemories+ ? () {+ widget.playbackCallback?.call(+ true,+ FullScreenRequestReason.userInteraction,+ );+ if (!widget.controller.player.state.playing) {+ widget.controller.player.play();+ }+ }+ : null,+ ),ValueListenableBuilder(valueListenable: showControlsNotifier,builder: (context, value, _) {@@ -130,46 +200,6 @@ class _VideoWidgetState extends State<VideoWidget> {VideoBottomScrim(hasCaption: widget.file.caption?.isNotEmpty ?? false,),- GestureDetector(- behavior: HitTestBehavior.translucent,- onTap: widget.isFromMemories- ? null- : () {- showControlsNotifier.value =- !showControlsNotifier.value;- if (widget.playbackCallback != null) {- widget.playbackCallback!(- !showControlsNotifier.value,- FullScreenRequestReason.userInteraction,- );- }- },- onLongPress: () {- if (widget.isFromMemories) {- widget.playbackCallback?.call(- false,- FullScreenRequestReason.userInteraction,- );- if (widget.controller.player.state.playing) {- widget.controller.player.pause();- }- }- },- onLongPressUp: () {- if (widget.isFromMemories) {- widget.playbackCallback?.call(- true,- FullScreenRequestReason.userInteraction,- );- if (!widget.controller.player.state.playing) {- widget.controller.player.play();- }- }- },- child: Container(- constraints: const BoxConstraints.expand(),- ),- ),widget.isFromMemories? const SizedBox.shrink(): IgnorePointer(@@ -190,7 +220,7 @@ class _VideoWidgetState extends State<VideoWidget> {right: false,child: _MediaKitVideoProgressControls(controller: widget.controller,- isSeekingNotifier: _isSeekingNotifier,+ seekController: _seekController,),),),@@ -211,7 +241,15 @@ class _VideoWidgetState extends State<VideoWidget> {showControls: value,file: widget.file,isPreviewPlayer: widget.isPreviewPlayer,- onStreamChange: widget.onStreamChange,+ onStreamChange: () {+ _seekController.reset(+ position:+ widget.controller.player.state.position,+ duration:+ widget.controller.player.state.duration,+ );+ widget.onStreamChange();+ },),),),@@ -310,11 +348,11 @@ class _PlayPauseButtonState extends State<PlayPauseButtonMediaKit> {class _MediaKitVideoProgressControls extends StatefulWidget {final VideoController controller;- final ValueNotifier<bool> isSeekingNotifier;+ final VideoSeekController seekController;const _MediaKitVideoProgressControls({required this.controller,- required this.isSeekingNotifier,+ required this.seekController,});@override@@ -324,48 +362,34 @@ class _MediaKitVideoProgressControls extends StatefulWidget {class _MediaKitVideoProgressControlsStateextends State<_MediaKitVideoProgressControls> {- double _sliderValue = 0.0;- Duration _elapsedTime = Duration.zero;late final StreamSubscription<Duration> _positionStreamSubscription;- final _debouncer = Debouncer(- const Duration(milliseconds: 300),- executionInterval: const Duration(milliseconds: 300),- );@overridevoid initState() {super.initState();+ widget.seekController.addListener(_onSeekStateChanged);_positionStreamSubscription = widget.controller.player.stream.position.listen((event) {- if (widget.isSeekingNotifier.value) return;- if (mounted) {- setState(() {- _elapsedTime = event;- _sliderValue =- (event.inMilliseconds /- widget- .controller- .player- .state- .duration- .inMilliseconds)- .clamp(0, 1);- if (_sliderValue.isNaN) {- _sliderValue = 0.0;- }- });- }+ widget.seekController.onPlayerPosition(+ event,+ duration: widget.controller.player.state.duration,+ );});}@overridevoid dispose() {+ widget.seekController.removeListener(_onSeekStateChanged);_positionStreamSubscription.cancel();- _debouncer.cancelDebounceTimer();super.dispose();}+ void _onSeekStateChanged() {+ if (mounted) setState(() {});+ }+@overrideWidget build(BuildContext context) {+ final canSeek = widget.seekController.canSeek;final seekBar = SliderTheme(data: SliderTheme.of(context).copyWith(trackHeight: 3.0,@@ -383,51 +407,40 @@ class _MediaKitVideoProgressControlsStatemin: 0.0,max: 1.0,value: _sliderValue,- onChangeStart: (value) {- if (mounted) {- setState(() {- widget.isSeekingNotifier.value = true;- });- }- },- onChanged: (value) {- if (mounted) {- setState(() {- _sliderValue = value;- _elapsedTime = _positionAt(value);- });- }-- _debouncer.run(() async {- await widget.controller.player.seek(_positionAt(value));- });- },+ onChangeStart: canSeek+ ? (value) => widget.seekController.beginSliderInteraction()+ : null,+ onChanged: canSeek+ ? (value) =>+ widget.seekController.updateSliderTarget(_positionAt(value))+ : null,divisions: 4500,- onChangeEnd: (value) async {- await widget.controller.player.seek(_positionAt(value));- if (mounted) {- setState(() {- widget.isSeekingNotifier.value = false;- });- }- },+ onChangeEnd: canSeek+ ? (value) =>+ widget.seekController.endSliderInteraction(_positionAt(value))+ : null,allowedInteraction: SliderInteraction.tapAndSlide,),);return VideoProgressRow(seekBar: seekBar,- elapsedTime: secondsToDuration(_elapsedTime.inSeconds),+ elapsedTime: secondsToDuration(widget.seekController.position.inSeconds),totalTime: secondsToDuration(- widget.controller.player.state.duration.inSeconds,+ (widget.seekController.duration ?? Duration.zero).inSeconds,),);}Duration _positionAt(double value) {- return Duration(- milliseconds:- (value * widget.controller.player.state.duration.inMilliseconds)- .round(),- );+ final duration = widget.seekController.duration ?? Duration.zero;+ return Duration(milliseconds: (value * duration.inMilliseconds).round());+ }++ double get _sliderValue {+ final duration = widget.seekController.duration;+ if (duration == null || duration <= Duration.zero) return 0;+ return (widget.seekController.position.inMilliseconds /+ duration.inMilliseconds)+ .clamp(0.0, 1.0);}}diff --git a/mobile/apps/photos/lib/ui/viewer/file/video_widget_native.dart b/mobile/apps/photos/lib/ui/viewer/file/video_widget_native.dartindex 4bc22e16d6..ae683b4418 100644--- a/mobile/apps/photos/lib/ui/viewer/file/video_widget_native.dart+++ b/mobile/apps/photos/lib/ui/viewer/file/video_widget_native.dart@@ -34,6 +34,8 @@ import "package:photos/ui/viewer/file/native_video_player_controls/play_pause_buimport "package:photos/ui/viewer/file/native_video_player_controls/seek_bar.dart";import "package:photos/ui/viewer/file/thumbnail_widget.dart";import "package:photos/ui/viewer/file/video_control/gallery_video_controls.dart";+import "package:photos/ui/viewer/file/video_double_tap_seek.dart";+import "package:photos/ui/viewer/file/video_seek_controller.dart";import "package:photos/ui/viewer/file/video_stream_change.dart";import "package:photos/ui/viewer/file/zoomable_video_viewer.dart";import "package:photos/utils/dialog_util.dart";@@ -92,6 +94,7 @@ class _VideoWidgetNativeState extends State<VideoWidgetNative>bool _isCompletelyVisible = false;final _showControls = ValueNotifier(true);final _isSeeking = ValueNotifier(false);+ late final VideoSeekController _seekController;final _debouncer = Debouncer(const Duration(milliseconds: 2000));StreamSubscription<PlaybackEvent>? _subscription;StreamSubscription<StreamSwitchedEvent>? _streamSwitchedSubscription;@@ -106,6 +109,25 @@ class _VideoWidgetNativeState extends State<VideoWidgetNative>);super.initState();widget.playbackSpeed.addListener(_onPlaybackSpeedChanged);+ _seekController = VideoSeekController(+ seek: (target) async {+ final controller = _controller;+ if (controller != null) await controller.seekTo(target);+ },+ readPosition: () => _controller?.playbackPosition ?? Duration.zero,+ readDuration: () {+ final milliseconds = _controller?.videoInfo?.durationInMilliseconds;+ if (milliseconds != null && milliseconds > 0) {+ return Duration(milliseconds: milliseconds);+ }+ final seconds = durationToSeconds(duration);+ return seconds == null ? null : Duration(seconds: seconds);+ },+ onSeekError: (error, stackTrace) {+ _logger.warning("Could not seek video", error, stackTrace);+ },+ );+ _seekController.addListener(_syncSeekInteraction);WidgetsBinding.instance.addObserver(this);if (widget.selectedPreview) {@@ -177,6 +199,7 @@ class _VideoWidgetNativeState extends State<VideoWidgetNative>}Future<void> setVideoSource() async {+ _seekController.reset();if (_filePath == null) {_logger.info('Stop video player, file path is null');await _controller?.stop();@@ -288,6 +311,8 @@ class _VideoWidgetNativeState extends State<VideoWidgetNative>_showControls.dispose();_isSeeking.removeListener(_seekListener);_isSeeking.dispose();+ _seekController.removeListener(_syncSeekInteraction);+ _seekController.dispose();_debouncer.cancelDebounceTimer();_transformationController.dispose();wakeLockService.updateWakeLock(@@ -378,9 +403,17 @@ class _VideoWidgetNativeState extends State<VideoWidgetNative>widget.file.caption?.isNotEmpty ?? false,),),- GestureDetector(- behavior: HitTestBehavior.translucent,- onTap: widget.isFromMemories+ DoubleTapSeekOverlay(+ enabled: () =>+ !widget.isFromMemories && isPlaybackReady,+ position: () => _seekController.position,+ duration: () =>+ _seekController.duration ?? Duration.zero,+ seekBy: _seekController.seekBy,+ onSeekInteraction: () {+ _showControls.value = true;+ },+ onSingleTap: widget.isFromMemories? null: () {_showControls.value = !_showControls.value;@@ -391,27 +424,25 @@ class _VideoWidgetNativeState extends State<VideoWidgetNative>);}},- onLongPress: () {- if (widget.isFromMemories) {- widget.playbackCallback?.call(- false,- FullScreenRequestReason.userInteraction,- );- _controller?.pause();- }- },- onLongPressUp: () {- if (widget.isFromMemories && widget.isActive) {- widget.playbackCallback?.call(- true,- FullScreenRequestReason.userInteraction,- );- _controller?.play();- }- },- child: Container(- constraints: const BoxConstraints.expand(),- ),+ onLongPress: widget.isFromMemories+ ? () {+ widget.playbackCallback?.call(+ false,+ FullScreenRequestReason.userInteraction,+ );+ _controller?.pause();+ }+ : null,+ onLongPressUp: widget.isFromMemories+ ? () {+ if (!widget.isActive) return;+ widget.playbackCallback?.call(+ true,+ FullScreenRequestReason.userInteraction,+ );+ _controller?.play();+ }+ : null,),if (!widget.isFromMemories && isPlaybackReady)Positioned.fill(@@ -451,7 +482,7 @@ class _VideoWidgetNativeState extends State<VideoWidgetNative>controller: _controller!,duration: duration,showControls: _showControls,- isSeeking: _isSeeking,+ seekController: _seekController,): const SizedBox.shrink(),),@@ -542,6 +573,10 @@ class _VideoWidgetNativeState extends State<VideoWidgetNative>void _seekListener() {if (widget.isFromMemories) return;+ if (_isSeeking.value) {+ _debouncer.cancelDebounceTimer();+ return;+ }if (!_isSeeking.value &&_controller?.playbackStatus == PlaybackStatus.playing) {_debouncer.run(() async {@@ -562,6 +597,13 @@ class _VideoWidgetNativeState extends State<VideoWidgetNative>}}+ void _syncSeekInteraction() {+ final isSeeking = _seekController.state.isInteracting;+ if (_isSeeking.value != isSeeking) {+ _isSeeking.value = isSeeking;+ }+ }+void _onPlaybackStatusChanged() {if (widget.isFromMemories) return;final duration = widget.file.duration != null@@ -591,6 +633,7 @@ class _VideoWidgetNativeState extends State<VideoWidgetNative>});}} else {+ _debouncer.cancelDebounceTimer();if (widget.playbackCallback != null && mounted) {widget.playbackCallback!(false,@@ -621,6 +664,8 @@ class _VideoWidgetNativeState extends State<VideoWidgetNative>}void _onPlaybackEnded() async {+ _seekController.reset(duration: _seekController.duration);+ _debouncer.cancelDebounceTimer();await _controller?.stop();if (widget.isActive && localSettings.shouldLoopVideo()) {Bus.instance.fire(SeekbarTriggeredEvent(position: 0));@@ -891,13 +936,13 @@ class _VideoProgressControls extends StatelessWidget {final NativeVideoPlayerController controller;final String? duration;final ValueNotifier<bool> showControls;- final ValueNotifier<bool> isSeeking;+ final VideoSeekController seekController;const _VideoProgressControls({required this.controller,required this.duration,required this.showControls,- required this.isSeeking,+ required this.seekController,});@override@@ -914,7 +959,7 @@ class _VideoProgressControls extends StatelessWidget {child: NativeVideoProgressControls(controller,durationToSeconds(duration),- isSeeking,+ seekController,),),);