NCPlayerToolBar.swift 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522
  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 NextcloudKit
  25. import CoreMedia
  26. import UIKit
  27. import AVKit
  28. import MediaPlayer
  29. class NCPlayerToolBar: UIView {
  30. @IBOutlet weak var playerTopToolBarView: UIStackView!
  31. @IBOutlet weak var playerToolBarView: UIView!
  32. @IBOutlet weak var pipButton: UIButton!
  33. @IBOutlet weak var subtitleButton: UIButton!
  34. @IBOutlet weak var muteButton: UIButton!
  35. @IBOutlet weak var playButton: UIButton!
  36. @IBOutlet weak var forwardButton: UIButton!
  37. @IBOutlet weak var backButton: UIButton!
  38. @IBOutlet weak var playbackSlider: UISlider!
  39. @IBOutlet weak var labelLeftTime: UILabel!
  40. @IBOutlet weak var labelCurrentTime: UILabel!
  41. enum sliderEventType {
  42. case began
  43. case ended
  44. case moved
  45. }
  46. var ncplayer: NCPlayer?
  47. private var metadata: tableMetadata?
  48. private var wasInPlay: Bool = false
  49. private var playbackSliderEvent: sliderEventType = .ended
  50. private var timerAutoHide: Timer?
  51. private var timerAutoHideSeconds: Double {
  52. get {
  53. if NCUtility.shared.isSimulator() { // for test
  54. return 15
  55. } else {
  56. return 3.5
  57. }
  58. }
  59. }
  60. // NCUtility.shared.isSimulatorOrTestFlight()
  61. var pictureInPictureController: AVPictureInPictureController?
  62. weak var viewerMediaPage: NCViewerMediaPage?
  63. // MARK: - View Life Cycle
  64. override func awakeFromNib() {
  65. super.awakeFromNib()
  66. let blurEffectView = UIVisualEffectView(effect: UIBlurEffect(style: .dark))
  67. blurEffectView.frame = self.bounds
  68. blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
  69. playerToolBarView.insertSubview(blurEffectView, at: 0)
  70. playerTopToolBarView.layer.cornerRadius = 10
  71. playerTopToolBarView.layer.masksToBounds = true
  72. playerTopToolBarView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(tapTopToolBarWith(gestureRecognizer:))))
  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. playerToolBarView.layer.cornerRadius = 10
  78. playerToolBarView.layer.masksToBounds = true
  79. playerToolBarView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(tapToolBarWith(gestureRecognizer:))))
  80. pipButton.setImage(NCUtility.shared.loadImage(named: "pip.enter", color: .lightGray), for: .normal)
  81. pipButton.isEnabled = false
  82. muteButton.setImage(NCUtility.shared.loadImage(named: "audioOff", color: .lightGray), for: .normal)
  83. muteButton.isEnabled = false
  84. subtitleButton.setImage(NCUtility.shared.loadImage(named: "captions.bubble", color: .white), for: .normal)
  85. subtitleButton.isEnabled = true
  86. subtitleButton.isHidden = true
  87. playbackSlider.value = 0
  88. playbackSlider.minimumValue = 0
  89. playbackSlider.maximumValue = 0
  90. playbackSlider.isContinuous = true
  91. playbackSlider.tintColor = .lightGray
  92. playbackSlider.isEnabled = false
  93. labelCurrentTime.text = NCUtility.shared.stringFromTime(.zero)
  94. labelCurrentTime.textColor = .lightGray
  95. labelLeftTime.text = NCUtility.shared.stringFromTime(.zero)
  96. labelLeftTime.textColor = .lightGray
  97. backButton.setImage(NCUtility.shared.loadImage(named: "gobackward.10", color: .lightGray), for: .normal)
  98. backButton.isEnabled = false
  99. playButton.setImage(NCUtility.shared.loadImage(named: "play.fill", color: .lightGray, symbolConfiguration: UIImage.SymbolConfiguration(pointSize: 30)), for: .normal)
  100. playButton.isEnabled = false
  101. forwardButton.setImage(NCUtility.shared.loadImage(named: "goforward.10", color: .lightGray), for: .normal)
  102. forwardButton.isEnabled = false
  103. NotificationCenter.default.addObserver(self, selector: #selector(handleInterruption), name: AVAudioSession.interruptionNotification, object: nil)
  104. NotificationCenter.default.addObserver(self, selector: #selector(handleRouteChange), name: AVAudioSession.routeChangeNotification, object: nil)
  105. }
  106. required init?(coder aDecoder: NSCoder) {
  107. super.init(coder: aDecoder)
  108. }
  109. deinit {
  110. print("deinit NCPlayerToolBar")
  111. NotificationCenter.default.removeObserver(self, name: AVAudioSession.interruptionNotification, object: nil)
  112. NotificationCenter.default.removeObserver(self, name: AVAudioSession.routeChangeNotification, object: nil)
  113. }
  114. // MARK: -
  115. func setMetadata(_ metadata: tableMetadata) {
  116. self.metadata = metadata
  117. }
  118. func setBarPlayer(ncplayer: NCPlayer) {
  119. self.ncplayer = ncplayer
  120. playbackSlider.value = 0
  121. playbackSlider.minimumValue = 0
  122. playbackSlider.maximumValue = Float(ncplayer.durationTime.seconds)
  123. playbackSlider.addTarget(self, action: #selector(onSliderValChanged(slider:event:)), for: .valueChanged)
  124. labelCurrentTime.text = NCUtility.shared.stringFromTime(.zero)
  125. labelLeftTime.text = "-" + NCUtility.shared.stringFromTime(ncplayer.durationTime)
  126. updateToolBar()
  127. }
  128. public func updateToolBar() {
  129. guard let ncplayer = self.ncplayer else { return }
  130. // MUTE
  131. if let muteButton = muteButton {
  132. if CCUtility.getAudioMute() {
  133. muteButton.setImage(NCUtility.shared.loadImage(named: "audioOff", color: .white), for: .normal)
  134. } else {
  135. muteButton.setImage(NCUtility.shared.loadImage(named: "audioOn", color: .white), for: .normal)
  136. }
  137. muteButton.isEnabled = true
  138. }
  139. // PIP
  140. if let pipButton = pipButton {
  141. if metadata?.classFile == NKCommon.TypeClassFile.video.rawValue && AVPictureInPictureController.isPictureInPictureSupported() {
  142. pipButton.setImage(NCUtility.shared.loadImage(named: "pip.enter", color: .white), for: .normal)
  143. pipButton.isEnabled = true
  144. } else {
  145. pipButton.setImage(NCUtility.shared.loadImage(named: "pip.enter", color: .gray), for: .normal)
  146. pipButton.isEnabled = false
  147. }
  148. }
  149. // SLIDER TIME (START - END)
  150. let time = (ncplayer.player?.currentTime() ?? .zero).convertScale(1000, method: .default)
  151. playbackSlider.value = Float(time.seconds)
  152. MPNowPlayingInfoCenter.default().nowPlayingInfo?[MPNowPlayingInfoPropertyElapsedPlaybackTime] = time.seconds
  153. playbackSlider.isEnabled = true
  154. labelCurrentTime.text = NCUtility.shared.stringFromTime(time)
  155. labelLeftTime.text = "-" + NCUtility.shared.stringFromTime(ncplayer.durationTime - time)
  156. // BACK
  157. backButton.setImage(NCUtility.shared.loadImage(named: "gobackward.10", color: .white), for: .normal)
  158. backButton.isEnabled = true
  159. // PLAY
  160. if ncplayer.isPlay() {
  161. MPNowPlayingInfoCenter.default().nowPlayingInfo?[MPNowPlayingInfoPropertyPlaybackRate] = 1
  162. } else {
  163. MPNowPlayingInfoCenter.default().nowPlayingInfo?[MPNowPlayingInfoPropertyPlaybackRate] = 0
  164. }
  165. let namedPlay = ncplayer.isPlay() ? "pause.fill" : "play.fill"
  166. playButton.setImage(NCUtility.shared.loadImage(named: namedPlay, color: .white, symbolConfiguration: UIImage.SymbolConfiguration(pointSize: 30)), for: .normal)
  167. playButton.isEnabled = true
  168. // FORWARD
  169. forwardButton.setImage(NCUtility.shared.loadImage(named: "goforward.10", color: .white), for: .normal)
  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. ncplayer?.playerPlay()
  181. startTimerAutoHide()
  182. break
  183. }
  184. case .oldDeviceUnavailable:
  185. if let previousRoute = userInfo[AVAudioSessionRouteChangePreviousRouteKey] as? AVAudioSessionRouteDescription {
  186. for output in previousRoute.outputs where output.portType == AVAudioSession.Port.headphones {
  187. print("headphones disconnected")
  188. ncplayer?.playerPause()
  189. ncplayer?.saveCurrentTime()
  190. break
  191. }
  192. }
  193. default: ()
  194. }
  195. }
  196. @objc func handleInterruption(notification: Notification) {
  197. guard let userInfo = notification.userInfo, let typeValue = userInfo[AVAudioSessionInterruptionTypeKey] as? UInt, let type = AVAudioSession.InterruptionType(rawValue: typeValue) else { return }
  198. if type == .began {
  199. print("Interruption began")
  200. } else if type == .ended {
  201. if let optionsValue = userInfo[AVAudioSessionInterruptionOptionKey] as? UInt {
  202. let options = AVAudioSession.InterruptionOptions(rawValue: optionsValue)
  203. if options.contains(.shouldResume) {
  204. print("Interruption Ended - playback should resume")
  205. ncplayer?.playerPlay()
  206. startTimerAutoHide()
  207. } else {
  208. print("Interruption Ended - playback should NOT resume")
  209. }
  210. }
  211. }
  212. }
  213. // MARK: -
  214. public func show(enableTimerAutoHide: Bool = false) {
  215. guard let metadata = self.metadata, ncplayer != nil, !metadata.livePhoto else { return }
  216. if metadata.classFile != NKCommon.TypeClassFile.video.rawValue && metadata.classFile != NKCommon.TypeClassFile.audio.rawValue { return }
  217. #if MFFFLIB
  218. if MFFF.shared.existsMFFFSession(url: URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView))) {
  219. self.hide()
  220. return
  221. }
  222. #endif
  223. timerAutoHide?.invalidate()
  224. if enableTimerAutoHide {
  225. startTimerAutoHide()
  226. }
  227. if !self.isHidden { return }
  228. UIView.animate(withDuration: 0.3, animations: {
  229. self.alpha = 1
  230. }, completion: { (_: Bool) in
  231. self.isHidden = false
  232. })
  233. updateToolBar()
  234. }
  235. func isShow() -> Bool {
  236. return !self.isHidden
  237. }
  238. public func hide() {
  239. UIView.animate(withDuration: 0.3, animations: {
  240. self.alpha = 0
  241. }, completion: { (_: Bool) in
  242. self.isHidden = true
  243. })
  244. }
  245. @objc private func automaticHide() {
  246. if let metadata = self.metadata {
  247. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterHidePlayerToolBar, userInfo: ["ocId": metadata.ocId])
  248. }
  249. }
  250. private func startTimerAutoHide() {
  251. timerAutoHide?.invalidate()
  252. timerAutoHide = Timer.scheduledTimer(timeInterval: timerAutoHideSeconds, target: self, selector: #selector(automaticHide), userInfo: nil, repeats: false)
  253. }
  254. private func reStartTimerAutoHide() {
  255. if let timerAutoHide = timerAutoHide, timerAutoHide.isValid {
  256. startTimerAutoHide()
  257. }
  258. }
  259. func skip(seconds: Float64) {
  260. guard let ncplayer = ncplayer, let player = ncplayer.player else { return }
  261. let currentTime = player.currentTime()
  262. var newTime: CMTime = .zero
  263. let timeToAdd: CMTime = CMTimeMakeWithSeconds(abs(seconds), preferredTimescale: 1)
  264. if seconds > 0 {
  265. newTime = CMTimeAdd(currentTime, timeToAdd)
  266. if newTime < ncplayer.durationTime {
  267. ncplayer.videoSeek(time: newTime)
  268. } else if newTime >= ncplayer.durationTime {
  269. let timeToSubtract: CMTime = CMTimeMakeWithSeconds(3, preferredTimescale: 1)
  270. newTime = CMTimeSubtract(ncplayer.durationTime, timeToSubtract)
  271. if newTime > currentTime {
  272. ncplayer.videoSeek(time: newTime)
  273. }
  274. }
  275. } else {
  276. newTime = CMTimeSubtract(currentTime, timeToAdd)
  277. if newTime.seconds < 0 {
  278. newTime = .zero
  279. }
  280. ncplayer.videoSeek(time: newTime)
  281. }
  282. updateToolBar()
  283. reStartTimerAutoHide()
  284. }
  285. func isPictureInPictureActive() -> Bool {
  286. if let pictureInPictureController = self.pictureInPictureController, pictureInPictureController.isPictureInPictureActive {
  287. return true
  288. } else {
  289. return false
  290. }
  291. }
  292. func stopTimerAutoHide() {
  293. timerAutoHide?.invalidate()
  294. }
  295. // MARK: - Event / Gesture
  296. @objc func onSliderValChanged(slider: UISlider, event: UIEvent) {
  297. if let touchEvent = event.allTouches?.first, let ncplayer = ncplayer {
  298. let seconds: Int64 = Int64(self.playbackSlider.value)
  299. let targetTime: CMTime = CMTimeMake(value: seconds, timescale: 1)
  300. switch touchEvent.phase {
  301. case .began:
  302. wasInPlay = ncplayer.isPlay()
  303. ncplayer.playerPause()
  304. playbackSliderEvent = .began
  305. case .moved:
  306. ncplayer.videoSeek(time: targetTime)
  307. playbackSliderEvent = .moved
  308. case .ended:
  309. ncplayer.videoSeek(time: targetTime)
  310. if wasInPlay {
  311. ncplayer.playerPlay()
  312. }
  313. playbackSliderEvent = .ended
  314. default:
  315. break
  316. }
  317. reStartTimerAutoHide()
  318. }
  319. }
  320. // MARK: - Action
  321. @objc func tapTopToolBarWith(gestureRecognizer: UITapGestureRecognizer) { }
  322. @objc func tapToolBarWith(gestureRecognizer: UITapGestureRecognizer) { }
  323. @IBAction func tapPlayerPause(_ sender: Any) {
  324. if ncplayer?.player?.timeControlStatus == .playing {
  325. CCUtility.setPlayerPlay(false)
  326. ncplayer?.playerPause()
  327. ncplayer?.saveCurrentTime()
  328. timerAutoHide?.invalidate()
  329. } else if ncplayer?.player?.timeControlStatus == .paused {
  330. CCUtility.setPlayerPlay(true)
  331. ncplayer?.playerPlay()
  332. startTimerAutoHide()
  333. } else if ncplayer?.player?.timeControlStatus == .waitingToPlayAtSpecifiedRate {
  334. print("timeControlStatus.waitingToPlayAtSpecifiedRate")
  335. if let reason = ncplayer?.player?.reasonForWaitingToPlay {
  336. switch reason {
  337. case .evaluatingBufferingRate:
  338. self.ncplayer?.player?.playImmediately(atRate: 1)
  339. print("reasonForWaitingToPlay.evaluatingBufferingRate")
  340. case .toMinimizeStalls:
  341. print("reasonForWaitingToPlay.toMinimizeStalls")
  342. case .noItemToPlay:
  343. print("reasonForWaitingToPlay.noItemToPlay")
  344. default:
  345. print("Unknown \(reason)")
  346. }
  347. }
  348. }
  349. }
  350. @IBAction func tapMute(_ sender: Any) {
  351. let mute = CCUtility.getAudioMute()
  352. CCUtility.setAudioMute(!mute)
  353. ncplayer?.player?.isMuted = !mute
  354. updateToolBar()
  355. reStartTimerAutoHide()
  356. }
  357. @IBAction func tapPip(_ sender: Any) {
  358. guard let videoLayer = ncplayer?.videoLayer else { return }
  359. if let pictureInPictureController = self.pictureInPictureController, pictureInPictureController.isPictureInPictureActive {
  360. pictureInPictureController.stopPictureInPicture()
  361. }
  362. if pictureInPictureController == nil {
  363. pictureInPictureController = AVPictureInPictureController(playerLayer: videoLayer)
  364. pictureInPictureController?.delegate = self
  365. }
  366. if let pictureInPictureController = pictureInPictureController, pictureInPictureController.isPictureInPicturePossible, let metadata = self.metadata {
  367. DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
  368. pictureInPictureController.startPictureInPicture()
  369. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterHidePlayerToolBar, userInfo: ["ocId": metadata.ocId])
  370. }
  371. }
  372. }
  373. @IBAction func tapForward(_ sender: Any) {
  374. skip(seconds: 10)
  375. }
  376. @IBAction func tapBack(_ sender: Any) {
  377. skip(seconds: -10)
  378. }
  379. @IBAction func tapSubtitle(_ sender: Any) {
  380. self.ncplayer?.showAlertSubtitles()
  381. }
  382. func forward() {
  383. var index: Int = 0
  384. if let currentIndex = self.viewerMediaPage?.currentIndex, let metadatas = self.viewerMediaPage?.metadatas, let ncplayer = self.ncplayer {
  385. if currentIndex == metadatas.count - 1 {
  386. index = 0
  387. } else {
  388. index = currentIndex + 1
  389. }
  390. self.viewerMediaPage?.goTo(index: index, direction: .forward, autoPlay: ncplayer.isPlay())
  391. }
  392. }
  393. func backward() {
  394. var index: Int = 0
  395. if let currentIndex = self.viewerMediaPage?.currentIndex, let metadatas = self.viewerMediaPage?.metadatas, let ncplayer = self.ncplayer {
  396. if currentIndex == 0 {
  397. index = metadatas.count - 1
  398. } else {
  399. index = currentIndex - 1
  400. }
  401. self.viewerMediaPage?.goTo(index: index, direction: .reverse, autoPlay: ncplayer.isPlay())
  402. }
  403. }
  404. }
  405. extension NCPlayerToolBar: AVPictureInPictureControllerDelegate {
  406. func pictureInPictureControllerDidStopPictureInPicture(_ pictureInPictureController: AVPictureInPictureController) {
  407. if let metadata = self.metadata, let ncplayer = self.ncplayer, !ncplayer.isPlay() {
  408. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterShowPlayerToolBar, userInfo: ["ocId": metadata.ocId, "enableTimerAutoHide": false])
  409. }
  410. }
  411. }