NCPlayerToolBar.swift 20 KB

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