NCPlayer.swift 12 KB

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