NCPlayer.swift 15 KB

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