NCPlayer.swift 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  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 NextcloudKit
  25. import UIKit
  26. import MobileVLCKit
  27. class NCPlayer: NSObject {
  28. internal let appDelegate = UIApplication.shared.delegate as! AppDelegate
  29. internal var url: URL?
  30. internal var player: VLCMediaPlayer?
  31. internal var thumbnailer: VLCMediaThumbnailer?
  32. internal var metadata: tableMetadata
  33. internal var singleTapGestureRecognizer: UITapGestureRecognizer!
  34. internal var width: Int64?
  35. internal var height: Int64?
  36. internal let fileNamePreviewLocalPath: String
  37. internal let fileNameIconLocalPath: String
  38. internal weak var playerToolBar: NCPlayerToolBar?
  39. internal weak var imageVideoContainer: imageVideoContainerView?
  40. internal weak var viewerMediaPage: NCViewerMediaPage?
  41. // MARK: - View Life Cycle
  42. init(imageVideoContainer: imageVideoContainerView, playerToolBar: NCPlayerToolBar?, metadata: tableMetadata, viewerMediaPage: NCViewerMediaPage?) {
  43. self.imageVideoContainer = imageVideoContainer
  44. self.playerToolBar = playerToolBar
  45. self.metadata = metadata
  46. self.viewerMediaPage = viewerMediaPage
  47. fileNamePreviewLocalPath = CCUtility.getDirectoryProviderStoragePreviewOcId(metadata.ocId, etag: metadata.etag)!
  48. fileNameIconLocalPath = CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag)!
  49. super.init()
  50. }
  51. deinit {
  52. print("deinit NCPlayer with ocId \(metadata.ocId)")
  53. player?.stop()
  54. }
  55. func openAVPlayer(url: URL) {
  56. let userAgent = CCUtility.getUserAgent()!
  57. var position: Float = 0
  58. self.url = url
  59. self.singleTapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(didSingleTapWith(gestureRecognizer:)))
  60. print("Play URL: \(url)")
  61. player = VLCMediaPlayer()
  62. player?.media = VLCMedia(url: url)
  63. player?.delegate = self
  64. player?.media?.addOption("--network-caching=5000")
  65. player?.media?.addOption(":http-user-agent=\(userAgent)")
  66. let volume = CCUtility.getAudioVolume()
  67. if metadata.livePhoto {
  68. player?.audio?.volume = 0
  69. } else if metadata.classFile == NKCommon.TypeClassFile.audio.rawValue {
  70. player?.audio?.volume = Int32(volume)
  71. } else {
  72. player?.audio?.volume = Int32(volume)
  73. if let result = NCManageDatabase.shared.getVideoPosition(metadata: metadata) {
  74. position = result
  75. player?.position = position
  76. }
  77. }
  78. player?.drawable = self.imageVideoContainer
  79. if let view = player?.drawable as? UIView {
  80. view.isUserInteractionEnabled = true
  81. view.addGestureRecognizer(singleTapGestureRecognizer)
  82. }
  83. playerToolBar?.setBarPlayer(ncplayer: self, position: position, metadata: self.metadata)
  84. if let media = player?.media {
  85. thumbnailer = VLCMediaThumbnailer(media: media, andDelegate: self)
  86. }
  87. NotificationCenter.default.addObserver(self, selector: #selector(applicationDidEnterBackground(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterApplicationDidEnterBackground), object: nil)
  88. NotificationCenter.default.addObserver(self, selector: #selector(applicationDidBecomeActive(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterApplicationDidBecomeActive), object: nil)
  89. NotificationCenter.default.addObserver(self, selector: #selector(playerPause), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterPauseMedia), object: nil)
  90. NotificationCenter.default.addObserver(self, selector: #selector(playerPlay), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterPlayMedia), object: nil)
  91. }
  92. func closeAVPlayer() {
  93. playerPause(withSnapshot: false)
  94. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterApplicationDidEnterBackground), object: nil)
  95. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterApplicationDidBecomeActive), object: nil)
  96. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterPauseMedia), object: nil)
  97. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterPlayMedia), object: nil)
  98. }
  99. // MARK: - UIGestureRecognizerDelegate
  100. @objc func didSingleTapWith(gestureRecognizer: UITapGestureRecognizer) {
  101. viewerMediaPage?.didSingleTapWith(gestureRecognizer: gestureRecognizer)
  102. }
  103. // MARK: - NotificationCenter
  104. @objc func applicationDidEnterBackground(_ notification: NSNotification) {
  105. if metadata.classFile == NKCommon.TypeClassFile.video.rawValue {
  106. playerPause()
  107. }
  108. }
  109. @objc func applicationDidBecomeActive(_ notification: NSNotification) {
  110. playerToolBar?.update(position: player?.position)
  111. }
  112. // MARK: -
  113. func isPlay() -> Bool {
  114. return player?.isPlaying ?? false
  115. }
  116. @objc func playerPlay() {
  117. player?.play()
  118. if let position = NCManageDatabase.shared.getVideoPosition(metadata: self.metadata) {
  119. player?.position = position
  120. playerToolBar?.update(position: position)
  121. } else {
  122. playerToolBar?.update(position: player?.position)
  123. }
  124. }
  125. @objc func playerPause(withSnapshot: Bool = true) {
  126. if let width = width, let height = height, withSnapshot {
  127. player?.saveVideoSnapshot(at: fileNamePreviewLocalPath, withWidth: Int32(width), andHeight: Int32(height))
  128. }
  129. player?.pause()
  130. playerToolBar?.update(position: player?.position)
  131. }
  132. func videoSeek(position: Float) {
  133. player?.position = position
  134. playerToolBar?.update(position: position)
  135. }
  136. func savePosition(_ position: Float) {
  137. if metadata.classFile == NKCommon.TypeClassFile.audio.rawValue { return }
  138. let length = Int(player?.media?.length.intValue ?? 0)
  139. NCManageDatabase.shared.addVideo(metadata: metadata, position: position, length: length)
  140. }
  141. func snapshot() {
  142. if let player = player, let width = width, let height = height {
  143. player.saveVideoSnapshot(at: fileNamePreviewLocalPath, withWidth: Int32(width), andHeight: Int32(height))
  144. }
  145. }
  146. }
  147. extension NCPlayer: VLCMediaPlayerDelegate {
  148. func mediaPlayerStateChanged(_ aNotification: Notification) {
  149. guard let player = self.player else { return }
  150. switch player.state {
  151. case .stopped:
  152. if let url = self.url {
  153. NCManageDatabase.shared.addVideo(metadata: metadata, position: 0)
  154. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterShowPlayerToolBar, userInfo: ["ocId": self.metadata.ocId, "enableTimerAutoHide": false])
  155. self.thumbnailer?.fetchThumbnail()
  156. self.openAVPlayer(url: url)
  157. }
  158. print("Played mode: STOPPED")
  159. break
  160. case .opening:
  161. playerToolBar?.buffering()
  162. print("Played mode: OPENING")
  163. break
  164. case .buffering:
  165. playerToolBar?.buffering()
  166. print("Played mode: BUFFERING")
  167. break
  168. case .ended:
  169. print("Played mode: ENDED")
  170. playerToolBar?.update(position: player.position)
  171. break
  172. case .error:
  173. let error = NKError(errorCode: NCGlobal.shared.errorInternalError, errorDescription: "_error_something_wrong_")
  174. NCContentPresenter.shared.showError(error: error, priority: .max)
  175. print("Played mode: ERROR")
  176. break
  177. case .playing:
  178. if let tracksInformation = player.media?.tracksInformation {
  179. for case let track as [String:Any] in tracksInformation {
  180. if track["type"] as? String == "video" {
  181. width = track["width"] as? Int64
  182. height = track["height"] as? Int64
  183. }
  184. }
  185. }
  186. // let metaDictionary = player.media?.metaData
  187. print("Played mode: PLAYING")
  188. break
  189. case .paused:
  190. print("Played mode: PAUSED")
  191. playerToolBar?.update(position: player.position)
  192. break
  193. default: break
  194. }
  195. print(player.state)
  196. }
  197. func mediaPlayerTimeChanged(_ aNotification: Notification) {
  198. self.playerToolBar?.update(position: player?.position)
  199. }
  200. func mediaPlayerTitleChanged(_ aNotification: Notification) {
  201. // Handle other states...
  202. }
  203. func mediaPlayerChapterChanged(_ aNotification: Notification) {
  204. // Handle other states...
  205. }
  206. func mediaPlayerLoudnessChanged(_ aNotification: Notification) {
  207. // Handle other states...
  208. }
  209. func mediaPlayerSnapshot(_ aNotification: Notification) {
  210. if let data = NSData(contentsOfFile: fileNamePreviewLocalPath),
  211. let image = UIImage(data: data as Data),
  212. let image = image.resizeImage(size: CGSize(width: NCGlobal.shared.sizeIcon, height: NCGlobal.shared.sizeIcon)),
  213. let data = image.jpegData(compressionQuality: 0.5) {
  214. try? data.write(to: URL(fileURLWithPath: fileNameIconLocalPath))
  215. }
  216. print("Snapshot saved")
  217. }
  218. func mediaPlayerStartedRecording(_ player: VLCMediaPlayer) {
  219. // Handle other states...
  220. }
  221. func mediaPlayer(_ player: VLCMediaPlayer, recordingStoppedAtPath path: String) {
  222. // Handle other states...
  223. }
  224. }
  225. extension NCPlayer: VLCMediaThumbnailerDelegate {
  226. func mediaThumbnailerDidTimeOut(_ mediaThumbnailer: VLCMediaThumbnailer) { }
  227. func mediaThumbnailer(_ mediaThumbnailer: VLCMediaThumbnailer, didFinishThumbnail thumbnail: CGImage) {
  228. var image: UIImage?
  229. do {
  230. image = UIImage(cgImage: thumbnail)
  231. // Update Playing Info Center
  232. // let mediaItemPropertyTitle = MPNowPlayingInfoCenter.default().nowPlayingInfo?[MPMediaItemPropertyTitle] as? String
  233. // if let image = image, mediaItemPropertyTitle == metadata.fileNameView {
  234. // MPNowPlayingInfoCenter.default().nowPlayingInfo?[MPMediaItemPropertyArtwork] = MPMediaItemArtwork(boundsSize: image.size) { _ in
  235. // return image
  236. // }
  237. // }
  238. // Preview
  239. if let data = image?.jpegData(compressionQuality: 0.5) {
  240. try data.write(to: URL(fileURLWithPath: fileNamePreviewLocalPath), options: .atomic)
  241. }
  242. // Icon
  243. if let data = image?.jpegData(compressionQuality: 0.5) {
  244. try data.write(to: URL(fileURLWithPath: fileNameIconLocalPath), options: .atomic)
  245. }
  246. } catch let error as NSError {
  247. print("GeneratorImagePreview localized error:")
  248. print(error.localizedDescription)
  249. }
  250. }
  251. }