NCPlayer.swift 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  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 metadata: tableMetadata
  32. internal var singleTapGestureRecognizer: UITapGestureRecognizer!
  33. internal var width: Int?
  34. internal var height: Int?
  35. internal var length: Int?
  36. internal let fileNameSnapshotLocalPath: String
  37. internal let fileNamePreviewLocalPath: String
  38. internal let userAgent = CCUtility.getUserAgent()!
  39. internal weak var playerToolBar: NCPlayerToolBar?
  40. internal weak var viewerMediaPage: NCViewerMediaPage?
  41. weak var imageVideoContainer: imageVideoContainerView?
  42. internal var counterSeconds: Double = 0
  43. // MARK: - View Life Cycle
  44. init(imageVideoContainer: imageVideoContainerView, playerToolBar: NCPlayerToolBar?, metadata: tableMetadata, viewerMediaPage: NCViewerMediaPage?) {
  45. self.imageVideoContainer = imageVideoContainer
  46. self.playerToolBar = playerToolBar
  47. self.metadata = metadata
  48. self.viewerMediaPage = viewerMediaPage
  49. fileNameSnapshotLocalPath = CCUtility.getDirectoryProviderStorageSnapshotOcId(metadata.ocId, etag: metadata.etag)!
  50. fileNamePreviewLocalPath = CCUtility.getDirectoryProviderStoragePreviewOcId(metadata.ocId, etag: metadata.etag)!
  51. super.init()
  52. }
  53. deinit {
  54. print("deinit NCPlayer with ocId \(metadata.ocId)")
  55. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterApplicationDidEnterBackground), object: nil)
  56. }
  57. func openAVPlayer(url: URL, autoplay: Bool = false) {
  58. var position: Float = 0
  59. self.url = url
  60. self.singleTapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(didSingleTapWith(gestureRecognizer:)))
  61. print("Play URL: \(url)")
  62. player.media = VLCMedia(url: url)
  63. player.delegate = self
  64. // player?.media?.addOption("--network-caching=500")
  65. player.media?.addOption(":http-user-agent=\(userAgent)")
  66. if let result = NCManageDatabase.shared.getVideo(metadata: metadata),
  67. let resultPosition = result.position {
  68. position = resultPosition
  69. player.position = position
  70. }
  71. player.drawable = imageVideoContainer
  72. if let view = player.drawable as? UIView {
  73. view.isUserInteractionEnabled = true
  74. view.addGestureRecognizer(singleTapGestureRecognizer)
  75. }
  76. playerToolBar?.setBarPlayer(position: position, ncplayer: self, metadata: metadata, viewerMediaPage: viewerMediaPage)
  77. if autoplay {
  78. player.play()
  79. } else {
  80. if position == 0 {
  81. imageVideoContainer?.image = UIImage(contentsOfFile: fileNamePreviewLocalPath)
  82. } else {
  83. imageVideoContainer?.image = UIImage(contentsOfFile: fileNameSnapshotLocalPath)
  84. }
  85. }
  86. NotificationCenter.default.addObserver(self, selector: #selector(applicationDidEnterBackground(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterApplicationDidEnterBackground), object: nil)
  87. }
  88. // MARK: - UIGestureRecognizerDelegate
  89. @objc func didSingleTapWith(gestureRecognizer: UITapGestureRecognizer) {
  90. viewerMediaPage?.didSingleTapWith(gestureRecognizer: gestureRecognizer)
  91. }
  92. // MARK: - NotificationCenter
  93. @objc func applicationDidEnterBackground(_ notification: NSNotification) {
  94. if metadata.isVideo {
  95. playerPause()
  96. }
  97. }
  98. // MARK: -
  99. func isPlay() -> Bool {
  100. return player.isPlaying
  101. }
  102. func playerPlay() {
  103. if let result = NCManageDatabase.shared.getVideo(metadata: metadata), let position = result.position {
  104. player.position = position
  105. playerToolBar?.playbackSliderEvent = .moved
  106. }
  107. playerToolBar?.playbackSliderEvent = .began
  108. player.play()
  109. playerToolBar?.playButtonPause()
  110. DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
  111. self.playerToolBar?.playbackSliderEvent = .ended
  112. }
  113. }
  114. @objc func playerStop() {
  115. player.stop()
  116. playerToolBar?.playButtonPlay()
  117. }
  118. @objc func playerPause() {
  119. savePosition()
  120. player.pause()
  121. playerToolBar?.playButtonPlay()
  122. }
  123. func playerPosition(_ position: Float) {
  124. NCManageDatabase.shared.addVideo(metadata: metadata, position: position)
  125. player.position = position
  126. }
  127. func savePosition() {
  128. guard metadata.isVideo, isPlay() else { return }
  129. NCManageDatabase.shared.addVideo(metadata: metadata, position: player.position)
  130. if let width = width, let height = height {
  131. player.saveVideoSnapshot(at: fileNameSnapshotLocalPath, withWidth: Int32(width), andHeight: Int32(height))
  132. }
  133. }
  134. func jumpForward(_ seconds: Int32) {
  135. player.play()
  136. player.jumpForward(seconds)
  137. playerToolBar?.playButtonPause()
  138. }
  139. func jumpBackward(_ seconds: Int32) {
  140. player.play()
  141. player.jumpBackward(seconds)
  142. playerToolBar?.playButtonPause()
  143. }
  144. }
  145. extension NCPlayer: VLCMediaPlayerDelegate {
  146. func mediaPlayerStateChanged(_ aNotification: Notification) {
  147. switch player.state {
  148. case .stopped:
  149. print("Played mode: STOPPED")
  150. break
  151. case .opening:
  152. print("Played mode: OPENING")
  153. break
  154. case .buffering:
  155. print("Played mode: BUFFERING")
  156. break
  157. case .ended:
  158. if let url = self.url {
  159. NCManageDatabase.shared.addVideo(metadata: metadata, position: 0)
  160. self.player.media = VLCMedia(url: url)
  161. self.player.position = 0
  162. self.playerToolBar?.setBarPlayer(position: 0)
  163. self.viewerMediaPage?.changeScreenMode(mode: .normal)
  164. NCUtilityFileSystem.shared.deleteFile(filePath: fileNameSnapshotLocalPath)
  165. imageVideoContainer?.image = UIImage(contentsOfFile: fileNamePreviewLocalPath)
  166. }
  167. print("Played mode: ENDED")
  168. break
  169. case .error:
  170. let error = NKError(errorCode: NCGlobal.shared.errorInternalError, errorDescription: "_error_something_wrong_")
  171. NCContentPresenter.shared.showError(error: error, priority: .max)
  172. playerToolBar?.removeFromSuperview()
  173. print("Played mode: ERROR")
  174. break
  175. case .playing:
  176. let size = player.videoSize
  177. if let mediaLength = player.media?.length.intValue {
  178. self.length = Int(mediaLength)
  179. }
  180. self.width = Int(size.width)
  181. self.height = Int(size.height)
  182. playerToolBar?.updateTopToolBar(videoSubTitlesIndexes: player.videoSubTitlesIndexes, audioTrackIndexes: player.audioTrackIndexes)
  183. NCManageDatabase.shared.addVideo(metadata: metadata, width: self.width, height: self.height, length: self.length)
  184. print("Played mode: PLAYING")
  185. break
  186. case .paused:
  187. print("Played mode: PAUSED")
  188. break
  189. default: break
  190. }
  191. }
  192. func mediaPlayerTimeChanged(_ aNotification: Notification) {
  193. playerToolBar?.update()
  194. }
  195. func mediaPlayerTitleChanged(_ aNotification: Notification) {
  196. // Handle other states...
  197. }
  198. func mediaPlayerChapterChanged(_ aNotification: Notification) {
  199. // Handle other states...
  200. }
  201. func mediaPlayerLoudnessChanged(_ aNotification: Notification) {
  202. // Handle other states...
  203. }
  204. func mediaPlayerSnapshot(_ aNotification: Notification) {
  205. imageVideoContainer?.image = UIImage(contentsOfFile: fileNameSnapshotLocalPath)
  206. print("Snapshot saved")
  207. }
  208. func mediaPlayerStartedRecording(_ player: VLCMediaPlayer) {
  209. // Handle other states...
  210. }
  211. func mediaPlayer(_ player: VLCMediaPlayer, recordingStoppedAtPath path: String) {
  212. // Handle other states...
  213. }
  214. }
  215. extension NCPlayer: VLCMediaThumbnailerDelegate {
  216. func mediaThumbnailerDidTimeOut(_ mediaThumbnailer: VLCMediaThumbnailer) { }
  217. func mediaThumbnailer(_ mediaThumbnailer: VLCMediaThumbnailer, didFinishThumbnail thumbnail: CGImage) { }
  218. }