NCPlayer.swift 12 KB

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