NCPlayerToolBar.swift 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  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. // 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.15", 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.15", color: .lightGray), for: .normal)
  93. forwardButton.isEnabled = false
  94. }
  95. deinit {
  96. print("deinit NCPlayerToolBar")
  97. if self.timeObserver != nil {
  98. appDelegate.player?.removeTimeObserver(self.timeObserver!)
  99. }
  100. }
  101. func setBarPlayer(ncplayer: NCPlayer, timeSeek: CMTime, metadata: tableMetadata) {
  102. self.ncplayer = ncplayer
  103. self.metadata = metadata
  104. if let durationTime = NCManageDatabase.shared.getVideoDurationTime(metadata: ncplayer.metadata) {
  105. self.durationTime = durationTime
  106. playbackSlider.value = 0
  107. playbackSlider.minimumValue = 0
  108. playbackSlider.maximumValue = Float(durationTime.value)
  109. playbackSlider.addTarget(self, action: #selector(onSliderValChanged(slider:event:)), for: .valueChanged)
  110. labelCurrentTime.text = NCUtility.shared.stringFromTime(.zero)
  111. labelOverallDuration.text = "-" + NCUtility.shared.stringFromTime(durationTime)
  112. }
  113. updateToolBar(timeSeek: timeSeek)
  114. self.timeObserver = appDelegate.player?.addPeriodicTimeObserver(forInterval: CMTimeMakeWithSeconds(1, preferredTimescale: 1), queue: .main, using: { (CMTime) in
  115. if self.appDelegate.player?.currentItem?.status == .readyToPlay {
  116. if self.isHidden == false {
  117. self.updateToolBar()
  118. }
  119. }
  120. })
  121. }
  122. public func hide() {
  123. UIView.animate(withDuration: 0.3, animations: {
  124. self.alpha = 0
  125. self.playerTopToolBarView.alpha = 0
  126. }, completion: { (value: Bool) in
  127. self.isHidden = true
  128. self.playerTopToolBarView.isHidden = true
  129. })
  130. }
  131. @objc private func automaticHide() {
  132. if let metadata = self.metadata {
  133. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterHidePlayerToolBar, userInfo: ["ocId":metadata.ocId])
  134. }
  135. }
  136. private func startTimerAutoHide() {
  137. timerAutoHide?.invalidate()
  138. timerAutoHide = Timer.scheduledTimer(timeInterval: 3.5, target: self, selector: #selector(automaticHide), userInfo: nil, repeats: false)
  139. }
  140. private func reStartTimerAutoHide() {
  141. if let timerAutoHide = timerAutoHide, timerAutoHide.isValid {
  142. startTimerAutoHide()
  143. }
  144. }
  145. public func show(enableTimerAutoHide: Bool) {
  146. guard let metadata = self.metadata else { return }
  147. if metadata.classFile != NCCommunicationCommon.typeClassFile.video.rawValue && metadata.classFile != NCCommunicationCommon.typeClassFile.audio.rawValue { return }
  148. if metadata.livePhoto { return }
  149. timerAutoHide?.invalidate()
  150. if enableTimerAutoHide {
  151. startTimerAutoHide()
  152. }
  153. if !self.isHidden { return }
  154. updateToolBar()
  155. UIView.animate(withDuration: 0.3, animations: {
  156. self.alpha = 1
  157. self.playerTopToolBarView.alpha = 1
  158. }, completion: { (value: Bool) in
  159. self.isHidden = false
  160. self.playerTopToolBarView.isHidden = false
  161. })
  162. }
  163. func isShow() -> Bool {
  164. return !self.isHidden
  165. }
  166. public func updateToolBar(timeSeek: CMTime? = nil) {
  167. guard let metadata = self.metadata else { return }
  168. var namedPlay = "play.fill"
  169. var currentTime = appDelegate.player?.currentTime() ?? .zero
  170. currentTime = currentTime.convertScale(1000, method: .default)
  171. if CCUtility.getAudioMute() {
  172. muteButton.setImage(NCUtility.shared.loadImage(named: "audioOff", color: .white), for: .normal)
  173. } else {
  174. muteButton.setImage(NCUtility.shared.loadImage(named: "audioOn", color: .white), for: .normal)
  175. }
  176. muteButton.isEnabled = true
  177. if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) && ncplayer?.pictureInPictureController != nil {
  178. pipButton.setImage(NCUtility.shared.loadImage(named: "pip.enter", color: .white), for: .normal)
  179. pipButton.isEnabled = true
  180. } else {
  181. pipButton.setImage(NCUtility.shared.loadImage(named: "pip.enter", color: .gray), for: .normal)
  182. pipButton.isEnabled = false
  183. }
  184. if let ncplayer = ncplayer, ncplayer.isPlay() {
  185. namedPlay = "pause.fill"
  186. }
  187. if timeSeek != nil {
  188. playbackSlider.value = Float(timeSeek!.value)
  189. } else {
  190. playbackSlider.value = Float(currentTime.value)
  191. }
  192. playbackSlider.isEnabled = true
  193. if #available(iOS 13.0, *) {
  194. backButton.setImage(NCUtility.shared.loadImage(named: "gobackward.15", color: .white), for: .normal)
  195. } else {
  196. backButton.setImage(NCUtility.shared.loadImage(named: "gobackward.15", color: .white, size: 30), for: .normal)
  197. }
  198. backButton.isEnabled = true
  199. if #available(iOS 13.0, *) {
  200. playButton.setImage(NCUtility.shared.loadImage(named: namedPlay, color: .white, symbolConfiguration: UIImage.SymbolConfiguration(pointSize: 30)), for: .normal)
  201. } else {
  202. playButton.setImage(NCUtility.shared.loadImage(named: namedPlay, color: .white, size: 30), for: .normal)
  203. }
  204. playButton.isEnabled = true
  205. if #available(iOS 13.0, *) {
  206. forwardButton.setImage(NCUtility.shared.loadImage(named: "goforward.15", color: .white), for: .normal)
  207. } else {
  208. forwardButton.setImage(NCUtility.shared.loadImage(named: "goforward.15", color: .white, size: 30), for: .normal)
  209. }
  210. forwardButton.isEnabled = true
  211. labelCurrentTime.text = NCUtility.shared.stringFromTime(currentTime)
  212. labelOverallDuration.text = "-" + NCUtility.shared.stringFromTime(self.durationTime - currentTime)
  213. }
  214. //MARK: - Event / Gesture
  215. @objc func onSliderValChanged(slider: UISlider, event: UIEvent) {
  216. if let touchEvent = event.allTouches?.first, let ncplayer = ncplayer {
  217. let seconds: Int64 = Int64(self.playbackSlider.value)
  218. let targetTime: CMTime = CMTimeMake(value: seconds, timescale: 1000)
  219. switch touchEvent.phase {
  220. case .began:
  221. wasInPlay = ncplayer.isPlay()
  222. ncplayer.playerPause()
  223. playbackSliderEvent = .began
  224. case .moved:
  225. ncplayer.videoSeek(time: targetTime)
  226. playbackSliderEvent = .moved
  227. case .ended:
  228. ncplayer.videoSeek(time: targetTime)
  229. if wasInPlay {
  230. ncplayer.playerPlay()
  231. }
  232. playbackSliderEvent = .ended
  233. default:
  234. break
  235. }
  236. reStartTimerAutoHide()
  237. }
  238. }
  239. @objc func didSingleTapWith(gestureRecognizer: UITapGestureRecognizer) {
  240. hide()
  241. }
  242. //MARK: - Action
  243. @IBAction func buttonTouchInside(_ sender: UIButton) {
  244. }
  245. @IBAction func playerPause(_ sender: Any) {
  246. if appDelegate.player?.timeControlStatus == .playing {
  247. ncplayer?.playerPause()
  248. ncplayer?.saveCurrentTime()
  249. timerAutoHide?.invalidate()
  250. } else if appDelegate.player?.timeControlStatus == .paused {
  251. ncplayer?.playerPlay()
  252. startTimerAutoHide()
  253. } else if appDelegate.player?.timeControlStatus == .waitingToPlayAtSpecifiedRate {
  254. print("timeControlStatus.waitingToPlayAtSpecifiedRate")
  255. if let reason = appDelegate.player?.reasonForWaitingToPlay {
  256. switch reason {
  257. case .evaluatingBufferingRate:
  258. print("reasonForWaitingToPlay.evaluatingBufferingRate")
  259. case .toMinimizeStalls:
  260. print("reasonForWaitingToPlay.toMinimizeStalls")
  261. case .noItemToPlay:
  262. print("reasonForWaitingToPlay.noItemToPlay")
  263. default:
  264. print("Unknown \(reason)")
  265. }
  266. }
  267. }
  268. }
  269. @IBAction func setMute(_ sender: Any) {
  270. let mute = CCUtility.getAudioMute()
  271. CCUtility.setAudioMute(!mute)
  272. appDelegate.player?.isMuted = !mute
  273. updateToolBar()
  274. reStartTimerAutoHide()
  275. }
  276. @IBAction func setPip(_ sender: Any) {
  277. guard let metadata = self.metadata else { return }
  278. ncplayer?.pictureInPictureController?.startPictureInPicture()
  279. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterHidePlayerToolBar, userInfo: ["ocId":metadata.ocId])
  280. }
  281. @IBAction func forwardButtonSec(_ sender: Any) {
  282. guard let ncplayer = ncplayer else { return }
  283. guard let player = appDelegate.player else { return }
  284. let currentTime = player.currentTime()
  285. var newTime = CMTimeAdd(currentTime, timeToAdd)
  286. if newTime < durationTime {
  287. ncplayer.videoSeek(time: newTime)
  288. } else if newTime >= durationTime {
  289. let timeToSubtract: CMTime = CMTimeMakeWithSeconds(3, preferredTimescale: 1)
  290. newTime = CMTimeSubtract(durationTime, timeToSubtract)
  291. if newTime > currentTime {
  292. ncplayer.videoSeek(time: newTime)
  293. }
  294. }
  295. reStartTimerAutoHide()
  296. }
  297. @IBAction func backButtonSec(_ sender: Any) {
  298. guard let ncplayer = ncplayer else { return }
  299. guard let player = appDelegate.player else { return }
  300. let currentTime = player.currentTime()
  301. let newTime = CMTimeSubtract(currentTime, timeToAdd)
  302. ncplayer.videoSeek(time: newTime)
  303. reStartTimerAutoHide()
  304. }
  305. }
  306. extension NCPlayerToolBar {
  307. func setupRemoteTransportControls() {
  308. guard let ncplayer = ncplayer else { return }
  309. let commandCenter = MPRemoteCommandCenter.shared()
  310. // Add handler for Play Command
  311. commandCenter.playCommand.addTarget { event in
  312. if !ncplayer.isPlay() {
  313. ncplayer.playerPlay()
  314. return .success
  315. }
  316. return .commandFailed
  317. }
  318. // Add handler for Pause Command
  319. commandCenter.pauseCommand.addTarget { event in
  320. if ncplayer.isPlay() {
  321. ncplayer.playerPause()
  322. return .success
  323. }
  324. return .commandFailed
  325. }
  326. }
  327. func setupNowPlaying() {
  328. var nowPlayingInfo = [String : Any]()
  329. nowPlayingInfo[MPMediaItemPropertyTitle] = metadata?.fileNameView
  330. // if let image = UIImage(named: "artist") {
  331. // nowPlayingInfo[MPMediaItemPropertyArtwork] = MPMediaItemArtwork(boundsSize: image.size) { size in
  332. // return image
  333. // }
  334. // }
  335. nowPlayingInfo[MPNowPlayingInfoPropertyElapsedPlaybackTime] = appDelegate.player?.currentTime
  336. nowPlayingInfo[MPMediaItemPropertyPlaybackDuration] = appDelegate.player?.currentItem?.asset.duration
  337. nowPlayingInfo[MPNowPlayingInfoPropertyPlaybackRate] = appDelegate.player?.rate
  338. MPNowPlayingInfoCenter.default().nowPlayingInfo = nowPlayingInfo
  339. }
  340. func updateNowPlaying(isPause: Bool) {
  341. var nowPlayingInfo = MPNowPlayingInfoCenter.default().nowPlayingInfo!
  342. nowPlayingInfo[MPNowPlayingInfoPropertyElapsedPlaybackTime] = appDelegate.player?.currentTime
  343. nowPlayingInfo[MPNowPlayingInfoPropertyPlaybackRate] = isPause ? 0 : 1
  344. // Set the metadata
  345. MPNowPlayingInfoCenter.default().nowPlayingInfo = nowPlayingInfo
  346. }
  347. }