NCPlayer.swift 12 KB

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