NCPlayer.swift 9.3 KB

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