video_widget_new.dart 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. import "dart:async";
  2. import "dart:io";
  3. import "package:flutter/cupertino.dart";
  4. import "package:flutter/material.dart";
  5. import "package:media_kit/media_kit.dart";
  6. import "package:media_kit_video/media_kit_video.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/services/files_service.dart";
  12. import "package:photos/theme/colors.dart";
  13. import "package:photos/theme/ente_theme.dart";
  14. import "package:photos/ui/actions/file/file_actions.dart";
  15. import "package:photos/ui/viewer/file/thumbnail_widget.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. class VideoWidgetNew extends StatefulWidget {
  20. final EnteFile file;
  21. final String? tagPrefix;
  22. final Function(bool)? playbackCallback;
  23. const VideoWidgetNew(
  24. this.file, {
  25. this.tagPrefix,
  26. this.playbackCallback,
  27. super.key,
  28. });
  29. @override
  30. State<VideoWidgetNew> createState() => _VideoWidgetNewState();
  31. }
  32. class _VideoWidgetNewState extends State<VideoWidgetNew>
  33. with WidgetsBindingObserver {
  34. static const verticalMargin = 72.0;
  35. late final player = Player();
  36. VideoController? controller;
  37. final _progressNotifier = ValueNotifier<double?>(null);
  38. late StreamSubscription<bool> playingStreamSubscription;
  39. bool _isAppInFG = true;
  40. @override
  41. void initState() {
  42. super.initState();
  43. WidgetsBinding.instance.addObserver(this);
  44. if (widget.file.isRemoteFile) {
  45. _loadNetworkVideo();
  46. _setFileSizeIfNull();
  47. } else if (widget.file.isSharedMediaToAppSandbox) {
  48. final localFile = File(getSharedMediaFilePath(widget.file));
  49. if (localFile.existsSync()) {
  50. _setVideoController(localFile.path);
  51. } else if (widget.file.uploadedFileID != null) {
  52. _loadNetworkVideo();
  53. }
  54. } else {
  55. widget.file.getAsset.then((asset) async {
  56. if (asset == null || !(await asset.exists)) {
  57. if (widget.file.uploadedFileID != null) {
  58. _loadNetworkVideo();
  59. }
  60. } else {
  61. asset.getMediaUrl().then((url) {
  62. _setVideoController(
  63. url ??
  64. 'https://user-images.githubusercontent.com/28951144/229373695-22f88f13-d18f-4288-9bf1-c3e078d83722.mp4',
  65. );
  66. });
  67. }
  68. });
  69. }
  70. playingStreamSubscription = player.stream.playing.listen((event) {
  71. if (widget.playbackCallback != null && mounted) {
  72. widget.playbackCallback!(event);
  73. }
  74. });
  75. }
  76. @override
  77. void didChangeAppLifecycleState(AppLifecycleState state) {
  78. if (state == AppLifecycleState.resumed) {
  79. _isAppInFG = true;
  80. } else {
  81. _isAppInFG = false;
  82. }
  83. }
  84. @override
  85. void dispose() {
  86. removeCallBack(widget.file);
  87. _progressNotifier.dispose();
  88. WidgetsBinding.instance.removeObserver(this);
  89. playingStreamSubscription.cancel();
  90. player.dispose();
  91. super.dispose();
  92. }
  93. @override
  94. Widget build(BuildContext context) {
  95. final colorScheme = getEnteColorScheme(context);
  96. return Hero(
  97. tag: widget.tagPrefix! + widget.file.tag,
  98. child: MaterialVideoControlsTheme(
  99. normal: MaterialVideoControlsThemeData(
  100. backdropColor: null,
  101. automaticallyImplySkipNextButton: false,
  102. automaticallyImplySkipPreviousButton: false,
  103. seekOnDoubleTap: false,
  104. displaySeekBar: true,
  105. seekBarMargin: const EdgeInsets.only(bottom: verticalMargin),
  106. bottomButtonBarMargin: const EdgeInsets.only(bottom: 112),
  107. controlsHoverDuration: const Duration(seconds: 3),
  108. seekBarHeight: 2,
  109. seekBarThumbSize: 16,
  110. seekBarBufferColor: Colors.transparent,
  111. seekBarThumbColor: backgroundElevatedLight,
  112. seekBarColor: fillMutedDark,
  113. seekBarPositionColor: colorScheme.primary300,
  114. seekBarContainerHeight: 56,
  115. seekBarAlignment: Alignment.center,
  116. ///topButtonBarMargin is needed for keeping the buffering loading
  117. ///indicator to be center aligned
  118. topButtonBarMargin: const EdgeInsets.only(top: verticalMargin),
  119. bottomButtonBar: [
  120. const Spacer(),
  121. PausePlayAndDuration(controller?.player),
  122. const Spacer(),
  123. ],
  124. primaryButtonBar: [],
  125. ),
  126. fullscreen: const MaterialVideoControlsThemeData(),
  127. child: GestureDetector(
  128. onVerticalDragUpdate: (d) => {
  129. if (d.delta.dy > dragSensitivity)
  130. {
  131. Navigator.of(context).pop(),
  132. }
  133. else if (d.delta.dy < (dragSensitivity * -1))
  134. {
  135. showDetailsSheet(context, widget.file),
  136. },
  137. },
  138. child: Center(
  139. child: controller != null
  140. ? Video(
  141. controller: controller!,
  142. )
  143. : _getLoadingWidget(),
  144. ),
  145. ),
  146. ),
  147. );
  148. }
  149. void _loadNetworkVideo() {
  150. getFileFromServer(
  151. widget.file,
  152. progressCallback: (count, total) {
  153. if(!mounted) {
  154. return;
  155. }
  156. _progressNotifier.value = count / (widget.file.fileSize ?? total);
  157. if (_progressNotifier.value == 1) {
  158. if (mounted) {
  159. showShortToast(context, S.of(context).decryptingVideo);
  160. }
  161. }
  162. },
  163. ).then((file) {
  164. if (file != null) {
  165. _setVideoController(file.path);
  166. }
  167. }).onError((error, stackTrace) {
  168. showErrorDialog(context, "Error", S.of(context).failedToDownloadVideo);
  169. });
  170. }
  171. void _setFileSizeIfNull() {
  172. if (widget.file.fileSize == null && widget.file.canEditMetaInfo) {
  173. FilesService.instance
  174. .getFileSize(widget.file.uploadedFileID!)
  175. .then((value) {
  176. widget.file.fileSize = value;
  177. if (mounted) {
  178. setState(() {});
  179. }
  180. });
  181. }
  182. }
  183. Widget _getLoadingWidget() {
  184. return Stack(
  185. children: [
  186. _getThumbnail(),
  187. Container(
  188. color: Colors.black12,
  189. constraints: const BoxConstraints.expand(),
  190. ),
  191. Center(
  192. child: SizedBox.fromSize(
  193. size: const Size.square(20),
  194. child: ValueListenableBuilder(
  195. valueListenable: _progressNotifier,
  196. builder: (BuildContext context, double? progress, _) {
  197. return progress == null || progress == 1
  198. ? const CupertinoActivityIndicator(
  199. color: Colors.white,
  200. )
  201. : CircularProgressIndicator(
  202. backgroundColor: Colors.black,
  203. value: progress,
  204. valueColor: const AlwaysStoppedAnimation<Color>(
  205. Color.fromRGBO(45, 194, 98, 1.0),
  206. ),
  207. );
  208. },
  209. ),
  210. ),
  211. ),
  212. ],
  213. );
  214. }
  215. Widget _getThumbnail() {
  216. return Container(
  217. color: Colors.black,
  218. constraints: const BoxConstraints.expand(),
  219. child: ThumbnailWidget(
  220. widget.file,
  221. fit: BoxFit.contain,
  222. ),
  223. );
  224. }
  225. void _setVideoController(String url) {
  226. if (mounted) {
  227. setState(() {
  228. player.setPlaylistMode(PlaylistMode.single);
  229. controller = VideoController(player);
  230. player.open(Media(url), play: _isAppInFG);
  231. });
  232. }
  233. }
  234. }
  235. class PausePlayAndDuration extends StatefulWidget {
  236. final Player? player;
  237. const PausePlayAndDuration(this.player, {super.key});
  238. @override
  239. State<PausePlayAndDuration> createState() => _PausePlayAndDurationState();
  240. }
  241. class _PausePlayAndDurationState extends State<PausePlayAndDuration> {
  242. Color backgroundColor = fillStrongLight;
  243. @override
  244. Widget build(BuildContext context) {
  245. return GestureDetector(
  246. onTapDown: (details) {
  247. setState(() {
  248. backgroundColor = fillMutedDark;
  249. });
  250. },
  251. onTapUp: (details) {
  252. Future.delayed(const Duration(milliseconds: 175), () {
  253. if (mounted) {
  254. setState(() {
  255. backgroundColor = fillStrongLight;
  256. });
  257. }
  258. });
  259. },
  260. onTapCancel: () {
  261. Future.delayed(const Duration(milliseconds: 175), () {
  262. if (mounted) {
  263. setState(() {
  264. backgroundColor = fillStrongLight;
  265. });
  266. }
  267. });
  268. },
  269. onTap: () => widget.player!.playOrPause(),
  270. child: AnimatedContainer(
  271. duration: const Duration(milliseconds: 150),
  272. curve: Curves.easeInBack,
  273. padding: const EdgeInsets.symmetric(vertical: 4, horizontal: 8),
  274. decoration: BoxDecoration(
  275. color: backgroundColor,
  276. border: Border.all(
  277. color: strokeFaintDark,
  278. width: 1,
  279. ),
  280. borderRadius: BorderRadius.circular(24),
  281. ),
  282. child: AnimatedSize(
  283. duration: const Duration(seconds: 2),
  284. curve: Curves.easeInOutExpo,
  285. child: Row(
  286. children: [
  287. StreamBuilder(
  288. builder: (context, snapshot) {
  289. final bool isPlaying = snapshot.data ?? false;
  290. return AnimatedSwitcher(
  291. duration: const Duration(milliseconds: 350),
  292. switchInCurve: Curves.easeInOutCirc,
  293. switchOutCurve: Curves.easeInOutCirc,
  294. child: Icon(
  295. key: ValueKey(
  296. isPlaying ? "pause_button" : "play_button",
  297. ),
  298. isPlaying
  299. ? Icons.pause_rounded
  300. : Icons.play_arrow_rounded,
  301. color: backdropBaseLight,
  302. size: 24,
  303. ),
  304. );
  305. },
  306. initialData: widget.player?.state.playing,
  307. stream: widget.player?.stream.playing,
  308. ),
  309. const SizedBox(width: 8),
  310. MaterialPositionIndicator(
  311. style: getEnteTextTheme(context).tiny.copyWith(
  312. color: textBaseDark,
  313. ),
  314. ),
  315. const SizedBox(width: 10),
  316. ],
  317. ),
  318. ),
  319. ),
  320. );
  321. }
  322. }