NCPlayer.swift 13 KB

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