NCPlayer.swift 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  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. internal let appDelegate = UIApplication.shared.delegate as! AppDelegate
  30. internal var url: URL
  31. internal 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. openAVPlayer() { status, error in
  62. switch status {
  63. case .loaded:
  64. if autoPlay {
  65. self.player?.play()
  66. }
  67. break
  68. case .failed:
  69. #if MFFFLIB
  70. self.convertVideo(error: error)
  71. #else
  72. if let title = error?.localizedDescription, let description = error?.localizedFailureReason {
  73. NCContentPresenter.shared.messageNotification(title, description: description, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: NCGlobal.shared.errorGeneric, priority: .max)
  74. } else {
  75. NCContentPresenter.shared.messageNotification("_error_", description: "_error_something_wrong_", delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: NCGlobal.shared.errorGeneric, priority: .max)
  76. }
  77. #endif
  78. break
  79. case .cancelled:
  80. break
  81. default:
  82. break
  83. }
  84. }
  85. }
  86. internal func openAVPlayer(completion: @escaping (_ status: AVKeyValueStatus, _ error: NSError?)->()) {
  87. print("Play URL: \(self.url)")
  88. player = AVPlayer(url: self.url)
  89. playerToolBar?.setMetadata(self.metadata)
  90. if metadata.livePhoto {
  91. player?.isMuted = false
  92. } else if metadata.classFile == NCCommunicationCommon.typeClassFile.audio.rawValue {
  93. player?.isMuted = CCUtility.getAudioMute()
  94. } else {
  95. player?.isMuted = CCUtility.getAudioMute()
  96. if let time = NCManageDatabase.shared.getVideoTime(metadata: metadata) {
  97. player?.seek(to: time)
  98. }
  99. }
  100. player?.currentItem?.asset.loadValuesAsynchronously(forKeys: ["playable"], completionHandler: {
  101. var error: NSError? = nil
  102. let status = self.player?.currentItem?.asset.statusOfValue(forKey: "playable", error: &error) ?? .unknown
  103. DispatchQueue.main.async {
  104. if status == .loaded {
  105. self.durationTime = self.player?.currentItem?.asset.duration ?? .zero
  106. NCManageDatabase.shared.addVideoTime(metadata: self.metadata, time: nil, durationTime: self.durationTime)
  107. self.activateObserver(playerToolBar: self.playerToolBar)
  108. self.videoLayer = AVPlayerLayer(player: self.player)
  109. self.videoLayer!.frame = self.imageVideoContainer.bounds
  110. self.videoLayer!.videoGravity = .resizeAspect
  111. if self.metadata.classFile == NCCommunicationCommon.typeClassFile.video.rawValue {
  112. self.imageVideoContainer.layer.addSublayer(self.videoLayer!)
  113. self.imageVideoContainer.playerLayer = self.videoLayer
  114. self.imageVideoContainer.metadata = self.metadata
  115. self.imageVideoContainer.image = self.imageVideoContainer.image?.image(alpha: 0)
  116. }
  117. self.playerToolBar?.setBarPlayer(ncplayer: self)
  118. self.generatorImagePreview()
  119. if !(self.detailView?.isShow() ?? false) {
  120. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterShowPlayerToolBar, userInfo: ["ocId":self.metadata.ocId, "enableTimerAutoHide": false])
  121. }
  122. }
  123. completion(status, error)
  124. }
  125. })
  126. }
  127. deinit {
  128. print("deinit NCPlayer")
  129. deactivateObserver()
  130. }
  131. func activateObserver(playerToolBar: NCPlayerToolBar?) {
  132. self.playerToolBar = playerToolBar
  133. // At end go back to start & show toolbar
  134. observerAVPlayerItemDidPlayToEndTime = NotificationCenter.default.addObserver(forName: .AVPlayerItemDidPlayToEndTime, object: player?.currentItem, queue: .main) { notification in
  135. if let item = notification.object as? AVPlayerItem, let currentItem = self.player?.currentItem, item == currentItem {
  136. NCKTVHTTPCache.shared.saveCache(metadata: self.metadata)
  137. self.videoSeek(time: .zero)
  138. if !(self.detailView?.isShow() ?? false) {
  139. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterShowPlayerToolBar, userInfo: ["ocId": self.metadata.ocId, "enableTimerAutoHide": false])
  140. }
  141. self.playerToolBar?.updateToolBar()
  142. }
  143. }
  144. // Evey 1 second update toolbar
  145. observerAVPlayertTime = player?.addPeriodicTimeObserver(forInterval: CMTimeMakeWithSeconds(1, preferredTimescale: 1), queue: .main, using: { _ in
  146. if self.player?.currentItem?.status == .readyToPlay {
  147. self.playerToolBar?.updateToolBar()
  148. }
  149. })
  150. NotificationCenter.default.addObserver(self, selector: #selector(generatorImagePreview), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterApplicationWillResignActive), object: nil)
  151. NotificationCenter.default.addObserver(self, selector: #selector(applicationDidEnterBackground(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterApplicationDidEnterBackground), object: nil)
  152. NotificationCenter.default.addObserver(self, selector: #selector(applicationDidBecomeActive(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterApplicationDidBecomeActive), object: nil)
  153. NotificationCenter.default.addObserver(self, selector: #selector(playerPause), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterPauseMedia), object: nil)
  154. NotificationCenter.default.addObserver(self, selector: #selector(playerPlay), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterPlayMedia), object: nil)
  155. }
  156. func deactivateObserver() {
  157. if isPlay() {
  158. playerPause()
  159. }
  160. self.playerToolBar = nil
  161. if let observerAVPlayerItemDidPlayToEndTime = self.observerAVPlayerItemDidPlayToEndTime {
  162. NotificationCenter.default.removeObserver(observerAVPlayerItemDidPlayToEndTime)
  163. }
  164. self.observerAVPlayerItemDidPlayToEndTime = nil
  165. if let observerAVPlayertTime = self.observerAVPlayertTime {
  166. player?.removeTimeObserver(observerAVPlayertTime)
  167. }
  168. self.observerAVPlayertTime = nil
  169. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterApplicationWillResignActive), object: nil)
  170. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterApplicationDidEnterBackground), object: nil)
  171. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterApplicationDidBecomeActive), object: nil)
  172. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterPauseMedia), object: nil)
  173. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterPlayMedia), object: nil)
  174. }
  175. // MARK: - NotificationCenter
  176. @objc func applicationDidEnterBackground(_ notification: NSNotification) {
  177. if metadata.classFile == NCCommunicationCommon.typeClassFile.video.rawValue, let playerToolBar = self.playerToolBar {
  178. if !playerToolBar.isPictureInPictureActive() {
  179. playerPause()
  180. }
  181. }
  182. }
  183. @objc func applicationDidBecomeActive(_ notification: NSNotification) {
  184. playerToolBar?.updateToolBar()
  185. }
  186. // MARK: -
  187. func isPlay() -> Bool {
  188. if player?.rate == 1 { return true } else { return false }
  189. }
  190. @objc func playerPlay() {
  191. player?.play()
  192. self.playerToolBar?.updateToolBar()
  193. }
  194. @objc func playerPause() {
  195. player?.pause()
  196. self.playerToolBar?.updateToolBar()
  197. if let playerToolBar = self.playerToolBar, playerToolBar.isPictureInPictureActive() {
  198. playerToolBar.pictureInPictureController?.stopPictureInPicture()
  199. }
  200. }
  201. func videoSeek(time: CMTime) {
  202. player?.seek(to: time)
  203. self.saveTime(time)
  204. }
  205. func saveTime(_ time: CMTime) {
  206. if metadata.classFile == NCCommunicationCommon.typeClassFile.audio.rawValue { return }
  207. NCManageDatabase.shared.addVideoTime(metadata: metadata, time: time, durationTime: nil)
  208. generatorImagePreview()
  209. }
  210. func saveCurrentTime() {
  211. if let player = self.player {
  212. saveTime(player.currentTime())
  213. }
  214. }
  215. @objc func generatorImagePreview() {
  216. guard let time = player?.currentTime(), !metadata.livePhoto, metadata.classFile != NCCommunicationCommon.typeClassFile.audio.rawValue else { return }
  217. var image: UIImage?
  218. if let asset = player?.currentItem?.asset {
  219. do {
  220. let fileNamePreviewLocalPath = CCUtility.getDirectoryProviderStoragePreviewOcId(metadata.ocId, etag: metadata.etag)!
  221. let fileNameIconLocalPath = CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag)!
  222. let imageGenerator = AVAssetImageGenerator(asset: asset)
  223. imageGenerator.appliesPreferredTrackTransform = true
  224. let cgImage = try imageGenerator.copyCGImage(at: time, actualTime: nil)
  225. image = UIImage(cgImage: cgImage)
  226. // Update Playing Info Center
  227. let mediaItemPropertyTitle = MPNowPlayingInfoCenter.default().nowPlayingInfo?[MPMediaItemPropertyTitle] as? String
  228. if let image = image, mediaItemPropertyTitle == metadata.fileNameView {
  229. MPNowPlayingInfoCenter.default().nowPlayingInfo?[MPMediaItemPropertyArtwork] = MPMediaItemArtwork(boundsSize: image.size) { _ in
  230. return image
  231. }
  232. }
  233. // Preview
  234. if let data = image?.jpegData(compressionQuality: 0.5) {
  235. try data.write(to: URL(fileURLWithPath: fileNamePreviewLocalPath), options: .atomic)
  236. }
  237. // Icon
  238. if let data = image?.jpegData(compressionQuality: 0.5) {
  239. try data.write(to: URL(fileURLWithPath: fileNameIconLocalPath), options: .atomic)
  240. }
  241. } catch let error as NSError {
  242. print(error.localizedDescription)
  243. }
  244. }
  245. }
  246. }