NCPlayer.swift 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  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 thumbnailer: VLCMediaThumbnailer?
  32. internal var metadata: tableMetadata
  33. internal var singleTapGestureRecognizer: UITapGestureRecognizer!
  34. internal var width: Int64?
  35. internal var height: Int64?
  36. internal let fileNamePreviewLocalPath: String
  37. internal let fileNameIconLocalPath: String
  38. internal weak var playerToolBar: NCPlayerToolBar?
  39. internal weak var viewerMediaPage: NCViewerMediaPage?
  40. weak var imageVideoContainer: imageVideoContainerView?
  41. // MARK: - View Life Cycle
  42. init(imageVideoContainer: imageVideoContainerView, playerToolBar: NCPlayerToolBar?, metadata: tableMetadata, viewerMediaPage: NCViewerMediaPage?) {
  43. self.imageVideoContainer = imageVideoContainer
  44. self.playerToolBar = playerToolBar
  45. self.metadata = metadata
  46. self.viewerMediaPage = viewerMediaPage
  47. fileNamePreviewLocalPath = CCUtility.getDirectoryProviderStoragePreviewOcId(metadata.ocId, etag: metadata.etag)!
  48. fileNameIconLocalPath = CCUtility.getDirectoryProviderStorageIconOcId(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) {
  56. let userAgent = CCUtility.getUserAgent()!
  57. var position: Float = 0
  58. self.url = url
  59. self.singleTapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(didSingleTapWith(gestureRecognizer:)))
  60. print("Play URL: \(url)")
  61. player = VLCMediaPlayer()
  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.getVideoPosition(metadata: metadata) {
  67. position = result
  68. player?.position = position
  69. }
  70. player?.drawable = imageVideoContainer
  71. if let view = player?.drawable as? UIView {
  72. view.isUserInteractionEnabled = true
  73. view.addGestureRecognizer(singleTapGestureRecognizer)
  74. }
  75. playerToolBar?.setBarPlayer(ncplayer: self, position: position, metadata: metadata)
  76. if let media = player?.media {
  77. thumbnailer = VLCMediaThumbnailer(media: media, andDelegate: self)
  78. }
  79. NotificationCenter.default.addObserver(self, selector: #selector(applicationDidEnterBackground(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterApplicationDidEnterBackground), object: nil)
  80. }
  81. // MARK: - UIGestureRecognizerDelegate
  82. @objc func didSingleTapWith(gestureRecognizer: UITapGestureRecognizer) {
  83. viewerMediaPage?.didSingleTapWith(gestureRecognizer: gestureRecognizer)
  84. }
  85. // MARK: - NotificationCenter
  86. @objc func applicationDidEnterBackground(_ notification: NSNotification) {
  87. if metadata.classFile == NKCommon.TypeClassFile.video.rawValue {
  88. playerStop()
  89. }
  90. }
  91. // MARK: -
  92. func isPlay() -> Bool {
  93. return player?.isPlaying ?? false
  94. }
  95. func playerPlay() {
  96. playerToolBar?.playbackSliderEvent = .began
  97. player?.play()
  98. playerToolBar?.playButtonPause()
  99. if let position = NCManageDatabase.shared.getVideoPosition(metadata: metadata) {
  100. player?.position = position
  101. playerToolBar?.playbackSliderEvent = .moved
  102. }
  103. DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
  104. self.playerToolBar?.playbackSliderEvent = .ended
  105. }
  106. }
  107. @objc func playerStop() {
  108. savePosition()
  109. player?.stop()
  110. playerToolBar?.playButtonPlay()
  111. }
  112. @objc func playerPause() {
  113. savePosition()
  114. player?.pause()
  115. playerToolBar?.playButtonPlay()
  116. }
  117. func playerPosizion(_ position: Float) {
  118. player?.position = position
  119. }
  120. func savePosition() {
  121. guard let position = player?.position, metadata.classFile == NKCommon.TypeClassFile.video.rawValue else { return }
  122. if isPlay(), let width = width, let height = height {
  123. player?.saveVideoSnapshot(at: fileNamePreviewLocalPath, withWidth: Int32(width), andHeight: Int32(height))
  124. }
  125. NCManageDatabase.shared.addVideo(metadata: metadata, position: position)
  126. }
  127. func snapshot() {
  128. if let player = player, let width = width, let height = height {
  129. player.saveVideoSnapshot(at: fileNamePreviewLocalPath, withWidth: Int32(width), andHeight: Int32(height))
  130. }
  131. }
  132. }
  133. extension NCPlayer: VLCMediaPlayerDelegate {
  134. func mediaPlayerStateChanged(_ aNotification: Notification) {
  135. guard let player = self.player else { return }
  136. switch player.state {
  137. case .stopped:
  138. print("Played mode: STOPPED")
  139. break
  140. case .opening:
  141. print("Played mode: OPENING")
  142. break
  143. case .buffering:
  144. print("Played mode: BUFFERING")
  145. break
  146. case .ended:
  147. if let url = self.url {
  148. NCManageDatabase.shared.addVideo(metadata: metadata, position: 0)
  149. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterShowPlayerToolBar, userInfo: ["ocId": self.metadata.ocId, "enableTimerAutoHide": false])
  150. self.thumbnailer?.fetchThumbnail()
  151. self.openAVPlayer(url: url)
  152. }
  153. print("Played mode: ENDED")
  154. break
  155. case .error:
  156. playerToolBar?.disableAllControl()
  157. let error = NKError(errorCode: NCGlobal.shared.errorInternalError, errorDescription: "_error_something_wrong_")
  158. NCContentPresenter.shared.showError(error: error, priority: .max)
  159. print("Played mode: ERROR")
  160. break
  161. case .playing:
  162. if let tracksInformation = player.media?.tracksInformation {
  163. for case let track as [String:Any] in tracksInformation {
  164. if track["type"] as? String == "video" {
  165. width = track["width"] as? Int64
  166. height = track["height"] as? Int64
  167. }
  168. }
  169. }
  170. print("Played mode: PLAYING")
  171. break
  172. case .paused:
  173. print("Played mode: PAUSED")
  174. break
  175. default: break
  176. }
  177. }
  178. func mediaPlayerTimeChanged(_ aNotification: Notification) {
  179. playerToolBar?.update()
  180. }
  181. func mediaPlayerTitleChanged(_ aNotification: Notification) {
  182. // Handle other states...
  183. }
  184. func mediaPlayerChapterChanged(_ aNotification: Notification) {
  185. // Handle other states...
  186. }
  187. func mediaPlayerLoudnessChanged(_ aNotification: Notification) {
  188. // Handle other states...
  189. }
  190. func mediaPlayerSnapshot(_ aNotification: Notification) {
  191. if let data = NSData(contentsOfFile: fileNamePreviewLocalPath),
  192. let image = UIImage(data: data as Data),
  193. let image = image.resizeImage(size: CGSize(width: NCGlobal.shared.sizeIcon, height: NCGlobal.shared.sizeIcon)),
  194. let data = image.jpegData(compressionQuality: 0.5) {
  195. try? data.write(to: URL(fileURLWithPath: fileNameIconLocalPath))
  196. }
  197. print("Snapshot saved on \(fileNameIconLocalPath)")
  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. var image: UIImage?
  210. do {
  211. image = UIImage(cgImage: thumbnail)
  212. if let data = image?.jpegData(compressionQuality: 0.5) {
  213. try data.write(to: URL(fileURLWithPath: fileNamePreviewLocalPath), options: .atomic)
  214. }
  215. if let data = image?.jpegData(compressionQuality: 0.5) {
  216. try data.write(to: URL(fileURLWithPath: fileNameIconLocalPath), options: .atomic)
  217. }
  218. } catch let error as NSError {
  219. print("GeneratorImagePreview localized error:")
  220. print(error.localizedDescription)
  221. }
  222. }
  223. }