NCPlayer.swift 8.6 KB

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