NCPlayerToolBar.swift 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544
  1. //
  2. // NCPlayerToolBar.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 01/07/21.
  6. // Copyright © 2021 Marino Faggiana. All rights reserved.
  7. //
  8. // Author Marino Faggiana <marino.faggiana@nextcloud.com>
  9. //
  10. // This program is free software: you can redistribute it and/or modify
  11. // it under the terms of the GNU General Public License as published by
  12. // the Free Software Foundation, either version 3 of the License, or
  13. // (at your option) any later version.
  14. //
  15. // This program is distributed in the hope that it will be useful,
  16. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. // GNU General Public License for more details.
  19. //
  20. // You should have received a copy of the GNU General Public License
  21. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. //
  23. import Foundation
  24. import NCCommunication
  25. import CoreMedia
  26. import UIKit
  27. import AVKit
  28. import MediaPlayer
  29. class NCPlayerToolBar: UIView {
  30. @IBOutlet weak var playerTopToolBarView: UIStackView!
  31. @IBOutlet weak var playerToolBarView: UIView!
  32. @IBOutlet weak var pipButton: UIButton!
  33. @IBOutlet weak var subtitleButton: UIButton!
  34. @IBOutlet weak var muteButton: UIButton!
  35. @IBOutlet weak var playButton: UIButton!
  36. @IBOutlet weak var forwardButton: UIButton!
  37. @IBOutlet weak var backButton: UIButton!
  38. @IBOutlet weak var playbackSlider: UISlider!
  39. @IBOutlet weak var labelLeftTime: UILabel!
  40. @IBOutlet weak var labelCurrentTime: UILabel!
  41. enum sliderEventType {
  42. case began
  43. case ended
  44. case moved
  45. }
  46. var ncplayer: NCPlayer?
  47. private var metadata: tableMetadata?
  48. private var wasInPlay: Bool = false
  49. private var playbackSliderEvent: sliderEventType = .ended
  50. private var timerAutoHide: Timer?
  51. var pictureInPictureController: AVPictureInPictureController?
  52. weak var viewerMediaPage: NCViewerMediaPage?
  53. // MARK: - View Life Cycle
  54. override func awakeFromNib() {
  55. super.awakeFromNib()
  56. let blurEffectView = UIVisualEffectView(effect: UIBlurEffect(style: .dark))
  57. blurEffectView.frame = self.bounds
  58. blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
  59. playerToolBarView.insertSubview(blurEffectView, at: 0)
  60. playerTopToolBarView.layer.cornerRadius = 10
  61. playerTopToolBarView.layer.masksToBounds = true
  62. playerTopToolBarView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(tapTopToolBarWith(gestureRecognizer:))))
  63. let blurEffectTopToolBarView = UIVisualEffectView(effect: UIBlurEffect(style: .dark))
  64. blurEffectTopToolBarView.frame = playerTopToolBarView.bounds
  65. blurEffectTopToolBarView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
  66. playerTopToolBarView.insertSubview(blurEffectTopToolBarView, at: 0)
  67. playerToolBarView.layer.cornerRadius = 10
  68. playerToolBarView.layer.masksToBounds = true
  69. playerToolBarView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(tapToolBarWith(gestureRecognizer:))))
  70. pipButton.setImage(NCUtility.shared.loadImage(named: "pip.enter", color: .lightGray), for: .normal)
  71. pipButton.isEnabled = false
  72. muteButton.setImage(NCUtility.shared.loadImage(named: "audioOff", color: .lightGray), for: .normal)
  73. muteButton.isEnabled = false
  74. subtitleButton.setImage(NCUtility.shared.loadImage(named: "captions.bubble", color: .lightGray), for: .normal)
  75. subtitleButton.isEnabled = false
  76. subtitleButton.isHidden = true
  77. playbackSlider.value = 0
  78. playbackSlider.minimumValue = 0
  79. playbackSlider.maximumValue = 0
  80. playbackSlider.isContinuous = true
  81. playbackSlider.tintColor = .lightGray
  82. playbackSlider.isEnabled = false
  83. labelCurrentTime.text = NCUtility.shared.stringFromTime(.zero)
  84. labelCurrentTime.textColor = .lightGray
  85. labelLeftTime.text = NCUtility.shared.stringFromTime(.zero)
  86. labelLeftTime.textColor = .lightGray
  87. backButton.setImage(NCUtility.shared.loadImage(named: "gobackward.10", color: .lightGray), for: .normal)
  88. backButton.isEnabled = false
  89. if #available(iOS 13.0, *) {
  90. playButton.setImage(NCUtility.shared.loadImage(named: "play.fill", color: .lightGray, symbolConfiguration: UIImage.SymbolConfiguration(pointSize: 30)), for: .normal)
  91. } else {
  92. playButton.setImage(NCUtility.shared.loadImage(named: "play.fill", color: .lightGray, size: 30), for: .normal)
  93. }
  94. playButton.isEnabled = false
  95. forwardButton.setImage(NCUtility.shared.loadImage(named: "goforward.10", color: .lightGray), for: .normal)
  96. forwardButton.isEnabled = false
  97. NotificationCenter.default.addObserver(self, selector: #selector(handleInterruption), name: AVAudioSession.interruptionNotification, object: nil)
  98. NotificationCenter.default.addObserver(self, selector: #selector(handleRouteChange), name: AVAudioSession.routeChangeNotification, object: nil)
  99. }
  100. required init?(coder aDecoder: NSCoder) {
  101. super.init(coder: aDecoder)
  102. }
  103. deinit {
  104. print("deinit NCPlayerToolBar")
  105. NotificationCenter.default.removeObserver(self, name: AVAudioSession.interruptionNotification, object: nil)
  106. NotificationCenter.default.removeObserver(self, name: AVAudioSession.routeChangeNotification, object: nil)
  107. }
  108. // MARK: -
  109. func setMetadata(_ metadata: tableMetadata) {
  110. self.metadata = metadata
  111. }
  112. func setBarPlayer(ncplayer: NCPlayer) {
  113. self.ncplayer = ncplayer
  114. playbackSlider.value = 0
  115. playbackSlider.minimumValue = 0
  116. playbackSlider.maximumValue = Float(ncplayer.durationTime.seconds)
  117. playbackSlider.addTarget(self, action: #selector(onSliderValChanged(slider:event:)), for: .valueChanged)
  118. labelCurrentTime.text = NCUtility.shared.stringFromTime(.zero)
  119. labelLeftTime.text = "-" + NCUtility.shared.stringFromTime(ncplayer.durationTime)
  120. updateToolBar()
  121. }
  122. public func updateToolBar() {
  123. guard let ncplayer = self.ncplayer else { return }
  124. // MUTE
  125. if let muteButton = muteButton {
  126. if CCUtility.getAudioMute() {
  127. muteButton.setImage(NCUtility.shared.loadImage(named: "audioOff", color: .white), for: .normal)
  128. } else {
  129. muteButton.setImage(NCUtility.shared.loadImage(named: "audioOn", color: .white), for: .normal)
  130. }
  131. muteButton.isEnabled = true
  132. }
  133. // PIP
  134. if let pipButton = pipButton {
  135. if metadata?.classFile == NCCommunicationCommon.typeClassFile.video.rawValue && AVPictureInPictureController.isPictureInPictureSupported() {
  136. pipButton.setImage(NCUtility.shared.loadImage(named: "pip.enter", color: .white), for: .normal)
  137. pipButton.isEnabled = true
  138. } else {
  139. pipButton.setImage(NCUtility.shared.loadImage(named: "pip.enter", color: .gray), for: .normal)
  140. pipButton.isEnabled = false
  141. }
  142. }
  143. // SLIDER TIME (START - END)
  144. let time = (ncplayer.player?.currentTime() ?? .zero).convertScale(1000, method: .default)
  145. playbackSlider.value = Float(time.seconds)
  146. MPNowPlayingInfoCenter.default().nowPlayingInfo?[MPNowPlayingInfoPropertyElapsedPlaybackTime] = time.seconds
  147. playbackSlider.isEnabled = true
  148. labelCurrentTime.text = NCUtility.shared.stringFromTime(time)
  149. labelLeftTime.text = "-" + NCUtility.shared.stringFromTime(ncplayer.durationTime - time)
  150. // BACK
  151. if #available(iOS 13.0, *) {
  152. backButton.setImage(NCUtility.shared.loadImage(named: "gobackward.10", color: .white), for: .normal)
  153. } else {
  154. backButton.setImage(NCUtility.shared.loadImage(named: "gobackward.10", color: .white, size: 30), for: .normal)
  155. }
  156. backButton.isEnabled = true
  157. // PLAY
  158. if ncplayer.isPlay() {
  159. MPNowPlayingInfoCenter.default().nowPlayingInfo?[MPNowPlayingInfoPropertyPlaybackRate] = 1
  160. } else {
  161. MPNowPlayingInfoCenter.default().nowPlayingInfo?[MPNowPlayingInfoPropertyPlaybackRate] = 0
  162. }
  163. let namedPlay = ncplayer.isPlay() ? "pause.fill" : "play.fill"
  164. if #available(iOS 13.0, *) {
  165. playButton.setImage(NCUtility.shared.loadImage(named: namedPlay, color: .white, symbolConfiguration: UIImage.SymbolConfiguration(pointSize: 30)), for: .normal)
  166. } else {
  167. playButton.setImage(NCUtility.shared.loadImage(named: namedPlay, color: .white, size: 30), for: .normal)
  168. }
  169. playButton.isEnabled = true
  170. // FORWARD
  171. if #available(iOS 13.0, *) {
  172. forwardButton.setImage(NCUtility.shared.loadImage(named: "goforward.10", color: .white), for: .normal)
  173. } else {
  174. forwardButton.setImage(NCUtility.shared.loadImage(named: "goforward.10", color: .white, size: 30), for: .normal)
  175. }
  176. forwardButton.isEnabled = true
  177. }
  178. // MARK: Handle Notifications
  179. @objc func handleRouteChange(notification: Notification) {
  180. guard let userInfo = notification.userInfo, let reasonValue = userInfo[AVAudioSessionRouteChangeReasonKey] as? UInt, let reason = AVAudioSession.RouteChangeReason(rawValue: reasonValue) else { return }
  181. switch reason {
  182. case .newDeviceAvailable:
  183. let session = AVAudioSession.sharedInstance()
  184. for output in session.currentRoute.outputs where output.portType == AVAudioSession.Port.headphones {
  185. print("headphones connected")
  186. DispatchQueue.main.sync {
  187. ncplayer?.playerPlay()
  188. startTimerAutoHide()
  189. }
  190. break
  191. }
  192. case .oldDeviceUnavailable:
  193. if let previousRoute = userInfo[AVAudioSessionRouteChangePreviousRouteKey] as? AVAudioSessionRouteDescription {
  194. for output in previousRoute.outputs where output.portType == AVAudioSession.Port.headphones {
  195. print("headphones disconnected")
  196. DispatchQueue.main.sync {
  197. ncplayer?.playerPause()
  198. ncplayer?.saveCurrentTime()
  199. }
  200. break
  201. }
  202. }
  203. default: ()
  204. }
  205. }
  206. @objc func handleInterruption(notification: Notification) {
  207. guard let userInfo = notification.userInfo, let typeValue = userInfo[AVAudioSessionInterruptionTypeKey] as? UInt, let type = AVAudioSession.InterruptionType(rawValue: typeValue) else { return }
  208. if type == .began {
  209. print("Interruption began")
  210. } else if type == .ended {
  211. if let optionsValue = userInfo[AVAudioSessionInterruptionOptionKey] as? UInt {
  212. let options = AVAudioSession.InterruptionOptions(rawValue: optionsValue)
  213. if options.contains(.shouldResume) {
  214. print("Interruption Ended - playback should resume")
  215. ncplayer?.playerPlay()
  216. startTimerAutoHide()
  217. } else {
  218. print("Interruption Ended - playback should NOT resume")
  219. }
  220. }
  221. }
  222. }
  223. // MARK: -
  224. public func show(enableTimerAutoHide: Bool = false) {
  225. guard let metadata = self.metadata, ncplayer != nil, !metadata.livePhoto else { return }
  226. if metadata.classFile != NCCommunicationCommon.typeClassFile.video.rawValue && metadata.classFile != NCCommunicationCommon.typeClassFile.audio.rawValue { return }
  227. #if MFFFLIB
  228. if MFFF.shared.existsMFFFSession(url: URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView))) {
  229. self.hide()
  230. return
  231. }
  232. #endif
  233. timerAutoHide?.invalidate()
  234. if enableTimerAutoHide {
  235. startTimerAutoHide()
  236. }
  237. if !self.isHidden { return }
  238. UIView.animate(withDuration: 0.3, animations: {
  239. self.alpha = 1
  240. }, completion: { (_: Bool) in
  241. self.isHidden = false
  242. })
  243. updateToolBar()
  244. }
  245. func isShow() -> Bool {
  246. return !self.isHidden
  247. }
  248. public func hide() {
  249. UIView.animate(withDuration: 0.3, animations: {
  250. self.alpha = 0
  251. }, completion: { (_: Bool) in
  252. self.isHidden = true
  253. })
  254. }
  255. @objc private func automaticHide() {
  256. if let metadata = self.metadata {
  257. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterHidePlayerToolBar, userInfo: ["ocId": metadata.ocId])
  258. }
  259. }
  260. private func startTimerAutoHide() {
  261. timerAutoHide?.invalidate()
  262. timerAutoHide = Timer.scheduledTimer(timeInterval: 3.5, target: self, selector: #selector(automaticHide), userInfo: nil, repeats: false)
  263. }
  264. private func reStartTimerAutoHide() {
  265. if let timerAutoHide = timerAutoHide, timerAutoHide.isValid {
  266. startTimerAutoHide()
  267. }
  268. }
  269. func skip(seconds: Float64) {
  270. guard let ncplayer = ncplayer, let player = ncplayer.player else { return }
  271. let currentTime = player.currentTime()
  272. var newTime: CMTime = .zero
  273. let timeToAdd: CMTime = CMTimeMakeWithSeconds(abs(seconds), preferredTimescale: 1)
  274. if seconds > 0 {
  275. newTime = CMTimeAdd(currentTime, timeToAdd)
  276. if newTime < ncplayer.durationTime {
  277. ncplayer.videoSeek(time: newTime)
  278. } else if newTime >= ncplayer.durationTime {
  279. let timeToSubtract: CMTime = CMTimeMakeWithSeconds(3, preferredTimescale: 1)
  280. newTime = CMTimeSubtract(ncplayer.durationTime, timeToSubtract)
  281. if newTime > currentTime {
  282. ncplayer.videoSeek(time: newTime)
  283. }
  284. }
  285. } else {
  286. newTime = CMTimeSubtract(currentTime, timeToAdd)
  287. if newTime.seconds < 0 {
  288. newTime = .zero
  289. }
  290. ncplayer.videoSeek(time: newTime)
  291. }
  292. updateToolBar()
  293. reStartTimerAutoHide()
  294. }
  295. func isPictureInPictureActive() -> Bool {
  296. if let pictureInPictureController = self.pictureInPictureController, pictureInPictureController.isPictureInPictureActive {
  297. return true
  298. } else {
  299. return false
  300. }
  301. }
  302. func stopTimerAutoHide() {
  303. timerAutoHide?.invalidate()
  304. }
  305. // MARK: - Event / Gesture
  306. @objc func onSliderValChanged(slider: UISlider, event: UIEvent) {
  307. if let touchEvent = event.allTouches?.first, let ncplayer = ncplayer {
  308. let seconds: Int64 = Int64(self.playbackSlider.value)
  309. let targetTime: CMTime = CMTimeMake(value: seconds, timescale: 1)
  310. switch touchEvent.phase {
  311. case .began:
  312. wasInPlay = ncplayer.isPlay()
  313. ncplayer.playerPause()
  314. playbackSliderEvent = .began
  315. case .moved:
  316. ncplayer.videoSeek(time: targetTime)
  317. playbackSliderEvent = .moved
  318. case .ended:
  319. ncplayer.videoSeek(time: targetTime)
  320. if wasInPlay {
  321. ncplayer.playerPlay()
  322. }
  323. playbackSliderEvent = .ended
  324. default:
  325. break
  326. }
  327. reStartTimerAutoHide()
  328. }
  329. }
  330. // MARK: - Action
  331. @objc func tapTopToolBarWith(gestureRecognizer: UITapGestureRecognizer) { }
  332. @objc func tapToolBarWith(gestureRecognizer: UITapGestureRecognizer) { }
  333. @IBAction func tapPlayerPause(_ sender: Any) {
  334. if ncplayer?.player?.timeControlStatus == .playing {
  335. ncplayer?.playerPause()
  336. ncplayer?.saveCurrentTime()
  337. timerAutoHide?.invalidate()
  338. } else if ncplayer?.player?.timeControlStatus == .paused {
  339. ncplayer?.playerPlay()
  340. startTimerAutoHide()
  341. } else if ncplayer?.player?.timeControlStatus == .waitingToPlayAtSpecifiedRate {
  342. print("timeControlStatus.waitingToPlayAtSpecifiedRate")
  343. if let reason = ncplayer?.player?.reasonForWaitingToPlay {
  344. switch reason {
  345. case .evaluatingBufferingRate:
  346. // TODO: need to be test
  347. self.ncplayer?.player?.playImmediately(atRate: 1)
  348. print("reasonForWaitingToPlay.evaluatingBufferingRate")
  349. case .toMinimizeStalls:
  350. print("reasonForWaitingToPlay.toMinimizeStalls")
  351. case .noItemToPlay:
  352. print("reasonForWaitingToPlay.noItemToPlay")
  353. default:
  354. print("Unknown \(reason)")
  355. }
  356. }
  357. }
  358. }
  359. @IBAction func tapMute(_ sender: Any) {
  360. let mute = CCUtility.getAudioMute()
  361. CCUtility.setAudioMute(!mute)
  362. ncplayer?.player?.isMuted = !mute
  363. updateToolBar()
  364. reStartTimerAutoHide()
  365. }
  366. @IBAction func tapPip(_ sender: Any) {
  367. guard let videoLayer = ncplayer?.videoLayer else { return }
  368. if let pictureInPictureController = self.pictureInPictureController, pictureInPictureController.isPictureInPictureActive {
  369. pictureInPictureController.stopPictureInPicture()
  370. }
  371. if pictureInPictureController == nil {
  372. pictureInPictureController = AVPictureInPictureController(playerLayer: videoLayer)
  373. pictureInPictureController?.delegate = self
  374. }
  375. if let pictureInPictureController = pictureInPictureController, pictureInPictureController.isPictureInPicturePossible, let metadata = self.metadata {
  376. DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
  377. pictureInPictureController.startPictureInPicture()
  378. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterHidePlayerToolBar, userInfo: ["ocId": metadata.ocId])
  379. }
  380. }
  381. }
  382. @IBAction func tapForward(_ sender: Any) {
  383. skip(seconds: 10)
  384. /*
  385. if metadata?.classFile == NCCommunicationCommon.typeClassFile.video.rawValue {
  386. skip(seconds: 10)
  387. } else if metadata?.classFile == NCCommunicationCommon.typeClassFile.audio.rawValue {
  388. forward()
  389. }
  390. */
  391. }
  392. @IBAction func tapBack(_ sender: Any) {
  393. skip(seconds: -10)
  394. /*
  395. if metadata?.classFile == NCCommunicationCommon.typeClassFile.video.rawValue {
  396. skip(seconds: -10)
  397. } else if metadata?.classFile == NCCommunicationCommon.typeClassFile.audio.rawValue {
  398. backward()
  399. }
  400. */
  401. }
  402. @IBAction func tapSubtitle(_ sender: Any) {
  403. self.subtitleIconTapped()
  404. }
  405. func forward() {
  406. var index: Int = 0
  407. if let currentIndex = self.viewerMediaPage?.currentIndex, let metadatas = self.viewerMediaPage?.metadatas, let ncplayer = self.ncplayer {
  408. if currentIndex == metadatas.count - 1 {
  409. index = 0
  410. } else {
  411. index = currentIndex + 1
  412. }
  413. self.viewerMediaPage?.goTo(index: index, direction: .forward, autoPlay: ncplayer.isPlay())
  414. }
  415. }
  416. func backward() {
  417. var index: Int = 0
  418. if let currentIndex = self.viewerMediaPage?.currentIndex, let metadatas = self.viewerMediaPage?.metadatas, let ncplayer = self.ncplayer {
  419. if currentIndex == 0 {
  420. index = metadatas.count - 1
  421. } else {
  422. index = currentIndex - 1
  423. }
  424. self.viewerMediaPage?.goTo(index: index, direction: .reverse, autoPlay: ncplayer.isPlay())
  425. }
  426. }
  427. }
  428. extension NCPlayerToolBar: AVPictureInPictureControllerDelegate {
  429. func pictureInPictureControllerDidStopPictureInPicture(_ pictureInPictureController: AVPictureInPictureController) {
  430. if let metadata = self.metadata, let ncplayer = self.ncplayer, !ncplayer.isPlay() {
  431. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterShowPlayerToolBar, userInfo: ["ocId": metadata.ocId, "enableTimerAutoHide": false])
  432. }
  433. }
  434. }