NCPlayerToolBar.swift 22 KB

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