NCPlayer.swift 18 KB

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