NCPlayer.swift 15 KB

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