NCPlayer.swift 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  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 dialogProvider: VLCDialogProvider?
  32. internal var metadata: tableMetadata
  33. internal var singleTapGestureRecognizer: UITapGestureRecognizer?
  34. internal var activityIndicator: UIActivityIndicatorView
  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: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterApplicationDidEnterBackground), 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 = NCManageDatabase.shared.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: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterApplicationDidEnterBackground), 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. let fileNamePreviewLocalPath = CCUtility.getDirectoryProviderStoragePreviewOcId(metadata.ocId, etag: metadata.etag)!
  111. imageVideoContainer?.image = UIImage(contentsOfFile: fileNamePreviewLocalPath)
  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 isPlay() -> Bool {
  138. return player.isPlaying
  139. }
  140. func playerPlay() {
  141. playerToolBar?.playbackSliderEvent = .began
  142. if let result = NCManageDatabase.shared.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. NCManageDatabase.shared.addVideo(metadata: metadata, position: position)
  161. player.position = position
  162. }
  163. func savePosition() {
  164. guard metadata.isVideo, isPlay() else { return }
  165. NCManageDatabase.shared.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. print("Played mode: STOPPED")
  187. break
  188. case .opening:
  189. print("Played mode: OPENING")
  190. break
  191. case .buffering:
  192. print("Played mode: BUFFERING")
  193. break
  194. case .ended:
  195. NCManageDatabase.shared.addVideo(metadata: self.metadata, position: 0)
  196. DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
  197. if let playRepeat = self.playerToolBar?.playRepeat {
  198. self.restartAVPlayer(position: 0, pauseAfterPlay: !playRepeat)
  199. }
  200. }
  201. playerToolBar?.playButtonPlay()
  202. print("Played mode: ENDED")
  203. break
  204. case .error:
  205. print("Played mode: ERROR")
  206. break
  207. case .playing:
  208. guard let playerToolBar = playerToolBar else { return }
  209. if playerToolBar.playerButtonView.isHidden {
  210. playerToolBar.playerButtonView.isHidden = false
  211. viewerMediaPage?.changeScreenMode(mode: .normal)
  212. }
  213. if pauseAfterPlay {
  214. player.pause()
  215. pauseAfterPlay = false
  216. self.viewerMediaPage?.updateCommandCenter(ncplayer: self, title: metadata.fileNameView)
  217. } else {
  218. playerToolBar.playButtonPause()
  219. // Set track audio/subtitle
  220. let data = NCManageDatabase.shared.getVideo(metadata: metadata)
  221. if let currentAudioTrackIndex = data?.currentAudioTrackIndex {
  222. player.currentAudioTrackIndex = Int32(currentAudioTrackIndex)
  223. }
  224. if let currentVideoSubTitleIndex = data?.currentVideoSubTitleIndex {
  225. player.currentVideoSubTitleIndex = Int32(currentVideoSubTitleIndex)
  226. }
  227. }
  228. let size = player.videoSize
  229. if let mediaLength = player.media?.length.intValue {
  230. self.length = Int(mediaLength)
  231. }
  232. self.width = Int(size.width)
  233. self.height = Int(size.height)
  234. playerToolBar.updateTopToolBar(videoSubTitlesIndexes: player.videoSubTitlesIndexes, audioTrackIndexes: player.audioTrackIndexes)
  235. NCManageDatabase.shared.addVideo(metadata: metadata, width: self.width, height: self.height, length: self.length)
  236. print("Played mode: PLAYING")
  237. break
  238. case .paused:
  239. playerToolBar?.playButtonPlay()
  240. print("Played mode: PAUSED")
  241. break
  242. default: break
  243. }
  244. }
  245. func mediaPlayerTimeChanged(_ aNotification: Notification) {
  246. activityIndicator.stopAnimating()
  247. playerToolBar?.update()
  248. }
  249. }
  250. extension NCPlayer: VLCMediaThumbnailerDelegate {
  251. func mediaThumbnailerDidTimeOut(_ mediaThumbnailer: VLCMediaThumbnailer) { }
  252. func mediaThumbnailer(_ mediaThumbnailer: VLCMediaThumbnailer, didFinishThumbnail thumbnail: CGImage) { }
  253. }
  254. extension NCPlayer: VLCCustomDialogRendererProtocol {
  255. func showError(withTitle error: String, message: String) {
  256. let alert = UIAlertController(title: error, message: message, preferredStyle: .alert)
  257. alert.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { _ in
  258. self.playerToolBar?.removeFromSuperview()
  259. self.viewerMediaPage?.viewUnload()
  260. }))
  261. self.viewerMediaPage?.present(alert, animated: true)
  262. }
  263. func showLogin(withTitle title: String, message: String, defaultUsername username: String?, askingForStorage: Bool, withReference reference: NSValue) {
  264. // UIAlertController other states...
  265. }
  266. func showQuestion(withTitle title: String, message: String, type questionType: VLCDialogQuestionType, cancel cancelString: String?, action1String: String?, action2String: String?, withReference reference: NSValue) {
  267. let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
  268. if let action1String = action1String {
  269. alert.addAction(UIAlertAction(title: action1String, style: .default, handler: { _ in
  270. self.dialogProvider?.postAction(1, forDialogReference: reference)
  271. }))
  272. }
  273. if let action2String = action2String {
  274. alert.addAction(UIAlertAction(title: action2String, style: .default, handler: { _ in
  275. self.dialogProvider?.postAction(2, forDialogReference: reference)
  276. }))
  277. }
  278. if let cancelString = cancelString {
  279. alert.addAction(UIAlertAction(title: cancelString, style: .cancel, handler: { _ in
  280. self.dialogProvider?.postAction(3, forDialogReference: reference)
  281. }))
  282. }
  283. self.viewerMediaPage?.present(alert, animated: true)
  284. }
  285. func showProgress(withTitle title: String, message: String, isIndeterminate: Bool, position: Float, cancel cancelString: String?, withReference reference: NSValue) {
  286. // UIAlertController other states...
  287. }
  288. func updateProgress(withReference reference: NSValue, message: String?, position: Float) {
  289. // UIAlertController other states...
  290. }
  291. func cancelDialog(withReference reference: NSValue) {
  292. // UIAlertController other states...
  293. }
  294. }