NCPlayer.swift 14 KB

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