NCPlayer.swift 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  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 {
  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. if let observerAVPlayerItemDidPlayToEndTime = self.observerAVPlayerItemDidPlayToEndTime {
  147. NotificationCenter.default.removeObserver(observerAVPlayerItemDidPlayToEndTime)
  148. }
  149. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterApplicationDidEnterBackground), object: nil)
  150. self.videoLayer?.removeFromSuperlayer()
  151. self.videoLayer = nil
  152. self.observerAVPlayerItemDidPlayToEndTime = nil
  153. self.imageVideoContainer = nil
  154. self.playerToolBar = nil
  155. self.metadata = nil
  156. do {
  157. try AVAudioSession.sharedInstance().setActive(false)
  158. } catch {
  159. print(error)
  160. }
  161. }
  162. //MARK: - NotificationCenter
  163. @objc func applicationDidEnterBackground(_ notification: NSNotification) {
  164. if metadata?.classFile == NCCommunicationCommon.typeClassFile.video.rawValue {
  165. if let pictureInPictureController = pictureInPictureController, pictureInPictureController.isPictureInPictureActive { return }
  166. playerPause()
  167. }
  168. }
  169. @objc func applicationDidBecomeActive(_ notification: NSNotification) {
  170. playerToolBar?.updateToolBar()
  171. }
  172. //MARK: -
  173. func isPlay() -> Bool {
  174. if appDelegate.player?.rate == 1 { return true } else { return false }
  175. }
  176. func isPictureInPictureActive() -> Bool {
  177. if let pictureInPictureController = pictureInPictureController, pictureInPictureController.isPictureInPictureActive {
  178. return true
  179. } else {
  180. return false
  181. }
  182. }
  183. func playerPlay() {
  184. appDelegate.player?.play()
  185. }
  186. func playerPause() {
  187. appDelegate.player?.pause()
  188. if let pictureInPictureController = pictureInPictureController, pictureInPictureController.isPictureInPictureActive {
  189. pictureInPictureController.stopPictureInPicture()
  190. }
  191. }
  192. func saveTime(_ time: CMTime) {
  193. guard let metadata = self.metadata else { return }
  194. if metadata.classFile == NCCommunicationCommon.typeClassFile.audio.rawValue { return }
  195. NCManageDatabase.shared.addVideoTime(metadata: metadata, time: time, durationTime: nil)
  196. generatorImagePreview()
  197. }
  198. func saveCurrentTime() {
  199. if let player = appDelegate.player {
  200. saveTime(player.currentTime())
  201. }
  202. }
  203. func videoSeek(time: CMTime) {
  204. appDelegate.player?.seek(to: time)
  205. self.saveTime(time)
  206. }
  207. @objc func generatorImagePreview() {
  208. guard let time = appDelegate.player?.currentTime() else { return }
  209. guard let metadata = self.metadata else { return }
  210. if metadata.livePhoto { return }
  211. if metadata.classFile == NCCommunicationCommon.typeClassFile.audio.rawValue { return }
  212. var image: UIImage?
  213. if let asset = appDelegate.player?.currentItem?.asset {
  214. do {
  215. let fileNamePreviewLocalPath = CCUtility.getDirectoryProviderStoragePreviewOcId(metadata.ocId, etag: metadata.etag)!
  216. let fileNameIconLocalPath = CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag)!
  217. let imageGenerator = AVAssetImageGenerator(asset: asset)
  218. imageGenerator.appliesPreferredTrackTransform = true
  219. let cgImage = try imageGenerator.copyCGImage(at: time, actualTime: nil)
  220. image = UIImage(cgImage: cgImage)
  221. // Update Playing Info Center
  222. if let image = image {
  223. MPNowPlayingInfoCenter.default().nowPlayingInfo?[MPMediaItemPropertyArtwork] = MPMediaItemArtwork(boundsSize: image.size) { size in
  224. return image
  225. }
  226. }
  227. // Preview
  228. if let data = image?.jpegData(compressionQuality: 0.5) {
  229. try data.write(to: URL.init(fileURLWithPath: fileNamePreviewLocalPath), options: .atomic)
  230. }
  231. // Icon
  232. if let data = image?.jpegData(compressionQuality: 0.5) {
  233. try data.write(to: URL.init(fileURLWithPath: fileNameIconLocalPath), options: .atomic)
  234. }
  235. }
  236. catch let error as NSError {
  237. print(error.localizedDescription)
  238. }
  239. }
  240. }
  241. }
  242. extension NCPlayer: AVPictureInPictureControllerDelegate {
  243. func pictureInPictureControllerWillStartPictureInPicture(_ pictureInPictureController: AVPictureInPictureController) {
  244. activeNCPlayer.insert(self)
  245. }
  246. func pictureInPictureControllerDidStartPictureInPicture(_ pictureInPictureController: AVPictureInPictureController) {
  247. // nothing
  248. }
  249. func pictureInPictureControllerWillStopPictureInPicture(_ pictureInPictureController: AVPictureInPictureController) {
  250. //nothing
  251. }
  252. func pictureInPictureControllerDidStopPictureInPicture(_ pictureInPictureController: AVPictureInPictureController) {
  253. guard let metadata = self.metadata else { return }
  254. if !isPlay() {
  255. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterShowPlayerToolBar, userInfo: ["ocId":metadata.ocId, "enableTimerAutoHide": false])
  256. }
  257. }
  258. }