NCPlayerToolBar.swift 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  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. class NCPlayerToolBar: UIView {
  28. @IBOutlet weak var playerTopToolBarView: UIView!
  29. @IBOutlet weak var pipButton: UIButton!
  30. @IBOutlet weak var muteButton: UIButton!
  31. @IBOutlet weak var playButton: UIButton!
  32. @IBOutlet weak var forwardButton: UIButton!
  33. @IBOutlet weak var backButton: UIButton!
  34. @IBOutlet weak var playbackSlider: UISlider!
  35. @IBOutlet weak var labelOverallDuration: UILabel!
  36. @IBOutlet weak var labelCurrentTime: UILabel!
  37. enum sliderEventType {
  38. case began
  39. case ended
  40. case moved
  41. }
  42. private let appDelegate = UIApplication.shared.delegate as! AppDelegate
  43. private var ncplayer: NCPlayer?
  44. private var wasInPlay: Bool = false
  45. private var playbackSliderEvent: sliderEventType = .ended
  46. private let timeToAdd: CMTime = CMTimeMakeWithSeconds(15, preferredTimescale: 1)
  47. private var durationTime: CMTime = .zero
  48. private var timeObserver: Any?
  49. private var timerAutoHide: Timer?
  50. private var metadata: tableMetadata!
  51. // MARK: - View Life Cycle
  52. override func awakeFromNib() {
  53. super.awakeFromNib()
  54. // for disable gesture of UIPageViewController
  55. let panRecognizer = UIPanGestureRecognizer(target: self, action: nil)
  56. addGestureRecognizer(panRecognizer)
  57. let singleTapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(didSingleTapWith(gestureRecognizer:)))
  58. addGestureRecognizer(singleTapGestureRecognizer)
  59. // self
  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. // Top ToolBar
  67. playerTopToolBarView.layer.cornerRadius = 10
  68. playerTopToolBarView.layer.masksToBounds = true
  69. let blurEffectTopToolBarView = UIVisualEffectView(effect: UIBlurEffect(style: .dark))
  70. blurEffectTopToolBarView.frame = playerTopToolBarView.bounds
  71. blurEffectTopToolBarView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
  72. playerTopToolBarView.insertSubview(blurEffectTopToolBarView, at:0)
  73. pipButton.setImage(NCUtility.shared.loadImage(named: "pip.enter", color: .lightGray), for: .normal)
  74. pipButton.isEnabled = false
  75. muteButton.setImage(NCUtility.shared.loadImage(named: "audioOff", color: .lightGray), for: .normal)
  76. muteButton.isEnabled = false
  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. labelOverallDuration.text = NCUtility.shared.stringFromTime(.zero)
  86. labelOverallDuration.textColor = .lightGray
  87. backButton.setImage(NCUtility.shared.loadImage(named: "gobackward.15", 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.15", color: .lightGray), for: .normal)
  92. forwardButton.isEnabled = false
  93. }
  94. deinit {
  95. print("deinit NCPlayerToolBar")
  96. if self.timeObserver != nil {
  97. appDelegate.player?.removeTimeObserver(self.timeObserver!)
  98. }
  99. }
  100. func setBarPlayer(ncplayer: NCPlayer, timeSeek: CMTime, metadata: tableMetadata) {
  101. self.ncplayer = ncplayer
  102. self.metadata = metadata
  103. if let durationTime = NCManageDatabase.shared.getVideoDurationTime(metadata: ncplayer.metadata) {
  104. self.durationTime = durationTime
  105. playbackSlider.value = 0
  106. playbackSlider.minimumValue = 0
  107. playbackSlider.maximumValue = Float(durationTime.value)
  108. playbackSlider.addTarget(self, action: #selector(onSliderValChanged(slider:event:)), for: .valueChanged)
  109. labelCurrentTime.text = NCUtility.shared.stringFromTime(.zero)
  110. labelOverallDuration.text = "-" + NCUtility.shared.stringFromTime(durationTime)
  111. }
  112. updateToolBar(timeSeek: timeSeek)
  113. self.timeObserver = appDelegate.player?.addPeriodicTimeObserver(forInterval: CMTimeMakeWithSeconds(1, preferredTimescale: 1), queue: .main, using: { (CMTime) in
  114. if self.appDelegate.player?.currentItem?.status == .readyToPlay {
  115. if self.isHidden == false {
  116. self.updateToolBar()
  117. }
  118. }
  119. })
  120. }
  121. public func hide() {
  122. UIView.animate(withDuration: 0.3, animations: {
  123. self.alpha = 0
  124. self.playerTopToolBarView.alpha = 0
  125. }, completion: { (value: Bool) in
  126. self.isHidden = true
  127. self.playerTopToolBarView.isHidden = true
  128. })
  129. }
  130. @objc private func automaticHide() {
  131. if let metadata = self.metadata {
  132. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterHidePlayerToolBar, userInfo: ["ocId":metadata.ocId])
  133. }
  134. }
  135. private func startTimerAutoHide() {
  136. timerAutoHide?.invalidate()
  137. timerAutoHide = Timer.scheduledTimer(timeInterval: 3.5, target: self, selector: #selector(automaticHide), userInfo: nil, repeats: false)
  138. }
  139. private func reStartTimerAutoHide() {
  140. if let timerAutoHide = timerAutoHide, timerAutoHide.isValid {
  141. startTimerAutoHide()
  142. }
  143. }
  144. public func show(enableTimerAutoHide: Bool) {
  145. if metadata.classFile != NCCommunicationCommon.typeClassFile.video.rawValue && metadata.classFile != NCCommunicationCommon.typeClassFile.audio.rawValue { return }
  146. if metadata.livePhoto { return }
  147. timerAutoHide?.invalidate()
  148. if enableTimerAutoHide {
  149. startTimerAutoHide()
  150. }
  151. if !self.isHidden { return }
  152. updateToolBar()
  153. UIView.animate(withDuration: 0.3, animations: {
  154. self.alpha = 1
  155. self.playerTopToolBarView.alpha = 1
  156. }, completion: { (value: Bool) in
  157. self.isHidden = false
  158. self.playerTopToolBarView.isHidden = false
  159. })
  160. }
  161. func isShow() -> Bool {
  162. return !self.isHidden
  163. }
  164. public func updateToolBar(timeSeek: CMTime? = nil) {
  165. var namedPlay = "play.fill"
  166. var currentTime = appDelegate.player?.currentTime() ?? .zero
  167. currentTime = currentTime.convertScale(1000, method: .default)
  168. if CCUtility.getAudioMute() {
  169. muteButton.setImage(NCUtility.shared.loadImage(named: "audioOff", color: .white), for: .normal)
  170. } else {
  171. muteButton.setImage(NCUtility.shared.loadImage(named: "audioOn", color: .white), for: .normal)
  172. }
  173. muteButton.isEnabled = true
  174. if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) && ncplayer?.pictureInPictureController != nil {
  175. pipButton.setImage(NCUtility.shared.loadImage(named: "pip.enter", color: .white), for: .normal)
  176. pipButton.isEnabled = true
  177. } else {
  178. pipButton.setImage(NCUtility.shared.loadImage(named: "pip.enter", color: .gray), for: .normal)
  179. pipButton.isEnabled = false
  180. }
  181. if let ncplayer = ncplayer, ncplayer.isPlay() {
  182. namedPlay = "pause.fill"
  183. }
  184. if timeSeek != nil {
  185. playbackSlider.value = Float(timeSeek!.value)
  186. } else {
  187. playbackSlider.value = Float(currentTime.value)
  188. }
  189. playbackSlider.isEnabled = true
  190. if #available(iOS 13.0, *) {
  191. backButton.setImage(NCUtility.shared.loadImage(named: "gobackward.15", color: .white), for: .normal)
  192. } else {
  193. backButton.setImage(NCUtility.shared.loadImage(named: "gobackward.15", color: .white, size: 30), for: .normal)
  194. }
  195. backButton.isEnabled = true
  196. if #available(iOS 13.0, *) {
  197. playButton.setImage(NCUtility.shared.loadImage(named: namedPlay, color: .white, symbolConfiguration: UIImage.SymbolConfiguration(pointSize: 30)), for: .normal)
  198. } else {
  199. playButton.setImage(NCUtility.shared.loadImage(named: namedPlay, color: .white, size: 30), for: .normal)
  200. }
  201. playButton.isEnabled = true
  202. if #available(iOS 13.0, *) {
  203. forwardButton.setImage(NCUtility.shared.loadImage(named: "goforward.15", color: .white), for: .normal)
  204. } else {
  205. forwardButton.setImage(NCUtility.shared.loadImage(named: "goforward.15", color: .white, size: 30), for: .normal)
  206. }
  207. forwardButton.isEnabled = true
  208. labelCurrentTime.text = NCUtility.shared.stringFromTime(currentTime)
  209. labelOverallDuration.text = "-" + NCUtility.shared.stringFromTime(self.durationTime - currentTime)
  210. }
  211. //MARK: - Event / Gesture
  212. @objc func onSliderValChanged(slider: UISlider, event: UIEvent) {
  213. if let touchEvent = event.allTouches?.first, let ncplayer = ncplayer {
  214. let seconds: Int64 = Int64(self.playbackSlider.value)
  215. let targetTime: CMTime = CMTimeMake(value: seconds, timescale: 1000)
  216. switch touchEvent.phase {
  217. case .began:
  218. wasInPlay = ncplayer.isPlay()
  219. ncplayer.playerPause()
  220. playbackSliderEvent = .began
  221. case .moved:
  222. ncplayer.videoSeek(time: targetTime)
  223. playbackSliderEvent = .moved
  224. case .ended:
  225. ncplayer.videoSeek(time: targetTime)
  226. if wasInPlay {
  227. ncplayer.playerPlay()
  228. }
  229. playbackSliderEvent = .ended
  230. default:
  231. break
  232. }
  233. reStartTimerAutoHide()
  234. }
  235. }
  236. @objc func didSingleTapWith(gestureRecognizer: UITapGestureRecognizer) {
  237. hide()
  238. }
  239. //MARK: - Action
  240. @IBAction func buttonTouchInside(_ sender: UIButton) {
  241. }
  242. @IBAction func playerPause(_ sender: Any) {
  243. if appDelegate.player?.timeControlStatus == .playing {
  244. ncplayer?.playerPause()
  245. ncplayer?.saveCurrentTime()
  246. timerAutoHide?.invalidate()
  247. } else if appDelegate.player?.timeControlStatus == .paused {
  248. ncplayer?.playerPlay()
  249. startTimerAutoHide()
  250. } else if appDelegate.player?.timeControlStatus == .waitingToPlayAtSpecifiedRate {
  251. print("timeControlStatus.waitingToPlayAtSpecifiedRate")
  252. if let reason = appDelegate.player?.reasonForWaitingToPlay {
  253. switch reason {
  254. case .evaluatingBufferingRate:
  255. print("reasonForWaitingToPlay.evaluatingBufferingRate")
  256. case .toMinimizeStalls:
  257. print("reasonForWaitingToPlay.toMinimizeStalls")
  258. case .noItemToPlay:
  259. print("reasonForWaitingToPlay.noItemToPlay")
  260. default:
  261. print("Unknown \(reason)")
  262. }
  263. }
  264. }
  265. }
  266. @IBAction func setMute(_ sender: Any) {
  267. let mute = CCUtility.getAudioMute()
  268. CCUtility.setAudioMute(!mute)
  269. appDelegate.player?.isMuted = !mute
  270. updateToolBar()
  271. reStartTimerAutoHide()
  272. }
  273. @IBAction func setPip(_ sender: Any) {
  274. ncplayer?.pictureInPictureController?.startPictureInPicture()
  275. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterHidePlayerToolBar, userInfo: ["ocId":metadata.ocId])
  276. }
  277. @IBAction func forwardButtonSec(_ sender: Any) {
  278. guard let ncplayer = ncplayer else { return }
  279. guard let player = appDelegate.player else { return }
  280. let currentTime = player.currentTime()
  281. var newTime = CMTimeAdd(currentTime, timeToAdd)
  282. if newTime < durationTime {
  283. ncplayer.videoSeek(time: newTime)
  284. } else if newTime >= durationTime {
  285. let timeToSubtract: CMTime = CMTimeMakeWithSeconds(3, preferredTimescale: 1)
  286. newTime = CMTimeSubtract(durationTime, timeToSubtract)
  287. if newTime > currentTime {
  288. ncplayer.videoSeek(time: newTime)
  289. }
  290. }
  291. reStartTimerAutoHide()
  292. }
  293. @IBAction func backButtonSec(_ sender: Any) {
  294. guard let ncplayer = ncplayer else { return }
  295. guard let player = appDelegate.player else { return }
  296. let currentTime = player.currentTime()
  297. let newTime = CMTimeSubtract(currentTime, timeToAdd)
  298. ncplayer.videoSeek(time: newTime)
  299. reStartTimerAutoHide()
  300. }
  301. }