NCViewerVideo.swift 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. //
  2. // NCViewerVideo.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. class NCViewerVideo: NSObject, AVAssetResourceLoaderDelegate {
  26. private let appDelegate = UIApplication.shared.delegate as! AppDelegate
  27. private var progressView: UIProgressView?
  28. private var view: UIView?
  29. private var timeObserver: Any?
  30. private var rateObserver: Any?
  31. private var metadata: tableMetadata?
  32. public var viewerVideoToolBar: NCViewerVideoToolBar?
  33. public var player: AVPlayer?
  34. public var videoLayer: AVPlayerLayer?
  35. public var playerItem: AVPlayerItem?
  36. public var pictureInPictureOcId: String = ""
  37. init(view: UIView?, progressView: UIProgressView?, viewerVideoToolBar: NCViewerVideoToolBar?) {
  38. super.init()
  39. self.view = view
  40. self.progressView = progressView
  41. self.viewerVideoToolBar = viewerVideoToolBar
  42. NotificationCenter.default.addObserver(self, selector: #selector(applicationDidEnterBackground(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterApplicationDidEnterBackground), object: nil)
  43. }
  44. deinit {
  45. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterApplicationDidEnterBackground), object: nil)
  46. }
  47. //MARK: - NotificationCenter
  48. @objc func applicationDidEnterBackground(_ notification: NSNotification) {
  49. if metadata?.classFile == NCCommunicationCommon.typeClassFile.video.rawValue {
  50. player?.pause()
  51. }
  52. }
  53. func videoPlay(metadata: tableMetadata) {
  54. guard let view = self.view else { return }
  55. self.metadata = metadata
  56. NCNetworking.shared.getVideoUrl(metadata: metadata) { url in
  57. if let url = url {
  58. let urlAsset = AVURLAsset(url: url)
  59. urlAsset.resourceLoader.setDelegate(self, queue: .main)
  60. self.playerItem = AVPlayerItem(asset: urlAsset)
  61. self.player = AVPlayer(playerItem: self.playerItem)
  62. self.player?.isMuted = CCUtility.getAudioMute()
  63. self.videoLayer = AVPlayerLayer(player: self.player)
  64. self.videoLayer?.frame = view.bounds
  65. self.videoLayer?.videoGravity = AVLayerVideoGravity.resizeAspectFill
  66. view.layer.addSublayer(self.videoLayer!)
  67. // At end go back to start
  68. NotificationCenter.default.addObserver(forName: .AVPlayerItemDidPlayToEndTime, object: self.player?.currentItem, queue: .main) { (notification) in
  69. if let item = notification.object as? AVPlayerItem, let currentItem = self.player?.currentItem, item == currentItem {
  70. self.player?.seek(to: .zero)
  71. if metadata.livePhoto {
  72. NCManageDatabase.shared.deleteVideoTime(metadata: metadata)
  73. }
  74. }
  75. }
  76. self.rateObserver = self.player?.addObserver(self, forKeyPath: "rate", options: [], context: nil)
  77. if self.pictureInPictureOcId != metadata.ocId {
  78. self.player?.play()
  79. }
  80. // TOOLBAR
  81. self.viewerVideoToolBar?.setPlayer(player: self.player)
  82. self.viewerVideoToolBar?.setToolBar()
  83. }
  84. }
  85. }
  86. func resourceLoader(_ resourceLoader: AVAssetResourceLoader, shouldWaitForResponseTo authenticationChallenge: URLAuthenticationChallenge) -> Bool {
  87. return true
  88. }
  89. func videoStop() {
  90. // guard let metadata = self.metadata else { return }
  91. player?.pause()
  92. player?.seek(to: CMTime.zero)
  93. // progressView.progress = 0
  94. if let timeObserver = timeObserver {
  95. player?.removeTimeObserver(timeObserver)
  96. self.timeObserver = nil
  97. }
  98. if rateObserver != nil {
  99. player?.removeObserver(self, forKeyPath: "rate")
  100. NotificationCenter.default.removeObserver(self, name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: nil)
  101. self.rateObserver = nil
  102. }
  103. videoLayer?.removeFromSuperlayer()
  104. }
  105. override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
  106. guard let metadata = self.metadata else { return }
  107. if keyPath != nil && keyPath == "rate" {
  108. self.viewerVideoToolBar?.setToolBar()
  109. if ((player?.rate) == 1) {
  110. if let time = NCManageDatabase.shared.getVideoTime(metadata: metadata) {
  111. player?.seek(to: time)
  112. player?.isMuted = CCUtility.getAudioMute()
  113. }
  114. if rateObserver != nil && !metadata.livePhoto {
  115. self.progressView?.progress = 0
  116. if let duration = self.player?.currentItem?.asset.duration {
  117. let durationSeconds = Double(CMTimeGetSeconds(duration))
  118. if durationSeconds > 0 {
  119. let width = Double(self.progressView?.bounds.width ?? 0)
  120. let interval = (0.5 * durationSeconds) / width
  121. let time = CMTime(seconds: interval, preferredTimescale: CMTimeScale(NSEC_PER_SEC))
  122. if CMTIME_IS_VALID(time) && CMTimeCompare(time, .zero) != 0 {
  123. self.timeObserver = self.player?.addPeriodicTimeObserver(forInterval: time, queue: .main, using: { [weak self] time in
  124. let durationSeconds = Float(CMTimeGetSeconds(duration))
  125. if durationSeconds > 0 {
  126. let currentTimeSeconds = Float(CMTimeGetSeconds(time))
  127. self?.progressView?.progress = currentTimeSeconds / durationSeconds
  128. } else {
  129. self?.progressView?.progress = 0
  130. }
  131. })
  132. }
  133. }
  134. }
  135. }
  136. } else if !metadata.livePhoto {
  137. if let time = player?.currentTime(), let duration = self.player?.currentItem?.asset.duration {
  138. let timeSecond = Double(CMTimeGetSeconds(time))
  139. let durationSeconds = Double(CMTimeGetSeconds(duration))
  140. if timeSecond < durationSeconds {
  141. NCManageDatabase.shared.addVideoTime(metadata: metadata, time: player?.currentTime())
  142. }
  143. }
  144. }
  145. }
  146. }
  147. }