yattee/Model/PlayerState.swift

246 lines
7.0 KiB
Swift
Raw Normal View History

2021-06-14 18:05:02 +00:00
import AVFoundation
import Foundation
2021-06-15 16:35:21 +00:00
import Logging
2021-06-18 10:17:01 +00:00
import UIKit
2021-06-14 18:05:02 +00:00
final class PlayerState: ObservableObject {
2021-06-15 16:35:21 +00:00
let logger = Logger(label: "net.arekf.Pearvidious.ps")
2021-06-15 21:21:57 +00:00
var video: Video
2021-06-16 19:12:41 +00:00
@Published private(set) var player: AVPlayer! = AVPlayer()
2021-06-18 10:17:01 +00:00
@Published private(set) var composition = AVMutableComposition()
@Published private(set) var nextComposition = AVMutableComposition()
2021-06-15 16:35:21 +00:00
@Published private(set) var currentStream: Stream!
2021-06-18 10:17:01 +00:00
@Published private(set) var nextStream: Stream!
2021-06-16 19:12:41 +00:00
@Published private(set) var streamLoading = false
2021-06-15 16:35:21 +00:00
2021-06-17 22:43:29 +00:00
@Published private(set) var currentTime: CMTime?
2021-06-16 19:12:41 +00:00
@Published private(set) var savedTime: CMTime?
2021-06-18 10:17:01 +00:00
2021-06-17 22:43:29 +00:00
@Published var currentSegment: Segment?
2021-06-15 21:21:57 +00:00
2021-06-19 20:10:14 +00:00
private var profile = Profile()
@Published private(set) var currentRate: Float = 0.0
static let availablePlaybackRates: [Double] = [0.25, 0.5, 0.75, 1, 1.25, 1.5, 1.75, 2]
2021-06-15 21:21:57 +00:00
var playerItem: AVPlayerItem {
let playerItem = AVPlayerItem(asset: composition)
2021-06-18 10:17:01 +00:00
var externalMetadata = [
2021-06-17 22:43:29 +00:00
makeMetadataItem(.commonIdentifierTitle, value: video.title),
makeMetadataItem(.quickTimeMetadataGenre, value: video.genre),
2021-06-19 20:17:48 +00:00
makeMetadataItem(.commonIdentifierDescription, value: video.description)
2021-06-17 22:43:29 +00:00
]
2021-06-18 10:17:01 +00:00
if let thumbnailData = try? Data(contentsOf: video.thumbnailURL!),
let image = UIImage(data: thumbnailData),
let pngData = image.pngData()
{
let artworkItem = makeMetadataItem(.commonIdentifierArtwork, value: pngData)
externalMetadata.append(artworkItem)
}
playerItem.externalMetadata = externalMetadata
2021-06-15 21:21:57 +00:00
playerItem.preferredForwardBufferDuration = 10
return playerItem
}
2021-06-17 22:43:29 +00:00
var segmentsProvider: SponsorBlockSegmentsProvider
var timeObserver: Any?
2021-06-15 21:21:57 +00:00
init(_ video: Video) {
self.video = video
2021-06-17 22:43:29 +00:00
segmentsProvider = SponsorBlockSegmentsProvider(video.id)
segmentsProvider.load()
2021-06-15 21:21:57 +00:00
}
2021-06-16 19:12:41 +00:00
deinit {
destroyPlayer()
2021-06-15 16:35:21 +00:00
}
func loadStream(_ stream: Stream?) {
2021-06-18 10:17:01 +00:00
guard nextStream != stream else {
2021-06-15 16:35:21 +00:00
return
}
2021-06-18 10:17:01 +00:00
nextStream?.cancelLoadingAssets()
removeTracksFromNextComposition()
2021-06-15 16:35:21 +00:00
2021-06-15 21:21:57 +00:00
DispatchQueue.main.async {
self.streamLoading = true
2021-06-18 10:17:01 +00:00
self.nextStream = stream
2021-06-15 21:21:57 +00:00
}
2021-06-18 10:17:01 +00:00
logger.info("replace streamToLoad: \(nextStream?.description ?? "nil"), streamLoading \(streamLoading)")
2021-06-15 16:35:21 +00:00
}
func streamDidLoad(_ stream: Stream?) {
logger.info("didload stream: \(stream!.description)")
2021-06-17 22:43:29 +00:00
currentStream?.cancelLoadingAssets()
2021-06-15 16:35:21 +00:00
currentStream = stream
2021-06-18 10:17:01 +00:00
streamLoading = nextStream != stream
2021-06-15 16:35:21 +00:00
2021-06-18 10:17:01 +00:00
if nextStream == stream {
nextStream = nil
2021-06-15 16:35:21 +00:00
}
2021-06-17 22:43:29 +00:00
addTimeObserver()
2021-06-16 19:12:41 +00:00
}
2021-06-15 16:35:21 +00:00
2021-06-16 19:12:41 +00:00
func cancelLoadingStream(_ stream: Stream) {
2021-06-18 10:17:01 +00:00
guard nextStream == stream else {
2021-06-16 19:12:41 +00:00
return
}
2021-06-18 10:17:01 +00:00
nextStream = nil
2021-06-16 19:12:41 +00:00
streamLoading = false
2021-06-18 10:17:01 +00:00
logger.info("cancel streamToLoad: \(nextStream?.description ?? "nil"), streamLoading \(streamLoading)")
2021-06-15 16:35:21 +00:00
}
2021-06-15 21:21:57 +00:00
2021-06-16 19:12:41 +00:00
func playStream(_ stream: Stream) {
guard player != nil else {
return
}
2021-06-15 21:21:57 +00:00
logger.warning("loading \(stream.description) to player")
2021-06-16 19:12:41 +00:00
saveTime()
2021-06-18 10:17:01 +00:00
replaceCompositionTracks()
2021-06-15 21:21:57 +00:00
player.replaceCurrentItem(with: playerItem)
streamDidLoad(stream)
2021-06-19 20:10:14 +00:00
player.play()
2021-06-16 19:12:41 +00:00
seekToSavedTime()
2021-06-15 21:21:57 +00:00
}
2021-06-18 10:17:01 +00:00
func addTrackToNextComposition(_ asset: AVURLAsset, type: AVMediaType) {
guard let assetTrack = asset.tracks(withMediaType: type).first else {
return
}
if let track = nextComposition.tracks(withMediaType: type).first {
logger.info("removing \(type) track")
nextComposition.removeTrack(track)
}
let track = nextComposition.addMutableTrack(withMediaType: type, preferredTrackID: kCMPersistentTrackID_Invalid)!
try! track.insertTimeRange(
CMTimeRange(start: .zero, duration: CMTime(seconds: video.length, preferredTimescale: 1000)),
of: assetTrack,
at: .zero
)
logger.info("inserted \(type) track")
}
func replaceCompositionTracks() {
logger.warning("replacing compositions")
composition = AVMutableComposition()
nextComposition.tracks.forEach { track in
let newTrack = composition.addMutableTrack(withMediaType: track.mediaType, preferredTrackID: kCMPersistentTrackID_Invalid)!
try? newTrack.insertTimeRange(
CMTimeRange(start: .zero, duration: CMTime(seconds: video.length, preferredTimescale: 1000)),
of: track,
at: .zero
)
}
}
func removeTracksFromNextComposition() {
nextComposition.tracks.forEach { nextComposition.removeTrack($0) }
}
2021-06-16 19:12:41 +00:00
func saveTime() {
guard player != nil else {
return
}
2021-06-15 21:21:57 +00:00
let currentTime = player.currentTime()
guard currentTime.seconds > 0 else {
return
}
savedTime = currentTime
}
2021-06-16 19:12:41 +00:00
func seekToSavedTime() {
guard player != nil else {
return
}
2021-06-15 21:21:57 +00:00
if let time = savedTime {
2021-06-19 20:10:14 +00:00
logger.info("seeking to \(time.seconds)")
2021-06-15 21:21:57 +00:00
player.seek(to: time)
}
}
2021-06-16 19:12:41 +00:00
func destroyPlayer() {
logger.critical("destroying player")
player.currentItem?.tracks.forEach { $0.assetTrack?.asset?.cancelLoading() }
currentStream?.cancelLoadingAssets()
2021-06-18 10:17:01 +00:00
nextStream?.cancelLoadingAssets()
2021-06-16 19:12:41 +00:00
player.cancelPendingPrerolls()
player.replaceCurrentItem(with: nil)
2021-06-17 22:43:29 +00:00
if timeObserver != nil {
player.removeTimeObserver(timeObserver!)
}
}
func addTimeObserver() {
let interval = CMTime(value: 1, timescale: 1)
timeObserver = player.addPeriodicTimeObserver(forInterval: interval, queue: .main) { time in
self.currentTime = time
2021-06-19 20:10:14 +00:00
let currentSegment = self.segmentsProvider.segments.first { $0.timeInSegment(time) }
if let segment = currentSegment {
if self.profile.skippedSegmentsCategories.contains(segment.category) {
if segment.shouldSkip(self.currentTime!) {
self.player.seek(to: segment.skipTo)
}
}
}
if self.player.rate != self.currentRate, self.player.rate != 0, self.currentRate != 0 {
self.player.rate = self.currentRate
}
self.currentSegment = currentSegment
2021-06-17 22:43:29 +00:00
}
2021-06-16 19:12:41 +00:00
}
2021-06-15 21:21:57 +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
}
2021-06-19 20:10:14 +00:00
func setPlayerRate(_ rate: Float) {
currentRate = rate
player.rate = rate
}
2021-06-14 18:05:02 +00:00
}