NCPlayerToolBar.swift 21 KB

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