NCPlayer.swift 13 KB

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