NCPlayer.swift 12 KB

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