yattee/Model/Player/PlayerQueue.swift

345 lines
9.9 KiB
Swift
Raw Normal View History

import AVKit
2021-10-25 08:25:41 +00:00
import Defaults
import Foundation
2021-10-16 22:48:58 +00:00
import Siesta
import SwiftUI
extension PlayerModel {
var currentVideo: Video? {
currentItem?.video
}
2022-09-04 15:23:02 +00:00
func play(_ videos: [Video], shuffling: Bool = false) {
playbackMode = shuffling ? .shuffle : .queue
2022-08-13 14:46:45 +00:00
videos.forEach { enqueueVideo($0, loadDetails: false) }
2022-07-10 22:24:56 +00:00
#if os(iOS)
2022-08-26 08:25:07 +00:00
onPresentPlayer.append { [weak self] in self?.advanceToNextItem() }
2022-07-10 22:24:56 +00:00
#else
advanceToNextItem()
#endif
show()
}
func playNext(_ video: Video) {
enqueueVideo(video, play: currentItem.isNil, prepending: true)
}
func playNow(_ video: Video, at time: CMTime? = nil) {
if playingInPictureInPicture, closePiPOnNavigation {
closePiP()
}
prepareCurrentItemForHistory()
enqueueVideo(video, play: true, atTime: time, prepending: true) { _, item in
2021-10-24 09:16:04 +00:00
self.advanceToItem(item, at: time)
}
}
func playItem(_ item: PlayerQueueItem, at time: CMTime? = nil) {
2022-07-10 22:24:56 +00:00
advancing = false
2022-08-14 17:06:22 +00:00
if !playingInPictureInPicture, !currentItem.isNil {
2022-02-16 20:23:11 +00:00
backend.closeItem()
}
comments.reset()
stream = nil
currentItem = item
2021-10-24 09:16:04 +00:00
if !time.isNil {
currentItem.playbackTime = time
2021-10-24 09:16:04 +00:00
} else if currentItem.playbackTime.isNil {
currentItem.playbackTime = .zero
}
2021-12-17 20:01:05 +00:00
preservedTime = currentItem.playbackTime
DispatchQueue.main.async { [weak self] in
2022-09-28 14:27:01 +00:00
guard let self else { return }
2022-11-11 18:19:48 +00:00
guard let video = item.video else {
return
}
2022-08-16 21:16:35 +00:00
self.videoBeingOpened = nil
2022-11-11 18:19:48 +00:00
if video.isLocal {
self.availableStreams = video.streams
return
}
2022-08-16 21:16:35 +00:00
guard let playerInstance = self.playerInstance else { return }
let streamsInstance = video.streams.compactMap(\.instance).first
2022-11-11 18:19:48 +00:00
if video.streams.isEmpty || streamsInstance != playerInstance {
2022-08-16 21:16:35 +00:00
self.loadAvailableStreams(video)
} else {
2022-08-16 21:16:35 +00:00
self.availableStreams = self.streamsWithInstance(instance: playerInstance, streams: video.streams)
}
}
}
2022-08-16 21:16:35 +00:00
var playerInstance: Instance? {
InstancesModel.forPlayer ?? accounts.current?.instance ?? InstancesModel.all.first
}
var playerAPI: VideosAPI {
playerInstance?.anonymous ?? accounts.api
}
2022-08-14 17:06:22 +00:00
var qualityProfile: QualityProfile? {
qualityProfileSelection ?? QualityProfilesModel.shared.automaticProfile
}
var streamByQualityProfile: Stream? {
let profile = qualityProfile ?? .defaultProfile
if let streamPreferredForProfile = backend.bestPlayable(
availableStreams.filter { backend.canPlay($0) && profile.isPreferred($0) },
maxResolution: profile.resolution
) {
return streamPreferredForProfile
}
return backend.bestPlayable(availableStreams.filter { backend.canPlay($0) }, maxResolution: profile.resolution)
2021-11-03 23:40:01 +00:00
}
func advanceToNextItem() {
2022-07-10 22:24:56 +00:00
guard !advancing else {
return
}
advancing = true
prepareCurrentItemForHistory()
2022-07-10 22:24:56 +00:00
var nextItem: PlayerQueueItem?
switch playbackMode {
case .queue:
nextItem = queue.first
case .shuffle:
nextItem = queue.randomElement()
case .related:
nextItem = autoplayItem
case .loopOne:
nextItem = nil
}
resetAutoplay()
2022-09-28 14:27:01 +00:00
if let nextItem {
advanceToItem(nextItem)
2022-08-14 17:06:22 +00:00
} else {
advancing = false
}
}
2022-07-10 22:24:56 +00:00
var isAdvanceToNextItemAvailable: Bool {
switch playbackMode {
case .loopOne:
return false
case .queue, .shuffle:
return !queue.isEmpty
case .related:
return !autoplayItem.isNil
}
}
func advanceToItem(_ newItem: PlayerQueueItem, at time: CMTime? = nil) {
prepareCurrentItemForHistory()
remove(newItem)
currentItem = newItem
2022-07-21 20:58:32 +00:00
currentItem.playbackTime = time
2022-07-21 20:58:32 +00:00
let playTime = currentItem.shouldRestartPlaying ? CMTime.zero : time
playerAPI.loadDetails(currentItem, failureHandler: { self.videoLoadFailureHandler($0, video: self.currentItem.video) }) { newItem in
2022-07-21 20:58:32 +00:00
self.playItem(newItem, at: playTime)
}
}
@discardableResult func remove(_ item: PlayerQueueItem) -> PlayerQueueItem? {
2021-10-26 22:59:59 +00:00
if let index = queue.firstIndex(where: { $0.videoID == item.videoID }) {
return queue.remove(at: index)
}
return nil
}
func resetQueue() {
DispatchQueue.main.async { [weak self] in
2022-09-28 14:27:01 +00:00
guard let self else {
return
}
self.currentItem = nil
self.stream = nil
self.removeQueueItems()
}
2022-02-16 20:23:11 +00:00
backend.closeItem()
}
@discardableResult func enqueueVideo(
_ video: Video,
play: Bool = false,
atTime: CMTime? = nil,
prepending: Bool = false,
loadDetails: Bool = true,
videoDetailsLoadHandler: @escaping (Video, PlayerQueueItem) -> Void = { _, _ in }
) -> PlayerQueueItem? {
let item = PlayerQueueItem(video, playbackTime: atTime)
if play {
currentItem = item
videoBeingOpened = video
}
if loadDetails {
playerAPI.loadDetails(item, failureHandler: { self.videoLoadFailureHandler($0, video: video) }) { [weak self] newItem in
2022-09-28 14:27:01 +00:00
guard let self else { return }
videoDetailsLoadHandler(newItem.video, newItem)
if play {
self.playItem(newItem)
} else {
self.queue.insert(newItem, at: prepending ? 0 : self.queue.endIndex)
}
}
} else {
2022-11-10 17:11:28 +00:00
videoDetailsLoadHandler(video, item)
queue.insert(item, at: prepending ? 0 : queue.endIndex)
}
return item
}
func prepareCurrentItemForHistory(finished: Bool = false) {
2022-11-10 17:11:28 +00:00
if let currentItem {
if Defaults[.saveHistory] {
if let video = currentVideo, !historyVideos.contains(where: { $0 == video }) {
historyVideos.append(video)
}
updateWatch(finished: finished)
}
if let video = currentItem.video,
video.isLocal,
video.localStreamIsFile,
let localURL = video.localStream?.localURL
{
logger.info("stopping security scoped resource access for \(localURL)")
localURL.stopAccessingSecurityScopedResource()
}
}
}
func playHistory(_ item: PlayerQueueItem, at time: CMTime? = nil) {
2022-06-29 21:57:42 +00:00
guard let video = item.video else { return }
var time = time ?? item.playbackTime
if item.shouldRestartPlaying {
time = .zero
}
2022-06-29 21:57:42 +00:00
let newItem = enqueueVideo(video, atTime: time, prepending: true)
2021-10-13 22:05:19 +00:00
advanceToItem(newItem!, at: time)
}
func removeQueueItems() {
queue.removeAll()
}
2022-01-09 15:05:05 +00:00
func restoreQueue() {
var restoredQueue = [PlayerQueueItem?]()
2022-09-28 14:27:01 +00:00
if let lastPlayed,
!Defaults[.queue].contains(where: { $0.videoID == lastPlayed.videoID })
{
restoredQueue.append(lastPlayed)
self.lastPlayed = nil
}
restoredQueue.append(contentsOf: Defaults[.queue])
queue = restoredQueue.compactMap { $0 }
2022-06-26 11:12:32 +00:00
}
2022-01-09 15:05:05 +00:00
2022-06-26 11:12:32 +00:00
func loadQueueVideoDetails(_ item: PlayerQueueItem) {
guard !accounts.current.isNil, !item.hasDetailsLoaded else { return }
2022-11-10 17:11:28 +00:00
let videoID = item.video?.videoID ?? item.videoID
if queueItemBeingLoaded == nil {
logger.info("loading queue details: \(videoID)")
queueItemBeingLoaded = item
} else {
logger.info("POSTPONING details load: \(videoID)")
queueItemsToLoad.append(item)
return
}
playerAPI.loadDetails(item, completionHandler: { [weak self] newItem in
guard let self else { return }
self.queue.filter { $0.videoID == item.videoID }.forEach { item in
if let index = self.queue.firstIndex(of: item) {
self.queue[index] = newItem
}
}
self.logger.info("LOADED queue details: \(videoID)")
if self.queueItemBeingLoaded == item {
self.logger.info("setting nothing loaded")
self.queueItemBeingLoaded = nil
}
if let item = self.queueItemsToLoad.popLast() {
self.loadQueueVideoDetails(item)
2022-01-09 15:05:05 +00:00
}
2022-06-29 22:44:32 +00:00
})
}
private func videoLoadFailureHandler(_ error: RequestError, video: Video? = nil) {
var message = error.userMessage
if let errorDictionary = error.json.dictionaryObject,
let errorMessage = errorDictionary["message"] ?? errorDictionary["error"],
let errorString = errorMessage as? String
{
message += "\n"
message += errorString
}
2022-11-13 17:50:23 +00:00
var retryButton: Alert.Button?
if let video {
retryButton = Alert.Button.default(Text("Retry")) { [weak self] in
if let self {
self.enqueueVideo(video, play: true, prepending: true, loadDetails: true)
}
}
2022-11-13 17:50:23 +00:00
}
var alert: Alert
if let retryButton {
alert = Alert(
title: Text("Could not load video"),
message: Text(message),
primaryButton: .cancel(),
secondaryButton: retryButton
)
} else {
alert = Alert(title: Text("Could not load video"))
}
navigation.presentAlert(alert)
2022-07-10 22:24:56 +00:00
advancing = false
2022-06-29 22:44:32 +00:00
videoBeingOpened = nil
currentItem = nil
2022-01-09 15:05:05 +00:00
}
}