Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

35.9 KB
Raw Blame
import "dart:async";
import "dart:io";

import "package:ente_pure_utils/ente_pure_utils.dart";
import "package:ente_strings/ente_strings.dart";
import "package:flutter/material.dart";
import "package:logging/logging.dart";
import "package:native_video_player/native_video_player.dart";
import "package:photos/core/constants.dart";
import "package:photos/core/event_bus.dart";
import "package:photos/events/guest_view_event.dart";
import "package:photos/events/pause_video_event.dart";
import "package:photos/events/resume_video_event.dart";
import "package:photos/events/seekbar_triggered_event.dart";
import "package:photos/events/stream_switched_event.dart";
import "package:photos/events/use_media_kit_for_video.dart";
import "package:photos/events/video_mute_changed_event.dart";
import "package:photos/models/file/extensions/file_props.dart";
import "package:photos/models/file/file.dart";
import "package:photos/models/preview/playlist_data.dart";
import 'package:photos/module/download/download_error.dart';
import "package:photos/module/download/file.dart";
import "package:photos/module/download/progressive_video_stream.dart";
import "package:photos/module/download/task.dart";
import "package:photos/module/metadata/video.dart";
import "package:photos/service_locator.dart";
import "package:photos/services/files_service.dart";
import "package:photos/services/wake_lock_service.dart";
import "package:photos/states/detail_page_state.dart";
import "package:photos/theme/colors.dart";
import "package:photos/ui/actions/file/file_actions.dart";
import "package:photos/ui/notification/toast.dart";
import "package:photos/ui/viewer/file/native_video_player_controls/play_pause_button.dart";
import "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_download_progress_indicator.dart";
import "package:photos/ui/viewer/file/video_seek_controller.dart";
import "package:photos/ui/viewer/file/zoomable_video_viewer.dart";
import "package:photos/utils/dialog_util.dart";
import "package:video_player/video_player.dart" as vp;
import "package:visibility_detector/visibility_detector.dart";

class VideoWidgetNative extends StatefulWidget {
  final EnteFile file;
  final String? tagPrefix;
  final FullScreenRequestCallback? playbackCallback;
  final Function(bool)? shouldDisableScroll;
  final bool isFromMemories;
  final bool isActive;
  final bool? isAudioMutedOverride;
  final PlaylistData? playlistData;
  final bool selectedPreview;
  final ValueNotifier<double> playbackSpeed;
  final Function({required int memoryDuration})? onFinalFileLoad;

  const VideoWidgetNative(
    this.file, {
    this.tagPrefix,
    this.playbackCallback,
    this.shouldDisableScroll,
    this.isFromMemories = false,
    required this.isActive,
    this.isAudioMutedOverride,
    super.key,
    this.playlistData,
    this.onFinalFileLoad,
    required this.selectedPreview,
    required this.playbackSpeed,
  });

  @override
  State<VideoWidgetNative> createState() => _VideoWidgetNativeState();
}

