NCPlayerToolBar.swift 20 KB

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