NCPlayer.swift 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  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 NCCommunication
  25. import UIKit
  26. import AVFoundation
  27. import MediaPlayer
  28. import JGProgressHUD
  29. import Alamofire
  30. class NCPlayer: NSObject {
  31. internal let appDelegate = UIApplication.shared.delegate as! AppDelegate
  32. internal var url: URL
  33. internal var playerToolBar: NCPlayerToolBar?
  34. internal var viewController: UIViewController
  35. internal var autoPlay: Bool
  36. internal var isProxy: Bool
  37. private var imageVideoContainer: imageVideoContainerView
  38. private var detailView: NCViewerMediaDetailView?
  39. private var observerAVPlayerItemDidPlayToEndTime: Any?
  40. private var observerAVPlayertTime: Any?
  41. public var player: AVPlayer?
  42. public var durationTime: CMTime = .zero
  43. public var metadata: tableMetadata
  44. public var videoLayer: AVPlayerLayer?
  45. // MARK: - View Life Cycle
  46. init(url: URL, autoPlay: Bool, isProxy: Bool, imageVideoContainer: imageVideoContainerView, playerToolBar: NCPlayerToolBar?, metadata: tableMetadata, detailView: NCViewerMediaDetailView?, viewController: UIViewController) {
  47. self.url = url
  48. self.autoPlay = autoPlay
  49. self.isProxy = isProxy
  50. self.imageVideoContainer = imageVideoContainer
  51. self.playerToolBar = playerToolBar
  52. self.metadata = metadata
  53. self.detailView = detailView
  54. self.viewController = viewController
  55. super.init()
  56. do {
  57. try AVAudioSession.sharedInstance().setCategory(.playback)
  58. try AVAudioSession.sharedInstance().overrideOutputAudioPort(AVAudioSession.PortOverride.none)
  59. try AVAudioSession.sharedInstance().setActive(true)
  60. } catch {
  61. print(error)
  62. }
  63. startSession()
  64. }
  65. internal func startSession() {
  66. #if MFFFLIB
  67. if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: NCGlobal.shared.fileNameVideoEncoded) {
  68. self.url = URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: NCGlobal.shared.fileNameVideoEncoded))
  69. }
  70. if MFFF.shared.existsMFFFSession(url: URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView))) {
  71. return
  72. } else {
  73. MFFF.shared.dismissMessage()
  74. }
  75. #endif
  76. openAVPlayer() { status, error in
  77. switch status {
  78. case .loaded:
  79. if self.autoPlay {
  80. self.player?.play()
  81. }
  82. break
  83. case .failed:
  84. #if MFFFLIB
  85. self.convertVideo(error: error)
  86. #else
  87. if self.isProxy && NCKTVHTTPCache.shared.getDownloadStatusCode(metadata: self.metadata) == 200 && error?.code != AVError.Code.fileFormatNotRecognized.rawValue {
  88. let alertController = UIAlertController(title: NSLocalizedString("_error_", value: "Error", comment: ""), message: NSLocalizedString("_video_not_streamed_", comment: ""), preferredStyle: .alert)
  89. alertController.addAction(UIAlertAction(title: NSLocalizedString("_yes_", value: "Yes", comment: ""), style: .default, handler: { action in
  90. self.downloadVideo(metadata: self.metadata, view: self.viewController.view) { error in
  91. let urlVideo = NCKTVHTTPCache.shared.getVideoURL(metadata: self.metadata)
  92. if error == nil, let url = urlVideo.url {
  93. self.url = url
  94. self.isProxy = urlVideo.isProxy
  95. self.startSession()
  96. }
  97. }
  98. }))
  99. alertController.addAction(UIAlertAction(title: NSLocalizedString("_no_", value: "No", comment: ""), style: .default, handler: { action in
  100. // nothing
  101. }))
  102. self.viewController.present(alertController, animated: true)
  103. self.playerToolBar?.hide()
  104. } else {
  105. if let title = error?.localizedDescription, let description = error?.localizedFailureReason {
  106. NCContentPresenter.shared.messageNotification(title, description: description, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: NCGlobal.shared.errorGeneric, priority: .max)
  107. } else {
  108. NCContentPresenter.shared.messageNotification("_error_", description: "_error_something_wrong_", delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: NCGlobal.shared.errorGeneric, priority: .max)
  109. }
  110. }
  111. #endif
  112. break
  113. case .cancelled:
  114. break
  115. default:
  116. break
  117. }
  118. }
  119. }
  120. internal func openAVPlayer(completion: @escaping (_ status: AVKeyValueStatus, _ error: NSError?)->()) {
  121. print("Play URL: \(self.url)")
  122. player = AVPlayer(url: self.url)
  123. playerToolBar?.setMetadata(self.metadata)
  124. if metadata.livePhoto {
  125. player?.isMuted = false
  126. } else if metadata.classFile == NCCommunicationCommon.typeClassFile.audio.rawValue {
  127. player?.isMuted = CCUtility.getAudioMute()
  128. } else {
  129. player?.isMuted = CCUtility.getAudioMute()
  130. if let time = NCManageDatabase.shared.getVideoTime(metadata: metadata) {
  131. player?.seek(to: time)
  132. }
  133. }
  134. player?.currentItem?.asset.loadValuesAsynchronously(forKeys: ["playable"], completionHandler: {
  135. var error: NSError? = nil
  136. let status = self.player?.currentItem?.asset.statusOfValue(forKey: "playable", error: &error) ?? .unknown
  137. DispatchQueue.main.async {
  138. if status == .loaded {
  139. self.durationTime = self.player?.currentItem?.asset.duration ?? .zero
  140. NCManageDatabase.shared.addVideoTime(metadata: self.metadata, time: nil, durationTime: self.durationTime)
  141. self.activateObserver(playerToolBar: self.playerToolBar)
  142. self.videoLayer = AVPlayerLayer(player: self.player)
  143. self.videoLayer!.frame = self.imageVideoContainer.bounds
  144. self.videoLayer!.videoGravity = .resizeAspect
  145. if self.metadata.classFile == NCCommunicationCommon.typeClassFile.video.rawValue {
  146. self.imageVideoContainer.layer.addSublayer(self.videoLayer!)
  147. self.imageVideoContainer.playerLayer = self.videoLayer
  148. self.imageVideoContainer.metadata = self.metadata
  149. self.imageVideoContainer.image = self.imageVideoContainer.image?.image(alpha: 0)
  150. }
  151. self.playerToolBar?.setBarPlayer(ncplayer: self)
  152. self.generatorImagePreview()
  153. if !(self.detailView?.isShow() ?? false) {
  154. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterShowPlayerToolBar, userInfo: ["ocId":self.metadata.ocId, "enableTimerAutoHide": false])
  155. }
  156. }
  157. completion(status, error)
  158. }
  159. })
  160. }
  161. internal func downloadVideo(metadata: tableMetadata, view: UIView, completion: @escaping (_ error: AFError?)->()) {
  162. let serverUrlFileName = metadata.serverUrl + "/" + metadata.fileName
  163. let fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)!
  164. let hud = JGProgressHUD()
  165. var downloadRequest: DownloadRequest?
  166. hud.indicatorView = JGProgressHUDRingIndicatorView()
  167. if let indicatorView = hud.indicatorView as? JGProgressHUDRingIndicatorView {
  168. indicatorView.ringWidth = 1.5
  169. }
  170. hud.show(in: view)
  171. hud.textLabel.text = NSLocalizedString(metadata.fileNameView, comment: "")
  172. hud.detailTextLabel.text = NSLocalizedString("_tap_to_cancel_", comment: "")
  173. hud.tapOnHUDViewBlock = { hud in
  174. downloadRequest?.cancel()
  175. hud.dismiss()
  176. }
  177. NCCommunication.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: { account, etag, date, lenght, allHeaderFields, error, errorCode, _ in
  184. if error == nil {
  185. NCManageDatabase.shared.addLocalFile(metadata: metadata)
  186. CCUtility.setExif(metadata) { _, _, _, _, _ in }
  187. }
  188. hud.dismiss()
  189. completion(error)
  190. }
  191. }
  192. deinit {
  193. print("deinit NCPlayer")
  194. deactivateObserver()
  195. }
  196. func activateObserver(playerToolBar: NCPlayerToolBar?) {
  197. self.playerToolBar = playerToolBar
  198. // At end go back to start & show toolbar
  199. observerAVPlayerItemDidPlayToEndTime = NotificationCenter.default.addObserver(forName: .AVPlayerItemDidPlayToEndTime, object: player?.currentItem, queue: .main) { notification in
  200. if let item = notification.object as? AVPlayerItem, let currentItem = self.player?.currentItem, item == currentItem {
  201. NCKTVHTTPCache.shared.saveCache(metadata: self.metadata)
  202. self.videoSeek(time: .zero)
  203. if !(self.detailView?.isShow() ?? false) {
  204. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterShowPlayerToolBar, userInfo: ["ocId": self.metadata.ocId, "enableTimerAutoHide": false])
  205. }
  206. self.playerToolBar?.updateToolBar()
  207. }
  208. }
  209. // Evey 1 second update toolbar
  210. observerAVPlayertTime = player?.addPeriodicTimeObserver(forInterval: CMTimeMakeWithSeconds(1, preferredTimescale: 1), queue: .main, using: { _ in
  211. if self.player?.currentItem?.status == .readyToPlay {
  212. self.playerToolBar?.updateToolBar()
  213. }
  214. })
  215. NotificationCenter.default.addObserver(self, selector: #selector(generatorImagePreview), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterApplicationWillResignActive), object: nil)
  216. NotificationCenter.default.addObserver(self, selector: #selector(applicationDidEnterBackground(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterApplicationDidEnterBackground), object: nil)
  217. NotificationCenter.default.addObserver(self, selector: #selector(applicationDidBecomeActive(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterApplicationDidBecomeActive), object: nil)
  218. NotificationCenter.default.addObserver(self, selector: #selector(playerPause), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterPauseMedia), object: nil)
  219. NotificationCenter.default.addObserver(self, selector: #selector(playerPlay), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterPlayMedia), object: nil)
  220. }
  221. func deactivateObserver() {
  222. if isPlay() {
  223. playerPause()
  224. }
  225. self.playerToolBar = nil
  226. if let observerAVPlayerItemDidPlayToEndTime = self.observerAVPlayerItemDidPlayToEndTime {
  227. NotificationCenter.default.removeObserver(observerAVPlayerItemDidPlayToEndTime)
  228. }
  229. self.observerAVPlayerItemDidPlayToEndTime = nil
  230. if let observerAVPlayertTime = self.observerAVPlayertTime {
  231. player?.removeTimeObserver(observerAVPlayertTime)
  232. }
  233. self.observerAVPlayertTime = nil
  234. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterApplicationWillResignActive), object: nil)
  235. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterApplicationDidEnterBackground), object: nil)
  236. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterApplicationDidBecomeActive), object: nil)
  237. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterPauseMedia), object: nil)
  238. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterPlayMedia), object: nil)
  239. }
  240. // MARK: - NotificationCenter
  241. @objc func applicationDidEnterBackground(_ notification: NSNotification) {
  242. if metadata.classFile == NCCommunicationCommon.typeClassFile.video.rawValue, let playerToolBar = self.playerToolBar {
  243. if !playerToolBar.isPictureInPictureActive() {
  244. playerPause()
  245. }
  246. }
  247. }
  248. @objc func applicationDidBecomeActive(_ notification: NSNotification) {
  249. playerToolBar?.updateToolBar()
  250. }
  251. // MARK: -
  252. func isPlay() -> Bool {
  253. if player?.rate == 1 { return true } else { return false }
  254. }
  255. @objc func playerPlay() {
  256. player?.play()
  257. self.playerToolBar?.updateToolBar()
  258. }
  259. @objc func playerPause() {
  260. player?.pause()
  261. self.playerToolBar?.updateToolBar()
  262. if let playerToolBar = self.playerToolBar, playerToolBar.isPictureInPictureActive() {
  263. playerToolBar.pictureInPictureController?.stopPictureInPicture()
  264. }
  265. }
  266. func videoSeek(time: CMTime) {
  267. player?.seek(to: time)
  268. self.saveTime(time)
  269. }
  270. func saveTime(_ time: CMTime) {
  271. if metadata.classFile == NCCommunicationCommon.typeClassFile.audio.rawValue { return }
  272. NCManageDatabase.shared.addVideoTime(metadata: metadata, time: time, durationTime: nil)
  273. generatorImagePreview()
  274. }
  275. func saveCurrentTime() {
  276. if let player = self.player {
  277. saveTime(player.currentTime())
  278. }
  279. }
  280. @objc func generatorImagePreview() {
  281. guard let time = player?.currentTime(), !metadata.livePhoto, metadata.classFile != NCCommunicationCommon.typeClassFile.audio.rawValue else { return }
  282. var image: UIImage?
  283. if let asset = player?.currentItem?.asset {
  284. do {
  285. let fileNamePreviewLocalPath = CCUtility.getDirectoryProviderStoragePreviewOcId(metadata.ocId, etag: metadata.etag)!
  286. let fileNameIconLocalPath = CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag)!
  287. let imageGenerator = AVAssetImageGenerator(asset: asset)
  288. imageGenerator.appliesPreferredTrackTransform = true
  289. let cgImage = try imageGenerator.copyCGImage(at: time, actualTime: nil)
  290. image = UIImage(cgImage: cgImage)
  291. // Update Playing Info Center
  292. let mediaItemPropertyTitle = MPNowPlayingInfoCenter.default().nowPlayingInfo?[MPMediaItemPropertyTitle] as? String
  293. if let image = image, mediaItemPropertyTitle == metadata.fileNameView {
  294. MPNowPlayingInfoCenter.default().nowPlayingInfo?[MPMediaItemPropertyArtwork] = MPMediaItemArtwork(boundsSize: image.size) { _ in
  295. return image
  296. }
  297. }
  298. // Preview
  299. if let data = image?.jpegData(compressionQuality: 0.5) {
  300. try data.write(to: URL(fileURLWithPath: fileNamePreviewLocalPath), options: .atomic)
  301. }
  302. // Icon
  303. if let data = image?.jpegData(compressionQuality: 0.5) {
  304. try data.write(to: URL(fileURLWithPath: fileNameIconLocalPath), options: .atomic)
  305. }
  306. } catch let error as NSError {
  307. print(error.localizedDescription)
  308. }
  309. }
  310. }
  311. }