yattee/Apple TV/PlayerViewController.swift

184 lines
5.8 KiB
Swift
Raw Normal View History

2021-06-14 18:05:02 +00:00
import AVKit
import Foundation
2021-06-15 16:35:21 +00:00
import Logging
2021-06-14 18:05:02 +00:00
import SwiftUI
struct PlayerViewController: UIViewControllerRepresentable {
@ObservedObject private var state = PlayerState()
@ObservedObject var video: Video
var player = AVPlayer()
var composition = AVMutableComposition()
2021-06-15 16:35:21 +00:00
let logger = Logger(label: "net.arekf.Pearvidious.pvc")
2021-06-14 18:05:02 +00:00
var playerItem: AVPlayerItem {
let playerItem = AVPlayerItem(asset: composition)
playerItem.externalMetadata = [makeMetadataItem(.commonIdentifierTitle, value: video.title)]
2021-06-15 16:35:21 +00:00
playerItem.preferredForwardBufferDuration = 10
2021-06-14 18:05:02 +00:00
return playerItem
}
init(video: Video) {
self.video = video
2021-06-15 16:35:21 +00:00
loadStream(video.defaultStream)
2021-06-14 18:05:02 +00:00
}
2021-06-15 16:35:21 +00:00
func loadStream(_ stream: Stream?) {
if stream != state.streamToLoad {
state.loadStream(stream)
addTracksAndLoadAssets(state.streamToLoad, loadBest: true)
}
}
2021-06-14 18:05:02 +00:00
2021-06-15 16:35:21 +00:00
func loadBestStream() {
guard state.currentStream != video.bestStream else {
return
}
2021-06-14 18:05:02 +00:00
2021-06-15 16:35:21 +00:00
loadStream(video.bestStream)
}
2021-06-14 18:05:02 +00:00
2021-06-15 16:35:21 +00:00
func addTracksAndLoadAssets(_ stream: Stream, loadBest: Bool = false) {
logger.info("adding tracks and loading assets for: \(stream.type), \(stream.description)")
2021-06-14 18:05:02 +00:00
2021-06-15 16:35:21 +00:00
stream.assets.forEach { asset in
asset.loadValuesAsynchronously(forKeys: ["playable"]) {
handleAssetLoad(stream, type: asset == stream.videoAsset ? .video : .audio, loadBest: loadBest)
2021-06-14 18:05:02 +00:00
}
}
2021-06-15 16:35:21 +00:00
}
2021-06-14 18:05:02 +00:00
2021-06-15 16:35:21 +00:00
func addTrack(_ asset: AVURLAsset, type: AVMediaType) {
guard let assetTrack = asset.tracks(withMediaType: type).first else {
return
}
2021-06-14 18:05:02 +00:00
2021-06-15 16:35:21 +00:00
if let track = composition.tracks(withMediaType: type).first {
logger.info("removing \(type) track")
composition.removeTrack(track)
2021-06-14 18:05:02 +00:00
}
2021-06-15 16:35:21 +00:00
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 18:05:02 +00:00
}
2021-06-15 16:35:21 +00:00
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 18:05:02 +00:00
2021-06-15 16:35:21 +00:00
loadedAssets.forEach { asset in
logger.info("both assets loaded: \(stream.type), \(stream.description)")
2021-06-14 18:05:02 +00:00
2021-06-15 16:35:21 +00:00
if stream.type == .stream {
addTrack(asset, type: .video)
addTrack(asset, type: .audio)
} else {
addTrack(asset, type: type)
2021-06-14 18:05:02 +00:00
}
2021-06-15 16:35:21 +00:00
if stream.assetsLoaded {
let resumeAt = player.currentTime()
if resumeAt.seconds > 0 {
state.seekTo = resumeAt
}
2021-06-14 18:05:02 +00:00
2021-06-15 16:35:21 +00:00
logger.warning("replacing player item")
player.replaceCurrentItem(with: playerItem)
state.streamDidLoad(stream)
2021-06-14 18:05:02 +00:00
2021-06-15 16:35:21 +00:00
if let time = state.seekTo {
player.seek(to: time)
}
2021-06-14 18:05:02 +00:00
2021-06-15 16:35:21 +00:00
player.play()
2021-06-14 18:05:02 +00:00
2021-06-15 16:35:21 +00:00
if loadBest {
loadBestStream()
}
2021-06-14 18:05:02 +00:00
}
}
}
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 16:35:21 +00:00
controller.player?.automaticallyWaitsToMinimizeStalling = true
2021-06-14 18:05:02 +00:00
return controller
}
func updateUIViewController(_ controller: AVPlayerViewController, context _: Context) {
2021-06-15 16:35:21 +00:00
var items: [UIMenuElement] = []
if state.streamToLoad != nil {
items.append(actionsMenu)
}
items.append(streamingQualityMenu)
controller.transportBarCustomMenuItems = items
2021-06-14 18:05:02 +00:00
}
var streamingQualityMenu: UIMenu {
2021-06-15 16:35:21 +00:00
UIMenu(title: "Streaming quality", image: UIImage(systemName: "waveform"), children: streamingQualityMenuActions)
2021-06-14 18:05:02 +00:00
}
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 16:35:21 +00:00
guard state.currentStream != stream else {
return
}
state.streamToLoad = stream
addTracksAndLoadAssets(state.streamToLoad)
2021-06-14 18:05:02 +00:00
}
}
}
}
2021-06-15 16:35:21 +00:00
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 18:05:02 +00:00
}