NCPlayer.swift 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  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 durationSeconds: Double = 0
  31. private var playerToolBar: NCPlayerToolBar?
  32. public var metadata: tableMetadata?
  33. public var videoLayer: AVPlayerLayer?
  34. init(url: URL) {
  35. appDelegate.player = AVPlayer(url: url)
  36. }
  37. deinit {
  38. print("deinit NCPlayer")
  39. }
  40. func setupVideoLayer(imageVideoContainer: imageVideoContainerView?, playerToolBar: NCPlayerToolBar?, metadata: tableMetadata) {
  41. self.playerToolBar = playerToolBar
  42. self.metadata = metadata
  43. appDelegate.player?.isMuted = CCUtility.getAudioMute()
  44. appDelegate.player?.seek(to: .zero)
  45. // At end go back to start & show toolbar
  46. NotificationCenter.default.addObserver(forName: .AVPlayerItemDidPlayToEndTime, object: appDelegate.player?.currentItem, queue: .main) { (notification) in
  47. if let item = notification.object as? AVPlayerItem, let currentItem = self.appDelegate.player?.currentItem, item == currentItem {
  48. self.appDelegate.player?.seek(to: .zero)
  49. self.playerToolBar?.showToolBar(metadata: metadata, detailView: nil)
  50. NCKTVHTTPCache.shared.saveCache(metadata: metadata)
  51. }
  52. }
  53. appDelegate.player?.currentItem?.asset.loadValuesAsynchronously(forKeys: ["duration", "playable"], completionHandler: {
  54. if let duration: CMTime = (self.appDelegate.player?.currentItem?.asset.duration) {
  55. var error: NSError? = nil
  56. let status = self.appDelegate.player?.currentItem?.asset.statusOfValue(forKey: "playable", error: &error)
  57. switch status {
  58. case .loaded:
  59. DispatchQueue.main.async {
  60. if let imageVideoContainer = imageVideoContainer {
  61. self.imageVideoContainer = imageVideoContainer
  62. self.videoLayer = AVPlayerLayer(player: self.appDelegate.player)
  63. self.videoLayer!.frame = imageVideoContainer.bounds
  64. self.videoLayer!.videoGravity = .resizeAspect
  65. imageVideoContainer.layer.addSublayer(self.videoLayer!)
  66. imageVideoContainer.playerLayer = self.videoLayer
  67. }
  68. self.durationSeconds = CMTimeGetSeconds(duration)
  69. NCManageDatabase.shared.addVideoTime(metadata: metadata, time: nil, durationSeconds: self.durationSeconds)
  70. // NO Live Photo, seek to datamebase time
  71. if !metadata.livePhoto, let time = NCManageDatabase.shared.getVideoTime(metadata: metadata) {
  72. self.appDelegate.player?.seek(to: time)
  73. }
  74. DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
  75. playerToolBar?.setBarPlayer(ncplayer: self)
  76. }
  77. }
  78. break
  79. case .failed:
  80. DispatchQueue.main.async {
  81. NCContentPresenter.shared.messageNotification("_error_", description: "_error_something_wrong_", delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.info, errorCode: NCGlobal.shared.errorGeneric, forced: false)
  82. }
  83. break
  84. case .cancelled:
  85. DispatchQueue.main.async {
  86. //do something, show alert, put a placeholder image etc.
  87. }
  88. break
  89. default:
  90. break
  91. }
  92. }
  93. })
  94. NotificationCenter.default.addObserver(self, selector: #selector(applicationDidEnterBackground(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterApplicationDidEnterBackground), object: nil)
  95. }
  96. //MARK: - NotificationCenter
  97. @objc func applicationDidEnterBackground(_ notification: NSNotification) {
  98. if metadata?.classFile == NCCommunicationCommon.typeClassFile.video.rawValue {
  99. appDelegate.player?.pause()
  100. }
  101. }
  102. //MARK: -
  103. func deleteLocalFile() {
  104. guard let metadata = self.metadata else { return }
  105. NCManageDatabase.shared.deleteVideoTime(metadata: metadata)
  106. NCManageDatabase.shared.deleteLocalFile(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  107. NCUtilityFileSystem.shared.deleteFile(filePath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId))
  108. }
  109. func videoPlay() {
  110. appDelegate.player?.play()
  111. }
  112. func videoPause() {
  113. appDelegate.player?.pause()
  114. }
  115. func saveCurrentTime() {
  116. guard let metadata = self.metadata else { return }
  117. NCManageDatabase.shared.addVideoTime(metadata: metadata, time: appDelegate.player?.currentTime(), durationSeconds: nil)
  118. }
  119. func videoSeek(time: CMTime) {
  120. guard let metadata = self.metadata else { return }
  121. appDelegate.player?.seek(to: time)
  122. NCManageDatabase.shared.addVideoTime(metadata: metadata, time: time, durationSeconds: nil)
  123. }
  124. func videoRemoved() {
  125. videoPause()
  126. self.videoLayer?.removeFromSuperlayer()
  127. }
  128. func getVideoCurrentSeconds() -> Float64 {
  129. return CMTimeGetSeconds(appDelegate.player?.currentTime() ?? .zero)
  130. }
  131. func getVideoDurationSeconds() -> Float64 {
  132. return self.durationSeconds
  133. }
  134. func generatorImage(to time: CMTime) -> UIImage? {
  135. var image: UIImage?
  136. if let asset = appDelegate.player?.currentItem?.asset {
  137. do {
  138. let imageGenerator = AVAssetImageGenerator(asset: asset)
  139. let cgImage = try imageGenerator.copyCGImage(at: time, actualTime: nil)
  140. image = UIImage(cgImage: cgImage)
  141. print("")
  142. }
  143. catch let error as NSError {
  144. print(error.localizedDescription)
  145. }
  146. }
  147. return image
  148. }
  149. }