NCPlayerToolBar.swift 20 KB

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