1
0
mirror of https://github.com/yattee/yattee.git synced 2024-12-15 14:50:32 +05:30
yattee/Apple TV/PlayerViewController.swift

184 lines
5.8 KiB
Swift
Raw Normal View History

2021-06-14 23:35:02 +05:30
import AVKit
import Foundation
2021-06-15 22:05:21 +05:30
import Logging
2021-06-14 23:35:02 +05:30
import SwiftUI
struct PlayerViewController: UIViewControllerRepresentable {
@ObservedObject private var state = PlayerState()
@ObservedObject var video: Video
var player = AVPlayer()
var composition = AVMutableComposition()
2021-06-15 22:05:21 +05:30
let logger = Logger(label: "net.arekf.Pearvidious.pvc")
2021-06-14 23:35:02 +05:30
var playerItem: AVPlayerItem {
let playerItem = AVPlayerItem(asset: composition)
playerItem.externalMetadata = [makeMetadataItem(.commonIdentifierTitle, value: video.title)]
2021-06-15 22:05:21 +05:30
playerItem.preferredForwardBufferDuration = 10
2021-06-14 23:35:02 +05:30
return playerItem
}
init(video: Video) {
self.video = video
2021-06-15 22:05:21 +05:30
loadStream(video.defaultStream)
2021-06-14 23:35:02 +05:30
}
2021-06-15 22:05:21 +05:30
func loadStream(_ stream: Stream?) {
if stream != state.streamToLoad {
state.loadStream(stream)
addTracksAndLoadAssets(state.streamToLoad, loadBest: true)
}
}
2021-06-14 23:35:02 +05:30
2021-06-15 22:05:21 +05:30
func loadBestStream() {
guard state.currentStream != video.bestStream else {
return
}
2021-06-14 23:35:02 +05:30
2021-06-15 22:05:21 +05:30
loadStream(video.bestStream)
}
2021-06-14 23:35:02 +05:30
2021-06-15 22:05:21 +05:30
func addTracksAndLoadAssets(_ stream: Stream, loadBest: Bool = false) {
logger.info("adding tracks and loading assets for: \(stream.type), \(stream.description)")
2021-06-14 23:35:02 +05:30
2021-06-15 22:05:21 +05:30
stream.assets.forEach { asset in
asset.loadValuesAsynchronously(forKeys: ["playable"]) {
handleAssetLoad(stream, type: asset == stream.videoAsset ? .video : .audio, loadBest: loadBest)
2021-06-14 23:35:02 +05:30
}
}
2021-06-15 22:05:21 +05:30
}
2021-06-14 23:35:02 +05:30
2021-06-15 22:05:21 +05:30
func addTrack(_ asset: AVURLAsset, type: AVMediaType) {
guard let assetTrack = asset.tracks(withMediaType: type).first else {
return
}
2021-06-14 23:35:02 +05:30
2021-06-15 22:05:21 +05:30
if let track = composition.tracks(withMediaType: type).first {
logger.info("removing \(type) track")
composition.removeTrack(track)
2021-06-14 23:35:02 +05:30
}
2021-06-15 22:05:21 +05:30
let track = composition.addMutableTrack(withMediaType: type, preferredTrackID: kCMPersistentTrackID_Invalid)!
try! track.insertTimeRange(
CMTimeRange(start: .zero, duration: CMTime(seconds: video.length, preferredTimescale: 1)),
of: assetTrack,
at: .zero
)
logger.info("inserted \(type) track")
2021-06-14 23:35:02 +05:30
}
2021-06-15 22:05:21 +05:30
func handleAssetLoad(_ stream: Stream, type: AVMediaType, loadBest: Bool = false) {
logger.info("handling asset load: \(stream.type), \(stream.description)")
guard stream != state.currentStream else {
logger.warning("IGNORING assets loaded: \(stream.type), \(stream.description)")
return
}
let loadedAssets = stream.assets.filter { $0.statusOfValue(forKey: "playable", error: nil) == .loaded }
2021-06-14 23:35:02 +05:30
2021-06-15 22:05:21 +05:30
loadedAssets.forEach { asset in
logger.info("both assets loaded: \(stream.type), \(stream.description)")
2021-06-14 23:35:02 +05:30
2021-06-15 22:05:21 +05:30
if stream.type == .stream {
addTrack(asset, type: .video)
addTrack(asset, type: .audio)
} else {
addTrack(asset, type: type)
2021-06-14 23:35:02 +05:30
}
2021-06-15 22:05:21 +05:30
if stream.assetsLoaded {
let resumeAt = player.currentTime()
if resumeAt.seconds > 0 {
state.seekTo = resumeAt
}
2021-06-14 23:35:02 +05:30
2021-06-15 22:05:21 +05:30
logger.warning("replacing player item")
player.replaceCurrentItem(with: playerItem)
state.streamDidLoad(stream)
2021-06-14 23:35:02 +05:30
2021-06-15 22:05:21 +05:30
if let time = state.seekTo {
player.seek(to: time)
}
2021-06-14 23:35:02 +05:30
2021-06-15 22:05:21 +05:30
player.play()
2021-06-14 23:35:02 +05:30
2021-06-15 22:05:21 +05:30
if loadBest {
loadBestStream()
}
2021-06-14 23:35:02 +05:30
}
}
}
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
}
func makeUIViewController(context _: Context) -> AVPlayerViewController {
let controller = AVPlayerViewController()
controller.transportBarCustomMenuItems = [streamingQualityMenu]
controller.modalPresentationStyle = .fullScreen
controller.player = player
2021-06-15 22:05:21 +05:30
controller.player?.automaticallyWaitsToMinimizeStalling = true
2021-06-14 23:35:02 +05:30
return controller
}
func updateUIViewController(_ controller: AVPlayerViewController, context _: Context) {
2021-06-15 22:05:21 +05:30
var items: [UIMenuElement] = []
if state.streamToLoad != nil {
items.append(actionsMenu)
}
items.append(streamingQualityMenu)
controller.transportBarCustomMenuItems = items
2021-06-14 23:35:02 +05:30
}
var streamingQualityMenu: UIMenu {
2021-06-15 22:05:21 +05:30
UIMenu(title: "Streaming quality", image: UIImage(systemName: "waveform"), children: streamingQualityMenuActions)
2021-06-14 23:35:02 +05:30
}
var streamingQualityMenuActions: [UIAction] {
video.selectableStreams.map { stream in
let image = self.state.currentStream == stream ? UIImage(systemName: "checkmark") : nil
return UIAction(title: stream.description, image: image) { _ in
DispatchQueue.main.async {
2021-06-15 22:05:21 +05:30
guard state.currentStream != stream else {
return
}
state.streamToLoad = stream
addTracksAndLoadAssets(state.streamToLoad)
2021-06-14 23:35:02 +05:30
}
}
}
}
2021-06-15 22:05:21 +05:30
var actionsMenu: UIMenu {
UIMenu(title: "Actions", image: UIImage(systemName: "bolt.horizontal.fill"), children: [cancelLoadingAction])
}
var cancelLoadingAction: UIAction {
UIAction(title: "Cancel loading \(state.streamToLoad.description) stream") { _ in
DispatchQueue.main.async {
state.streamToLoad.cancelLoadingAssets()
state.cancelLoadingStream(state.streamToLoad)
}
}
}
2021-06-14 23:35:02 +05:30
}