NCPlayer.swift 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  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. class NCPlayer: NSObject {
  28. private let appDelegate = UIApplication.shared.delegate as! AppDelegate
  29. private var imageVideoContainer: imageVideoContainerView?
  30. private var playerToolBar: NCPlayerToolBar?
  31. private var detailView: NCViewerMediaDetailView?
  32. private var observerAVPlayerItemDidPlayToEndTime: Any?
  33. public var metadata: tableMetadata?
  34. public var videoLayer: AVPlayerLayer?
  35. init(url: URL, imageVideoContainer: imageVideoContainerView?, playerToolBar: NCPlayerToolBar?, metadata: tableMetadata, detailView: NCViewerMediaDetailView?) {
  36. super.init()
  37. var timeSeek: CMTime = .zero
  38. print("Play URL: \(url)")
  39. appDelegate.player?.pause()
  40. appDelegate.player = AVPlayer(url: url)
  41. self.playerToolBar = playerToolBar
  42. self.metadata = metadata
  43. self.detailView = detailView
  44. if metadata.livePhoto {
  45. appDelegate.player?.isMuted = false
  46. } else if metadata.classFile == NCCommunicationCommon.typeClassFile.audio.rawValue {
  47. appDelegate.player?.isMuted = CCUtility.getAudioMute()
  48. } else {
  49. appDelegate.player?.isMuted = CCUtility.getAudioMute()
  50. if let time = NCManageDatabase.shared.getVideoTime(metadata: metadata) {
  51. timeSeek = time
  52. }
  53. }
  54. appDelegate.player?.seek(to: timeSeek)
  55. // At end go back to start & show toolbar
  56. observerAVPlayerItemDidPlayToEndTime = NotificationCenter.default.addObserver(forName: .AVPlayerItemDidPlayToEndTime, object: appDelegate.player?.currentItem, queue: .main) { (notification) in
  57. if let item = notification.object as? AVPlayerItem, let currentItem = self.appDelegate.player?.currentItem, item == currentItem {
  58. self.videoSeek(time: .zero)
  59. self.playerToolBar?.showToolBar(metadata: metadata, detailView: nil)
  60. NCKTVHTTPCache.shared.saveCache(metadata: metadata)
  61. }
  62. }
  63. appDelegate.player?.currentItem?.asset.loadValuesAsynchronously(forKeys: ["duration", "playable"], completionHandler: {
  64. if let durationTime: CMTime = (self.appDelegate.player?.currentItem?.asset.duration) {
  65. var error: NSError? = nil
  66. let status = self.appDelegate.player?.currentItem?.asset.statusOfValue(forKey: "playable", error: &error)
  67. switch status {
  68. case .loaded:
  69. DispatchQueue.main.async {
  70. if let imageVideoContainer = imageVideoContainer {
  71. self.imageVideoContainer = imageVideoContainer
  72. self.videoLayer = AVPlayerLayer(player: self.appDelegate.player)
  73. self.videoLayer!.frame = imageVideoContainer.bounds
  74. self.videoLayer!.videoGravity = .resizeAspect
  75. if metadata.classFile != NCCommunicationCommon.typeClassFile.audio.rawValue {
  76. if !metadata.livePhoto {
  77. imageVideoContainer.image = imageVideoContainer.image?.image(alpha: 0)
  78. }
  79. imageVideoContainer.layer.addSublayer(self.videoLayer!)
  80. imageVideoContainer.playerLayer = self.videoLayer
  81. imageVideoContainer.metadata = self.metadata
  82. }
  83. }
  84. NCManageDatabase.shared.addVideoTime(metadata: metadata, time: nil, durationTime: durationTime)
  85. self.playerToolBar?.setBarPlayer(ncplayer: self, timeSeek: timeSeek, metadata: metadata)
  86. self.generatorImagePreview()
  87. self.playerToolBar?.showToolBar(metadata: metadata, detailView: detailView)
  88. }
  89. break
  90. case .failed:
  91. DispatchQueue.main.async {
  92. NCContentPresenter.shared.messageNotification("_error_", description: "_error_something_wrong_", delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.info, errorCode: NCGlobal.shared.errorGeneric, forced: false)
  93. }
  94. break
  95. case .cancelled:
  96. DispatchQueue.main.async {
  97. //do something, show alert, put a placeholder image etc.
  98. }
  99. break
  100. default:
  101. break
  102. }
  103. }
  104. })
  105. NotificationCenter.default.addObserver(self, selector: #selector(applicationDidEnterBackground(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterApplicationDidEnterBackground), object: nil)
  106. NotificationCenter.default.addObserver(self, selector: #selector(applicationDidBecomeActive(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterApplicationDidBecomeActive), object: nil)
  107. }
  108. deinit {
  109. print("deinit NCPlayer")
  110. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterApplicationDidEnterBackground), object: nil)
  111. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterApplicationDidBecomeActive), object: nil)
  112. videoRemoved()
  113. }
  114. //MARK: - NotificationCenter
  115. @objc func applicationDidEnterBackground(_ notification: NSNotification) {
  116. if metadata?.classFile == NCCommunicationCommon.typeClassFile.video.rawValue {
  117. appDelegate.player?.pause()
  118. }
  119. }
  120. @objc func applicationDidBecomeActive(_ notification: NSNotification) {
  121. playerToolBar?.updateToolBar()
  122. }
  123. //MARK: -
  124. func videoPlay() {
  125. appDelegate.player?.play()
  126. }
  127. func videoPause() {
  128. appDelegate.player?.pause()
  129. }
  130. func saveTime(_ time: CMTime) {
  131. guard let metadata = self.metadata else { return }
  132. if metadata.classFile == NCCommunicationCommon.typeClassFile.audio.rawValue { return }
  133. NCManageDatabase.shared.addVideoTime(metadata: metadata, time: time, durationTime: nil)
  134. generatorImagePreview()
  135. }
  136. func videoSeek(time: CMTime) {
  137. appDelegate.player?.seek(to: time)
  138. self.saveTime(time)
  139. }
  140. func videoRemoved() {
  141. videoPause()
  142. if let observerAVPlayerItemDidPlayToEndTime = self.observerAVPlayerItemDidPlayToEndTime {
  143. NotificationCenter.default.removeObserver(observerAVPlayerItemDidPlayToEndTime)
  144. }
  145. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterApplicationDidEnterBackground), object: nil)
  146. self.videoLayer?.removeFromSuperlayer()
  147. self.videoLayer = nil
  148. self.observerAVPlayerItemDidPlayToEndTime = nil
  149. self.imageVideoContainer = nil
  150. self.playerToolBar = nil
  151. self.metadata = nil
  152. }
  153. func generatorImagePreview() {
  154. guard let time = appDelegate.player?.currentTime() else { return }
  155. guard let metadata = self.metadata else { return }
  156. if metadata.livePhoto { return }
  157. if metadata.classFile == NCCommunicationCommon.typeClassFile.audio.rawValue { return }
  158. var image: UIImage?
  159. if let asset = appDelegate.player?.currentItem?.asset {
  160. do {
  161. let fileNamePreviewLocalPath = CCUtility.getDirectoryProviderStoragePreviewOcId(metadata.ocId, etag: metadata.etag)!
  162. let fileNameIconLocalPath = CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag)!
  163. let imageGenerator = AVAssetImageGenerator(asset: asset)
  164. imageGenerator.appliesPreferredTrackTransform = true
  165. let cgImage = try imageGenerator.copyCGImage(at: time, actualTime: nil)
  166. image = UIImage(cgImage: cgImage)
  167. // Preview
  168. if let data = image?.jpegData(compressionQuality: 0.5) {
  169. try data.write(to: URL.init(fileURLWithPath: fileNamePreviewLocalPath), options: .atomic)
  170. }
  171. // Icon
  172. if let data = image?.jpegData(compressionQuality: 0.5) {
  173. try data.write(to: URL.init(fileURLWithPath: fileNameIconLocalPath), options: .atomic)
  174. }
  175. }
  176. catch let error as NSError {
  177. print(error.localizedDescription)
  178. }
  179. }
  180. }
  181. }