NCPlayer.swift 9.2 KB

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