NCPlayer.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  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. if metadata.isVideo {
  81. player.drawable = imageVideoContainer
  82. if let view = player.drawable as? UIView, let singleTapGestureRecognizer = singleTapGestureRecognizer {
  83. view.isUserInteractionEnabled = true
  84. view.addGestureRecognizer(singleTapGestureRecognizer)
  85. }
  86. }
  87. player.play()
  88. player.position = position
  89. if autoplay {
  90. pauseAfterPlay = false
  91. } else {
  92. pauseAfterPlay = true
  93. }
  94. playerToolBar?.setBarPlayer(position: position, ncplayer: self, metadata: metadata, viewerMediaPage: viewerMediaPage)
  95. NotificationCenter.default.addObserver(self, selector: #selector(applicationDidEnterBackground(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterApplicationDidEnterBackground), object: nil)
  96. }
  97. func restartAVPlayer(position: Float, pauseAfterPlay: Bool) {
  98. if let url = self.url, !player.isPlaying {
  99. player.media = VLCMedia(url: url)
  100. player.position = position
  101. playerToolBar?.setBarPlayer(position: position)
  102. viewerMediaPage?.changeScreenMode(mode: .normal)
  103. self.pauseAfterPlay = pauseAfterPlay
  104. player.play()
  105. if metadata.isVideo {
  106. if position == 0 {
  107. let fileNamePreviewLocalPath = CCUtility.getDirectoryProviderStoragePreviewOcId(metadata.ocId, etag: metadata.etag)!
  108. imageVideoContainer?.image = UIImage(contentsOfFile: fileNamePreviewLocalPath)
  109. } else {
  110. imageVideoContainer?.image = nil
  111. }
  112. }
  113. }
  114. }
  115. // MARK: - UIGestureRecognizerDelegate
  116. @objc func didSingleTapWith(gestureRecognizer: UITapGestureRecognizer) {
  117. changeScreenMode()
  118. }
  119. func changeScreenMode() {
  120. guard let viewerMediaPage = viewerMediaPage else { return }
  121. if viewerMediaScreenMode == .full {
  122. viewerMediaPage.changeScreenMode(mode: .normal)
  123. } else {
  124. viewerMediaPage.changeScreenMode(mode: .full)
  125. }
  126. }
  127. // MARK: - NotificationCenter
  128. @objc func applicationDidEnterBackground(_ notification: NSNotification) {
  129. if metadata.isVideo {
  130. playerPause()
  131. }
  132. }
  133. // MARK: -
  134. func isPlay() -> Bool {
  135. return player.isPlaying
  136. }
  137. func playerPlay() {
  138. playerToolBar?.playbackSliderEvent = .began
  139. if let result = NCManageDatabase.shared.getVideo(metadata: metadata), let position = result.position {
  140. player.position = position
  141. playerToolBar?.playbackSliderEvent = .moved
  142. }
  143. player.play()
  144. DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
  145. self.playerToolBar?.playbackSliderEvent = .ended
  146. }
  147. }
  148. @objc func playerStop() {
  149. player.stop()
  150. }
  151. @objc func playerPause() {
  152. savePosition()
  153. player.pause()
  154. }
  155. func playerPosition(_ position: Float) {
  156. NCManageDatabase.shared.addVideo(metadata: metadata, position: position)
  157. player.position = position
  158. }
  159. func savePosition() {
  160. guard metadata.isVideo, isPlay() else { return }
  161. NCManageDatabase.shared.addVideo(metadata: metadata, position: player.position)
  162. }
  163. func jumpForward(_ seconds: Int32) {
  164. player.play()
  165. player.jumpForward(seconds)
  166. }
  167. func jumpBackward(_ seconds: Int32) {
  168. player.play()
  169. player.jumpBackward(seconds)
  170. }
  171. }
  172. extension NCPlayer: VLCMediaPlayerDelegate {
  173. func mediaPlayerStateChanged(_ aNotification: Notification) {
  174. if player.state == .buffering && player.isPlaying {
  175. activityIndicator.startAnimating()
  176. } else {
  177. activityIndicator.stopAnimating()
  178. }
  179. switch player.state {
  180. case .stopped:
  181. playerToolBar?.playButtonPlay()
  182. print("Played mode: STOPPED")
  183. break
  184. case .opening:
  185. print("Played mode: OPENING")
  186. break
  187. case .buffering:
  188. print("Played mode: BUFFERING")
  189. break
  190. case .ended:
  191. NCManageDatabase.shared.addVideo(metadata: self.metadata, position: 0)
  192. DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
  193. if let playRepeat = self.playerToolBar?.playRepeat {
  194. self.restartAVPlayer(position: 0, pauseAfterPlay: !playRepeat)
  195. }
  196. }
  197. playerToolBar?.playButtonPlay()
  198. print("Played mode: ENDED")
  199. break
  200. case .error:
  201. let error = NKError(errorCode: NCGlobal.shared.errorInternalError, errorDescription: "_error_something_wrong_")
  202. NCContentPresenter.shared.showError(error: error, priority: .max)
  203. playerToolBar?.removeFromSuperview()
  204. print("Played mode: ERROR")
  205. break
  206. case .playing:
  207. guard let playerToolBar = playerToolBar else { return }
  208. if playerToolBar.playerButtonView.isHidden {
  209. playerToolBar.playerButtonView.isHidden = false
  210. viewerMediaPage?.changeScreenMode(mode: .normal)
  211. }
  212. if pauseAfterPlay {
  213. player.pause()
  214. pauseAfterPlay = false
  215. self.viewerMediaPage?.updateCommandCenter(ncplayer: self, title: metadata.fileNameView)
  216. } else {
  217. playerToolBar.playButtonPause()
  218. // Set track audio/subtitle
  219. let data = NCManageDatabase.shared.getVideo(metadata: metadata)
  220. if let currentAudioTrackIndex = data?.currentAudioTrackIndex {
  221. player.currentAudioTrackIndex = Int32(currentAudioTrackIndex)
  222. }
  223. if let currentVideoSubTitleIndex = data?.currentVideoSubTitleIndex {
  224. player.currentVideoSubTitleIndex = Int32(currentVideoSubTitleIndex)
  225. }
  226. }
  227. let size = player.videoSize
  228. if let mediaLength = player.media?.length.intValue {
  229. self.length = Int(mediaLength)
  230. }
  231. self.width = Int(size.width)
  232. self.height = Int(size.height)
  233. playerToolBar.updateTopToolBar(videoSubTitlesIndexes: player.videoSubTitlesIndexes, audioTrackIndexes: player.audioTrackIndexes)
  234. NCManageDatabase.shared.addVideo(metadata: metadata, width: self.width, height: self.height, length: self.length)
  235. print("Played mode: PLAYING")
  236. break
  237. case .paused:
  238. playerToolBar?.playButtonPlay()
  239. print("Played mode: PAUSED")
  240. break
  241. default: break
  242. }
  243. }
  244. func mediaPlayerTimeChanged(_ aNotification: Notification) {
  245. activityIndicator.stopAnimating()
  246. playerToolBar?.update()
  247. }
  248. func mediaPlayerTitleChanged(_ aNotification: Notification) {
  249. // Handle other states...
  250. }
  251. func mediaPlayerChapterChanged(_ aNotification: Notification) {
  252. // Handle other states...
  253. }
  254. func mediaPlayerLoudnessChanged(_ aNotification: Notification) {
  255. // Handle other states...
  256. }
  257. func mediaPlayerSnapshot(_ aNotification: Notification) {
  258. // Handle other states...
  259. }
  260. func mediaPlayerStartedRecording(_ player: VLCMediaPlayer) {
  261. // Handle other states...
  262. }
  263. func mediaPlayer(_ player: VLCMediaPlayer, recordingStoppedAtPath path: String) {
  264. // Handle other states...
  265. }
  266. }
  267. extension NCPlayer: VLCMediaThumbnailerDelegate {
  268. func mediaThumbnailerDidTimeOut(_ mediaThumbnailer: VLCMediaThumbnailer) { }
  269. func mediaThumbnailer(_ mediaThumbnailer: VLCMediaThumbnailer, didFinishThumbnail thumbnail: CGImage) { }
  270. }