class _VideoWidgetNativeState extends State<VideoWidgetNative>
    with WidgetsBindingObserver {
  final Logger _logger = Logger("VideoWidgetNative");
  final _progressNotifier = ValueNotifier<double?>(null);
  late StreamSubscription<PauseVideoEvent> pauseVideoSubscription;
  late StreamSubscription<ResumeVideoEvent> resumeVideoSubscription;
  StreamSubscription<VideoMuteChangedEvent>? _muteSubscription;
  bool _isGuestView = false;
  late final StreamSubscription<GuestViewEvent> _guestViewEventSubscription;
  NativeVideoPlayerController? _controller;
  String? _filePath;
  String? duration;
  double? aspectRatio;
  final _isPlaybackReady = ValueNotifier(false);
  bool _shouldClearCache = false;
  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;
  StreamSubscription<DownloadTask>? downloadTaskSubscription;
  ProgressiveVideoStream? _progressive;
  Future<void>? _progressiveCleanup;
  int _videoLoad = 0;
  int _nativePlayerVersion = 0;
  String? _loadedProgressiveUrl;
  bool get _isProgressiveSource =>
      _filePath?.startsWith('http://127.0.0.1:') ?? false;
  final _transformationController = TransformationController();
  bool _isZooming = false;
  OverlayEntry? _longPressSpeedIndicatorEntry;

  @override
  void initState() {
    _logger.info(
      'initState for ${widget.file.generatedID} with tag ${widget.file.tag} and name ${widget.file.displayName}',
    );
    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) {
      loadPreview();
    } else {
      loadOriginal();
    }

    pauseVideoSubscription = Bus.instance.on<PauseVideoEvent>().listen((event) {
      if (event.fileTag != null && event.fileTag != widget.file.tag) return;
      _controller?.pause();
    });
    resumeVideoSubscription = Bus.instance.on<ResumeVideoEvent>().listen((
      event,
    ) {
      if (widget.isActive) _controller?.play();
    });
    if (!widget.isFromMemories) {
      _muteSubscription = Bus.instance.on<VideoMuteChangedEvent>().listen((
        event,
      ) async {
        final controller = _controller;
        if (controller == null) return;
        await controller.setVolume(event.isMuted ? 0.0 : 1.0);
      });
    }
    _guestViewEventSubscription = Bus.instance.on<GuestViewEvent>().listen((
      event,
    ) {
      if (!mounted) return;
      setState(() {
        _isGuestView = event.isGuestView;
      });
    });
    _streamSwitchedSubscription = Bus.instance.on<StreamSwitchedEvent>().listen(
      (event) {
        if (event.fileTag != widget.file.tag ||
            event.type != PlayerType.nativeVideoPlayer) {
          return;
        }
        if (event.selectedPreview) {
          loadPreview(update: true);
        } else {
          loadOriginal(update: true);
        }
      },
    );

    if (widget.file.isUploaded) {
      downloadTaskSubscription = downloadManager
          .watchDownload(widget.file.uploadedFileID!)
          .listen((event) {
            _progressNotifier.value = event.progress;
          });
    }

    wakeLockService.updateWakeLock(
      enable: true,
      wakeLockFor: WakeLockFor.videoPlayback,
    );
  }

  @override
  void didUpdateWidget(covariant VideoWidgetNative oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (oldWidget.isActive != widget.isActive) {
      unawaited(_syncPlayback());
    }
    if (oldWidget.isAudioMutedOverride != widget.isAudioMutedOverride) {
      unawaited(_applyVolume());
    }
  }

  Future<void> setVideoSource() async {
    _seekController.reset();
    if (_filePath == null) {
      _logger.info('Stop video player, file path is null');
      await _controller?.stop();
      return;
    }
    final videoSource = VideoSource(
      path: _filePath!,
      type: _isProgressiveSource
          ? VideoSourceType.network
          : VideoSourceType.file,
    );
    _loadedProgressiveUrl = _isProgressiveSource ? _filePath : null;
    await _controller?.loadVideo(videoSource);
    await _applyVolume();
    await _controller?.setPlaybackSpeed(widget.playbackSpeed.value);
    await _syncPlayback();

    Bus.instance.fire(SeekbarTriggeredEvent(position: 0));
  }

  void loadPreview({bool update = false}) async {
    final generation = ++_videoLoad;
    final cleanup = _disposeProgressive();
    if (cleanup != null) {
      await cleanup;
      if (!mounted || generation != _videoLoad) {
        return;
      }
    }
    final previewPath = widget.playlistData?.preview.path;
    if (previewPath == null) {
      loadOriginal(update: true);
      return;
    }
    _setFilePathForNativePlayer(previewPath, update);

    await setVideoSource();
  }

  void loadOriginal({bool update = false}) async {
    final generation = ++_videoLoad;
    final cleanup = _disposeProgressive();
    if (cleanup != null) {
      await cleanup;
      if (!mounted || generation != _videoLoad) {
        return;
      }
    }
    setState(() => _filePath = null);
    if (widget.file.isRemoteOnlyFile) {
      _loadNetworkVideo(update);
      _setFileSizeIfNull();
    } else if (widget.file.isSharedMediaToAppSandbox) {
      final localFile = File(getSharedMediaFilePath(widget.file));
      if (localFile.existsSync()) {
        _setFilePathForNativePlayer(localFile.path, update);
      } else if (widget.file.uploadedFileID != null) {
        _loadNetworkVideo(update);
      }
    } else {
      await widget.file.getAsset.then((asset) async {
        // Android trash assets may report that they do not exist.
        final exists = await asset?.exists ?? false;
        if (!mounted || generation != _videoLoad) {
          return;
        }
        if (asset == null || !(exists || widget.file.isDeviceTrash)) {
          if (widget.file.uploadedFileID != null) {
            _loadNetworkVideo(update);
          }
        } else {
          // ignore: unawaited_futures
          getFile(widget.file, isOrigin: true).then((file) {
            if (!mounted || generation != _videoLoad) {
              return;
            }
            if (file == null) {
              _loadNetworkVideo(update);
              return;
            }
            _setFilePathForNativePlayer(file.path, update);
            if (Platform.isIOS) {
              _shouldClearCache = true;
            }
          });
        }
      });
    }
    if (update && mounted && generation == _videoLoad) {
      await setVideoSource();
    }
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (state != AppLifecycleState.resumed) {
      if (_controller?.playbackStatus == PlaybackStatus.playing) {
        _controller?.pause();
      }
    }
  }

  @override
  void dispose() {
    _videoLoad++;
    _progressive?.dispose().ignore();
    _progressive = null;
    _longPressSpeedIndicatorEntry?.remove();
    widget.playbackSpeed.removeListener(_onPlaybackSpeedChanged);
    _subscription?.cancel();
    _controller?.stop().ignore();
    _controller?.dispose();
    if (downloadTaskSubscription != null) {
      downloadTaskSubscription!.cancel();
      downloadManager.pause(widget.file.uploadedFileID!).ignore();
    }

    //https://github.com/fluttercandies/flutter_photo_manager/blob/8afba2745ebaac6af8af75de9cbded9157bc2690/README.md#clear-caches
    if (_shouldClearCache) {
      _logger.info("Clearing cache");
      final file = File(_filePath!);

      // Avoid an observed PathNotFoundException.
      if (file.existsSync()) {
        file.delete().then((value) {
          _logger.info("Cache cleared");
        });
      }
    }
    _streamSwitchedSubscription?.cancel();
    _guestViewEventSubscription.cancel();
    pauseVideoSubscription.cancel();
    resumeVideoSubscription.cancel();
    _muteSubscription?.cancel();
    removeDownloadCallback(widget.file);
    _progressNotifier.dispose();
    WidgetsBinding.instance.removeObserver(this);
    _isPlaybackReady.dispose();
    _showControls.dispose();
    _isSeeking.removeListener(_seekListener);
    _isSeeking.dispose();
    _seekController.removeListener(_syncSeekInteraction);
    _seekController.dispose();
    _debouncer.cancelDebounceTimer();
    _transformationController.dispose();
    wakeLockService.updateWakeLock(
      enable: false,
      wakeLockFor: WakeLockFor.videoPlayback,
    );
    super.dispose();
  }

  void _onPlaybackSpeedChanged() {
    _controller?.setPlaybackSpeed(widget.playbackSpeed.value);
  }

  void _startLongPressSpeed() {
    final controller = _controller;
    if (_longPressSpeedIndicatorEntry != null || controller == null) return;
    _longPressSpeedIndicatorEntry = showVideoLongPressSpeedIndicator(context);
    controller.setPlaybackSpeed(kVideoLongPressPlaybackSpeed).ignore();
  }

  void _restorePlaybackSpeed() {
    if (_longPressSpeedIndicatorEntry == null) return;
    _longPressSpeedIndicatorEntry?.remove();
    _longPressSpeedIndicatorEntry = null;
    _controller?.setPlaybackSpeed(widget.playbackSpeed.value).ignore();
  }

  void _onInteractionLockChanged(bool shouldLock) {
    if (!mounted) return;
    if (_isZooming != shouldLock) {
      setState(() {
        _isZooming = shouldLock;
      });
    }
    widget.shouldDisableScroll?.call(shouldLock);
  }

  @override
  Widget build(BuildContext context) {
    return Hero(
      tag: widget.tagPrefix! + widget.file.tag,
      child: VisibilityDetector(
        key: Key(widget.file.generatedID?.toString() ?? widget.file.tag),
        onVisibilityChanged: (info) {
          if (info.visibleFraction == 1) {
            setState(() {
              _isCompletelyVisible = true;
            });
          }
        },
        child: GestureDetector(
          // During zoom, keep this recognizer out of multi-touch gesture arenas.
          onVerticalDragUpdate: _isGuestView || _isZooming
              ? null
              : (d) {
                  if (d.delta.dy > dragSensitivity) {
                    _stopPlaybackBeforeDismiss();
                    Navigator.of(context).pop();
                  } else if (d.delta.dy < (dragSensitivity * -1)) {
                    showDetailsSheet(context, widget.file);
                  }
                },
          child: ValueListenableBuilder(
            valueListenable: _isPlaybackReady,
            builder: (context, isPlaybackReady, _) {
              return AnimatedSwitcher(
                duration: const Duration(milliseconds: 750),
                switchOutCurve: Curves.easeOutExpo,
                switchInCurve: Curves.easeInExpo,
                // Two high-resolution portrait videos can blank one another.
                // Load only the completely visible one.
                child: !_isCompletelyVisible || _filePath == null
                    ? _getLoadingWidget()
                    : Stack(
                        key: const ValueKey("video_ready"),
                        children: [
                          ZoomableVideoViewer(
                            transformationController: _transformationController,
                            onInteractionLockChanged: _onInteractionLockChanged,
                            child: Center(
                              child: AspectRatio(
                                aspectRatio: aspectRatio ?? 1,
                                child: NativeVideoPlayerView(
                                  key: ValueKey(_nativePlayerVersion),
                                  onViewReady: _initializeController,
                                ),
                              ),
                            ),
                          ),
                          if (!widget.isFromMemories)
                            ValueListenableBuilder(
                              valueListenable: _showControls,
                              builder: (context, showControls, child) {
                                return AnimatedOpacity(
                                  duration: const Duration(milliseconds: 200),
                                  opacity: showControls ? 1 : 0,
                                  curve: Curves.easeInOutQuad,
                                  child: child,
                                );
                              },
                              child: VideoBottomScrim(
                                hasCaption:
                                    widget.file.caption?.isNotEmpty ?? false,
                              ),
                            ),
                          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;
                                    if (widget.playbackCallback != null) {
                                      widget.playbackCallback!(
                                        !_showControls.value,
                                        FullScreenRequestReason.userInteraction,
                                      );
                                    }
                                  },
                            onLongPress: () {
                              if (widget.isFromMemories) {
                                widget.playbackCallback?.call(
                                  false,
                                  FullScreenRequestReason.userInteraction,
                                );
                                _controller?.pause();
                              } else {
                                _startLongPressSpeed();
                              }
                            },
                            onLongPressUp: () {
                              if (widget.isFromMemories && widget.isActive) {
                                widget.playbackCallback?.call(
                                  true,
                                  FullScreenRequestReason.userInteraction,
                                );
                                _controller?.play();
                              } else if (!widget.isFromMemories) {
                                _restorePlaybackSpeed();
                              }
                            },
                            onLongPressCancel: widget.isFromMemories
                                ? null
                                : _restorePlaybackSpeed,
                          ),
                          if (!widget.isFromMemories && isPlaybackReady)
                            Positioned.fill(
                              child: Center(
                                child: ValueListenableBuilder(
                                  valueListenable: _showControls,
                                  builder: (context, showControls, _) {
                                    return AnimatedOpacity(
                                      duration: const Duration(
                                        milliseconds: 200,
                                      ),
                                      opacity: showControls ? 1 : 0,
                                      curve: Curves.easeInOutQuad,
                                      child: IgnorePointer(
                                        ignoring: !showControls,
                                        child: PlayPauseButton(_controller),
                                      ),
                                    );
                                  },
                                ),
                              ),
                            ),
                          if (!isPlaybackReady)
                            Positioned.fill(child: _getLoadingWidget()),
                          widget.isFromMemories
                              ? const SizedBox.shrink()
                              : GalleryBottomControlsPositioned(
                                  bottom: kVideoProgressRowBottomInset,
                                  child: SafeArea(
                                    top: false,
                                    left: false,
                                    right: false,
                                    child: isPlaybackReady
                                        ? _VideoProgressControls(
                                            controller: _controller!,
                                            duration: duration,
                                            showControls: _showControls,
                                            seekController: _seekController,
                                          )
                                        : const SizedBox.shrink(),
                                  ),
                                ),
                        ],
                      ),
              );
            },
          ),
        ),
      ),
    );
  }

  void _stopPlaybackBeforeDismiss() {
    _controller?.pause();
    _controller?.stop().ignore();
    widget.playbackCallback?.call(
      false,
      FullScreenRequestReason.userInteraction,
    );
  }

  Future<void> _initializeController(
    NativeVideoPlayerController controller,
  ) async {
    try {
      _logger.info(
        "Initializing native video player controller for file gen id: ${widget.file.generatedID}",
      );
      _controller = controller;

      _subscription = controller.events.listen(_listen);

      _isSeeking.addListener(_seekListener);

      await setVideoSource();
    } catch (e) {
      _logger.severe(
        "Error initializing native video player controller for file gen id: ${widget.file.generatedID}",
        e,
      );
    }
  }

  void _listen(PlaybackEvent event) {
    switch (event) {
      case PlaybackStatusChangedEvent():
        _onPlaybackStatusChanged();
      case PlaybackReadyEvent():
        _onPlaybackReady();
        break;
      case PlaybackEndedEvent():
        _onPlaybackEnded();
        break;
      case PlaybackErrorEvent():
        _onError(event.errorMessage);
        break;
      default:
    }
  }

  void _seekListener() {
    if (widget.isFromMemories) return;
    if (_isSeeking.value) {
      _debouncer.cancelDebounceTimer();
      return;
    }
    if (!_isSeeking.value &&
        _controller?.playbackStatus == PlaybackStatus.playing) {
      _debouncer.run(() async {
        if (mounted) {
          if (_isSeeking.value ||
              _controller?.playbackStatus != PlaybackStatus.playing) {
            return;
          }
          _showControls.value = false;
          if (widget.playbackCallback != null) {
            widget.playbackCallback!(
              true,
              FullScreenRequestReason.playbackStateChange,
            );
          }
        }
      });
    }
  }

  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
        ? widget.file.duration! * 1000
        : _controller?.videoInfo?.durationInMilliseconds;

    if (_isSeeking.value ||
        _controller?.playbackPosition.inMilliseconds == duration) {
      return;
    }
    if (_controller!.playbackStatus == PlaybackStatus.playing) {
      if (mounted) {
        _debouncer.run(() async {
          if (mounted) {
            if (_isSeeking.value ||
                _controller!.playbackStatus != PlaybackStatus.playing) {
              return;
            }
            _showControls.value = false;
            if (widget.playbackCallback != null) {
              widget.playbackCallback!(
                true,
                FullScreenRequestReason.playbackStateChange,
              );
            }
          }
        });
      }
    } else {
      _debouncer.cancelDebounceTimer();
      if (widget.playbackCallback != null && mounted) {
        widget.playbackCallback!(
          false,
          FullScreenRequestReason.playbackStateChange,
        );
      }
    }

    _handleWakeLockOnPlaybackChanges();
  }

  void _onError(String errorMessage) {
    if (_loadedProgressiveUrl != null) {
      if (_progressive?.url == _loadedProgressiveUrl) {
        _progressive?.playbackFailed();
      }
      return;
    }
    _logger.severe(
      "Error in native video player controller for file gen id: ${widget.file.generatedID}",
    );
    _logger.severe(errorMessage);
    Bus.instance.fire(UseMediaKitForVideo());
  }

  Future<void> _onPlaybackReady() async {
    if (_isPlaybackReady.value) return;
    if (_loadedProgressiveUrl != null &&
        _progressive?.url != _loadedProgressiveUrl) {
      return;
    }
    await _applyVolume();
    await _controller?.setPlaybackSpeed(widget.playbackSpeed.value);
    await _syncPlayback();
    final durationInSeconds = durationToSeconds(duration) ?? 10;
    widget.onFinalFileLoad?.call(memoryDuration: durationInSeconds);
    _isPlaybackReady.value = true;
  }

  void _onPlaybackEnded() async {
    _seekController.reset(duration: _seekController.duration);
    _debouncer.cancelDebounceTimer();
    await _controller?.stop();
    if (widget.isActive && localSettings.shouldLoopVideo()) {
      Bus.instance.fire(SeekbarTriggeredEvent(position: 0));
      await _controller?.play();
    }
  }

  Future<void> _applyVolume() async {
    final controller = _controller;
    if (controller == null) return;
    final mutedOverride = widget.isAudioMutedOverride;
    if (mutedOverride != null) {
      await controller.setVolume(mutedOverride ? 0.0 : 1.0);
    } else if (!widget.isFromMemories) {
      await controller.setVolume(localSettings.isMuted() ? 0.0 : 1.0);
    }
  }

  Future<void> _syncPlayback() async {
    final controller = _controller;
    if (controller == null) return;
    if (widget.isActive) {
      await controller.play();
    } else {
      await controller.pause();
    }
  }

  Future<void>? _disposeProgressive() {
    final stream = _progressive;
    _progressive = null;
    if (stream == null) {
      return _progressiveCleanup;
    }
    return _progressiveCleanup = (_controller?.stop() ?? Future<void>.value())
        .catchError((Object _) {})
        .whenComplete(stream.dispose);
  }

  void _loadNetworkVideo(bool update) {
    if (flagService.progressiveOriginalVideoPlayback &&
        widget.file.hasDimensions &&
        (widget.file.duration ?? 0) > 0) {
      unawaited(_loadProgressively(update));
    } else {
      _loadNetworkVideoFully(update);
    }
  }

  Future<void> _loadProgressively(bool update) async {
    final generation = _videoLoad;
    bool isCurrent() => mounted && generation == _videoLoad;
    final stream = ProgressiveVideoStream(
      widget.file,
      onProgress: (count, total) {
        if (isCurrent()) {
          _progressNotifier.value = count / total;
        }
      },
    );
    _progressive = stream;
    try {
      final url = await stream.open();
      if (!isCurrent()) {
        return;
      }
      if (url != null) {
        _setFilePathForNativePlayer(url, update);
        await stream.failure;
        return;
      }
    } catch (error) {
      if (isCurrent()) {
        _logger.info('Progressive playback unavailable (${error.runtimeType})');
      }
    }
    if (!isCurrent()) {
      return;
    }
    _isPlaybackReady.value = false;
    await _disposeProgressive();
    if (!isCurrent()) {
      return;
    }
    if (Platform.isIOS && stream.url != null) {
      _debouncer.cancelDebounceTimer();
      unawaited(_subscription?.cancel());
      _subscription = null;
      _controller?.dispose();
      _controller = null;
      _isSeeking.removeListener(_seekListener);
      setState(() {
        _filePath = null;
        _nativePlayerVersion++;
      });
    }
    _loadNetworkVideoFully(
      update || stream.url != null,
      generation: generation,
    );
  }

  void _loadNetworkVideoFully(bool update, {int? generation}) {
    bool isCurrent() =>
        mounted && (generation == null || generation == _videoLoad);
    getFileFromServer(
          widget.file,
          throwOnDecryptionFailure: true,
          progressCallback: (count, total) {
            if (!isCurrent()) {
              return;
            }
            _progressNotifier.value = count / (widget.file.fileSize ?? total);
            if (_progressNotifier.value == 1) {
              if (mounted) {
                showShortToast(context, context.strings.decryptingVideo);
              }
            }
          },
        )
        .then((file) {
          if (file != null && isCurrent()) {
            _setFilePathForNativePlayer(file.path, update);
          }
        })
        .onError((error, stackTrace) {
          if (!mounted || !isCurrent()) {
            return;
          }
          if (error is DownloadDecryptionError) {
            showDownloadDecryptionFailedDialog(context: context);
          } else {
            showErrorDialog(
              context,
              context.strings.error,
              context.strings.failedToDownloadVideo,
            );
          }
        });
  }

  void _setFileSizeIfNull() {
    if (widget.file.fileSize == null && widget.file.canEditMetaInfo) {
      FilesService.instance.getFileSize(widget.file.uploadedFileID!).then((
        value,
      ) {
        widget.file.fileSize = value;
        if (mounted) {
          setState(() {});
        }
      });
    }
  }

  void _handleWakeLockOnPlaybackChanges() {
    final playbackStatus = _controller?.playbackStatus;
    if (playbackStatus == PlaybackStatus.playing) {
      wakeLockService.updateWakeLock(
        enable: true,
        wakeLockFor: WakeLockFor.videoPlayback,
      );
    } else {
      wakeLockService.updateWakeLock(
        enable: false,
        wakeLockFor: WakeLockFor.videoPlayback,
      );
    }
  }

  Widget _getLoadingWidget() {
    return Stack(
      key: const ValueKey("video_loading"),
      children: [
        Container(
          color: Colors.black,
          constraints: const BoxConstraints.expand(),
          child: _getThumbnail(),
        ),
        Container(
          color: Colors.black.withValues(alpha: 0.3),
          constraints: const BoxConstraints.expand(),
        ),
        Center(
          child: Container(
            width: 48,
            height: 48,
            padding: const EdgeInsets.all(8),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(24),
              color: Colors.black.withValues(alpha: 0.3),
              border: Border.all(color: strokeFaintDark, width: 1),
            ),
            child: ValueListenableBuilder(
              valueListenable: _progressNotifier,
              builder: (BuildContext context, double? progress, _) {
                return VideoDownloadProgressIndicator(progress: progress);
              },
            ),
          ),
        ),
      ],
    );
  }

  Widget _getThumbnail() {
    return ThumbnailWidget(
      widget.file,
      fit: BoxFit.contain,
      shouldShowVideoOverlayIcon: false,
      rawThumbnail: true,
    );
  }

  void _setFilePathForNativePlayer(String url, bool update) {
    if (!mounted) return;
    _isPlaybackReady.value = false;
    setState(() {
      _filePath = url;
    });
    _setAspectRatioFromVideoProps().then((_) {
      if (!mounted) return;
      setState(() {});
    });

    if (update) {
      setVideoSource();
    }
  }

  Future<void> _setAspectRatioFromVideoProps() async {
    if (_isProgressiveSource) {
      aspectRatio = widget.file.width / widget.file.height;
      duration = secondsToDuration(widget.file.duration!);
      return;
    }
    if (aspectRatio != null && duration != null) return;

    if (widget.playlistData != null && widget.selectedPreview) {
      aspectRatio = widget.playlistData!.width! / widget.playlistData!.height!;
      if (duration == "0:00" || duration == null) {
        if ((widget.file.duration ?? 0) > 0) {
          duration = secondsToDuration(widget.file.duration!);
        } else if (widget.playlistData!.durationInSeconds != null) {
          duration = secondsToDuration(widget.playlistData!.durationInSeconds!);
        }
      }
      _logger.info("Getting aspect ratio from preview video");
      return;
    }
    if (Platform.isIOS) {
      // FFprobe can crash on some iOS media; use AVPlayer metadata instead.
      if (widget.file.hasDimensions) {
        aspectRatio = widget.file.width / widget.file.height;
      } else {
        aspectRatio ??= 1;
      }
      if ((duration == null || duration == "0:00") &&
          (widget.file.duration ?? 0) > 0) {
        duration = secondsToDuration(widget.file.duration!);
      }
      await _setAspectAndDurationFromIosPlayerProbe();
      return;
    }
    final videoProps = await getVideoProps(File(_filePath!));
    if (videoProps != null) {
      duration = videoProps.propData?["duration"];

      if (videoProps.width != null && videoProps.height != null) {
        if (videoProps.width != null && videoProps.height != 0) {
          aspectRatio = videoProps.width! / videoProps.height!;
        } else {
          _logger.info("Video props height or width is 0");
          aspectRatio = 1;
        }
      } else {
        _logger.info("Video props width and height are null");
        aspectRatio = 1;
      }
    } else {
      _logger.info("Video props are null");
      aspectRatio = 1;
    }
  }

  Future<void> _setAspectAndDurationFromIosPlayerProbe() async {
    final path = _filePath;
    if (path == null) return;
    vp.VideoPlayerController? metadataController;
    try {
      metadataController = vp.VideoPlayerController.file(File(path));
      await metadataController.initialize().timeout(const Duration(seconds: 4));
      final value = metadataController.value;
      final probeAspectRatio = value.aspectRatio;
      // AVPlayer's aspect ratio includes rotation; stored dimensions may not.
      if (probeAspectRatio > 0) {
        aspectRatio = probeAspectRatio;
      }
      final durationInMilliseconds = value.duration.inMilliseconds;
      if ((duration == null || duration == "0:00") &&
          durationInMilliseconds > 0) {
        duration = secondsToDuration(durationInMilliseconds ~/ 1000);
      }
    } on TimeoutException catch (e, s) {
      _logger.warning(
        "_setAspectAndDurationFromIosPlayerProbe timed out for ${widget.file.generatedID}",
        e,
        s,
      );
    } catch (e, s) {
      _logger.warning(
        "_setAspectAndDurationFromIosPlayerProbe failed for ${widget.file.generatedID}",
        e,
        s,
      );
    } finally {
      try {
        await metadataController?.dispose();
      } catch (e, s) {
        _logger.warning(
          "_setAspectAndDurationFromIosPlayerProbe dispose failed for ${widget.file.generatedID}",
          e,
          s,
        );
      }
    }
  }
}

class _VideoProgressControls extends StatelessWidget {
  final NativeVideoPlayerController controller;
  final String? duration;
  final ValueNotifier<bool> showControls;
  final VideoSeekController seekController;

  const _VideoProgressControls({
    required this.controller,
    required this.duration,
    required this.showControls,
    required this.seekController,
  });

  @override
  Widget build(BuildContext context) {
    return ValueListenableBuilder(
      valueListenable: showControls,
      builder: (BuildContext context, bool value, _) {
        return AnimatedOpacity(
          duration: const Duration(milliseconds: 200),
          curve: Curves.easeInQuad,
          opacity: value ? 1 : 0,
          child: IgnorePointer(
            ignoring: !value,
            child: NativeVideoProgressControls(
              controller,
              durationToSeconds(duration),
              seekController,
            ),
          ),
        );
      },
    );
  }
}