2021-10-05 20:20:09 +00:00
|
|
|
import AVKit
|
|
|
|
import Defaults
|
2021-06-14 18:05:02 +00:00
|
|
|
import Foundation
|
2021-06-15 16:35:21 +00:00
|
|
|
import Logging
|
2021-07-11 20:52:49 +00:00
|
|
|
#if !os(macOS)
|
|
|
|
import UIKit
|
|
|
|
#endif
|
2021-10-16 22:48:58 +00:00
|
|
|
import Siesta
|
2021-10-23 16:49:45 +00:00
|
|
|
import SwiftUI
|
2021-10-16 22:48:58 +00:00
|
|
|
import SwiftyJSON
|
2021-06-14 18:05:02 +00:00
|
|
|
|
2021-09-25 08:18:22 +00:00
|
|
|
final class PlayerModel: ObservableObject {
|
2021-06-15 16:35:21 +00:00
|
|
|
let logger = Logger(label: "net.arekf.Pearvidious.ps")
|
|
|
|
|
2021-10-05 20:20:09 +00:00
|
|
|
private(set) var player = AVPlayer()
|
|
|
|
var controller: PlayerViewController?
|
|
|
|
#if os(tvOS)
|
|
|
|
var avPlayerViewController: AVPlayerViewController?
|
|
|
|
#endif
|
2021-06-15 21:21:57 +00:00
|
|
|
|
2021-10-05 20:20:09 +00:00
|
|
|
@Published var presentingPlayer = false
|
2021-06-18 10:17:01 +00:00
|
|
|
|
2021-10-05 20:20:09 +00:00
|
|
|
@Published var stream: Stream?
|
|
|
|
@Published var currentRate: Float?
|
2021-06-15 16:35:21 +00:00
|
|
|
|
2021-10-23 16:49:45 +00:00
|
|
|
@Published var availableStreams = [Stream]() { didSet { rebuildTVMenu() } }
|
|
|
|
@Published var streamSelection: Stream? { didSet { rebuildTVMenu() } }
|
2021-10-16 22:48:58 +00:00
|
|
|
|
2021-10-05 20:20:09 +00:00
|
|
|
@Published var queue = [PlayerQueueItem]()
|
|
|
|
@Published var currentItem: PlayerQueueItem!
|
2021-06-15 16:35:21 +00:00
|
|
|
|
2021-10-05 20:20:09 +00:00
|
|
|
@Published var history = [PlayerQueueItem]()
|
2021-10-16 22:48:58 +00:00
|
|
|
@Published var savedTime: CMTime?
|
2021-06-17 22:43:29 +00:00
|
|
|
|
2021-10-22 23:04:03 +00:00
|
|
|
@Published var playerNavigationLinkActive = false
|
2021-08-22 19:13:33 +00:00
|
|
|
|
2021-10-23 16:49:45 +00:00
|
|
|
@Published var sponsorBlock = SponsorBlockAPI()
|
|
|
|
@Published var segmentRestorationTime: CMTime?
|
|
|
|
@Published var lastSkipped: Segment? { didSet { rebuildTVMenu() } }
|
|
|
|
@Published var restoredSegments = [Segment]()
|
|
|
|
|
2021-10-16 22:48:58 +00:00
|
|
|
var accounts: AccountsModel
|
|
|
|
var instances: InstancesModel
|
2021-10-05 20:20:09 +00:00
|
|
|
|
2021-10-22 23:04:03 +00:00
|
|
|
var composition = AVMutableComposition()
|
2021-10-16 22:48:58 +00:00
|
|
|
var timeObserver: Any?
|
|
|
|
private var shouldResumePlaying = true
|
|
|
|
private var statusObservation: NSKeyValueObservation?
|
|
|
|
|
2021-10-24 14:01:36 +00:00
|
|
|
#if os(macOS)
|
|
|
|
var playerTimeControlStatusObserver: Any?
|
|
|
|
#endif
|
|
|
|
|
2021-10-16 22:48:58 +00:00
|
|
|
init(accounts: AccountsModel? = nil, instances: InstancesModel? = nil) {
|
|
|
|
self.accounts = accounts ?? AccountsModel()
|
|
|
|
self.instances = instances ?? InstancesModel()
|
2021-10-05 20:20:09 +00:00
|
|
|
addItemDidPlayToEndTimeObserver()
|
2021-10-16 22:48:58 +00:00
|
|
|
addTimeObserver()
|
2021-10-24 14:01:36 +00:00
|
|
|
|
|
|
|
#if os(macOS)
|
|
|
|
addPlayerTimeControlStatusObserver()
|
|
|
|
#endif
|
2021-10-05 20:20:09 +00:00
|
|
|
}
|
2021-08-17 22:00:53 +00:00
|
|
|
|
2021-10-05 20:20:09 +00:00
|
|
|
func presentPlayer() {
|
|
|
|
presentingPlayer = true
|
2021-06-15 21:21:57 +00:00
|
|
|
}
|
|
|
|
|
2021-10-16 22:48:58 +00:00
|
|
|
var isPlaying: Bool {
|
|
|
|
player.timeControlStatus == .playing
|
|
|
|
}
|
|
|
|
|
2021-10-22 20:49:31 +00:00
|
|
|
var time: CMTime? {
|
|
|
|
currentItem?.playbackTime
|
|
|
|
}
|
|
|
|
|
2021-10-22 23:04:03 +00:00
|
|
|
var live: Bool {
|
|
|
|
currentItem?.video.live ?? false
|
|
|
|
}
|
|
|
|
|
2021-10-22 20:49:31 +00:00
|
|
|
var playerItemDuration: CMTime? {
|
|
|
|
player.currentItem?.asset.duration
|
|
|
|
}
|
|
|
|
|
|
|
|
var videoDuration: TimeInterval? {
|
|
|
|
currentItem?.duration ?? currentVideo?.length
|
|
|
|
}
|
|
|
|
|
2021-10-05 20:20:09 +00:00
|
|
|
func togglePlay() {
|
|
|
|
isPlaying ? pause() : play()
|
2021-06-15 16:35:21 +00:00
|
|
|
}
|
|
|
|
|
2021-10-05 20:20:09 +00:00
|
|
|
func play() {
|
|
|
|
guard !isPlaying else {
|
2021-06-15 16:35:21 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2021-10-05 20:20:09 +00:00
|
|
|
player.play()
|
2021-07-29 22:28:28 +00:00
|
|
|
}
|
|
|
|
|
2021-10-05 20:20:09 +00:00
|
|
|
func pause() {
|
|
|
|
guard isPlaying else {
|
2021-07-29 22:28:28 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2021-10-05 20:20:09 +00:00
|
|
|
player.pause()
|
2021-09-25 08:18:22 +00:00
|
|
|
}
|
|
|
|
|
2021-10-22 20:49:31 +00:00
|
|
|
func playVideo(_ video: Video, time: CMTime? = nil) {
|
|
|
|
savedTime = time
|
2021-10-16 22:48:58 +00:00
|
|
|
shouldResumePlaying = true
|
2021-10-13 22:10:29 +00:00
|
|
|
|
2021-10-16 22:48:58 +00:00
|
|
|
loadAvailableStreams(video) { streams in
|
|
|
|
guard let stream = streams.first else {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
self.streamSelection = stream
|
2021-10-22 20:49:31 +00:00
|
|
|
self.playStream(stream, of: video, preservingTime: !time.isNil)
|
2021-06-15 21:21:57 +00:00
|
|
|
}
|
2021-10-16 22:48:58 +00:00
|
|
|
}
|
2021-07-18 22:32:46 +00:00
|
|
|
|
2021-10-16 22:48:58 +00:00
|
|
|
func upgradeToStream(_ stream: Stream) {
|
|
|
|
if !self.stream.isNil, self.stream != stream {
|
2021-10-22 20:49:31 +00:00
|
|
|
playStream(stream, of: currentVideo!, preservingTime: true)
|
2021-07-22 12:43:13 +00:00
|
|
|
}
|
2021-10-16 22:48:58 +00:00
|
|
|
}
|
2021-07-18 22:32:46 +00:00
|
|
|
|
2021-10-16 22:48:58 +00:00
|
|
|
private func playStream(
|
|
|
|
_ stream: Stream,
|
|
|
|
of video: Video,
|
|
|
|
preservingTime: Bool = false
|
|
|
|
) {
|
2021-10-24 14:01:36 +00:00
|
|
|
#if !os(macOS)
|
|
|
|
try? AVAudioSession.sharedInstance().setActive(false)
|
|
|
|
#endif
|
2021-10-23 16:49:45 +00:00
|
|
|
resetSegments()
|
|
|
|
sponsorBlock.loadSegments(videoID: video.videoID)
|
|
|
|
|
2021-10-16 22:48:58 +00:00
|
|
|
if let url = stream.singleAssetURL {
|
|
|
|
logger.info("playing stream with one asset\(stream.kind == .hls ? " (HLS)" : ""): \(url)")
|
|
|
|
|
2021-10-22 20:49:31 +00:00
|
|
|
insertPlayerItem(stream, for: video, preservingTime: preservingTime)
|
2021-10-05 20:20:09 +00:00
|
|
|
} else {
|
2021-10-16 22:48:58 +00:00
|
|
|
logger.info("playing stream with many assets:")
|
|
|
|
logger.info("composition audio asset: \(stream.audioAsset.url)")
|
|
|
|
logger.info("composition video asset: \(stream.videoAsset.url)")
|
|
|
|
|
2021-10-05 20:20:09 +00:00
|
|
|
Task {
|
2021-10-22 20:49:31 +00:00
|
|
|
await self.loadComposition(stream, of: video, preservingTime: preservingTime)
|
2021-07-18 22:32:46 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-10-16 22:48:58 +00:00
|
|
|
private func insertPlayerItem(
|
|
|
|
_ stream: Stream,
|
|
|
|
for video: Video,
|
|
|
|
preservingTime: Bool = false
|
|
|
|
) {
|
|
|
|
let playerItem = playerItem(stream)
|
2021-10-05 20:20:09 +00:00
|
|
|
guard playerItem != nil else {
|
2021-07-18 22:32:46 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2021-10-16 22:48:58 +00:00
|
|
|
attachMetadata(to: playerItem!, video: video, for: stream)
|
2021-10-22 20:49:31 +00:00
|
|
|
|
2021-07-22 12:43:13 +00:00
|
|
|
DispatchQueue.main.async {
|
2021-10-05 20:20:09 +00:00
|
|
|
self.stream = stream
|
2021-10-16 22:48:58 +00:00
|
|
|
self.composition = AVMutableComposition()
|
2021-10-05 20:20:09 +00:00
|
|
|
}
|
|
|
|
|
2021-10-22 20:49:31 +00:00
|
|
|
let replaceItemAndSeek = {
|
|
|
|
self.player.replaceCurrentItem(with: playerItem)
|
|
|
|
self.seekToSavedTime { finished in
|
|
|
|
guard finished else {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
self.savedTime = nil
|
|
|
|
DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
|
|
|
|
self.play()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
let startPlaying = {
|
2021-10-24 14:01:36 +00:00
|
|
|
#if !os(macOS)
|
|
|
|
try? AVAudioSession.sharedInstance().setActive(true)
|
|
|
|
#endif
|
|
|
|
|
2021-10-22 20:49:31 +00:00
|
|
|
DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
|
|
|
|
self.play()
|
|
|
|
}
|
|
|
|
}
|
2021-07-18 22:32:46 +00:00
|
|
|
|
2021-10-16 22:48:58 +00:00
|
|
|
if preservingTime {
|
2021-10-22 20:49:31 +00:00
|
|
|
if savedTime.isNil {
|
|
|
|
saveTime {
|
|
|
|
replaceItemAndSeek()
|
|
|
|
startPlaying()
|
2021-10-16 22:48:58 +00:00
|
|
|
}
|
2021-10-22 20:49:31 +00:00
|
|
|
} else {
|
|
|
|
replaceItemAndSeek()
|
|
|
|
startPlaying()
|
2021-10-16 22:48:58 +00:00
|
|
|
}
|
2021-07-22 12:43:13 +00:00
|
|
|
} else {
|
2021-10-16 22:48:58 +00:00
|
|
|
player.replaceCurrentItem(with: playerItem)
|
2021-10-22 20:49:31 +00:00
|
|
|
startPlaying()
|
2021-06-15 16:35:21 +00:00
|
|
|
}
|
2021-06-16 19:12:41 +00:00
|
|
|
}
|
2021-06-15 16:35:21 +00:00
|
|
|
|
2021-10-16 22:48:58 +00:00
|
|
|
private func loadComposition(
|
|
|
|
_ stream: Stream,
|
|
|
|
of video: Video,
|
|
|
|
preservingTime: Bool = false
|
|
|
|
) async {
|
|
|
|
await loadCompositionAsset(stream.audioAsset, type: .audio, of: video)
|
|
|
|
await loadCompositionAsset(stream.videoAsset, type: .video, of: video)
|
|
|
|
|
|
|
|
guard streamSelection == stream else {
|
|
|
|
logger.critical("IGNORING LOADED")
|
|
|
|
return
|
2021-06-16 19:12:41 +00:00
|
|
|
}
|
|
|
|
|
2021-10-22 20:49:31 +00:00
|
|
|
insertPlayerItem(stream, for: video, preservingTime: preservingTime)
|
2021-06-15 16:35:21 +00:00
|
|
|
}
|
2021-06-15 21:21:57 +00:00
|
|
|
|
2021-10-16 22:48:58 +00:00
|
|
|
private func loadCompositionAsset(_ asset: AVURLAsset, type: AVMediaType, of video: Video) async {
|
|
|
|
async let assetTracks = asset.loadTracks(withMediaType: type)
|
|
|
|
|
|
|
|
logger.info("loading \(type.rawValue) track")
|
|
|
|
guard let compositionTrack = composition.addMutableTrack(
|
|
|
|
withMediaType: type,
|
|
|
|
preferredTrackID: kCMPersistentTrackID_Invalid
|
|
|
|
) else {
|
|
|
|
logger.critical("composition \(type.rawValue) addMutableTrack FAILED")
|
|
|
|
return
|
2021-10-05 20:20:09 +00:00
|
|
|
}
|
2021-06-16 19:12:41 +00:00
|
|
|
|
2021-10-16 22:48:58 +00:00
|
|
|
guard let assetTrack = try? await assetTracks.first else {
|
|
|
|
logger.critical("asset \(type.rawValue) track FAILED")
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
try! compositionTrack.insertTimeRange(
|
2021-10-23 16:49:45 +00:00
|
|
|
CMTimeRange(start: .zero, duration: CMTime(seconds: video.length, preferredTimescale: 1_000_000)),
|
2021-10-16 22:48:58 +00:00
|
|
|
of: assetTrack,
|
|
|
|
at: .zero
|
|
|
|
)
|
|
|
|
|
|
|
|
logger.critical("\(type.rawValue) LOADED")
|
|
|
|
}
|
|
|
|
|
|
|
|
private func playerItem(_ stream: Stream) -> AVPlayerItem? {
|
|
|
|
if let url = stream.singleAssetURL {
|
|
|
|
return AVPlayerItem(asset: AVURLAsset(url: url))
|
|
|
|
} else {
|
|
|
|
return AVPlayerItem(asset: composition)
|
|
|
|
}
|
|
|
|
}
|
2021-07-22 12:43:13 +00:00
|
|
|
|
2021-10-16 22:48:58 +00:00
|
|
|
private func attachMetadata(to item: AVPlayerItem, video: Video, for _: Stream? = nil) {
|
2021-07-22 12:43:13 +00:00
|
|
|
#if !os(macOS)
|
2021-10-16 22:48:58 +00:00
|
|
|
var externalMetadata = [
|
|
|
|
makeMetadataItem(.commonIdentifierTitle, value: video.title),
|
2021-10-20 22:21:50 +00:00
|
|
|
makeMetadataItem(.quickTimeMetadataGenre, value: video.genre ?? ""),
|
|
|
|
makeMetadataItem(.commonIdentifierDescription, value: video.description ?? "")
|
2021-10-16 22:48:58 +00:00
|
|
|
]
|
2021-10-05 20:20:09 +00:00
|
|
|
if let thumbnailData = try? Data(contentsOf: video.thumbnailURL(quality: .medium)!),
|
2021-07-22 12:43:13 +00:00
|
|
|
let image = UIImage(data: thumbnailData),
|
|
|
|
let pngData = image.pngData()
|
|
|
|
{
|
|
|
|
let artworkItem = makeMetadataItem(.commonIdentifierArtwork, value: pngData)
|
|
|
|
externalMetadata.append(artworkItem)
|
|
|
|
}
|
2021-06-15 21:21:57 +00:00
|
|
|
|
2021-10-16 22:48:58 +00:00
|
|
|
item.externalMetadata = externalMetadata
|
2021-07-22 12:43:13 +00:00
|
|
|
#endif
|
2021-06-15 21:21:57 +00:00
|
|
|
|
2021-10-16 22:48:58 +00:00
|
|
|
item.preferredForwardBufferDuration = 5
|
2021-06-15 21:21:57 +00:00
|
|
|
|
2021-10-05 20:20:09 +00:00
|
|
|
statusObservation?.invalidate()
|
2021-10-16 22:48:58 +00:00
|
|
|
statusObservation = item.observe(\.status, options: [.old, .new]) { playerItem, _ in
|
2021-10-05 20:20:09 +00:00
|
|
|
switch playerItem.status {
|
|
|
|
case .readyToPlay:
|
2021-10-16 22:48:58 +00:00
|
|
|
if self.isAutoplaying(playerItem), self.shouldResumePlaying {
|
|
|
|
self.play()
|
2021-10-05 20:20:09 +00:00
|
|
|
}
|
2021-10-16 22:48:58 +00:00
|
|
|
case .failed:
|
|
|
|
print("item error: \(String(describing: item.error))")
|
|
|
|
print((item.asset as! AVURLAsset).url)
|
|
|
|
|
2021-10-05 20:20:09 +00:00
|
|
|
default:
|
|
|
|
return
|
|
|
|
}
|
2021-06-18 10:17:01 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-10-16 22:48:58 +00:00
|
|
|
#if !os(macOS)
|
|
|
|
private func makeMetadataItem(_ identifier: AVMetadataIdentifier, value: Any) -> AVMetadataItem {
|
|
|
|
let item = AVMutableMetadataItem()
|
|
|
|
|
|
|
|
item.identifier = identifier
|
|
|
|
item.value = value as? NSCopying & NSObjectProtocol
|
|
|
|
item.extendedLanguageTag = "und"
|
|
|
|
|
|
|
|
return item.copy() as! AVMetadataItem
|
|
|
|
}
|
|
|
|
#endif
|
|
|
|
|
|
|
|
private func addItemDidPlayToEndTimeObserver() {
|
2021-10-05 20:20:09 +00:00
|
|
|
NotificationCenter.default.addObserver(
|
|
|
|
self,
|
|
|
|
selector: #selector(itemDidPlayToEndTime),
|
|
|
|
name: NSNotification.Name.AVPlayerItemDidPlayToEndTime,
|
|
|
|
object: nil
|
|
|
|
)
|
2021-06-18 10:17:01 +00:00
|
|
|
}
|
|
|
|
|
2021-10-05 20:20:09 +00:00
|
|
|
@objc func itemDidPlayToEndTime() {
|
2021-10-24 14:01:36 +00:00
|
|
|
#if !os(macOS)
|
|
|
|
try? AVAudioSession.sharedInstance().setActive(false)
|
|
|
|
#endif
|
|
|
|
|
2021-10-05 20:20:09 +00:00
|
|
|
if queue.isEmpty {
|
2021-10-22 20:49:31 +00:00
|
|
|
addCurrentItemToHistory()
|
2021-10-05 20:20:09 +00:00
|
|
|
resetQueue()
|
|
|
|
#if os(tvOS)
|
|
|
|
avPlayerViewController!.dismiss(animated: true) {
|
|
|
|
self.controller!.dismiss(animated: true)
|
|
|
|
}
|
|
|
|
#endif
|
|
|
|
presentingPlayer = false
|
|
|
|
} else {
|
|
|
|
advanceToNextItem()
|
2021-06-15 21:21:57 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-10-16 22:48:58 +00:00
|
|
|
private func saveTime(completionHandler: @escaping () -> Void = {}) {
|
|
|
|
let currentTime = player.currentTime()
|
|
|
|
|
|
|
|
guard currentTime.seconds > 0 else {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
DispatchQueue.main.async {
|
|
|
|
self.savedTime = currentTime
|
|
|
|
completionHandler()
|
2021-06-17 22:43:29 +00:00
|
|
|
}
|
2021-10-16 22:48:58 +00:00
|
|
|
}
|
2021-07-22 12:43:13 +00:00
|
|
|
|
2021-10-16 22:48:58 +00:00
|
|
|
private func seekToSavedTime(completionHandler: @escaping (Bool) -> Void = { _ in }) {
|
|
|
|
guard let time = savedTime else {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
player.seek(
|
|
|
|
to: time,
|
2021-10-23 16:49:45 +00:00
|
|
|
toleranceBefore: .init(seconds: 1, preferredTimescale: 1_000_000),
|
2021-10-16 22:48:58 +00:00
|
|
|
toleranceAfter: .zero,
|
|
|
|
completionHandler: completionHandler
|
|
|
|
)
|
2021-06-17 22:43:29 +00:00
|
|
|
}
|
|
|
|
|
2021-10-05 20:20:09 +00:00
|
|
|
private func addTimeObserver() {
|
2021-10-23 16:49:45 +00:00
|
|
|
let interval = CMTime(seconds: 0.5, preferredTimescale: 1_000_000)
|
2021-06-19 20:10:14 +00:00
|
|
|
|
2021-07-22 12:43:13 +00:00
|
|
|
timeObserver = player.addPeriodicTimeObserver(forInterval: interval, queue: .main) { _ in
|
2021-10-05 20:20:09 +00:00
|
|
|
self.currentRate = self.player.rate
|
2021-10-23 16:49:45 +00:00
|
|
|
|
|
|
|
guard !self.currentItem.isNil else {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
let time = self.player.currentTime()
|
|
|
|
|
|
|
|
self.currentItem!.playbackTime = time
|
|
|
|
self.currentItem!.videoDuration = self.player.currentItem?.asset.duration.seconds
|
|
|
|
|
|
|
|
self.handleSegments(at: time)
|
2021-06-17 22:43:29 +00:00
|
|
|
}
|
2021-06-16 19:12:41 +00:00
|
|
|
}
|
2021-10-24 14:01:36 +00:00
|
|
|
|
|
|
|
#if os(macOS)
|
|
|
|
private func addPlayerTimeControlStatusObserver() {
|
|
|
|
playerTimeControlStatusObserver = player.observe(\.timeControlStatus) { player, _ in
|
|
|
|
guard self.player == player else {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if player.timeControlStatus == .playing {
|
|
|
|
ScreenSaverManager.shared.disable(reason: "Yattee is playing video")
|
|
|
|
} else {
|
|
|
|
ScreenSaverManager.shared.enable()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
#endif
|
2021-06-14 18:05:02 +00:00
|
|
|
}
|