controller_widget_builder.dart 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666
  1. import 'dart:async';
  2. import 'package:flutter/cupertino.dart';
  3. import 'package:flutter/material.dart';
  4. import 'package:flutter/services.dart';
  5. import 'package:flutter_ijkplayer/flutter_ijkplayer.dart';
  6. import 'package:flutter_ijkplayer/src/helper/time_helper.dart';
  7. import 'package:flutter_ijkplayer/src/helper/logutil.dart';
  8. import 'package:flutter_ijkplayer/src/helper/ui_helper.dart';
  9. import 'package:flutter_ijkplayer/src/widget/progress_bar.dart';
  10. /// Using mediaController to Construct a Controller UI
  11. typedef Widget IJKControllerWidgetBuilder(IjkMediaController controller);
  12. /// default create IJK Controller UI
  13. Widget defaultBuildIjkControllerWidget(IjkMediaController controller) {
  14. return DefaultIJKControllerWidget(
  15. controller: controller,
  16. // verticalGesture: false,
  17. // horizontalGesture: false,
  18. );
  19. }
  20. /// Default Controller Widget
  21. ///
  22. /// see [IjkPlayer] and [IJKControllerWidgetBuilder]
  23. class DefaultIJKControllerWidget extends StatefulWidget {
  24. final IjkMediaController controller;
  25. /// If [doubleTapPlay] is true, can double tap to play or pause media.
  26. final bool doubleTapPlay;
  27. /// If [verticalGesture] is false, vertical gesture will be ignored.
  28. final bool verticalGesture;
  29. /// If [horizontalGesture] is false, horizontal gesture will be ignored.
  30. final bool horizontalGesture;
  31. /// Controlling [verticalGesture] is controlling system volume or media volume.
  32. final VolumeType volumeType;
  33. final bool playWillPauseOther;
  34. /// Control whether there is a full-screen button.
  35. final bool showFullScreenButton;
  36. /// The current full-screen button style should not be changed by users.
  37. final bool currentFullScreenState;
  38. /// The UI of the controller.
  39. const DefaultIJKControllerWidget({
  40. @required this.controller,
  41. this.doubleTapPlay = false,
  42. this.verticalGesture = true,
  43. this.horizontalGesture = true,
  44. this.volumeType = VolumeType.system,
  45. this.playWillPauseOther = true,
  46. this.currentFullScreenState = false,
  47. this.showFullScreenButton = true,
  48. Key key,
  49. }) : super(key: key);
  50. @override
  51. _DefaultIJKControllerWidgetState createState() =>
  52. _DefaultIJKControllerWidgetState();
  53. }
  54. class _DefaultIJKControllerWidgetState extends State<DefaultIJKControllerWidget>
  55. implements TooltipDelegate {
  56. IjkMediaController get controller => widget.controller;
  57. GlobalKey currentKey = GlobalKey();
  58. bool _isShow = true;
  59. set isShow(bool value) {
  60. _isShow = value;
  61. setState(() {});
  62. if (value == true) {
  63. controller.refreshVideoInfo();
  64. }
  65. }
  66. bool get isShow => _isShow;
  67. Timer progressTimer;
  68. StreamSubscription controllerSubscription;
  69. @override
  70. void initState() {
  71. super.initState();
  72. startTimer();
  73. controllerSubscription =
  74. controller.textureIdStream.listen(_onTextureIdChange);
  75. }
  76. void _onTextureIdChange(int textureId) {
  77. LogUtils.debug("onTextureChange $textureId");
  78. if (textureId != null) {
  79. startTimer();
  80. } else {
  81. stopTimer();
  82. }
  83. }
  84. @override
  85. void deactivate() {
  86. super.deactivate();
  87. }
  88. @override
  89. void dispose() {
  90. controllerSubscription.cancel();
  91. stopTimer();
  92. IjkManager.resetBrightness();
  93. super.dispose();
  94. }
  95. void startTimer() {
  96. if (controller.textureId == null) {
  97. return;
  98. }
  99. progressTimer?.cancel();
  100. progressTimer = Timer.periodic(Duration(milliseconds: 350), (timer) {
  101. LogUtils.verbose("timer will call refresh info");
  102. controller.refreshVideoInfo();
  103. });
  104. }
  105. void stopTimer() {
  106. progressTimer?.cancel();
  107. }
  108. @override
  109. Widget build(BuildContext context) {
  110. return GestureDetector(
  111. behavior: HitTestBehavior.opaque,
  112. child: buildContent(),
  113. onDoubleTap: onDoubleTap(),
  114. onHorizontalDragStart: wrapHorizontalGesture(_onHorizontalDragStart),
  115. onHorizontalDragUpdate: wrapHorizontalGesture(_onHorizontalDragUpdate),
  116. onHorizontalDragEnd: wrapHorizontalGesture(_onHorizontalDragEnd),
  117. onVerticalDragStart: wrapVerticalGesture(_onVerticalDragStart),
  118. onVerticalDragUpdate: wrapVerticalGesture(_onVerticalDragUpdate),
  119. onVerticalDragEnd: wrapVerticalGesture(_onVerticalDragEnd),
  120. onTap: onTap,
  121. key: currentKey,
  122. );
  123. }
  124. Widget buildContent() {
  125. if (!isShow) {
  126. return Container();
  127. }
  128. return StreamBuilder<VideoInfo>(
  129. stream: controller.videoInfoStream,
  130. builder: (context, snapshot) {
  131. var info = snapshot.data;
  132. if (info == null || !info.hasData) {
  133. return Container();
  134. }
  135. return buildPortrait(info);
  136. },
  137. );
  138. }
  139. Widget _buildFullScreenButton() {
  140. if (widget.showFullScreenButton != true) {
  141. return Container();
  142. }
  143. var isFull = widget.currentFullScreenState;
  144. return IconButton(
  145. color: Colors.white,
  146. icon: Icon(isFull ? Icons.fullscreen_exit : Icons.fullscreen),
  147. onPressed: () {
  148. if (isFull) {
  149. Navigator.pop(context);
  150. } else {
  151. showFullScreenIJKPlayer(context, controller);
  152. }
  153. },
  154. );
  155. }
  156. Widget buildPortrait(VideoInfo info) {
  157. return PortraitController(
  158. controller: controller,
  159. info: info,
  160. tooltipDelegate: this,
  161. playWillPauseOther: widget.playWillPauseOther,
  162. fullScreenWidget: _buildFullScreenButton(),
  163. );
  164. }
  165. OverlayEntry _tipOverlay;
  166. Widget createTooltipWidgetWrapper(Widget widget) {
  167. var typography = Typography(platform: TargetPlatform.android);
  168. var theme = typography.white;
  169. const style = const TextStyle(
  170. fontSize: 15.0,
  171. color: Colors.white,
  172. fontWeight: FontWeight.normal,
  173. );
  174. var mergedTextStyle = theme.body2.merge(style);
  175. return Container(
  176. decoration: BoxDecoration(
  177. color: Colors.black.withOpacity(0.5),
  178. borderRadius: BorderRadius.circular(20.0),
  179. ),
  180. height: 100.0,
  181. width: 100.0,
  182. child: DefaultTextStyle(
  183. child: widget,
  184. style: mergedTextStyle,
  185. ),
  186. );
  187. }
  188. void showTooltip(Widget widget) {
  189. hideTooltip();
  190. _tipOverlay = OverlayEntry(
  191. builder: (BuildContext context) {
  192. return IgnorePointer(
  193. child: Center(
  194. child: widget,
  195. ),
  196. );
  197. },
  198. );
  199. Overlay.of(context).insert(_tipOverlay);
  200. }
  201. void hideTooltip() {
  202. _tipOverlay?.remove();
  203. _tipOverlay = null;
  204. }
  205. _ProgressCalculator _calculator;
  206. onTap() => isShow = !isShow;
  207. Function onDoubleTap() {
  208. return widget.doubleTapPlay
  209. ? () {
  210. LogUtils.debug("ondouble tap");
  211. controller.playOrPause();
  212. }
  213. : null;
  214. }
  215. Function wrapHorizontalGesture(Function function) =>
  216. widget.horizontalGesture == true ? function : null;
  217. Function wrapVerticalGesture(Function function) =>
  218. widget.verticalGesture == true ? function : null;
  219. void _onHorizontalDragStart(DragStartDetails details) async {
  220. var videoInfo = await controller.getVideoInfo();
  221. _calculator = _ProgressCalculator(details, videoInfo);
  222. }
  223. void _onHorizontalDragUpdate(DragUpdateDetails details) {
  224. if (_calculator == null || details == null) {
  225. return;
  226. }
  227. var updateText = _calculator.calcUpdate(details);
  228. var offsetPosition = _calculator.getOffsetPosition();
  229. IconData iconData =
  230. offsetPosition > 0 ? Icons.fast_forward : Icons.fast_rewind;
  231. var w = Column(
  232. mainAxisAlignment: MainAxisAlignment.center,
  233. children: <Widget>[
  234. Icon(
  235. iconData,
  236. color: Colors.white,
  237. size: 40.0,
  238. ),
  239. Text(
  240. updateText,
  241. textAlign: TextAlign.center,
  242. ),
  243. ],
  244. );
  245. showTooltip(createTooltipWidgetWrapper(w));
  246. }
  247. void _onHorizontalDragEnd(DragEndDetails details) async {
  248. hideTooltip();
  249. var targetSeek = _calculator.getTargetSeek(details);
  250. _calculator = null;
  251. await controller.seekTo(targetSeek);
  252. var videoInfo = await controller.getVideoInfo();
  253. if (targetSeek < videoInfo.duration) await controller.play();
  254. }
  255. bool verticalDragging = false;
  256. bool leftVerticalDrag;
  257. void _onVerticalDragStart(DragStartDetails details) {
  258. verticalDragging = true;
  259. var width = UIHelper.findGlobalRect(currentKey).width;
  260. var dx =
  261. UIHelper.globalOffsetToLocal(currentKey, details.globalPosition).dx;
  262. leftVerticalDrag = dx / width <= 0.5;
  263. }
  264. void _onVerticalDragUpdate(DragUpdateDetails details) async {
  265. if (verticalDragging == false) return;
  266. String text = "";
  267. IconData iconData = Icons.volume_up;
  268. if (leftVerticalDrag == false) {
  269. if (details.delta.dy > 0) {
  270. await volumeDown();
  271. } else if (details.delta.dy < 0) {
  272. await volumeUp();
  273. }
  274. var currentVolume = await getVolume();
  275. text = currentVolume.toString();
  276. } else if (leftVerticalDrag == true) {
  277. var currentBright = await IjkManager.getSystemBrightness();
  278. double target;
  279. if (details.delta.dy > 0) {
  280. target = currentBright - 0.05;
  281. } else {
  282. target = currentBright + 0.05;
  283. }
  284. if (target > 1) {
  285. target = 1;
  286. } else if (target < 0) {
  287. target = 0;
  288. }
  289. await IjkManager.setSystemBrightness(target);
  290. iconData = Icons.brightness_high;
  291. text = (target * 100).toStringAsFixed(0);
  292. } else {
  293. return;
  294. }
  295. var column = Column(
  296. mainAxisAlignment: MainAxisAlignment.center,
  297. children: <Widget>[
  298. Icon(
  299. iconData,
  300. color: Colors.white,
  301. size: 25.0,
  302. ),
  303. Padding(
  304. padding: const EdgeInsets.only(top: 10.0),
  305. child: Text(text),
  306. ),
  307. ],
  308. );
  309. showTooltip(createTooltipWidgetWrapper(column));
  310. }
  311. void _onVerticalDragEnd(DragEndDetails details) async {
  312. verticalDragging = false;
  313. leftVerticalDrag = null;
  314. hideTooltip();
  315. Future.delayed(const Duration(milliseconds: 2000), () {
  316. hideTooltip();
  317. });
  318. }
  319. Future<int> getVolume() async {
  320. switch (widget.volumeType) {
  321. case VolumeType.media:
  322. return controller.volume;
  323. case VolumeType.system:
  324. return controller.getSystemVolume();
  325. }
  326. return 0;
  327. }
  328. Future<void> volumeUp() async {
  329. var volume = await getVolume();
  330. volume++;
  331. switch (widget.volumeType) {
  332. case VolumeType.media:
  333. controller.volume = volume;
  334. break;
  335. case VolumeType.system:
  336. await IjkManager.systemVolumeUp();
  337. break;
  338. }
  339. }
  340. Future<void> volumeDown() async {
  341. var volume = await getVolume();
  342. volume--;
  343. switch (widget.volumeType) {
  344. case VolumeType.media:
  345. controller.volume = volume;
  346. break;
  347. case VolumeType.system:
  348. await IjkManager.systemVolumeDown();
  349. break;
  350. }
  351. }
  352. }
  353. class _ProgressCalculator {
  354. DragStartDetails startDetails;
  355. VideoInfo info;
  356. double dx;
  357. _ProgressCalculator(this.startDetails, this.info);
  358. String calcUpdate(DragUpdateDetails details) {
  359. dx = details.globalPosition.dx - startDetails.globalPosition.dx;
  360. var f = dx > 0 ? "+" : "-";
  361. var offset = getOffsetPosition().round().abs();
  362. return "$f${offset}s";
  363. }
  364. double getTargetSeek(DragEndDetails details) {
  365. var target = info.currentPosition + getOffsetPosition();
  366. if (target < 0) {
  367. target = 0;
  368. } else if (target > info.duration) {
  369. target = info.duration;
  370. }
  371. return target;
  372. }
  373. double getOffsetPosition() {
  374. return dx / 10;
  375. }
  376. }
  377. class PortraitController extends StatelessWidget {
  378. final IjkMediaController controller;
  379. final VideoInfo info;
  380. final TooltipDelegate tooltipDelegate;
  381. final bool playWillPauseOther;
  382. final Widget fullScreenWidget;
  383. const PortraitController({
  384. Key key,
  385. this.controller,
  386. this.info,
  387. this.tooltipDelegate,
  388. this.playWillPauseOther = true,
  389. this.fullScreenWidget,
  390. }) : super(key: key);
  391. bool get haveTime {
  392. return info.hasData && info.duration > 0;
  393. }
  394. @override
  395. Widget build(BuildContext context) {
  396. if (!info.hasData) {
  397. return Container();
  398. }
  399. Widget bottomBar = buildBottomBar(context);
  400. return Column(
  401. children: <Widget>[
  402. Expanded(
  403. child: Container(),
  404. ),
  405. bottomBar,
  406. ],
  407. );
  408. }
  409. Widget buildBottomBar(BuildContext context) {
  410. var currentTime = buildCurrentText();
  411. var maxTime = buildMaxTimeText();
  412. var progress = buildProgress(info);
  413. var playButton = buildPlayButton(context);
  414. var fullScreenButton = buildFullScreenButton();
  415. Widget widget = Row(
  416. children: <Widget>[
  417. playButton,
  418. Padding(
  419. padding: const EdgeInsets.all(8.0),
  420. child: currentTime,
  421. ),
  422. Expanded(child: progress),
  423. Padding(
  424. padding: const EdgeInsets.all(8.0),
  425. child: maxTime,
  426. ),
  427. fullScreenButton,
  428. ],
  429. );
  430. widget = DefaultTextStyle(
  431. style: const TextStyle(
  432. color: Colors.white,
  433. ),
  434. child: widget,
  435. );
  436. widget = Container(
  437. color: Colors.black.withOpacity(0.12),
  438. child: widget,
  439. );
  440. return widget;
  441. }
  442. Widget buildProgress(VideoInfo info) {
  443. if (!info.hasData || info.duration == 0) {
  444. return Container();
  445. }
  446. return Container(
  447. height: 22,
  448. child: ProgressBar(
  449. current: info.currentPosition,
  450. max: info.duration,
  451. changeProgressHandler: (progress) async {
  452. await controller.seekToProgress(progress);
  453. tooltipDelegate?.hideTooltip();
  454. },
  455. tapProgressHandler: (progress) {
  456. showProgressTooltip(info, progress);
  457. },
  458. ),
  459. );
  460. }
  461. buildCurrentText() {
  462. return haveTime
  463. ? Text(
  464. TimeHelper.getTimeText(info.currentPosition),
  465. )
  466. : Container();
  467. }
  468. buildMaxTimeText() {
  469. return haveTime
  470. ? Text(
  471. TimeHelper.getTimeText(info.duration),
  472. )
  473. : Container();
  474. }
  475. buildPlayButton(BuildContext context) {
  476. return IconButton(
  477. onPressed: () {
  478. controller.playOrPause(pauseOther: playWillPauseOther);
  479. },
  480. color: Colors.white,
  481. icon: Icon(info.isPlaying ? Icons.pause : Icons.play_arrow),
  482. iconSize: 25.0,
  483. );
  484. }
  485. void showProgressTooltip(VideoInfo info, double progress) {
  486. var target = info.duration * progress;
  487. var diff = info.currentPosition - target;
  488. String diffString;
  489. if (diff < 1 && diff > -1) {
  490. diffString = "0s";
  491. } else if (diff < 0) {
  492. diffString = "+${TimeHelper.getTimeText(diff.abs())}";
  493. } else if (diff > 0) {
  494. diffString = "-${TimeHelper.getTimeText(diff.abs())}";
  495. } else {
  496. diffString = "0s";
  497. }
  498. Widget text = Container(
  499. alignment: Alignment.center,
  500. child: Column(
  501. mainAxisAlignment: MainAxisAlignment.center,
  502. children: <Widget>[
  503. Text(
  504. TimeHelper.getTimeText(target),
  505. style: TextStyle(fontSize: 20),
  506. ),
  507. Container(
  508. height: 10,
  509. ),
  510. Text(diffString),
  511. ],
  512. ),
  513. );
  514. var tooltip = tooltipDelegate?.createTooltipWidgetWrapper(text);
  515. tooltipDelegate?.showTooltip(tooltip);
  516. }
  517. Widget buildFullScreenButton() {
  518. return fullScreenWidget ?? Container();
  519. }
  520. }
  521. abstract class TooltipDelegate {
  522. void showTooltip(Widget widget);
  523. Widget createTooltipWidgetWrapper(Widget widget);
  524. void hideTooltip();
  525. }
  526. enum VolumeType {
  527. system,
  528. media,
  529. }
  530. showFullScreenIJKPlayer(
  531. BuildContext context, IjkMediaController controller) async {
  532. showDialog(
  533. context: context,
  534. builder: (ctx) => IjkPlayer(
  535. mediaController: controller,
  536. controllerWidgetBuilder: (ctl) =>
  537. _buildFullScreenMediaController(ctl, true),
  538. ),
  539. ).then((_) {
  540. IjkManager.unlockOrientation();
  541. IjkManager.setCurrentOrientation(DeviceOrientation.portraitUp);
  542. });
  543. var info = await controller.getVideoInfo();
  544. Axis axis;
  545. if (info.width == 0 || info.height == 0) {
  546. axis = Axis.horizontal;
  547. } else if (info.width > info.height) {
  548. if (info.degree == 90 || info.degree == 270) {
  549. axis = Axis.vertical;
  550. } else {
  551. axis = Axis.horizontal;
  552. }
  553. } else {
  554. if (info.degree == 90 || info.degree == 270) {
  555. axis = Axis.horizontal;
  556. } else {
  557. axis = Axis.vertical;
  558. }
  559. }
  560. if (axis == Axis.horizontal) {
  561. IjkManager.setLandScape();
  562. } else {
  563. IjkManager.setPortrait();
  564. }
  565. }
  566. Widget _buildFullScreenMediaController(
  567. IjkMediaController controller, bool fullScreen) {
  568. return DefaultIJKControllerWidget(
  569. controller: controller,
  570. currentFullScreenState: true,
  571. );
  572. }