NCPlayerToolBar.swift 19 KB

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