NCPlayerToolBar.swift 21 KB

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