video_widget.dart 7.8 KB

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