NCPlayerToolBar.swift 19 KB

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