NCPlayer.swift 13 KB

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