NCPlayer.swift 12 KB

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