NCPlayer.swift 12 KB

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