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

288 lines
8.2 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
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")
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 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-09-25 13:48:22 +05:30
var api: InvidiousAPI
var playback: PlaybackModel
2021-06-18 04:13:29 +05:30
var timeObserver: Any?
2021-09-25 13:48:22 +05:30
let resolution: Stream.ResolutionSetting?
2021-08-23 00:43:33 +05:30
2021-08-18 03:30:53 +05:30
var playingOutsideViewController = false
2021-09-25 13:48:22 +05:30
init(_ video: Video? = nil, playback: PlaybackModel, api: InvidiousAPI, resolution: Stream.ResolutionSetting? = nil) {
2021-06-16 02:51:57 +05:30
self.video = video
2021-09-25 13:48:22 +05:30
self.playback = playback
self.api = api
self.resolution = resolution
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-09-25 13:48:22 +05:30
playback.reset()
2021-08-24 03:01:51 +05:30
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-09-25 13:48:22 +05:30
api.video(video!.id).load().onSuccess { response in
2021-07-19 04:02:46 +05:30
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-09-25 13:48:22 +05:30
var requestedResolution: Bool {
resolution != nil && resolution != .hd720pFirstThenBest
}
2021-07-22 18:13:13 +05:30
fileprivate func playVideo(_ video: Video) {
2021-09-25 13:48:22 +05:30
playback.live = video.live
2021-09-14 02:11:16 +05:30
if video.live {
2021-07-22 18:13:13 +05:30
playHlsUrl()
return
2021-06-16 02:51:57 +05:30
}
2021-07-19 04:02:46 +05:30
2021-09-25 13:48:22 +05:30
let stream = requestedResolution ? video.streamWithResolution(resolution!.value) : 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-09-25 13:48:22 +05:30
if resolution == .hd720pFirstThenBest {
2021-07-22 18:13:13 +05:30
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 {
2021-09-25 13:48:22 +05:30
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) {
2021-08-24 03:01:51 +05:30
guard player != nil else {
return
}
2021-07-22 18:13:13 +05:30
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))
2021-09-25 13:48:22 +05:30
self.playback.stream = stream
if self.timeObserver.isNil {
2021-08-23 00:43:33 +05:30
self.addTimeObserver()
}
2021-09-25 13:48:22 +05:30
self.player?.play()
2021-07-22 18:13:13 +05:30
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].isNil {
2021-07-22 18:13:13 +05:30
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-08-23 00:43:33 +05:30
guard self.player != nil else {
return
}
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-08-23 00:43:33 +05:30
2021-09-25 13:48:22 +05:30
self.playback.time = self.player.currentTime()
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
}