NCPlayer.swift 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  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. import JGProgressHUD
  29. import Alamofire
  30. class NCPlayer: NSObject {
  31. internal let appDelegate = UIApplication.shared.delegate as! AppDelegate
  32. internal var url: URL
  33. internal weak var playerToolBar: NCPlayerToolBar?
  34. internal weak var viewController: UIViewController?
  35. internal var autoPlay: Bool
  36. internal var isProxy: Bool
  37. internal var isStartPlayer: Bool
  38. private weak var imageVideoContainer: imageVideoContainerView?
  39. private weak var detailView: NCViewerMediaDetailView?
  40. private var observerAVPlayerItemDidPlayToEndTime: Any?
  41. private var observerAVPlayertTime: Any?
  42. private var observerAVPlayertStatus: Any?
  43. public var player: AVPlayer?
  44. public var durationTime: CMTime = .zero
  45. public var metadata: tableMetadata
  46. public var videoLayer: AVPlayerLayer?
  47. public var isSubtitleShowed: Bool = false{
  48. didSet {
  49. self.playerToolBar?.changeSubtitleIconTo(visible: isSubtitleShowed)
  50. }
  51. }
  52. public var subtitleUrls: [URL] = []
  53. // MARK: - View Life Cycle
  54. init(url: URL, autoPlay: Bool, isProxy: Bool, imageVideoContainer: imageVideoContainerView, playerToolBar: NCPlayerToolBar?, metadata: tableMetadata, detailView: NCViewerMediaDetailView?, viewController: UIViewController) {
  55. self.url = url
  56. self.autoPlay = autoPlay
  57. self.isProxy = isProxy
  58. self.isStartPlayer = false
  59. self.imageVideoContainer = imageVideoContainer
  60. self.playerToolBar = playerToolBar
  61. self.metadata = metadata
  62. self.detailView = detailView
  63. self.viewController = viewController
  64. super.init()
  65. do {
  66. try AVAudioSession.sharedInstance().setCategory(.playback)
  67. try AVAudioSession.sharedInstance().overrideOutputAudioPort(AVAudioSession.PortOverride.none)
  68. try AVAudioSession.sharedInstance().setActive(true)
  69. } catch {
  70. print(error)
  71. }
  72. }
  73. deinit {
  74. print("deinit NCPlayer with ocId \(metadata.ocId)")
  75. deactivateObserver()
  76. }
  77. func openAVPlayer() {
  78. #if MFFFLIB
  79. MFFF.shared.setDelegate = self
  80. MFFF.shared.dismissMessage()
  81. NotificationCenter.default.addObserver(self, selector: #selector(convertVideoDidFinish(_:)), name: NSNotification.Name(rawValue: self.metadata.ocId), object: nil)
  82. if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: NCGlobal.shared.fileNameVideoEncoded) {
  83. self.url = URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: NCGlobal.shared.fileNameVideoEncoded))
  84. self.isProxy = false
  85. }
  86. if MFFF.shared.existsMFFFSession(url: URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView))) {
  87. return
  88. }
  89. #endif
  90. // Check already started
  91. if self.isStartPlayer { return }
  92. self.playerToolBar?.show()
  93. self.setUpForSubtitle()
  94. self.isSubtitleShowed = false
  95. print("Play URL: \(self.url)")
  96. player = AVPlayer(url: self.url)
  97. playerToolBar?.setMetadata(self.metadata)
  98. if metadata.livePhoto {
  99. player?.isMuted = false
  100. } else if metadata.classFile == NCCommunicationCommon.typeClassFile.audio.rawValue {
  101. player?.isMuted = CCUtility.getAudioMute()
  102. } else {
  103. player?.isMuted = CCUtility.getAudioMute()
  104. if let time = NCManageDatabase.shared.getVideoTime(metadata: metadata) {
  105. player?.seek(to: time)
  106. }
  107. }
  108. observerAVPlayertStatus = player?.currentItem?.addObserver(self, forKeyPath: "status", options: [.new, .initial], context: nil)
  109. }
  110. override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
  111. switch keyPath {
  112. case "status":
  113. if let playerItem = self.player?.currentItem,
  114. let object = object as? AVPlayerItem,
  115. playerItem === object{
  116. if (playerItem.status == .readyToPlay || playerItem.status == .failed) {
  117. print("player ready")
  118. self.startPlayer()
  119. } else {
  120. print("player not ready")
  121. }
  122. }
  123. break
  124. default:
  125. break
  126. }
  127. }
  128. func startPlayer() {
  129. player?.currentItem?.asset.loadValuesAsynchronously(forKeys: ["playable"], completionHandler: {
  130. var error: NSError? = nil
  131. let status = self.player?.currentItem?.asset.statusOfValue(forKey: "playable", error: &error) ?? .unknown
  132. DispatchQueue.main.async {
  133. switch status {
  134. case .loaded:
  135. self.durationTime = self.player?.currentItem?.asset.duration ?? .zero
  136. NCManageDatabase.shared.addVideoTime(metadata: self.metadata, time: nil, durationTime: self.durationTime)
  137. self.activateObserver(playerToolBar: self.playerToolBar)
  138. self.videoLayer = AVPlayerLayer(player: self.player)
  139. self.videoLayer!.frame = self.imageVideoContainer?.bounds ?? .zero
  140. self.videoLayer!.videoGravity = .resizeAspect
  141. if self.metadata.classFile == NCCommunicationCommon.typeClassFile.video.rawValue {
  142. self.imageVideoContainer?.layer.addSublayer(self.videoLayer!)
  143. self.imageVideoContainer?.playerLayer = self.videoLayer
  144. self.imageVideoContainer?.metadata = self.metadata
  145. self.imageVideoContainer?.image = self.imageVideoContainer?.image?.image(alpha: 0)
  146. }
  147. self.playerToolBar?.setBarPlayer(ncplayer: self)
  148. self.generatorImagePreview()
  149. if !(self.detailView?.isShow() ?? false) {
  150. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterShowPlayerToolBar, userInfo: ["ocId":self.metadata.ocId, "enableTimerAutoHide": false])
  151. }
  152. if self.autoPlay {
  153. self.player?.play()
  154. }
  155. self.isStartPlayer = true
  156. break
  157. case .failed:
  158. self.playerToolBar?.hide()
  159. if self.isProxy && NCKTVHTTPCache.shared.getDownloadStatusCode(metadata: self.metadata) == 200 {
  160. let alertController = UIAlertController(title: NSLocalizedString("_error_", value: "Error", comment: ""), message: NSLocalizedString("_video_not_streamed_", comment: ""), preferredStyle: .alert)
  161. alertController.addAction(UIAlertAction(title: NSLocalizedString("_yes_", value: "Yes", comment: ""), style: .default, handler: { _ in
  162. self.downloadVideo()
  163. }))
  164. alertController.addAction(UIAlertAction(title: NSLocalizedString("_no_", value: "No", comment: ""), style: .default, handler: { _ in }))
  165. self.viewController?.present(alertController, animated: true)
  166. } else {
  167. #if MFFFLIB
  168. if error?.code == AVError.Code.fileFormatNotRecognized.rawValue {
  169. self.convertVideo(withAlert: true)
  170. break
  171. }
  172. #endif
  173. if let title = error?.localizedDescription, let description = error?.localizedFailureReason {
  174. NCContentPresenter.shared.messageNotification(title, description: description, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: NCGlobal.shared.errorGeneric, priority: .max)
  175. } else {
  176. NCContentPresenter.shared.messageNotification("_error_", description: "_error_something_wrong_", delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: NCGlobal.shared.errorGeneric, priority: .max)
  177. }
  178. }
  179. break
  180. case .cancelled:
  181. break
  182. default:
  183. break
  184. }
  185. }
  186. })
  187. }
  188. func activateObserver(playerToolBar: NCPlayerToolBar?) {
  189. self.playerToolBar = playerToolBar
  190. // At end go back to start & show toolbar
  191. observerAVPlayerItemDidPlayToEndTime = NotificationCenter.default.addObserver(forName: .AVPlayerItemDidPlayToEndTime, object: player?.currentItem, queue: .main) { [weak self] notification in
  192. guard let self = self else {
  193. return
  194. }
  195. if let item = notification.object as? AVPlayerItem, let currentItem = self.player?.currentItem, item == currentItem {
  196. NCKTVHTTPCache.shared.saveCache(metadata: self.metadata)
  197. self.videoSeek(time: .zero)
  198. if !(self.detailView?.isShow() ?? false) {
  199. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterShowPlayerToolBar, userInfo: ["ocId": self.metadata.ocId, "enableTimerAutoHide": false])
  200. }
  201. self.playerToolBar?.updateToolBar()
  202. }
  203. }
  204. // Evey 1 second update toolbar
  205. observerAVPlayertTime = player?.addPeriodicTimeObserver(forInterval: CMTimeMakeWithSeconds(1, preferredTimescale: 1), queue: .main, using: { [weak self] _ in
  206. guard let self = self else {
  207. return
  208. }
  209. if self.player?.currentItem?.status == .readyToPlay {
  210. self.playerToolBar?.updateToolBar()
  211. }
  212. })
  213. NotificationCenter.default.addObserver(self, selector: #selector(generatorImagePreview), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterApplicationWillResignActive), object: nil)
  214. NotificationCenter.default.addObserver(self, selector: #selector(applicationDidEnterBackground(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterApplicationDidEnterBackground), object: nil)
  215. NotificationCenter.default.addObserver(self, selector: #selector(applicationDidBecomeActive(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterApplicationDidBecomeActive), object: nil)
  216. NotificationCenter.default.addObserver(self, selector: #selector(playerPause), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterPauseMedia), object: nil)
  217. NotificationCenter.default.addObserver(self, selector: #selector(playerPlay), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterPlayMedia), object: nil)
  218. if let player = self.player {
  219. NotificationCenter.default.addObserver(self, selector: #selector(playerStalled), name: NSNotification.Name.AVPlayerItemPlaybackStalled, object: player.currentItem)
  220. }
  221. }
  222. func deactivateObserver() {
  223. print("deactivating Observer")
  224. if isPlay() {
  225. playerPause()
  226. }
  227. self.playerToolBar = nil
  228. if let observerAVPlayerItemDidPlayToEndTime = self.observerAVPlayerItemDidPlayToEndTime {
  229. NotificationCenter.default.removeObserver(observerAVPlayerItemDidPlayToEndTime)
  230. }
  231. self.observerAVPlayerItemDidPlayToEndTime = nil
  232. if let observerAVPlayertTime = self.observerAVPlayertTime {
  233. player?.removeTimeObserver(observerAVPlayertTime)
  234. }
  235. self.observerAVPlayertTime = nil
  236. if observerAVPlayertStatus != nil {
  237. player?.currentItem?.removeObserver(self, forKeyPath: "status")
  238. }
  239. self.observerAVPlayertStatus = nil
  240. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterApplicationWillResignActive), object: nil)
  241. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterApplicationDidEnterBackground), object: nil)
  242. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterApplicationDidBecomeActive), object: nil)
  243. NotificationCenter.default.removeObserver(self, name: NSNotification.Name.AVPlayerItemPlaybackStalled, object: nil)
  244. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterPauseMedia), object: nil)
  245. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterPlayMedia), object: nil)
  246. }
  247. // MARK: - NotificationCenter
  248. @objc func applicationDidEnterBackground(_ notification: NSNotification) {
  249. if metadata.classFile == NCCommunicationCommon.typeClassFile.video.rawValue, let playerToolBar = self.playerToolBar {
  250. if !playerToolBar.isPictureInPictureActive() {
  251. playerPause()
  252. }
  253. }
  254. }
  255. @objc func applicationDidBecomeActive(_ notification: NSNotification) {
  256. playerToolBar?.updateToolBar()
  257. }
  258. // MARK: -
  259. func isPlay() -> Bool {
  260. if player?.rate == 1 { return true } else { return false }
  261. }
  262. @objc func playerStalled() {
  263. print("current player \(String(describing: player)) stalled.\nCalling playerPlay()")
  264. self.playerPlay()
  265. }
  266. @objc func playerPlay() {
  267. player?.play()
  268. self.playerToolBar?.updateToolBar()
  269. }
  270. @objc func playerPause() {
  271. player?.pause()
  272. self.playerToolBar?.updateToolBar()
  273. if let playerToolBar = self.playerToolBar, playerToolBar.isPictureInPictureActive() {
  274. playerToolBar.pictureInPictureController?.stopPictureInPicture()
  275. }
  276. }
  277. func videoSeek(time: CMTime) {
  278. player?.seek(to: time)
  279. self.saveTime(time)
  280. }
  281. func saveTime(_ time: CMTime) {
  282. if metadata.classFile == NCCommunicationCommon.typeClassFile.audio.rawValue { return }
  283. NCManageDatabase.shared.addVideoTime(metadata: metadata, time: time, durationTime: nil)
  284. generatorImagePreview()
  285. }
  286. func saveCurrentTime() {
  287. if let player = self.player {
  288. saveTime(player.currentTime())
  289. }
  290. }
  291. @objc func generatorImagePreview() {
  292. guard let time = player?.currentTime(), !metadata.livePhoto, metadata.classFile != NCCommunicationCommon.typeClassFile.audio.rawValue else { return }
  293. var image: UIImage?
  294. if let asset = player?.currentItem?.asset {
  295. do {
  296. let fileNamePreviewLocalPath = CCUtility.getDirectoryProviderStoragePreviewOcId(metadata.ocId, etag: metadata.etag)!
  297. let fileNameIconLocalPath = CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag)!
  298. let imageGenerator = AVAssetImageGenerator(asset: asset)
  299. imageGenerator.appliesPreferredTrackTransform = true
  300. let cgImage = try imageGenerator.copyCGImage(at: time, actualTime: nil)
  301. image = UIImage(cgImage: cgImage)
  302. // Update Playing Info Center
  303. let mediaItemPropertyTitle = MPNowPlayingInfoCenter.default().nowPlayingInfo?[MPMediaItemPropertyTitle] as? String
  304. if let image = image, mediaItemPropertyTitle == metadata.fileNameView {
  305. MPNowPlayingInfoCenter.default().nowPlayingInfo?[MPMediaItemPropertyArtwork] = MPMediaItemArtwork(boundsSize: image.size) { _ in
  306. return image
  307. }
  308. }
  309. // Preview
  310. if let data = image?.jpegData(compressionQuality: 0.5) {
  311. try data.write(to: URL(fileURLWithPath: fileNamePreviewLocalPath), options: .atomic)
  312. }
  313. // Icon
  314. if let data = image?.jpegData(compressionQuality: 0.5) {
  315. try data.write(to: URL(fileURLWithPath: fileNameIconLocalPath), options: .atomic)
  316. }
  317. } catch let error as NSError {
  318. print("GeneratorImagePreview localized error:")
  319. print(error.localizedDescription)
  320. }
  321. }
  322. }
  323. internal func downloadVideo(requiredConvert: Bool = false) {
  324. guard let view = appDelegate.window?.rootViewController?.view else { return }
  325. let serverUrlFileName = metadata.serverUrl + "/" + metadata.fileName
  326. let fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)!
  327. let hud = JGProgressHUD()
  328. var downloadRequest: DownloadRequest?
  329. hud.indicatorView = JGProgressHUDRingIndicatorView()
  330. if let indicatorView = hud.indicatorView as? JGProgressHUDRingIndicatorView {
  331. indicatorView.ringWidth = 1.5
  332. }
  333. hud.show(in: view)
  334. hud.textLabel.text = NSLocalizedString(metadata.fileNameView, comment: "")
  335. hud.detailTextLabel.text = NSLocalizedString("_tap_to_cancel_", comment: "")
  336. hud.tapOnHUDViewBlock = { hud in
  337. downloadRequest?.cancel()
  338. }
  339. NCCommunication.shared.download(serverUrlFileName: serverUrlFileName, fileNameLocalPath: fileNameLocalPath) { request in
  340. downloadRequest = request
  341. } taskHandler: { task in
  342. // task
  343. } progressHandler: { progress in
  344. hud.progress = Float(progress.fractionCompleted)
  345. } completionHandler: { _, _, _, _, _, error, _, _ in
  346. if error == nil {
  347. NCManageDatabase.shared.addLocalFile(metadata: self.metadata)
  348. let urlVideo = NCKTVHTTPCache.shared.getVideoURL(metadata: self.metadata)
  349. if let url = urlVideo.url {
  350. self.url = url
  351. self.isProxy = urlVideo.isProxy
  352. if requiredConvert {
  353. #if MFFFLIB
  354. self.convertVideo(withAlert: false)
  355. #endif
  356. } else {
  357. self.openAVPlayer()
  358. }
  359. }
  360. }
  361. hud.dismiss()
  362. }
  363. }
  364. }