NCPlayer.swift 8.6 KB

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