NCPlayer.swift 8.5 KB

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