video_widget.dart 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. import 'dart:async';
  2. import 'dart:io';
  3. import 'package:chewie/chewie.dart';
  4. import 'package:flutter/cupertino.dart';
  5. import 'package:flutter/material.dart';
  6. import 'package:logging/logging.dart';
  7. import 'package:photos/core/constants.dart';
  8. import "package:photos/generated/l10n.dart";
  9. import "package:photos/models/file/extensions/file_props.dart";
  10. import 'package:photos/models/file/file.dart';
  11. import "package:photos/service_locator.dart";
  12. import 'package:photos/services/files_service.dart';
  13. import "package:photos/ui/actions/file/file_actions.dart";
  14. import 'package:photos/ui/viewer/file/thumbnail_widget.dart';
  15. import 'package:photos/ui/viewer/file/video_controls.dart';
  16. import "package:photos/utils/dialog_util.dart";
  17. import 'package:photos/utils/file_util.dart';
  18. import 'package:photos/utils/toast_util.dart';
  19. import "package:photos/utils/wakelock_util.dart";
  20. import 'package:video_player/video_player.dart';
  21. import 'package:visibility_detector/visibility_detector.dart';
  22. class VideoWidget extends StatefulWidget {
  23. final EnteFile file;
  24. final bool? autoPlay;
  25. final String? tagPrefix;
  26. final Function(bool)? playbackCallback;
  27. const VideoWidget(
  28. this.file, {
  29. this.autoPlay = false,
  30. this.tagPrefix,
  31. this.playbackCallback,
  32. Key? key,
  33. }) : super(key: key);
  34. @override
  35. State<VideoWidget> createState() => _VideoWidgetState();
  36. }
  37. class _VideoWidgetState extends State<VideoWidget> {
  38. final _logger = Logger("VideoWidget");
  39. VideoPlayerController? _videoPlayerController;
  40. ChewieController? _chewieController;
  41. final _progressNotifier = ValueNotifier<double?>(null);
  42. bool _isPlaying = false;
  43. final EnteWakeLock _wakeLock = EnteWakeLock();
  44. @override
  45. void initState() {
  46. super.initState();
  47. if (widget.file.isRemoteFile) {
  48. _loadNetworkVideo();
  49. _setFileSizeIfNull();
  50. } else if (widget.file.isSharedMediaToAppSandbox) {
  51. final localFile = File(getSharedMediaFilePath(widget.file));
  52. if (localFile.existsSync()) {
  53. _logger.fine("loading from app cache");
  54. _setVideoPlayerController(file: localFile);
  55. } else if (widget.file.uploadedFileID != null) {
  56. _loadNetworkVideo();
  57. }
  58. } else {
  59. widget.file.getAsset.then((asset) async {
  60. if (asset == null || !(await asset.exists)) {
  61. if (widget.file.uploadedFileID != null) {
  62. _loadNetworkVideo();
  63. }
  64. } else {
  65. // ignore: unawaited_futures
  66. asset.getMediaUrl().then((url) {
  67. _setVideoPlayerController(url: url);
  68. });
  69. }
  70. });
  71. }
  72. }
  73. void _setFileSizeIfNull() {
  74. if (widget.file.fileSize == null && widget.file.canEditMetaInfo) {
  75. FilesService.instance
  76. .getFileSize(widget.file.uploadedFileID!)
  77. .then((value) {
  78. widget.file.fileSize = value;
  79. if (mounted) {
  80. setState(() {});
  81. }
  82. });
  83. }
  84. }
  85. void _loadNetworkVideo() {
  86. getFileFromServer(
  87. widget.file,
  88. progressCallback: (count, total) {
  89. if (!mounted) {
  90. return;
  91. }
  92. _progressNotifier.value = count / (widget.file.fileSize ?? total);
  93. if (_progressNotifier.value == 1) {
  94. if (mounted) {
  95. showShortToast(context, S.of(context).decryptingVideo);
  96. }
  97. }
  98. },
  99. ).then((file) {
  100. if (file != null && mounted) {
  101. _setVideoPlayerController(file: file);
  102. }
  103. }).onError((error, stackTrace) {
  104. if (mounted) {
  105. showErrorDialog(
  106. context,
  107. "Error",
  108. S.of(context).failedToDownloadVideo,
  109. );
  110. }
  111. });
  112. }
  113. @override
  114. void dispose() {
  115. removeCallBack(widget.file);
  116. _videoPlayerController?.dispose();
  117. _chewieController?.dispose();
  118. _progressNotifier.dispose();
  119. _wakeLock.dispose();
  120. super.dispose();
  121. }
  122. void _setVideoPlayerController({
  123. String? url,
  124. File? file,
  125. }) {
  126. if (!mounted) {
  127. // Note: Do not initiale video player if widget is not mounted.
  128. // On Android, if multiple instance of ExoPlayer is created, it will start
  129. // resulting in playback errors for videos. See https://github.com/google/ExoPlayer/issues/6168
  130. return;
  131. }
  132. VideoPlayerController videoPlayerController;
  133. if (url != null) {
  134. videoPlayerController = VideoPlayerController.network(url);
  135. } else {
  136. videoPlayerController = VideoPlayerController.file(file!);
  137. }
  138. debugPrint("videoPlayerController: $videoPlayerController");
  139. _videoPlayerController = videoPlayerController
  140. ..initialize().whenComplete(() {
  141. if (mounted) {
  142. setState(() {});
  143. }
  144. }).onError(
  145. (error, stackTrace) {
  146. if (mounted && flagService.internalUser) {
  147. if (error is Exception) {
  148. showErrorDialogForException(
  149. context: context,
  150. exception: error,
  151. message: "Failed to play video\n ${error.toString()}",
  152. );
  153. } else {
  154. showToast(context, "Failed to play video");
  155. }
  156. }
  157. },
  158. );
  159. }
  160. @override
  161. Widget build(BuildContext context) {
  162. final content = _videoPlayerController != null &&
  163. _videoPlayerController!.value.isInitialized
  164. ? _getVideoPlayer()
  165. : _getLoadingWidget();
  166. final contentWithDetector = GestureDetector(
  167. child: content,
  168. onVerticalDragUpdate: (d) => {
  169. if (d.delta.dy > dragSensitivity)
  170. {
  171. Navigator.of(context).pop(),
  172. }
  173. else if (d.delta.dy < (dragSensitivity * -1))
  174. {
  175. showDetailsSheet(context, widget.file),
  176. },
  177. },
  178. );
  179. return VisibilityDetector(
  180. key: Key(widget.file.tag),
  181. onVisibilityChanged: (info) {
  182. if (info.visibleFraction < 1) {
  183. if (mounted && _chewieController != null) {
  184. _chewieController!.pause();
  185. }
  186. }
  187. },
  188. child: Hero(
  189. tag: widget.tagPrefix! + widget.file.tag,
  190. child: contentWithDetector,
  191. ),
  192. );
  193. }
  194. Widget _getLoadingWidget() {
  195. return Stack(
  196. children: [
  197. _getThumbnail(),
  198. Container(
  199. color: Colors.black12,
  200. constraints: const BoxConstraints.expand(),
  201. ),
  202. Center(
  203. child: SizedBox.fromSize(
  204. size: const Size.square(20),
  205. child: ValueListenableBuilder(
  206. valueListenable: _progressNotifier,
  207. builder: (BuildContext context, double? progress, _) {
  208. return progress == null || progress == 1
  209. ? const CupertinoActivityIndicator(
  210. color: Colors.white,
  211. )
  212. : CircularProgressIndicator(
  213. backgroundColor: Colors.black,
  214. value: progress,
  215. valueColor: const AlwaysStoppedAnimation<Color>(
  216. Color.fromRGBO(45, 194, 98, 1.0),
  217. ),
  218. );
  219. },
  220. ),
  221. ),
  222. ),
  223. ],
  224. );
  225. }
  226. Widget _getThumbnail() {
  227. return Container(
  228. color: Colors.black,
  229. constraints: const BoxConstraints.expand(),
  230. child: ThumbnailWidget(
  231. widget.file,
  232. fit: BoxFit.contain,
  233. ),
  234. );
  235. }
  236. Future<void> _keepScreenAliveOnPlaying(bool isPlaying) async {
  237. if (isPlaying) {
  238. _wakeLock.enable();
  239. }
  240. if (!isPlaying) {
  241. _wakeLock.disable();
  242. }
  243. }
  244. Widget _getVideoPlayer() {
  245. _videoPlayerController!.addListener(() {
  246. if (_isPlaying != _videoPlayerController!.value.isPlaying) {
  247. _isPlaying = _videoPlayerController!.value.isPlaying;
  248. if (widget.playbackCallback != null) {
  249. widget.playbackCallback!(_isPlaying);
  250. }
  251. unawaited(_keepScreenAliveOnPlaying(_isPlaying));
  252. }
  253. });
  254. _chewieController = ChewieController(
  255. videoPlayerController: _videoPlayerController!,
  256. aspectRatio: _videoPlayerController!.value.aspectRatio,
  257. autoPlay: widget.autoPlay!,
  258. autoInitialize: true,
  259. looping: true,
  260. allowMuting: true,
  261. allowFullScreen: false,
  262. customControls: const VideoControls(),
  263. );
  264. return Container(
  265. color: Colors.black,
  266. child: Chewie(controller: _chewieController!),
  267. );
  268. }
  269. }