NCPlayer.swift 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  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 AVKit
  28. import MediaPlayer
  29. /// The Set of custom player controllers currently using or transitioning out of PiP
  30. private var activeNCPlayer = Set<NCPlayer>()
  31. class NCPlayer: NSObject {
  32. private let appDelegate = UIApplication.shared.delegate as! AppDelegate
  33. private var imageVideoContainer: imageVideoContainerView?
  34. private var playerToolBar: NCPlayerToolBar?
  35. private var detailView: NCViewerMediaDetailView?
  36. private var observerAVPlayerItemDidPlayToEndTime: Any?
  37. private var observerAVPlayertTime: Any?
  38. public var player: AVPlayer?
  39. public var durationTime: CMTime = .zero
  40. public var metadata: tableMetadata?
  41. public var videoLayer: AVPlayerLayer?
  42. public var pictureInPictureController: AVPictureInPictureController?
  43. // MARK: - View Life Cycle
  44. init(url: URL, autoPlay: Bool, imageVideoContainer: imageVideoContainerView?, playerToolBar: NCPlayerToolBar?, metadata: tableMetadata, detailView: NCViewerMediaDetailView?) {
  45. super.init()
  46. var timeSeek: CMTime = .zero
  47. self.metadata = metadata
  48. self.detailView = detailView
  49. do {
  50. try AVAudioSession.sharedInstance().setCategory(.playback)
  51. try AVAudioSession.sharedInstance().overrideOutputAudioPort(AVAudioSession.PortOverride.none)
  52. try AVAudioSession.sharedInstance().setActive(true)
  53. } catch {
  54. print(error)
  55. }
  56. print("Play URL: \(url)")
  57. player = AVPlayer(url: url)
  58. if metadata.livePhoto {
  59. player?.isMuted = false
  60. } else if metadata.classFile == NCCommunicationCommon.typeClassFile.audio.rawValue {
  61. player?.isMuted = CCUtility.getAudioMute()
  62. } else {
  63. player?.isMuted = CCUtility.getAudioMute()
  64. if let time = NCManageDatabase.shared.getVideoTime(metadata: metadata) {
  65. timeSeek = time
  66. }
  67. }
  68. player?.seek(to: timeSeek)
  69. player?.currentItem?.asset.loadValuesAsynchronously(forKeys: ["playable"], completionHandler: {
  70. var error: NSError? = nil
  71. let status = self.player?.currentItem?.asset.statusOfValue(forKey: "playable", error: &error)
  72. switch status {
  73. case .loaded:
  74. DispatchQueue.main.async {
  75. self.activateObserver(playerToolBar: playerToolBar)
  76. if let imageVideoContainer = imageVideoContainer {
  77. self.imageVideoContainer = imageVideoContainer
  78. self.videoLayer = AVPlayerLayer(player: self.player)
  79. self.videoLayer!.frame = imageVideoContainer.bounds
  80. self.videoLayer!.videoGravity = .resizeAspect
  81. if metadata.classFile == NCCommunicationCommon.typeClassFile.video.rawValue {
  82. imageVideoContainer.layer.addSublayer(self.videoLayer!)
  83. imageVideoContainer.playerLayer = self.videoLayer
  84. imageVideoContainer.metadata = self.metadata
  85. if !metadata.livePhoto {
  86. DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
  87. imageVideoContainer.image = imageVideoContainer.image?.image(alpha: 0)
  88. }
  89. }
  90. // PIP
  91. if let playerLayer = self.videoLayer, CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  92. self.pictureInPictureController = AVPictureInPictureController(playerLayer: playerLayer)
  93. self.pictureInPictureController?.delegate = self
  94. }
  95. }
  96. }
  97. self.durationTime = self.player?.currentItem?.asset.duration ?? .zero
  98. NCManageDatabase.shared.addVideoTime(metadata: metadata, time: nil, durationTime: self.durationTime)
  99. if autoPlay {
  100. self.player?.play()
  101. }
  102. self.playerToolBar?.setBarPlayer(ncplayer: self, timeSeek: timeSeek, metadata: metadata, image: imageVideoContainer?.image)
  103. self.generatorImagePreview()
  104. if !(detailView?.isShow() ?? false) {
  105. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterShowPlayerToolBar, userInfo: ["ocId":metadata.ocId, "enableTimerAutoHide": false])
  106. }
  107. }
  108. break
  109. case .failed:
  110. DispatchQueue.main.async {
  111. if let title = error?.localizedDescription, let description = error?.localizedFailureReason {
  112. NCContentPresenter.shared.messageNotification(title, description: description, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: NCGlobal.shared.errorGeneric, forced: false)
  113. } else {
  114. NCContentPresenter.shared.messageNotification("_error_", description: "_error_something_wrong_", delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: NCGlobal.shared.errorGeneric, forced: false)
  115. }
  116. }
  117. break
  118. case .cancelled:
  119. DispatchQueue.main.async {
  120. //do something, show alert, put a placeholder image etc.
  121. }
  122. break
  123. default:
  124. break
  125. }
  126. })
  127. }
  128. deinit {
  129. print("deinit NCPlayer")
  130. }
  131. func activateObserver(playerToolBar: NCPlayerToolBar?) {
  132. guard let metadata = self.metadata else { return }
  133. self.playerToolBar = playerToolBar
  134. // At end go back to start & show toolbar
  135. observerAVPlayerItemDidPlayToEndTime = NotificationCenter.default.addObserver(forName: .AVPlayerItemDidPlayToEndTime, object: player?.currentItem, queue: .main) { (notification) in
  136. if let item = notification.object as? AVPlayerItem, let currentItem = self.player?.currentItem, item == currentItem {
  137. NCKTVHTTPCache.shared.saveCache(metadata: metadata)
  138. self.videoSeek(time: .zero)
  139. if !(self.detailView?.isShow() ?? false) {
  140. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterShowPlayerToolBar, userInfo: ["ocId":metadata.ocId, "enableTimerAutoHide": false])
  141. }
  142. self.playerToolBar?.updateToolBar(commandCenter: true)
  143. }
  144. }
  145. // Evey 1 second update toolbar
  146. observerAVPlayertTime = player?.addPeriodicTimeObserver(forInterval: CMTimeMakeWithSeconds(1, preferredTimescale: 1), queue: .main, using: { (CMTime) in
  147. if self.player?.currentItem?.status == .readyToPlay {
  148. self.playerToolBar?.updateToolBar()
  149. }
  150. })
  151. NotificationCenter.default.addObserver(self, selector: #selector(generatorImagePreview), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterApplicationWillResignActive), object: nil)
  152. NotificationCenter.default.addObserver(self, selector: #selector(applicationDidEnterBackground(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterApplicationDidEnterBackground), object: nil)
  153. NotificationCenter.default.addObserver(self, selector: #selector(applicationDidBecomeActive(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterApplicationDidBecomeActive), object: nil)
  154. }
  155. func deactivateObserver(livePhoto: Bool) {
  156. if isPlay() {
  157. playerPause()
  158. }
  159. self.playerToolBar?.disableCommandCenter()
  160. self.playerToolBar = nil
  161. if livePhoto {
  162. self.videoLayer?.removeFromSuperlayer()
  163. self.videoLayer = nil
  164. }
  165. if let observerAVPlayerItemDidPlayToEndTime = self.observerAVPlayerItemDidPlayToEndTime {
  166. NotificationCenter.default.removeObserver(observerAVPlayerItemDidPlayToEndTime)
  167. }
  168. self.observerAVPlayerItemDidPlayToEndTime = nil
  169. if let observerAVPlayertTime = self.observerAVPlayertTime {
  170. player?.removeTimeObserver(observerAVPlayertTime)
  171. }
  172. self.observerAVPlayertTime = nil
  173. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterApplicationWillResignActive), object: nil)
  174. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterApplicationDidEnterBackground), object: nil)
  175. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterApplicationDidBecomeActive), object: nil)
  176. }
  177. //MARK: - NotificationCenter
  178. @objc func applicationDidEnterBackground(_ notification: NSNotification) {
  179. if metadata?.classFile == NCCommunicationCommon.typeClassFile.video.rawValue {
  180. if let pictureInPictureController = pictureInPictureController, pictureInPictureController.isPictureInPictureActive { return }
  181. playerPause()
  182. }
  183. }
  184. @objc func applicationDidBecomeActive(_ notification: NSNotification) {
  185. playerToolBar?.updateToolBar()
  186. }
  187. //MARK: -
  188. func isPlay() -> Bool {
  189. if player?.rate == 1 { return true } else { return false }
  190. }
  191. func isPictureInPictureActive() -> Bool {
  192. if let pictureInPictureController = pictureInPictureController, pictureInPictureController.isPictureInPictureActive {
  193. return true
  194. } else {
  195. return false
  196. }
  197. }
  198. func playerPlay() {
  199. player?.play()
  200. self.playerToolBar?.updateToolBar()
  201. }
  202. func playerPause() {
  203. player?.pause()
  204. self.playerToolBar?.updateToolBar()
  205. if let pictureInPictureController = pictureInPictureController, pictureInPictureController.isPictureInPictureActive {
  206. pictureInPictureController.stopPictureInPicture()
  207. }
  208. }
  209. func videoSeek(time: CMTime) {
  210. player?.seek(to: time)
  211. self.saveTime(time)
  212. }
  213. func saveTime(_ time: CMTime) {
  214. guard let metadata = self.metadata else { return }
  215. if metadata.classFile == NCCommunicationCommon.typeClassFile.audio.rawValue { return }
  216. NCManageDatabase.shared.addVideoTime(metadata: metadata, time: time, durationTime: nil)
  217. generatorImagePreview()
  218. }
  219. func saveCurrentTime() {
  220. if let player = self.player {
  221. saveTime(player.currentTime())
  222. }
  223. }
  224. @objc func generatorImagePreview() {
  225. guard let time = player?.currentTime() else { return }
  226. guard let metadata = self.metadata else { return }
  227. if metadata.livePhoto { return }
  228. if metadata.classFile == NCCommunicationCommon.typeClassFile.audio.rawValue { return }
  229. var image: UIImage?
  230. if let asset = player?.currentItem?.asset {
  231. do {
  232. let fileNamePreviewLocalPath = CCUtility.getDirectoryProviderStoragePreviewOcId(metadata.ocId, etag: metadata.etag)!
  233. let fileNameIconLocalPath = CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag)!
  234. let imageGenerator = AVAssetImageGenerator(asset: asset)
  235. imageGenerator.appliesPreferredTrackTransform = true
  236. let cgImage = try imageGenerator.copyCGImage(at: time, actualTime: nil)
  237. image = UIImage(cgImage: cgImage)
  238. // Update Playing Info Center
  239. let mediaItemPropertyTitle = MPNowPlayingInfoCenter.default().nowPlayingInfo?[MPMediaItemPropertyTitle] as? String
  240. if let image = image, mediaItemPropertyTitle == metadata.fileNameView {
  241. MPNowPlayingInfoCenter.default().nowPlayingInfo?[MPMediaItemPropertyArtwork] = MPMediaItemArtwork(boundsSize: image.size) { size in
  242. return image
  243. }
  244. }
  245. // Preview
  246. if let data = image?.jpegData(compressionQuality: 0.5) {
  247. try data.write(to: URL.init(fileURLWithPath: fileNamePreviewLocalPath), options: .atomic)
  248. }
  249. // Icon
  250. if let data = image?.jpegData(compressionQuality: 0.5) {
  251. try data.write(to: URL.init(fileURLWithPath: fileNameIconLocalPath), options: .atomic)
  252. }
  253. }
  254. catch let error as NSError {
  255. print(error.localizedDescription)
  256. }
  257. }
  258. }
  259. }
  260. extension NCPlayer: AVPictureInPictureControllerDelegate {
  261. func pictureInPictureControllerWillStartPictureInPicture(_ pictureInPictureController: AVPictureInPictureController) {
  262. activeNCPlayer.insert(self)
  263. }
  264. func pictureInPictureControllerDidStartPictureInPicture(_ pictureInPictureController: AVPictureInPictureController) {
  265. // nothing
  266. }
  267. func pictureInPictureControllerWillStopPictureInPicture(_ pictureInPictureController: AVPictureInPictureController) {
  268. //nothing
  269. }
  270. func pictureInPictureControllerDidStopPictureInPicture(_ pictureInPictureController: AVPictureInPictureController) {
  271. guard let metadata = self.metadata else { return }
  272. if !isPlay() {
  273. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterShowPlayerToolBar, userInfo: ["ocId":metadata.ocId, "enableTimerAutoHide": false])
  274. }
  275. }
  276. }