NCPlayer.swift 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  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 AVFoundation
  27. import MediaPlayer
  28. import JGProgressHUD
  29. import Alamofire
  30. import MobileVLCKit
  31. class NCPlayer: NSObject {
  32. internal let appDelegate = UIApplication.shared.delegate as! AppDelegate
  33. internal var url: URL?
  34. internal weak var playerToolBar: NCPlayerToolBar?
  35. internal weak var viewController: UIViewController?
  36. private weak var imageVideoContainer: imageVideoContainerView?
  37. private weak var detailView: NCViewerMediaDetailView?
  38. private weak var viewerMediaPage: NCViewerMediaPage?
  39. var player: VLCMediaPlayer?
  40. var metadata: tableMetadata
  41. var singleTapGestureRecognizer: UITapGestureRecognizer!
  42. // MARK: - View Life Cycle
  43. init(imageVideoContainer: imageVideoContainerView, playerToolBar: NCPlayerToolBar?, metadata: tableMetadata, detailView: NCViewerMediaDetailView?, viewController: UIViewController, viewerMediaPage: NCViewerMediaPage?) {
  44. self.imageVideoContainer = imageVideoContainer
  45. self.playerToolBar = playerToolBar
  46. self.metadata = metadata
  47. self.detailView = detailView
  48. self.viewController = viewController
  49. self.viewerMediaPage = viewerMediaPage
  50. super.init()
  51. do {
  52. try AVAudioSession.sharedInstance().setCategory(.playback)
  53. try AVAudioSession.sharedInstance().overrideOutputAudioPort(AVAudioSession.PortOverride.none)
  54. try AVAudioSession.sharedInstance().setActive(true)
  55. } catch {
  56. print(error)
  57. }
  58. }
  59. deinit {
  60. print("deinit NCPlayer with ocId \(metadata.ocId)")
  61. player?.stop()
  62. if let playerToolBar = self.playerToolBar, playerToolBar.isPictureInPictureActive() {
  63. playerToolBar.pictureInPictureController?.stopPictureInPicture()
  64. }
  65. }
  66. func openAVPlayer(url: URL) {
  67. var position: Float = 0
  68. self.url = url
  69. self.singleTapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(didSingleTapWith(gestureRecognizer:)))
  70. #if MFFFLIB
  71. MFFF.shared.setDelegate = self
  72. MFFF.shared.dismissMessage()
  73. NotificationCenter.default.addObserver(self, selector: #selector(convertVideoDidFinish(_:)), name: NSNotification.Name(rawValue: self.metadata.ocId), object: nil)
  74. if CCUtility.fileProviderStorageExists(metadata) {
  75. self.url = URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: NCGlobal.shared.fileNameVideoEncoded))
  76. self.isProxy = false
  77. }
  78. if MFFF.shared.existsMFFFSession(url: URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView))) {
  79. return
  80. }
  81. #endif
  82. print("Play URL: \(url)")
  83. player = VLCMediaPlayer()
  84. player?.media = VLCMedia(url: url)
  85. player?.delegate = self
  86. player?.media?.addOption("--network-caching=10000")
  87. let volume = CCUtility.getAudioVolume()
  88. if metadata.livePhoto {
  89. player?.audio?.volume = 0
  90. } else if metadata.classFile == NKCommon.TypeClassFile.audio.rawValue {
  91. player?.audio?.volume = Int32(volume)
  92. } else {
  93. player?.audio?.volume = Int32(volume)
  94. if let result = NCManageDatabase.shared.getVideoPosition(metadata: metadata) {
  95. position = result
  96. player?.position = position
  97. }
  98. }
  99. player?.drawable = self.imageVideoContainer
  100. if let view = player?.drawable as? UIView {
  101. view.isUserInteractionEnabled = true
  102. view.addGestureRecognizer(singleTapGestureRecognizer)
  103. }
  104. if NCManageDatabase.shared.getVideoAutoplay(metadata: metadata) {
  105. playerPlay()
  106. playerToolBar?.show(enableTimerAutoHide: true)
  107. } else {
  108. playerToolBar?.show(enableTimerAutoHide: false)
  109. }
  110. playerToolBar?.setBarPlayer(ncplayer: self, position: position)
  111. playerToolBar?.setMetadata(self.metadata)
  112. }
  113. func deactivatePlayer() {
  114. playerPause()
  115. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterApplicationWillResignActive), object: nil)
  116. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterApplicationDidEnterBackground), object: nil)
  117. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterApplicationDidBecomeActive), object: nil)
  118. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterPauseMedia), object: nil)
  119. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterPlayMedia), object: nil)
  120. }
  121. // MARK: - UIGestureRecognizerDelegate
  122. @objc func didSingleTapWith(gestureRecognizer: UITapGestureRecognizer) {
  123. viewerMediaPage?.didSingleTapWith(gestureRecognizer: gestureRecognizer)
  124. }
  125. // MARK: - NotificationCenter
  126. @objc func applicationDidEnterBackground(_ notification: NSNotification) {
  127. if metadata.classFile == NKCommon.TypeClassFile.video.rawValue, let playerToolBar = self.playerToolBar {
  128. if !playerToolBar.isPictureInPictureActive() {
  129. playerPause()
  130. }
  131. }
  132. }
  133. @objc func applicationDidBecomeActive(_ notification: NSNotification) {
  134. playerToolBar?.update(position: player?.position)
  135. }
  136. // MARK: -
  137. func isPlay() -> Bool {
  138. return player?.isPlaying ?? false
  139. }
  140. @objc func playerPlay() {
  141. player?.play()
  142. if let position = NCManageDatabase.shared.getVideoPosition(metadata: self.metadata) {
  143. player?.position = position
  144. }
  145. playerToolBar?.update(position: player?.position)
  146. }
  147. @objc func playerPause() {
  148. player?.pause()
  149. playerToolBar?.update(position: player?.position)
  150. if let playerToolBar = self.playerToolBar, playerToolBar.isPictureInPictureActive() {
  151. playerToolBar.pictureInPictureController?.stopPictureInPicture()
  152. }
  153. }
  154. func videoSeek(position: Float) {
  155. player?.position = position
  156. playerToolBar?.update(position: position)
  157. }
  158. func savePosition(_ position: Float) {
  159. if metadata.classFile == NKCommon.TypeClassFile.audio.rawValue { return }
  160. let length = Int(player?.media?.length.intValue ?? 0)
  161. NCManageDatabase.shared.addVideo(metadata: metadata, position: position, length: length, autoplay: isPlay())
  162. }
  163. internal func downloadVideo(isEncrypted: Bool = false, requiredConvert: Bool = false) {
  164. guard let view = appDelegate.window?.rootViewController?.view else { return }
  165. let serverUrlFileName = metadata.serverUrl + "/" + metadata.fileName
  166. let fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileName)!
  167. let hud = JGProgressHUD()
  168. var downloadRequest: DownloadRequest?
  169. hud.indicatorView = JGProgressHUDRingIndicatorView()
  170. if let indicatorView = hud.indicatorView as? JGProgressHUDRingIndicatorView {
  171. indicatorView.ringWidth = 1.5
  172. }
  173. hud.textLabel.text = NSLocalizedString(metadata.fileNameView, comment: "")
  174. hud.detailTextLabel.text = NSLocalizedString("_tap_to_cancel_", comment: "")
  175. hud.show(in: view)
  176. hud.tapOnHUDViewBlock = { hud in
  177. downloadRequest?.cancel()
  178. }
  179. NextcloudKit.shared.download(serverUrlFileName: serverUrlFileName, fileNameLocalPath: fileNameLocalPath) { request in
  180. downloadRequest = request
  181. } taskHandler: { task in
  182. // task
  183. } progressHandler: { progress in
  184. hud.progress = Float(progress.fractionCompleted)
  185. } completionHandler: { _, _, _, _, _, afError, error in
  186. if afError == nil {
  187. NCManageDatabase.shared.addLocalFile(metadata: self.metadata)
  188. if isEncrypted {
  189. if let result = NCManageDatabase.shared.getE2eEncryption(predicate: NSPredicate(format: "fileNameIdentifier == %@ AND serverUrl == %@", self.metadata.fileName, self.metadata.serverUrl)) {
  190. NCEndToEndEncryption.sharedManager()?.decryptFile(self.metadata.fileName, fileNameView: self.metadata.fileNameView, ocId: self.metadata.ocId, key: result.key, initializationVector: result.initializationVector, authenticationTag: result.authenticationTag)
  191. }
  192. }
  193. if CCUtility.fileProviderStorageExists(self.metadata) || self.metadata.isDirectoryE2EE {
  194. let url = URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(self.metadata.ocId, fileNameView: self.metadata.fileNameView))
  195. if requiredConvert {
  196. #if MFFFLIB
  197. self.convertVideo(withAlert: false)
  198. #endif
  199. } else {
  200. self.openAVPlayer(url: url)
  201. }
  202. }
  203. }
  204. hud.dismiss()
  205. }
  206. }
  207. }
  208. extension NCPlayer: VLCMediaPlayerDelegate {
  209. func mediaPlayerStateChanged(_ aNotification: Notification) {
  210. guard let player = self.player else { return }
  211. switch player.state {
  212. case .stopped:
  213. if let url = self.url {
  214. NCManageDatabase.shared.addVideo(metadata: metadata, position: 0, autoplay: false)
  215. if !(self.detailView?.isShow() ?? false) {
  216. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterShowPlayerToolBar, userInfo: ["ocId": self.metadata.ocId, "enableTimerAutoHide": false])
  217. }
  218. self.openAVPlayer(url: url)
  219. }
  220. print("Played mode: STOPPED")
  221. break
  222. case .opening:
  223. print("Played mode: OPENING")
  224. break
  225. case .buffering:
  226. print("Played mode: BUFFERING")
  227. break
  228. case .ended:
  229. print("Played mode: ENDED")
  230. playerToolBar?.update(position: player.position)
  231. break
  232. case .error:
  233. print("Played mode: ERROR")
  234. break
  235. case .playing:
  236. print("Played mode: PLAYING")
  237. playerToolBar?.update(position: player.position)
  238. break
  239. case .paused:
  240. print("Played mode: PAUSED")
  241. playerToolBar?.update(position: player.position)
  242. break
  243. default: break
  244. }
  245. print(player.state)
  246. }
  247. func mediaPlayerTimeChanged(_ aNotification: Notification) {
  248. self.playerToolBar?.update(position: player?.position)
  249. }
  250. func mediaPlayerTitleChanged(_ aNotification: Notification) {
  251. guard let player = self.player else { return }
  252. print(".")
  253. }
  254. func mediaPlayerChapterChanged(_ aNotification: Notification) {
  255. guard let player = self.player else { return }
  256. print(".")
  257. }
  258. func mediaPlayerLoudnessChanged(_ aNotification: Notification) {
  259. guard let player = self.player else { return }
  260. print(".")
  261. }
  262. func mediaPlayerSnapshot(_ aNotification: Notification) {
  263. guard let player = self.player else { return }
  264. print(".")
  265. }
  266. func mediaPlayerStartedRecording(_ player: VLCMediaPlayer) {
  267. // Handle other states...
  268. }
  269. func mediaPlayer(_ player: VLCMediaPlayer, recordingStoppedAtPath path: String) {
  270. // Handle other states...
  271. }
  272. }