NCPlayerToolBar.swift 22 KB

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