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

262 lines
8.1 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-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
@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-09-25 13:48:22 +05:30
var api: InvidiousAPI
2021-06-18 04:13:29 +05:30
var timeObserver: Any?
private var statusObservation: NSKeyValueObservation?
2021-08-23 00:43:33 +05:30
var isPlaying: Bool {
stream != nil && currentRate != 0.0
}
init(api: InvidiousAPI? = nil) {
self.api = api ?? InvidiousAPI()
addItemDidPlayToEndTimeObserver()
}
2021-08-18 03:30:53 +05:30
func presentPlayer() {
presentingPlayer = true
2021-06-16 02:51:57 +05:30
}
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-09-14 02:11:16 +05:30
if video.live {
playHlsUrl(video)
2021-07-22 18:13:13 +05:30
return
2021-06-16 02:51:57 +05:30
}
2021-07-19 04:02:46 +05:30
guard let stream = video.streamWithResolution(Defaults[.quality].value) ?? video.defaultStream else {
2021-07-22 18:13:13 +05:30
return
}
2021-07-19 04:02:46 +05:30
if stream.oneMeaningfullAsset {
playStream(stream, for: video)
} else {
Task {
await playComposition(video, for: stream)
2021-07-19 04:02:46 +05:30
}
}
}
private func playHlsUrl(_ video: Video) {
player.replaceCurrentItem(with: playerItemWithMetadata(video))
2021-07-22 18:13:13 +05:30
player.playImmediately(atRate: 1.0)
}
private func playStream(_ stream: Stream, for video: Video) {
logger.warning("loading \(stream.description) to player")
2021-07-19 04:02:46 +05:30
let playerItem: AVPlayerItem! = playerItemWithMetadata(video, for: stream)
guard playerItem != nil else {
2021-07-19 04:02:46 +05:30
return
}
if let index = queue.firstIndex(where: { $0.video.id == video.id }) {
queue[index].playerItems.append(playerItem)
2021-08-24 03:01:51 +05:30
}
2021-07-22 18:13:13 +05:30
DispatchQueue.main.async {
self.stream = stream
self.player.replaceCurrentItem(with: playerItem)
}
if timeObserver.isNil {
addTimeObserver()
2021-07-22 18:13:13 +05:30
}
2021-07-19 04:02:46 +05:30
}
private func playComposition(_ video: Video, for stream: Stream) async {
2021-07-22 18:13:13 +05:30
async let assetAudioTrack = stream.audioAsset.loadTracks(withMediaType: .audio)
async let assetVideoTrack = stream.videoAsset.loadTracks(withMediaType: .video)
2021-07-19 04:02:46 +05:30
logger.info("loading audio track")
if let audioTrack = composition(video, for: stream)?.addMutableTrack(withMediaType: .audio, preferredTrackID: kCMPersistentTrackID_Invalid),
2021-07-22 18:13:13 +05:30
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 {
logger.critical("NO audio track")
2021-07-19 04:02:46 +05:30
}
2021-06-15 22:05:21 +05:30
logger.info("loading video track")
if let videoTrack = composition(video, for: stream)?.addMutableTrack(withMediaType: .video, preferredTrackID: kCMPersistentTrackID_Invalid),
2021-07-22 18:13:13 +05:30
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")
playStream(stream, for: video)
2021-07-22 18:13:13 +05:30
} else {
logger.critical("NO video 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
private func playerItem(_ video: Video, for stream: Stream? = nil) -> AVPlayerItem? {
2021-07-22 18:13:13 +05:30
if stream != nil {
if stream!.oneMeaningfullAsset {
logger.info("stream has one meaningfull asset")
return AVPlayerItem(asset: AVURLAsset(url: stream!.videoAsset.url))
}
if let composition = composition(video, for: stream!) {
logger.info("stream has MANY assets, using composition")
return AVPlayerItem(asset: composition)
2021-07-22 18:13:13 +05:30
} else {
return nil
2021-07-22 18:13:13 +05:30
}
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
private func playerItemWithMetadata(_ video: Video, for stream: Stream? = nil) -> AVPlayerItem? {
logger.info("building player item metadata")
let playerItemWithMetadata: AVPlayerItem! = playerItem(video, for: stream)
guard playerItemWithMetadata != nil else {
return nil
}
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: .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-07-22 18:13:13 +05:30
playerItemWithMetadata.externalMetadata = externalMetadata
#endif
2021-06-16 02:51:57 +05:30
playerItemWithMetadata.preferredForwardBufferDuration = 15
2021-06-16 02:51:57 +05:30
statusObservation?.invalidate()
statusObservation = playerItemWithMetadata.observe(\.status, options: [.old, .new]) { playerItem, _ in
switch playerItem.status {
case .readyToPlay:
if self.isAutoplaying(playerItem) {
self.player.play()
}
default:
return
}
2021-06-18 15:47:01 +05:30
}
logger.info("item metadata retrieved")
return playerItemWithMetadata
2021-06-18 15:47:01 +05:30
}
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
}
}
private func composition(_ video: Video, for stream: Stream) -> AVMutableComposition? {
if let index = queue.firstIndex(where: { $0.video == video }) {
if queue[index].compositions[stream].isNil {
queue[index].compositions[stream] = AVMutableComposition()
}
return queue[index].compositions[stream]!
2021-06-18 04:13:29 +05:30
}
2021-07-22 18:13:13 +05:30
return nil
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
}
private 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
}