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

264 lines
7.7 KiB
Swift
Raw Normal View History

2021-06-14 23:35:02 +05:30
import AVFoundation
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-06-14 23:35:02 +05:30
final class PlayerState: ObservableObject {
2021-06-15 22:05:21 +05:30
let logger = Logger(label: "net.arekf.Pearvidious.ps")
2021-07-19 04:02:46 +05:30
var video: Video!
2021-06-16 02:51:57 +05:30
2021-07-22 18:13:13 +05:30
var player: AVPlayer!
2021-06-18 15:47:01 +05:30
2021-07-22 18:13:13 +05:30
private var compositions = [Stream: AVMutableComposition]()
2021-06-15 22:05:21 +05:30
2021-07-19 04:02:46 +05:30
private(set) var currentTime: CMTime?
private(set) var savedTime: CMTime?
2021-06-15 22:05:21 +05:30
2021-07-19 04:02:46 +05:30
private(set) var currentRate: Float = 0.0
2021-07-22 18:13:13 +05:30
static let availableRates: [Double] = [0.25, 0.5, 0.75, 1, 1.25, 1.5, 1.75, 2]
2021-07-12 02:22:49 +05:30
2021-07-22 18:13:13 +05:30
let maxResolution: Stream.Resolution?
2021-06-18 04:13:29 +05:30
var timeObserver: Any?
2021-08-18 03:30:53 +05:30
var playingOutsideViewController = false
2021-07-22 18:13:13 +05:30
init(_ video: Video? = nil, maxResolution: Stream.Resolution? = nil) {
2021-06-16 02:51:57 +05:30
self.video = video
2021-07-22 18:13:13 +05:30
self.maxResolution = maxResolution
2021-06-16 02:51:57 +05:30
}
2021-06-17 00:42:41 +05:30
deinit {
destroyPlayer()
2021-06-15 22:05:21 +05:30
}
2021-07-19 04:02:46 +05:30
func loadVideo(_ video: Video?) {
guard video != nil else {
2021-06-15 22:05:21 +05:30
return
}
2021-07-30 03:58:28 +05:30
loadExtendedVideoDetails(video) { video in
self.video = video
self.playVideo(video)
}
}
func loadExtendedVideoDetails(_ video: Video?, onSuccess: @escaping (Video) -> Void) {
guard video != nil else {
return
}
2021-07-19 04:02:46 +05:30
InvidiousAPI.shared.video(video!.id).load().onSuccess { response in
if let video: Video = response.typedContent() {
2021-07-30 03:58:28 +05:30
onSuccess(video)
2021-07-19 04:02:46 +05:30
}
}
}
2021-07-22 18:13:13 +05:30
fileprivate func playVideo(_ video: Video) {
if video.hlsUrl != nil {
playHlsUrl()
return
2021-06-16 02:51:57 +05:30
}
2021-07-19 04:02:46 +05:30
2021-07-22 18:13:13 +05:30
let stream = maxResolution != nil ? video.streamWithResolution(maxResolution!) : video.defaultStream
2021-07-19 04:02:46 +05:30
2021-07-22 18:13:13 +05:30
guard stream != nil else {
return
}
2021-07-19 04:02:46 +05:30
2021-07-22 18:13:13 +05:30
Task {
await self.loadStream(stream!)
2021-07-20 02:57:18 +05:30
2021-07-22 18:13:13 +05:30
if stream != video.bestStream {
await self.loadBestStream()
2021-07-19 04:02:46 +05:30
}
}
}
2021-07-22 18:13:13 +05:30
fileprivate func playHlsUrl() {
player.replaceCurrentItem(with: playerItemWithMetadata())
player.playImmediately(atRate: 1.0)
}
fileprivate func loadStream(_ stream: Stream) async {
if stream.oneMeaningfullAsset {
DispatchQueue.main.async {
self.playStream(stream)
}
2021-07-19 04:02:46 +05:30
return
2021-07-22 18:13:13 +05:30
} else {
await playComposition(for: stream)
2021-07-19 04:02:46 +05:30
}
}
2021-07-22 18:13:13 +05:30
fileprivate func playStream(_ stream: Stream) {
logger.warning("loading \(stream.description) to player")
2021-07-19 04:02:46 +05:30
2021-07-22 18:13:13 +05:30
DispatchQueue.main.async {
self.saveTime()
self.player?.replaceCurrentItem(with: self.playerItemWithMetadata(for: stream))
self.player?.playImmediately(atRate: 1.0)
self.seekToSavedTime()
}
2021-07-19 04:02:46 +05:30
}
2021-07-22 18:13:13 +05:30
fileprivate func playComposition(for stream: Stream) async {
async let assetAudioTrack = stream.audioAsset.loadTracks(withMediaType: .audio)
async let assetVideoTrack = stream.videoAsset.loadTracks(withMediaType: .video)
2021-07-19 04:02:46 +05:30
2021-07-22 18:13:13 +05:30
if let audioTrack = composition(for: stream).addMutableTrack(withMediaType: .audio, preferredTrackID: kCMPersistentTrackID_Invalid),
let assetTrack = try? await assetAudioTrack.first
{
try! audioTrack.insertTimeRange(
CMTimeRange(start: .zero, duration: CMTime(seconds: video.length, preferredTimescale: 1000)),
of: assetTrack,
at: .zero
)
logger.critical("audio loaded")
} else {
fatalError("no track")
2021-07-19 04:02:46 +05:30
}
2021-06-15 22:05:21 +05:30
2021-07-22 18:13:13 +05:30
if let videoTrack = composition(for: stream).addMutableTrack(withMediaType: .video, preferredTrackID: kCMPersistentTrackID_Invalid),
let assetTrack = try? await assetVideoTrack.first
{
try! videoTrack.insertTimeRange(
CMTimeRange(start: .zero, duration: CMTime(seconds: video.length, preferredTimescale: 1000)),
of: assetTrack,
at: .zero
)
logger.critical("video loaded")
2021-06-15 22:05:21 +05:30
2021-07-22 18:13:13 +05:30
playStream(stream)
} else {
fatalError("no track")
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-07-22 18:13:13 +05:30
fileprivate func playerItem(for stream: Stream? = nil) -> AVPlayerItem {
if stream != nil {
if stream!.oneMeaningfullAsset {
return AVPlayerItem(asset: stream!.videoAsset, automaticallyLoadedAssetKeys: [.isPlayable])
} else {
return AVPlayerItem(asset: composition(for: stream!))
}
2021-06-17 00:42:41 +05:30
}
2021-07-22 18:13:13 +05:30
return AVPlayerItem(url: video.hlsUrl!)
2021-06-15 22:05:21 +05:30
}
2021-06-16 02:51:57 +05:30
2021-07-22 18:13:13 +05:30
fileprivate func playerItemWithMetadata(for stream: Stream? = nil) -> AVPlayerItem {
let playerItemWithMetadata = playerItem(for: stream)
2021-06-17 00:42:41 +05:30
2021-07-22 18:13:13 +05:30
var externalMetadata = [
makeMetadataItem(.commonIdentifierTitle, value: video.title),
makeMetadataItem(.quickTimeMetadataGenre, value: video.genre),
makeMetadataItem(.commonIdentifierDescription, value: video.description)
]
#if !os(macOS)
if let thumbnailData = try? Data(contentsOf: video.thumbnailURL(quality: .high)!),
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-07-22 18:13:13 +05:30
playerItemWithMetadata.externalMetadata = externalMetadata
#endif
2021-06-16 02:51:57 +05:30
2021-07-22 18:13:13 +05:30
playerItemWithMetadata.preferredForwardBufferDuration = 10
2021-06-16 02:51:57 +05:30
2021-07-22 18:13:13 +05:30
return playerItemWithMetadata
2021-06-16 02:51:57 +05:30
}
2021-07-22 18:13:13 +05:30
func setPlayerRate(_ rate: Float) {
currentRate = rate
player.rate = rate
}
2021-06-18 15:47:01 +05:30
2021-07-22 18:13:13 +05:30
fileprivate func composition(for stream: Stream) -> AVMutableComposition {
if compositions[stream] == nil {
compositions[stream] = AVMutableComposition()
2021-06-18 15:47:01 +05:30
}
2021-07-22 18:13:13 +05:30
return compositions[stream]!
2021-06-18 15:47:01 +05:30
}
2021-07-22 18:13:13 +05:30
fileprivate func loadBestStream() async {
if let bestStream = video.bestStream {
await loadStream(bestStream)
2021-06-18 15:47:01 +05:30
}
}
2021-07-22 18:13:13 +05:30
fileprivate func saveTime() {
2021-06-17 00:42:41 +05:30
guard player != nil else {
return
}
2021-06-16 02:51:57 +05:30
let currentTime = player.currentTime()
guard currentTime.seconds > 0 else {
return
}
savedTime = currentTime
}
2021-07-22 18:13:13 +05:30
fileprivate func seekToSavedTime() {
2021-06-17 00:42:41 +05:30
guard player != nil else {
return
}
2021-06-16 02:51:57 +05:30
if let time = savedTime {
2021-06-20 01:40:14 +05:30
logger.info("seeking to \(time.seconds)")
2021-07-30 03:58:28 +05:30
player.seek(to: time, toleranceBefore: CMTime.zero, toleranceAfter: CMTime.zero)
2021-06-16 02:51:57 +05:30
}
}
2021-07-22 18:13:13 +05:30
fileprivate func destroyPlayer() {
2021-06-17 00:42:41 +05:30
logger.critical("destroying player")
2021-08-18 03:30:53 +05:30
guard !playingOutsideViewController else {
logger.critical("cannot destroy, playing outside view controller")
return
}
2021-07-19 04:02:46 +05:30
player?.currentItem?.tracks.forEach { $0.assetTrack?.asset?.cancelLoading() }
2021-06-17 00:42:41 +05:30
2021-07-19 04:02:46 +05:30
player?.replaceCurrentItem(with: nil)
2021-06-18 04:13:29 +05:30
if timeObserver != nil {
2021-07-19 04:02:46 +05:30
player?.removeTimeObserver(timeObserver!)
timeObserver = nil
2021-06-18 04:13:29 +05:30
}
2021-07-22 18:13:13 +05:30
2021-07-19 04:02:46 +05:30
player = nil
2021-06-18 04:13:29 +05:30
}
2021-07-22 18:13:13 +05:30
fileprivate func addTimeObserver() {
2021-06-18 04:13:29 +05:30
let interval = CMTime(value: 1, timescale: 1)
2021-06-20 01:40:14 +05:30
2021-07-22 18:13:13 +05:30
timeObserver = player.addPeriodicTimeObserver(forInterval: interval, queue: .main) { _ in
2021-06-20 01:40:14 +05:30
if self.player.rate != self.currentRate, self.player.rate != 0, self.currentRate != 0 {
self.player.rate = self.currentRate
}
2021-06-18 04:13:29 +05:30
}
2021-06-17 00:42:41 +05:30
}
2021-07-22 18:13:13 +05:30
fileprivate func makeMetadataItem(_ identifier: AVMetadataIdentifier, value: Any) -> AVMetadataItem {
2021-06-16 02:51:57 +05:30
let item = AVMutableMetadataItem()
item.identifier = identifier
item.value = value as? NSCopying & NSObjectProtocol
item.extendedLanguageTag = "und"
return item.copy() as! AVMetadataItem
}
2021-06-14 23:35:02 +05:30
}