NCPlayer.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  1. //
  2. // NCPlayer.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 UIKit
  26. import MobileVLCKit
  27. class NCPlayer: NSObject {
  28. internal let appDelegate = UIApplication.shared.delegate as! AppDelegate
  29. internal var url: URL?
  30. internal var player = VLCMediaPlayer()
  31. internal var metadata: tableMetadata
  32. internal var singleTapGestureRecognizer: UITapGestureRecognizer?
  33. internal var activityIndicator: UIActivityIndicatorView
  34. internal var width: Int?
  35. internal var height: Int?
  36. internal var length: Int?
  37. internal var pauseAfterPlay: Bool = false
  38. internal weak var playerToolBar: NCPlayerToolBar?
  39. internal weak var viewerMediaPage: NCViewerMediaPage?
  40. weak var imageVideoContainer: UIImageView?
  41. internal var counterSeconds: Double = 0
  42. // MARK: - View Life Cycle
  43. init(imageVideoContainer: UIImageView, playerToolBar: NCPlayerToolBar?, metadata: tableMetadata, viewerMediaPage: NCViewerMediaPage?) {
  44. self.imageVideoContainer = imageVideoContainer
  45. self.playerToolBar = playerToolBar
  46. self.metadata = metadata
  47. self.viewerMediaPage = viewerMediaPage
  48. self.activityIndicator = UIActivityIndicatorView(style: .large)
  49. self.activityIndicator.color = .white
  50. self.activityIndicator.hidesWhenStopped = true
  51. self.activityIndicator.translatesAutoresizingMaskIntoConstraints = false
  52. if let viewerMediaPage = viewerMediaPage {
  53. viewerMediaPage.view.addSubview(activityIndicator)
  54. NSLayoutConstraint.activate([
  55. activityIndicator.centerXAnchor.constraint(equalTo: viewerMediaPage.view.centerXAnchor),
  56. activityIndicator.centerYAnchor.constraint(equalTo: viewerMediaPage.view.centerYAnchor)
  57. ])
  58. }
  59. super.init()
  60. }
  61. deinit {
  62. player.stop()
  63. print("deinit NCPlayer with ocId \(metadata.ocId)")
  64. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterApplicationDidEnterBackground), object: nil)
  65. }
  66. func openAVPlayer(url: URL, autoplay: Bool = false) {
  67. var position: Float = 0
  68. let userAgent = CCUtility.getUserAgent()!
  69. self.url = url
  70. self.singleTapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(didSingleTapWith(gestureRecognizer:)))
  71. print("Play URL: \(url)")
  72. player.media = VLCMedia(url: url)
  73. player.delegate = self
  74. // player?.media?.addOption("--network-caching=500")
  75. player.media?.addOption(":http-user-agent=\(userAgent)")
  76. if let result = NCManageDatabase.shared.getVideo(metadata: metadata),
  77. let resultPosition = result.position {
  78. position = resultPosition
  79. }
  80. player.drawable = imageVideoContainer
  81. if let view = player.drawable as? UIView, let singleTapGestureRecognizer = singleTapGestureRecognizer {
  82. view.isUserInteractionEnabled = true
  83. view.addGestureRecognizer(singleTapGestureRecognizer)
  84. }
  85. player.play()
  86. player.position = position
  87. if autoplay {
  88. pauseAfterPlay = false
  89. } else {
  90. pauseAfterPlay = true
  91. }
  92. playerToolBar?.setBarPlayer(position: position, ncplayer: self, metadata: metadata, viewerMediaPage: viewerMediaPage)
  93. NotificationCenter.default.addObserver(self, selector: #selector(applicationDidEnterBackground(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterApplicationDidEnterBackground), object: nil)
  94. }
  95. func restartAVPlayer(position: Float, pauseAfterPlay: Bool) {
  96. if let url = self.url, !player.isPlaying {
  97. player.media = VLCMedia(url: url)
  98. player.position = position
  99. playerToolBar?.setBarPlayer(position: position)
  100. viewerMediaPage?.changeScreenMode(mode: .normal)
  101. self.pauseAfterPlay = pauseAfterPlay
  102. player.play()
  103. if position == 0 {
  104. let fileNamePreviewLocalPath = CCUtility.getDirectoryProviderStoragePreviewOcId(metadata.ocId, etag: metadata.etag)!
  105. imageVideoContainer?.image = UIImage(contentsOfFile: fileNamePreviewLocalPath)
  106. } else {
  107. imageVideoContainer?.image = nil
  108. }
  109. }
  110. }
  111. // MARK: - UIGestureRecognizerDelegate
  112. @objc func didSingleTapWith(gestureRecognizer: UITapGestureRecognizer) {
  113. changeScreenMode()
  114. }
  115. func changeScreenMode() {
  116. guard let viewerMediaPage = viewerMediaPage else { return }
  117. if viewerMediaScreenMode == .full {
  118. viewerMediaPage.changeScreenMode(mode: .normal)
  119. } else {
  120. viewerMediaPage.changeScreenMode(mode: .full)
  121. }
  122. }
  123. // MARK: - NotificationCenter
  124. @objc func applicationDidEnterBackground(_ notification: NSNotification) {
  125. if metadata.isVideo {
  126. playerPause()
  127. }
  128. }
  129. // MARK: -
  130. func isPlay() -> Bool {
  131. return player.isPlaying
  132. }
  133. func playerPlay() {
  134. playerToolBar?.playbackSliderEvent = .began
  135. if let result = NCManageDatabase.shared.getVideo(metadata: metadata), let position = result.position {
  136. player.position = position
  137. playerToolBar?.playbackSliderEvent = .moved
  138. }
  139. player.play()
  140. DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
  141. self.playerToolBar?.playbackSliderEvent = .ended
  142. }
  143. }
  144. @objc func playerStop() {
  145. player.stop()
  146. }
  147. @objc func playerPause() {
  148. savePosition()
  149. player.pause()
  150. }
  151. func playerPosition(_ position: Float) {
  152. NCManageDatabase.shared.addVideo(metadata: metadata, position: position)
  153. player.position = position
  154. }
  155. func savePosition() {
  156. guard metadata.isVideo, isPlay() else { return }
  157. NCManageDatabase.shared.addVideo(metadata: metadata, position: player.position)
  158. }
  159. func jumpForward(_ seconds: Int32) {
  160. player.play()
  161. player.jumpForward(seconds)
  162. }
  163. func jumpBackward(_ seconds: Int32) {
  164. player.play()
  165. player.jumpBackward(seconds)
  166. }
  167. }
  168. extension NCPlayer: VLCMediaPlayerDelegate {
  169. func mediaPlayerStateChanged(_ aNotification: Notification) {
  170. if player.state == .buffering && player.isPlaying {
  171. activityIndicator.startAnimating()
  172. } else {
  173. activityIndicator.stopAnimating()
  174. }
  175. switch player.state {
  176. case .stopped:
  177. playerToolBar?.playButtonPlay()
  178. print("Played mode: STOPPED")
  179. break
  180. case .opening:
  181. print("Played mode: OPENING")
  182. break
  183. case .buffering:
  184. print("Played mode: BUFFERING")
  185. break
  186. case .ended:
  187. NCManageDatabase.shared.addVideo(metadata: self.metadata, position: 0)
  188. DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
  189. if let playRepeat = self.playerToolBar?.playRepeat {
  190. self.restartAVPlayer(position: 0, pauseAfterPlay: !playRepeat)
  191. }
  192. }
  193. playerToolBar?.playButtonPlay()
  194. print("Played mode: ENDED")
  195. break
  196. case .error:
  197. let error = NKError(errorCode: NCGlobal.shared.errorInternalError, errorDescription: "_error_something_wrong_")
  198. NCContentPresenter.shared.showError(error: error, priority: .max)
  199. playerToolBar?.removeFromSuperview()
  200. print("Played mode: ERROR")
  201. break
  202. case .playing:
  203. guard let playerToolBar = playerToolBar else { return }
  204. if playerToolBar.playerButtonView.isHidden {
  205. playerToolBar.playerButtonView.isHidden = false
  206. viewerMediaPage?.changeScreenMode(mode: .normal)
  207. }
  208. if pauseAfterPlay {
  209. player.pause()
  210. pauseAfterPlay = false
  211. self.viewerMediaPage?.updateCommandCenter(ncplayer: self, title: metadata.fileNameView)
  212. } else {
  213. playerToolBar.playButtonPause()
  214. // Set track audio/subtitle
  215. let data = NCManageDatabase.shared.getVideo(metadata: metadata)
  216. if let currentAudioTrackIndex = data?.currentAudioTrackIndex {
  217. player.currentAudioTrackIndex = Int32(currentAudioTrackIndex)
  218. }
  219. if let currentVideoSubTitleIndex = data?.currentVideoSubTitleIndex {
  220. player.currentVideoSubTitleIndex = Int32(currentVideoSubTitleIndex)
  221. }
  222. }
  223. let size = player.videoSize
  224. if let mediaLength = player.media?.length.intValue {
  225. self.length = Int(mediaLength)
  226. }
  227. self.width = Int(size.width)
  228. self.height = Int(size.height)
  229. playerToolBar.updateTopToolBar(videoSubTitlesIndexes: player.videoSubTitlesIndexes, audioTrackIndexes: player.audioTrackIndexes)
  230. NCManageDatabase.shared.addVideo(metadata: metadata, width: self.width, height: self.height, length: self.length)
  231. print("Played mode: PLAYING")
  232. break
  233. case .paused:
  234. playerToolBar?.playButtonPlay()
  235. print("Played mode: PAUSED")
  236. break
  237. default: break
  238. }
  239. }
  240. func mediaPlayerTimeChanged(_ aNotification: Notification) {
  241. activityIndicator.stopAnimating()
  242. playerToolBar?.update()
  243. }
  244. func mediaPlayerTitleChanged(_ aNotification: Notification) {
  245. // Handle other states...
  246. }
  247. func mediaPlayerChapterChanged(_ aNotification: Notification) {
  248. // Handle other states...
  249. }
  250. func mediaPlayerLoudnessChanged(_ aNotification: Notification) {
  251. // Handle other states...
  252. }
  253. func mediaPlayerSnapshot(_ aNotification: Notification) {
  254. // Handle other states...
  255. }
  256. func mediaPlayerStartedRecording(_ player: VLCMediaPlayer) {
  257. // Handle other states...
  258. }
  259. func mediaPlayer(_ player: VLCMediaPlayer, recordingStoppedAtPath path: String) {
  260. // Handle other states...
  261. }
  262. }
  263. extension NCPlayer: VLCMediaThumbnailerDelegate {
  264. func mediaThumbnailerDidTimeOut(_ mediaThumbnailer: VLCMediaThumbnailer) { }
  265. func mediaThumbnailer(_ mediaThumbnailer: VLCMediaThumbnailer, didFinishThumbnail thumbnail: CGImage) { }
  266. }