1
0
mirror of https://github.com/yattee/yattee.git synced 2024-12-13 22:00:31 +05:30
yattee/Model/Player/PlayerModel.swift

325 lines
9.8 KiB
Swift
Raw Normal View History

import AVKit
import Defaults
2021-06-14 23:35:02 +05:30
import Foundation
2021-06-15 22:05:21 +05:30
import Logging
2021-07-12 02:22:49 +05:30
#if !os(macOS)
import UIKit
#endif
2021-10-17 04:18:58 +05:30
import Siesta
import SwiftyJSON
2021-06-14 23:35:02 +05:30
2021-09-25 13:48:22 +05:30
final class PlayerModel: ObservableObject {
2021-06-15 22:05:21 +05:30
let logger = Logger(label: "net.arekf.Pearvidious.ps")
private(set) var player = AVPlayer()
var controller: PlayerViewController?
#if os(tvOS)
var avPlayerViewController: AVPlayerViewController?
#endif
2021-06-16 02:51:57 +05:30
@Published var presentingPlayer = false
2021-06-18 15:47:01 +05:30
@Published var stream: Stream?
@Published var currentRate: Float?
2021-06-15 22:05:21 +05:30
2021-10-19 03:23:02 +05:30
@Published var availableStreams = [Stream]() { didSet { rebuildStreamsMenu() } }
@Published var streamSelection: Stream? { didSet { rebuildStreamsMenu() } }
2021-10-17 04:18:58 +05:30
@Published var queue = [PlayerQueueItem]()
@Published var currentItem: PlayerQueueItem!
@Published var live = false
@Published var time: CMTime?
2021-06-15 22:05:21 +05:30
@Published var history = [PlayerQueueItem]()
2021-07-12 02:22:49 +05:30
2021-10-17 04:18:58 +05:30
@Published var savedTime: CMTime?
2021-06-18 04:13:29 +05:30
2021-10-17 04:18:58 +05:30
@Published var composition = AVMutableComposition()
2021-08-23 00:43:33 +05:30
2021-10-17 04:18:58 +05:30
var accounts: AccountsModel
var instances: InstancesModel
2021-10-17 04:18:58 +05:30
var timeObserver: Any?
private var shouldResumePlaying = true
private var statusObservation: NSKeyValueObservation?
init(accounts: AccountsModel? = nil, instances: InstancesModel? = nil) {
self.accounts = accounts ?? AccountsModel()
self.instances = instances ?? InstancesModel()
addItemDidPlayToEndTimeObserver()
2021-10-17 04:18:58 +05:30
addTimeObserver()
}
2021-08-18 03:30:53 +05:30
func presentPlayer() {
presentingPlayer = true
2021-06-16 02:51:57 +05:30
}
2021-10-17 04:18:58 +05:30
var isPlaying: Bool {
player.timeControlStatus == .playing
}
func togglePlay() {
isPlaying ? pause() : play()
2021-06-15 22:05:21 +05:30
}
func play() {
guard !isPlaying else {
2021-06-15 22:05:21 +05:30
return
}
player.play()
2021-07-30 03:58:28 +05:30
}
func pause() {
guard isPlaying else {
2021-07-30 03:58:28 +05:30
return
}
player.pause()
2021-09-25 13:48:22 +05:30
}
func playVideo(_ video: Video) {
2021-10-17 04:18:58 +05:30
savedTime = nil
shouldResumePlaying = true
2021-10-14 03:40:29 +05:30
2021-10-17 04:18:58 +05:30
loadAvailableStreams(video) { streams in
guard let stream = streams.first else {
return
}
self.streamSelection = stream
self.playStream(stream, of: video, forcePlay: true)
2021-06-16 02:51:57 +05:30
}
2021-10-17 04:18:58 +05:30
}
2021-07-19 04:02:46 +05:30
2021-10-17 04:18:58 +05:30
func upgradeToStream(_ stream: Stream) {
if !self.stream.isNil, self.stream != stream {
playStream(stream, of: currentItem.video, preservingTime: true)
2021-07-22 18:13:13 +05:30
}
2021-10-17 04:18:58 +05:30
}
2021-07-19 04:02:46 +05:30
2021-10-17 04:18:58 +05:30
private func playStream(
_ stream: Stream,
of video: Video,
forcePlay: Bool = false,
preservingTime: Bool = false
) {
if let url = stream.singleAssetURL {
logger.info("playing stream with one asset\(stream.kind == .hls ? " (HLS)" : ""): \(url)")
insertPlayerItem(stream, for: video, forcePlay: forcePlay, preservingTime: preservingTime)
} else {
2021-10-17 04:18:58 +05:30
logger.info("playing stream with many assets:")
logger.info("composition audio asset: \(stream.audioAsset.url)")
logger.info("composition video asset: \(stream.videoAsset.url)")
Task {
2021-10-17 04:18:58 +05:30
await self.loadComposition(stream, of: video, forcePlay: forcePlay, preservingTime: preservingTime)
2021-07-19 04:02:46 +05:30
}
}
}
2021-10-17 04:18:58 +05:30
private func insertPlayerItem(
_ stream: Stream,
for video: Video,
forcePlay: Bool = false,
preservingTime: Bool = false
) {
let playerItem = playerItem(stream)
2021-07-19 04:02:46 +05:30
guard playerItem != nil else {
2021-07-19 04:02:46 +05:30
return
}
2021-10-17 04:18:58 +05:30
attachMetadata(to: playerItem!, video: video, for: stream)
2021-07-22 18:13:13 +05:30
DispatchQueue.main.async {
self.stream = stream
2021-10-17 04:18:58 +05:30
self.composition = AVMutableComposition()
}
2021-10-17 04:18:58 +05:30
shouldResumePlaying = forcePlay || isPlaying
2021-07-19 04:02:46 +05:30
2021-10-17 04:18:58 +05:30
if preservingTime {
saveTime {
self.player.replaceCurrentItem(with: playerItem)
2021-06-15 22:05:21 +05:30
2021-10-17 04:18:58 +05:30
self.seekToSavedTime { finished in
guard finished else {
return
}
DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
forcePlay || self.shouldResumePlaying ? self.play() : self.pause()
self.shouldResumePlaying = false
}
}
}
2021-07-22 18:13:13 +05:30
} else {
2021-10-17 04:18:58 +05:30
player.replaceCurrentItem(with: playerItem)
DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
forcePlay || self.shouldResumePlaying ? self.play() : self.pause()
self.shouldResumePlaying = false
}
2021-06-15 22:05:21 +05:30
}
2021-06-17 00:42:41 +05:30
}
2021-06-15 22:05:21 +05:30
2021-10-17 04:18:58 +05:30
private func loadComposition(
_ stream: Stream,
of video: Video,
forcePlay: Bool = false,
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-17 00:42:41 +05:30
}
2021-10-17 04:18:58 +05:30
insertPlayerItem(stream, for: video, forcePlay: forcePlay, preservingTime: preservingTime)
2021-06-15 22:05:21 +05:30
}
2021-06-16 02:51:57 +05:30
2021-10-17 04:18:58 +05:30
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-06-17 00:42:41 +05:30
2021-10-17 04:18:58 +05:30
guard let assetTrack = try? await assetTracks.first else {
logger.critical("asset \(type.rawValue) track FAILED")
return
}
try! compositionTrack.insertTimeRange(
CMTimeRange(start: .zero, duration: CMTime(seconds: video.length, preferredTimescale: 1000)),
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 18:13:13 +05:30
2021-10-17 04:18:58 +05:30
private func attachMetadata(to item: AVPlayerItem, video: Video, for _: Stream? = nil) {
2021-07-22 18:13:13 +05:30
#if !os(macOS)
2021-10-17 04:18:58 +05:30
var externalMetadata = [
makeMetadataItem(.commonIdentifierTitle, value: video.title),
2021-10-21 03:51:50 +05:30
makeMetadataItem(.quickTimeMetadataGenre, value: video.genre ?? ""),
makeMetadataItem(.commonIdentifierDescription, value: video.description ?? "")
2021-10-17 04:18:58 +05:30
]
if let thumbnailData = try? Data(contentsOf: video.thumbnailURL(quality: .medium)!),
2021-07-22 18:13:13 +05:30
let image = UIImage(data: thumbnailData),
let pngData = image.pngData()
{
let artworkItem = makeMetadataItem(.commonIdentifierArtwork, value: pngData)
externalMetadata.append(artworkItem)
}
2021-06-16 02:51:57 +05:30
2021-10-17 04:18:58 +05:30
item.externalMetadata = externalMetadata
2021-07-22 18:13:13 +05:30
#endif
2021-06-16 02:51:57 +05:30
2021-10-17 04:18:58 +05:30
item.preferredForwardBufferDuration = 5
2021-06-16 02:51:57 +05:30
statusObservation?.invalidate()
2021-10-17 04:18:58 +05:30
statusObservation = item.observe(\.status, options: [.old, .new]) { playerItem, _ in
switch playerItem.status {
case .readyToPlay:
2021-10-17 04:18:58 +05:30
if self.isAutoplaying(playerItem), self.shouldResumePlaying {
self.play()
}
2021-10-17 04:18:58 +05:30
case .failed:
print("item error: \(String(describing: item.error))")
print((item.asset as! AVURLAsset).url)
default:
return
}
2021-06-18 15:47:01 +05:30
}
}
2021-10-17 04:18:58 +05:30
#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() {
NotificationCenter.default.addObserver(
self,
selector: #selector(itemDidPlayToEndTime),
name: NSNotification.Name.AVPlayerItemDidPlayToEndTime,
object: nil
)
2021-06-18 15:47:01 +05:30
}
@objc func itemDidPlayToEndTime() {
if queue.isEmpty {
resetQueue()
#if os(tvOS)
avPlayerViewController!.dismiss(animated: true) {
self.controller!.dismiss(animated: true)
}
#endif
presentingPlayer = false
} else {
advanceToNextItem()
2021-06-16 02:51:57 +05:30
}
}
2021-10-17 04:18:58 +05:30
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-18 04:13:29 +05:30
}
2021-10-17 04:18:58 +05:30
}
2021-07-22 18:13:13 +05:30
2021-10-17 04:18:58 +05:30
private func seekToSavedTime(completionHandler: @escaping (Bool) -> Void = { _ in }) {
guard let time = savedTime else {
return
}
player.seek(
to: time,
toleranceBefore: .init(seconds: 1, preferredTimescale: 1000),
toleranceAfter: .zero,
completionHandler: completionHandler
)
2021-06-18 04:13:29 +05:30
}
private func addTimeObserver() {
let interval = CMTime(seconds: 0.5, preferredTimescale: 1000)
2021-06-20 01:40:14 +05:30
2021-07-22 18:13:13 +05:30
timeObserver = player.addPeriodicTimeObserver(forInterval: interval, queue: .main) { _ in
self.currentRate = self.player.rate
self.live = self.currentVideo?.live ?? false
self.time = self.player.currentTime()
2021-06-18 04:13:29 +05:30
}
2021-06-17 00:42:41 +05:30
}
2021-06-14 23:35:02 +05:30
}