NCPlayer.swift 13 KB

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