NCPlayerToolBar.swift 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542
  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 MediaPlayer
  28. class NCPlayerToolBar: UIView {
  29. @IBOutlet weak var playerTopToolBarView: UIView!
  30. @IBOutlet weak var pipButton: UIButton!
  31. @IBOutlet weak var muteButton: UIButton!
  32. @IBOutlet weak var playButton: UIButton!
  33. @IBOutlet weak var forwardButton: UIButton!
  34. @IBOutlet weak var backButton: UIButton!
  35. @IBOutlet weak var playbackSlider: UISlider!
  36. @IBOutlet weak var labelOverallDuration: UILabel!
  37. @IBOutlet weak var labelCurrentTime: UILabel!
  38. enum sliderEventType {
  39. case began
  40. case ended
  41. case moved
  42. }
  43. private let appDelegate = UIApplication.shared.delegate as! AppDelegate
  44. private var ncplayer: NCPlayer?
  45. private var wasInPlay: Bool = false
  46. private var playbackSliderEvent: sliderEventType = .ended
  47. private let timeToAdd: CMTime = CMTimeMakeWithSeconds(15, preferredTimescale: 1)
  48. private var durationTime: CMTime = .zero
  49. private var timeObserver: Any?
  50. private var timerAutoHide: Timer?
  51. private var metadata: tableMetadata?
  52. private var image: UIImage?
  53. // MARK: - View Life Cycle
  54. override func awakeFromNib() {
  55. super.awakeFromNib()
  56. // for disable gesture of UIPageViewController
  57. let panRecognizer = UIPanGestureRecognizer(target: self, action: nil)
  58. addGestureRecognizer(panRecognizer)
  59. let singleTapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(didSingleTapWith(gestureRecognizer:)))
  60. addGestureRecognizer(singleTapGestureRecognizer)
  61. // self
  62. self.layer.cornerRadius = 15
  63. self.layer.masksToBounds = true
  64. let blurEffectView = UIVisualEffectView(effect: UIBlurEffect(style: .dark))
  65. blurEffectView.frame = self.bounds
  66. blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
  67. self.insertSubview(blurEffectView, at:0)
  68. // Top ToolBar
  69. playerTopToolBarView.layer.cornerRadius = 10
  70. playerTopToolBarView.layer.masksToBounds = true
  71. let blurEffectTopToolBarView = UIVisualEffectView(effect: UIBlurEffect(style: .dark))
  72. blurEffectTopToolBarView.frame = playerTopToolBarView.bounds
  73. blurEffectTopToolBarView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
  74. playerTopToolBarView.insertSubview(blurEffectTopToolBarView, at:0)
  75. pipButton.setImage(NCUtility.shared.loadImage(named: "pip.enter", color: .lightGray), for: .normal)
  76. pipButton.isEnabled = false
  77. muteButton.setImage(NCUtility.shared.loadImage(named: "audioOff", color: .lightGray), for: .normal)
  78. muteButton.isEnabled = false
  79. playbackSlider.value = 0
  80. playbackSlider.minimumValue = 0
  81. playbackSlider.maximumValue = 0
  82. playbackSlider.isContinuous = true
  83. playbackSlider.tintColor = .lightGray
  84. playbackSlider.isEnabled = false
  85. labelCurrentTime.text = NCUtility.shared.stringFromTime(.zero)
  86. labelCurrentTime.textColor = .lightGray
  87. labelOverallDuration.text = NCUtility.shared.stringFromTime(.zero)
  88. labelOverallDuration.textColor = .lightGray
  89. backButton.setImage(NCUtility.shared.loadImage(named: "gobackward.15", color: .lightGray), for: .normal)
  90. backButton.isEnabled = false
  91. playButton.setImage(NCUtility.shared.loadImage(named: "play.fill", color: .lightGray), for: .normal)
  92. playButton.isEnabled = false
  93. forwardButton.setImage(NCUtility.shared.loadImage(named: "goforward.15", color: .lightGray), for: .normal)
  94. forwardButton.isEnabled = false
  95. NotificationCenter.default.addObserver(self, selector: #selector(handleInterruption), name: AVAudioSession.interruptionNotification, object: nil)
  96. NotificationCenter.default.addObserver(self, selector: #selector(handleRouteChange), name: AVAudioSession.routeChangeNotification, object: nil)
  97. }
  98. deinit {
  99. print("deinit NCPlayerToolBar")
  100. if self.timeObserver != nil {
  101. appDelegate.player?.removeTimeObserver(self.timeObserver!)
  102. }
  103. NotificationCenter.default.removeObserver(self, name: AVAudioSession.interruptionNotification, object: nil)
  104. NotificationCenter.default.removeObserver(self, name: AVAudioSession.routeChangeNotification, object: nil)
  105. }
  106. // MARK: Handle Notifications
  107. @objc func handleRouteChange(notification: Notification) {
  108. guard let userInfo = notification.userInfo, let reasonValue = userInfo[AVAudioSessionRouteChangeReasonKey] as? UInt, let reason = AVAudioSession.RouteChangeReason(rawValue:reasonValue) else { return }
  109. switch reason {
  110. case .newDeviceAvailable:
  111. let session = AVAudioSession.sharedInstance()
  112. for output in session.currentRoute.outputs where output.portType == AVAudioSession.Port.headphones {
  113. print("headphones connected")
  114. DispatchQueue.main.sync {
  115. //self.play()
  116. }
  117. break
  118. }
  119. case .oldDeviceUnavailable:
  120. if let previousRoute =
  121. userInfo[AVAudioSessionRouteChangePreviousRouteKey] as? AVAudioSessionRouteDescription {
  122. for output in previousRoute.outputs where output.portType == AVAudioSession.Port.headphones {
  123. print("headphones disconnected")
  124. DispatchQueue.main.sync {
  125. //self.pause()
  126. }
  127. break
  128. }
  129. }
  130. default: ()
  131. }
  132. }
  133. @objc func handleInterruption(notification: Notification) {
  134. guard let userInfo = notification.userInfo, let typeValue = userInfo[AVAudioSessionInterruptionTypeKey] as? UInt, let type = AVAudioSession.InterruptionType(rawValue: typeValue) else { return }
  135. if type == .began {
  136. print("Interruption began")
  137. // Interruption began, take appropriate actions
  138. } else if type == .ended {
  139. if let optionsValue = userInfo[AVAudioSessionInterruptionOptionKey] as? UInt {
  140. let options = AVAudioSession.InterruptionOptions(rawValue: optionsValue)
  141. if options.contains(.shouldResume) {
  142. // Interruption Ended - playback should resume
  143. print("Interruption Ended - playback should resume")
  144. //play()
  145. } else {
  146. // Interruption Ended - playback should NOT resume
  147. print("Interruption Ended - playback should NOT resume")
  148. }
  149. }
  150. }
  151. }
  152. func setBarPlayer(ncplayer: NCPlayer, timeSeek: CMTime, metadata: tableMetadata, image: UIImage?) {
  153. self.ncplayer = ncplayer
  154. self.metadata = metadata
  155. if let durationTime = NCManageDatabase.shared.getVideoDurationTime(metadata: ncplayer.metadata) {
  156. self.durationTime = durationTime
  157. playbackSlider.value = 0
  158. playbackSlider.minimumValue = 0
  159. playbackSlider.maximumValue = Float(durationTime.value)
  160. playbackSlider.addTarget(self, action: #selector(onSliderValChanged(slider:event:)), for: .valueChanged)
  161. labelCurrentTime.text = NCUtility.shared.stringFromTime(.zero)
  162. labelOverallDuration.text = "-" + NCUtility.shared.stringFromTime(durationTime)
  163. }
  164. setupRemoteTransportControls()
  165. updateToolBar(timeSeek: timeSeek)
  166. self.timeObserver = appDelegate.player?.addPeriodicTimeObserver(forInterval: CMTimeMakeWithSeconds(1, preferredTimescale: 1), queue: .main, using: { (CMTime) in
  167. if self.appDelegate.player?.currentItem?.status == .readyToPlay {
  168. if self.isHidden == false {
  169. self.updateToolBar()
  170. }
  171. }
  172. })
  173. }
  174. public func hide() {
  175. UIView.animate(withDuration: 0.3, animations: {
  176. self.alpha = 0
  177. self.playerTopToolBarView.alpha = 0
  178. }, completion: { (value: Bool) in
  179. self.isHidden = true
  180. self.playerTopToolBarView.isHidden = true
  181. })
  182. }
  183. @objc private func automaticHide() {
  184. if let metadata = self.metadata {
  185. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterHidePlayerToolBar, userInfo: ["ocId":metadata.ocId])
  186. }
  187. }
  188. private func startTimerAutoHide() {
  189. timerAutoHide?.invalidate()
  190. timerAutoHide = Timer.scheduledTimer(timeInterval: 3.5, target: self, selector: #selector(automaticHide), userInfo: nil, repeats: false)
  191. }
  192. private func reStartTimerAutoHide() {
  193. if let timerAutoHide = timerAutoHide, timerAutoHide.isValid {
  194. startTimerAutoHide()
  195. }
  196. }
  197. public func show(enableTimerAutoHide: Bool) {
  198. guard let metadata = self.metadata else { return }
  199. if metadata.classFile != NCCommunicationCommon.typeClassFile.video.rawValue && metadata.classFile != NCCommunicationCommon.typeClassFile.audio.rawValue { return }
  200. if metadata.livePhoto { return }
  201. timerAutoHide?.invalidate()
  202. if enableTimerAutoHide {
  203. startTimerAutoHide()
  204. }
  205. if !self.isHidden { return }
  206. updateToolBar()
  207. UIView.animate(withDuration: 0.3, animations: {
  208. self.alpha = 1
  209. self.playerTopToolBarView.alpha = 1
  210. }, completion: { (value: Bool) in
  211. self.isHidden = false
  212. self.playerTopToolBarView.isHidden = false
  213. })
  214. }
  215. func isShow() -> Bool {
  216. return !self.isHidden
  217. }
  218. public func updateToolBar(timeSeek: CMTime? = nil) {
  219. guard let metadata = self.metadata else { return }
  220. var namedPlay = "play.fill"
  221. var currentTime = appDelegate.player?.currentTime() ?? .zero
  222. currentTime = currentTime.convertScale(1000, method: .default)
  223. if CCUtility.getAudioMute() {
  224. muteButton.setImage(NCUtility.shared.loadImage(named: "audioOff", color: .white), for: .normal)
  225. } else {
  226. muteButton.setImage(NCUtility.shared.loadImage(named: "audioOn", color: .white), for: .normal)
  227. }
  228. muteButton.isEnabled = true
  229. if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) && ncplayer?.pictureInPictureController != nil {
  230. pipButton.setImage(NCUtility.shared.loadImage(named: "pip.enter", color: .white), for: .normal)
  231. pipButton.isEnabled = true
  232. } else {
  233. pipButton.setImage(NCUtility.shared.loadImage(named: "pip.enter", color: .gray), for: .normal)
  234. pipButton.isEnabled = false
  235. }
  236. if let ncplayer = ncplayer, ncplayer.isPlay() {
  237. namedPlay = "pause.fill"
  238. }
  239. if timeSeek != nil {
  240. playbackSlider.value = Float(timeSeek!.value)
  241. } else {
  242. playbackSlider.value = Float(currentTime.value)
  243. }
  244. playbackSlider.isEnabled = true
  245. if #available(iOS 13.0, *) {
  246. backButton.setImage(NCUtility.shared.loadImage(named: "gobackward.15", color: .white), for: .normal)
  247. } else {
  248. backButton.setImage(NCUtility.shared.loadImage(named: "gobackward.15", color: .white, size: 30), for: .normal)
  249. }
  250. backButton.isEnabled = true
  251. if #available(iOS 13.0, *) {
  252. playButton.setImage(NCUtility.shared.loadImage(named: namedPlay, color: .white, symbolConfiguration: UIImage.SymbolConfiguration(pointSize: 30)), for: .normal)
  253. } else {
  254. playButton.setImage(NCUtility.shared.loadImage(named: namedPlay, color: .white, size: 30), for: .normal)
  255. }
  256. playButton.isEnabled = true
  257. if #available(iOS 13.0, *) {
  258. forwardButton.setImage(NCUtility.shared.loadImage(named: "goforward.15", color: .white), for: .normal)
  259. } else {
  260. forwardButton.setImage(NCUtility.shared.loadImage(named: "goforward.15", color: .white, size: 30), for: .normal)
  261. }
  262. forwardButton.isEnabled = true
  263. labelCurrentTime.text = NCUtility.shared.stringFromTime(currentTime)
  264. labelOverallDuration.text = "-" + NCUtility.shared.stringFromTime(self.durationTime - currentTime)
  265. }
  266. //MARK: - Event / Gesture
  267. @objc func onSliderValChanged(slider: UISlider, event: UIEvent) {
  268. if let touchEvent = event.allTouches?.first, let ncplayer = ncplayer {
  269. let seconds: Int64 = Int64(self.playbackSlider.value)
  270. let targetTime: CMTime = CMTimeMake(value: seconds, timescale: 1000)
  271. switch touchEvent.phase {
  272. case .began:
  273. wasInPlay = ncplayer.isPlay()
  274. ncplayer.playerPause()
  275. playbackSliderEvent = .began
  276. case .moved:
  277. ncplayer.videoSeek(time: targetTime)
  278. playbackSliderEvent = .moved
  279. case .ended:
  280. ncplayer.videoSeek(time: targetTime)
  281. if wasInPlay {
  282. ncplayer.playerPlay()
  283. }
  284. playbackSliderEvent = .ended
  285. default:
  286. break
  287. }
  288. reStartTimerAutoHide()
  289. }
  290. }
  291. @objc func didSingleTapWith(gestureRecognizer: UITapGestureRecognizer) {
  292. hide()
  293. }
  294. //MARK: - Action
  295. @IBAction func buttonTouchInside(_ sender: UIButton) {
  296. }
  297. @IBAction func playerPause(_ sender: Any) {
  298. if appDelegate.player?.timeControlStatus == .playing {
  299. ncplayer?.playerPause()
  300. ncplayer?.saveCurrentTime()
  301. timerAutoHide?.invalidate()
  302. } else if appDelegate.player?.timeControlStatus == .paused {
  303. ncplayer?.playerPlay()
  304. startTimerAutoHide()
  305. } else if appDelegate.player?.timeControlStatus == .waitingToPlayAtSpecifiedRate {
  306. print("timeControlStatus.waitingToPlayAtSpecifiedRate")
  307. if let reason = appDelegate.player?.reasonForWaitingToPlay {
  308. switch reason {
  309. case .evaluatingBufferingRate:
  310. print("reasonForWaitingToPlay.evaluatingBufferingRate")
  311. case .toMinimizeStalls:
  312. print("reasonForWaitingToPlay.toMinimizeStalls")
  313. case .noItemToPlay:
  314. print("reasonForWaitingToPlay.noItemToPlay")
  315. default:
  316. print("Unknown \(reason)")
  317. }
  318. }
  319. }
  320. }
  321. @IBAction func setMute(_ sender: Any) {
  322. let mute = CCUtility.getAudioMute()
  323. CCUtility.setAudioMute(!mute)
  324. appDelegate.player?.isMuted = !mute
  325. updateToolBar()
  326. reStartTimerAutoHide()
  327. }
  328. @IBAction func setPip(_ sender: Any) {
  329. guard let metadata = self.metadata else { return }
  330. ncplayer?.pictureInPictureController?.startPictureInPicture()
  331. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterHidePlayerToolBar, userInfo: ["ocId":metadata.ocId])
  332. }
  333. @IBAction func forwardButtonSec(_ sender: Any) {
  334. guard let ncplayer = ncplayer else { return }
  335. guard let player = appDelegate.player else { return }
  336. let currentTime = player.currentTime()
  337. var newTime = CMTimeAdd(currentTime, timeToAdd)
  338. if newTime < durationTime {
  339. ncplayer.videoSeek(time: newTime)
  340. } else if newTime >= durationTime {
  341. let timeToSubtract: CMTime = CMTimeMakeWithSeconds(3, preferredTimescale: 1)
  342. newTime = CMTimeSubtract(durationTime, timeToSubtract)
  343. if newTime > currentTime {
  344. ncplayer.videoSeek(time: newTime)
  345. }
  346. }
  347. reStartTimerAutoHide()
  348. }
  349. @IBAction func backButtonSec(_ sender: Any) {
  350. guard let ncplayer = ncplayer else { return }
  351. guard let player = appDelegate.player else { return }
  352. let currentTime = player.currentTime()
  353. let newTime = CMTimeSubtract(currentTime, timeToAdd)
  354. ncplayer.videoSeek(time: newTime)
  355. reStartTimerAutoHide()
  356. }
  357. }
  358. //MARK: - Remote Command Center
  359. extension NCPlayerToolBar {
  360. func setupRemoteTransportControls() {
  361. guard let ncplayer = ncplayer else { return }
  362. UIApplication.shared.beginReceivingRemoteControlEvents()
  363. let commandCenter = MPRemoteCommandCenter.shared()
  364. var nowPlayingInfo = [String : Any]()
  365. commandCenter.playCommand.isEnabled = true
  366. // Add handler for Play Command
  367. commandCenter.playCommand.addTarget { event in
  368. if !ncplayer.isPlay() {
  369. ncplayer.playerPlay()
  370. return .success
  371. }
  372. return .commandFailed
  373. }
  374. // Add handler for Pause Command
  375. commandCenter.pauseCommand.addTarget { event in
  376. if ncplayer.isPlay() {
  377. ncplayer.playerPause()
  378. return .success
  379. }
  380. return .commandFailed
  381. }
  382. nowPlayingInfo[MPMediaItemPropertyTitle] = metadata?.fileNameView
  383. if let image = self.image {
  384. nowPlayingInfo[MPMediaItemPropertyArtwork] = MPMediaItemArtwork(boundsSize: image.size) { size in
  385. return image
  386. }
  387. }
  388. nowPlayingInfo[MPNowPlayingInfoPropertyElapsedPlaybackTime] = appDelegate.player?.currentTime
  389. nowPlayingInfo[MPMediaItemPropertyPlaybackDuration] = appDelegate.player?.currentItem?.asset.duration
  390. nowPlayingInfo[MPNowPlayingInfoPropertyPlaybackRate] = appDelegate.player?.rate
  391. MPNowPlayingInfoCenter.default().nowPlayingInfo = nowPlayingInfo
  392. }
  393. func updateNowPlaying(isPause: Bool) {
  394. var nowPlayingInfo = MPNowPlayingInfoCenter.default().nowPlayingInfo!
  395. nowPlayingInfo[MPNowPlayingInfoPropertyElapsedPlaybackTime] = appDelegate.player?.currentTime
  396. nowPlayingInfo[MPNowPlayingInfoPropertyPlaybackRate] = isPause ? 0 : 1
  397. // Set the metadata
  398. MPNowPlayingInfoCenter.default().nowPlayingInfo = nowPlayingInfo
  399. }
  400. // MARK: AVAudioPlayerDelegate
  401. func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
  402. print("Audio player did finish playing: \(flag)")
  403. if (flag) {
  404. updateNowPlaying(isPause: true)
  405. //playPauseButton.setTitle("Play", for: UIControl.State.normal)
  406. }
  407. }
  408. /*
  409. // MARK: Actions
  410. @IBAction func togglePlayPause(_ sender: Any) {
  411. if (player.isPlaying) {
  412. pause()
  413. }
  414. else {
  415. play()
  416. }
  417. }
  418. func play() {
  419. player.play()
  420. playPauseButton.setTitle("Pause", for: UIControl.State.normal)
  421. updateNowPlaying(isPause: false)
  422. print("Play - current time: \(player.currentTime) - is playing: \(player.isPlaying)")
  423. }
  424. func pause() {
  425. player.pause()
  426. playPauseButton.setTitle("Play", for: UIControl.State.normal)
  427. updateNowPlaying(isPause: true)
  428. print("Pause - current time: \(player.currentTime) - is playing: \(player.isPlaying)")
  429. }
  430. @IBAction func stop(_ sender: Any) {
  431. player.stop()
  432. player.currentTime = 0
  433. playPauseButton.setTitle("Play", for: UIControl.State.normal)
  434. }
  435. */
  436. }