1
0
mirror of https://github.com/yattee/yattee.git synced 2024-12-13 22:00:31 +05:30
yattee/Model/Player/PlayerModel.swift

985 lines
30 KiB
Swift
Raw Normal View History

import AVKit
import CoreData
#if os(iOS)
import CoreMotion
#endif
import Defaults
2021-06-14 23:35:02 +05:30
import Foundation
2021-06-15 22:05:21 +05:30
import Logging
2021-10-29 01:48:23 +05:30
import MediaPlayer
2021-10-17 04:18:58 +05:30
import Siesta
2021-10-23 22:19:45 +05:30
import SwiftUI
2021-10-17 04:18:58 +05:30
import SwiftyJSON
#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 {
2022-07-11 03:54:56 +05:30
enum PlaybackMode: String, CaseIterable, Defaults.Serializable {
case queue, shuffle, loopOne, related
var systemImage: String {
switch self {
case .queue:
return "list.number"
case .shuffle:
return "shuffle"
case .loopOne:
return "repeat.1"
case .related:
return "infinity"
}
}
var description: String {
switch self {
case .queue:
return "Queue"
case .shuffle:
return "Queue, shuffled"
case .loopOne:
return "Loop one"
case .related:
return "Autoplay next"
}
}
2022-07-11 03:54:56 +05:30
}
2021-11-02 22:54:59 +05:30
static let availableRates: [Float] = [0.5, 0.67, 0.8, 1, 1.25, 1.5, 2]
2021-11-07 19:02:01 +05:30
let logger = Logger(label: "stream.yattee.app")
2021-06-15 22:05:21 +05:30
2022-02-28 02:01:17 +05:30
var avPlayerView = AppleAVPlayerView()
var playerItem: AVPlayerItem?
2021-06-16 02:51:57 +05:30
2022-02-17 01:53:11 +05:30
var mpvPlayerView = MPVPlayerView()
2022-08-29 19:19:27 +05:30
@Published var presentingPlayer = false
2022-02-17 01:53:11 +05:30
@Published var activeBackend = PlayerBackendType.mpv
var avPlayerBackend: AVPlayerBackend!
var mpvBackend: MPVBackend!
2022-08-14 22:23:03 +05:30
#if !os(macOS)
var mpvController = MPVViewController()
#endif
2022-02-17 01:53:11 +05:30
var backends: [PlayerBackend] {
[avPlayerBackend, mpvBackend]
}
2021-06-18 15:47:01 +05:30
2022-02-17 01:53:11 +05:30
var backend: PlayerBackend! {
switch activeBackend {
case .mpv:
return mpvBackend
case .appleAVPlayer:
return avPlayerBackend
}
}
2022-08-19 04:10:46 +05:30
var playerBackendView = PlayerBackendView()
2022-03-27 17:12:20 +05:30
@Published var playerSize: CGSize = .zero { didSet {
2022-08-14 22:29:04 +05:30
#if !os(tvOS)
backend.setSize(playerSize.width, playerSize.height)
#endif
2022-03-27 17:12:20 +05:30
}}
2022-07-10 06:45:15 +05:30
@Published var aspectRatio = VideoPlayerView.defaultAspectRatio
@Published var stream: Stream?
2022-02-17 01:53:11 +05:30
@Published var currentRate: Float = 1.0 { didSet { backend.setRate(currentRate) } }
2021-06-15 22:05:21 +05:30
2022-08-29 17:25:23 +05:30
@Published var qualityProfileSelection: QualityProfile? { didSet { handleQualityProfileChange() } }
2022-08-14 22:36:22 +05:30
@Published var availableStreams = [Stream]() { didSet { handleAvailableStreamsChange() } }
2021-10-23 22:19:45 +05:30
@Published var streamSelection: Stream? { didSet { rebuildTVMenu() } }
2021-10-17 04:18:58 +05:30
2022-06-26 20:16:29 +05:30
@Published var queue = [PlayerQueueItem]() { didSet { handleQueueChange() } }
2022-01-09 20:35:05 +05:30
@Published var currentItem: PlayerQueueItem! { didSet { handleCurrentItemChange() } }
2022-08-29 17:25:23 +05:30
@Published var videoBeingOpened: Video? { didSet { seek.reset() } }
@Published var historyVideos = [Video]()
2021-06-15 22:05:21 +05:30
2021-12-18 01:31:05 +05:30
@Published var preservedTime: CMTime?
2021-06-18 04:13:29 +05:30
2021-10-23 22:19:45 +05:30
@Published var sponsorBlock = SponsorBlockAPI()
@Published var segmentRestorationTime: CMTime?
@Published var lastSkipped: Segment? { didSet { rebuildTVMenu() } }
@Published var restoredSegments = [Segment]()
2022-06-08 02:57:48 +05:30
@Published var musicMode = false
@Published var playbackMode = PlaybackMode.queue { didSet { handlePlaybackModeChange() } }
2022-07-11 03:54:56 +05:30
@Published var autoplayItem: PlayerQueueItem?
@Published var autoplayItemSource: Video?
@Published var advancing = false
2022-03-20 04:34:56 +05:30
@Published var returnYouTubeDislike = ReturnYouTubeDislikeAPI()
@Published var isSeeking = false { didSet {
2022-06-25 05:09:29 +05:30
backend.setNeedsNetworkStateUpdates(true)
}}
2022-07-11 04:56:35 +05:30
#if os(iOS)
@Published var lockedOrientation: UIInterfaceOrientationMask?
@Default(.rotateToPortraitOnExitFullScreen) private var rotateToPortraitOnExitFullScreen
2022-07-11 04:56:35 +05:30
#endif
2021-10-17 04:18:58 +05:30
var accounts: AccountsModel
2021-12-05 01:05:41 +05:30
var comments: CommentsModel
2022-02-17 01:53:11 +05:30
var controls: PlayerControlsModel { didSet {
backends.forEach { backend in
var backend = backend
backend.controls = controls
backend.controls.player = self
2022-02-17 01:53:11 +05:30
}
}}
var playerTime: PlayerTimeModel { didSet {
backends.forEach { backend in
var backend = backend
backend.playerTime = playerTime
backend.playerTime.player = self
}
}}
var networkState: NetworkStateModel { didSet {
backends.forEach { backend in
var backend = backend
backend.networkState = networkState
backend.networkState.player = self
}
}}
2022-08-29 17:25:23 +05:30
var seek: SeekModel { didSet {
backends.forEach { backend in
var backend = backend
backend.seek = seek
backend.seek.player = self
}
}}
2022-06-30 04:14:32 +05:30
var navigation: NavigationModel
var context: NSManagedObjectContext = PersistenceController.shared.container.viewContext
var backgroundContext = PersistenceController.shared.container.newBackgroundContext()
2022-07-10 23:21:46 +05:30
#if os(tvOS)
static let fullScreenIsDefault = true
#else
static let fullScreenIsDefault = false
#endif
@Published var playingFullScreen = PlayerModel.fullScreenIsDefault
2022-02-17 01:53:11 +05:30
@Published var playingInPictureInPicture = false
2022-05-21 02:53:14 +05:30
var pipController: AVPictureInPictureController?
var pipDelegate = PiPDelegate()
2021-10-28 22:44:55 +05:30
2021-11-07 22:22:42 +05:30
var playerError: Error? { didSet {
2022-08-19 04:06:16 +05:30
if let error = playerError {
navigation.presentAlert(title: "Failed loading video", message: error.localizedDescription)
}
2021-11-07 22:22:42 +05:30
}}
2022-08-14 22:36:22 +05:30
@Default(.qualityProfiles) var qualityProfiles
@Default(.forceAVPlayerForLiveStreams) var forceAVPlayerForLiveStreams
@Default(.pauseOnHidingPlayer) private var pauseOnHidingPlayer
@Default(.closePiPOnNavigation) var closePiPOnNavigation
@Default(.closePiPOnOpeningPlayer) var closePiPOnOpeningPlayer
2022-08-08 23:32:46 +05:30
@Default(.resetWatchedStatusOnPlaying) var resetWatchedStatusOnPlaying
#if !os(macOS)
@Default(.closePiPAndOpenPlayerOnEnteringForeground) var closePiPAndOpenPlayerOnEnteringForeground
@Default(.closePlayerOnItemClose) private var closePlayerOnItemClose
#endif
2022-02-17 02:40:57 +05:30
private var currentArtwork: MPMediaItemArtwork?
2022-08-26 13:55:07 +05:30
var onPresentPlayer = [() -> Void]()
private var remoteCommandCenterConfigured = false
2022-02-17 01:53:11 +05:30
init(
accounts: AccountsModel = AccountsModel(),
comments: CommentsModel = CommentsModel(),
controls: PlayerControlsModel = PlayerControlsModel(),
2022-06-30 04:14:32 +05:30
navigation: NavigationModel = NavigationModel(),
playerTime: PlayerTimeModel = PlayerTimeModel(),
2022-08-29 17:25:23 +05:30
networkState: NetworkStateModel = NetworkStateModel(),
seek: SeekModel = SeekModel()
) {
self.accounts = accounts
self.comments = comments
self.controls = controls
2022-06-30 04:14:32 +05:30
self.navigation = navigation
self.playerTime = playerTime
self.networkState = networkState
2022-08-29 17:25:23 +05:30
self.seek = seek
self.avPlayerBackend = AVPlayerBackend(
model: self,
controls: controls,
playerTime: playerTime
)
self.mpvBackend = MPVBackend(
model: self,
playerTime: playerTime,
networkState: networkState
)
2021-10-25 13:55:41 +05:30
2022-08-14 22:23:03 +05:30
#if !os(macOS)
mpvBackend.controller = mpvController
mpvBackend.client = mpvController.client
#endif
2022-06-08 02:57:48 +05:30
Defaults[.activeBackend] = .mpv
2022-07-11 03:54:56 +05:30
playbackMode = Defaults[.playbackMode]
2022-08-19 04:10:46 +05:30
guard pipController.isNil else { return }
pipController = .init(playerLayer: avPlayerBackend.playerLayer)
let pipDelegate = PiPDelegate()
pipDelegate.player = self
self.pipDelegate = pipDelegate
pipController?.delegate = pipDelegate
}
func show() {
#if os(macOS)
if presentingPlayer {
2022-01-06 21:05:45 +05:30
Windows.player.focus()
return
}
#endif
2022-08-25 22:39:55 +05:30
#if os(iOS)
Delay.by(0.5) {
self.navigation.hideKeyboard()
2022-07-09 05:51:04 +05:30
}
2022-08-25 22:39:55 +05:30
#endif
2022-08-29 17:37:27 +05:30
presentingPlayer = true
2022-08-29 21:26:49 +05:30
setNeedsDrawing(true)
#if os(macOS)
2022-01-06 21:05:45 +05:30
Windows.player.open()
Windows.player.focus()
#endif
2021-06-16 02:51:57 +05:30
}
2022-08-25 22:39:55 +05:30
func hide(animate: Bool = true) {
if animate {
withAnimation(.easeOut(duration: 0.2)) {
presentingPlayer = false
}
} else {
2022-08-08 23:32:46 +05:30
presentingPlayer = false
}
2022-06-26 20:53:56 +05:30
DispatchQueue.main.async { [weak self] in
2022-08-25 22:39:55 +05:30
self?.exitFullScreen(showControls: false)
2022-06-26 20:53:56 +05:30
}
#if os(iOS)
if Defaults[.lockPortraitWhenBrowsing] {
Orientation.lockOrientation(.portrait, andRotateTo: .portrait)
} else {
Orientation.lockOrientation(.allButUpsideDown)
}
#endif
2022-08-27 01:47:21 +05:30
#if os(macOS)
Windows.player.hide()
#endif
}
2021-11-09 04:44:28 +05:30
func togglePlayer() {
#if os(macOS)
if !presentingPlayer {
2022-01-06 21:05:45 +05:30
Windows.player.open()
}
2022-01-06 21:05:45 +05:30
Windows.player.focus()
2022-08-27 01:47:21 +05:30
if Windows.player.visible,
closePiPOnOpeningPlayer
{
closePiP()
}
#else
if presentingPlayer {
hide()
} else {
show()
}
#endif
2021-11-09 04:44:28 +05:30
}
var isLoadingVideo: Bool {
guard !currentVideo.isNil else {
return false
}
2022-02-17 01:53:11 +05:30
return backend.isLoadingVideo
}
2021-10-17 04:18:58 +05:30
var isPlaying: Bool {
2022-02-17 01:53:11 +05:30
backend.isPlaying
2021-10-17 04:18:58 +05:30
}
2022-02-17 01:53:11 +05:30
var playerItemDuration: CMTime? {
guard !currentItem.isNil else {
return nil
}
return backend.playerItemDuration
}
2022-02-17 01:53:11 +05:30
var playerItemDurationWithoutSponsorSegments: CMTime? {
guard let playerItemDuration = playerItemDuration, !playerItemDuration.seconds.isZero else {
return nil
}
return playerItemDuration - .secondsInDefaultTimescale(
2022-02-17 01:53:11 +05:30
sponsorBlock.segments.reduce(0) { $0 + $1.duration }
)
2021-10-23 04:34:03 +05:30
}
2022-02-17 01:53:11 +05:30
var videoDuration: TimeInterval? {
2022-07-22 04:14:21 +05:30
playerItemDuration?.seconds ?? currentItem?.duration ?? currentVideo?.length
}
2022-02-17 01:53:11 +05:30
var time: CMTime? {
currentItem?.playbackTime
}
var live: Bool {
currentVideo?.live ?? false
}
2022-07-22 04:14:21 +05:30
var playingLive: Bool {
guard live,
let videoDuration = videoDuration,
let time = backend.currentTime?.seconds else { return false }
return videoDuration - time < 30
}
var liveStreamInAVPlayer: Bool {
live && activeBackend == .appleAVPlayer
}
func togglePlay() {
2022-02-17 01:53:11 +05:30
backend.togglePlay()
2021-06-15 22:05:21 +05:30
}
func play() {
2022-02-17 01:53:11 +05:30
backend.play()
2021-07-30 03:58:28 +05:30
}
func pause() {
2022-02-17 01:53:11 +05:30
backend.pause()
2021-09-25 13:48:22 +05:30
}
2022-05-29 20:08:37 +05:30
func play(_ video: Video, at time: CMTime? = nil, showingPlayer: Bool = true) {
2022-05-31 00:30:53 +05:30
pause()
2022-08-21 02:01:03 +05:30
var changeBackendHandler: (() -> Void)?
if let backend = (live && forceAVPlayerForLiveStreams) ? PlayerBackendType.appleAVPlayer :
(qualityProfile?.backend ?? QualityProfilesModel.shared.automaticProfile?.backend),
activeBackend != backend,
backend == .appleAVPlayer || !avPlayerBackend.startPictureInPictureOnPlay
2022-08-21 02:01:03 +05:30
{
changeBackendHandler = { [weak self] in
guard let self = self else { return }
self.changeActiveBackend(from: self.activeBackend, to: backend)
}
}
2022-05-31 00:30:53 +05:30
#if os(iOS)
if !playingInPictureInPicture, showingPlayer {
2022-08-26 13:55:07 +05:30
onPresentPlayer.append { [weak self] in
2022-08-21 02:01:03 +05:30
changeBackendHandler?()
self?.playNow(video, at: time)
}
show()
return
}
#endif
2022-08-21 02:01:03 +05:30
changeBackendHandler?()
playNow(video, at: time)
guard !playingInPictureInPicture else {
return
}
2022-05-29 20:08:37 +05:30
if showingPlayer {
show()
}
2021-10-17 04:18:58 +05:30
}
2021-07-19 04:02:46 +05:30
func playStream(
2021-10-17 04:18:58 +05:30
_ stream: Stream,
of video: Video,
preservingTime: Bool = false,
2022-08-27 01:47:21 +05:30
upgrading: Bool = false,
withBackend: PlayerBackend? = nil
2021-10-17 04:18:58 +05:30
) {
2021-11-07 22:22:42 +05:30
playerError = nil
if !upgrading {
resetSegments()
DispatchQueue.main.async { [weak self] in
self?.sponsorBlock.loadSegments(
videoID: video.videoID,
categories: Defaults[.sponsorBlockCategories]
)
2022-03-20 04:34:56 +05:30
2022-03-21 02:01:19 +05:30
guard Defaults[.enableReturnYouTubeDislike] else {
return
}
2022-03-20 04:34:56 +05:30
self?.returnYouTubeDislike.loadDislikes(videoID: video.videoID) { [weak self] dislikes in
self?.currentItem?.video?.dislikes = dislikes
}
}
}
2021-10-23 22:19:45 +05:30
2022-08-27 01:47:21 +05:30
(withBackend ?? backend).playStream(
2022-02-17 01:53:11 +05:30
stream,
of: video,
preservingTime: preservingTime,
upgrading: upgrading
)
2022-02-17 02:40:57 +05:30
if !upgrading {
updateCurrentArtwork()
}
2022-02-17 01:53:11 +05:30
}
func saveTime(completionHandler: @escaping () -> Void = {}) {
guard let currentTime = backend.currentTime, currentTime.seconds > 0 else {
2022-05-29 20:08:37 +05:30
completionHandler()
2022-02-17 01:53:11 +05:30
return
2021-07-19 04:02:46 +05:30
}
2021-10-29 01:48:23 +05:30
2022-02-17 01:53:11 +05:30
DispatchQueue.main.async { [weak self] in
self?.preservedTime = currentTime
completionHandler()
}
2021-07-19 04:02:46 +05:30
}
2022-02-17 01:53:11 +05:30
func upgradeToStream(_ stream: Stream, force: Bool = false) {
guard let video = currentVideo else {
return
}
2022-02-17 01:53:11 +05:30
if !self.stream.isNil, force || self.stream != stream {
playStream(stream, of: video, preservingTime: true, upgrading: true)
}
}
2021-12-19 22:26:47 +05:30
private func handleAvailableStreamsChange() {
rebuildTVMenu()
guard stream.isNil else {
return
}
if let backend = (live && forceAVPlayerForLiveStreams) ? PlayerBackendType.appleAVPlayer : qualityProfile?.backend,
backend != activeBackend,
backend == .appleAVPlayer || !(avPlayerBackend.startPictureInPictureOnPlay || playingInPictureInPicture)
2022-08-19 04:10:46 +05:30
{
changeActiveBackend(from: activeBackend, to: backend)
2022-08-14 22:36:22 +05:30
}
guard let stream = streamByQualityProfile else {
2021-12-19 22:26:47 +05:30
return
}
streamSelection = stream
playStream(
stream,
of: currentVideo!,
preservingTime: !currentItem.playbackTime.isNil
)
}
private func handlePresentationChange() {
var delay = 0.0
#if os(iOS)
if presentingPlayer {
delay = 0.2
}
#endif
2022-08-29 21:26:49 +05:30
backend.setNeedsDrawing(presentingPlayer)
controls.hide()
2022-02-17 01:53:11 +05:30
2022-04-03 20:33:56 +05:30
#if !os(macOS)
UIApplication.shared.isIdleTimerDisabled = presentingPlayer
#endif
if presentingPlayer, closePiPOnOpeningPlayer, playingInPictureInPicture {
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { [weak self] in
self?.closePiP()
}
}
if !presentingPlayer, pauseOnHidingPlayer, !playingInPictureInPicture {
2022-08-19 04:10:46 +05:30
DispatchQueue.main.async { [weak self] in
self?.pause()
}
}
2021-11-05 20:28:51 +05:30
}
2022-08-27 01:47:21 +05:30
func changeActiveBackend(from: PlayerBackendType, to: PlayerBackendType, changingStream: Bool = true) {
2022-05-29 20:08:37 +05:30
guard activeBackend != to else {
return
}
logger.info("changing backend from \(from.rawValue) to \(to.rawValue)")
let wasPlaying = isPlaying
2022-08-19 04:10:46 +05:30
if to == .mpv {
closePiP()
}
2022-02-17 01:53:11 +05:30
Defaults[.activeBackend] = to
self.activeBackend = to
2022-08-27 01:47:21 +05:30
let fromBackend: PlayerBackend = from == .appleAVPlayer ? avPlayerBackend : mpvBackend
let toBackend: PlayerBackend = to == .appleAVPlayer ? avPlayerBackend : mpvBackend
2022-08-21 02:01:03 +05:30
self.backend.didChangeTo()
if wasPlaying {
fromBackend.pause()
}
2022-08-27 01:47:21 +05:30
guard var stream = stream, changingStream else {
2021-07-19 04:02:46 +05:30
return
}
2022-02-17 01:53:11 +05:30
if let stream = toBackend.stream, toBackend.video == fromBackend.video {
toBackend.seek(to: fromBackend.currentTime?.seconds ?? .zero, seekType: .backendSync) { finished in
guard finished else {
return
}
if wasPlaying {
toBackend.play()
}
}
2021-10-17 04:18:58 +05:30
2022-02-17 01:53:11 +05:30
self.stream = stream
streamSelection = stream
2021-07-22 18:13:13 +05:30
2021-10-17 04:18:58 +05:30
return
}
if !backend.canPlay(stream) || (to == .mpv && !stream.hlsURL.isNil) {
2022-08-14 22:36:22 +05:30
guard let preferredStream = streamByQualityProfile else {
return
}
2022-02-17 01:53:11 +05:30
stream = preferredStream
streamSelection = preferredStream
}
2022-02-17 01:53:11 +05:30
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { [weak self] in
guard let self = self else {
return
}
self.upgradeToStream(stream, force: true)
}
2021-10-29 01:48:23 +05:30
}
2022-08-14 22:36:22 +05:30
func handleQualityProfileChange() {
guard let profile = qualityProfile else { return }
if activeBackend != profile.backend { changeActiveBackend(from: activeBackend, to: profile.backend) }
guard let profileStream = streamByQualityProfile, stream != profileStream else { return }
DispatchQueue.main.async { [weak self] in
self?.streamSelection = profileStream
self?.upgradeToStream(profileStream)
}
2021-10-29 01:48:23 +05:30
}
2021-11-02 22:54:59 +05:30
func rateLabel(_ rate: Float) -> String {
let formatter = NumberFormatter()
formatter.minimumFractionDigits = 0
formatter.maximumFractionDigits = 2
return "\(formatter.string(from: NSNumber(value: rate))!)×"
}
2021-12-03 01:49:10 +05:30
2022-04-03 17:53:42 +05:30
func closeCurrentItem(finished: Bool = false) {
pause()
2022-08-19 04:10:46 +05:30
closePiP()
2022-04-03 17:53:42 +05:30
prepareCurrentItemForHistory(finished: finished)
2021-12-03 01:49:10 +05:30
currentItem = nil
updateNowPlayingInfo()
2022-02-17 01:53:11 +05:30
backend.closeItem()
2022-07-10 06:45:15 +05:30
aspectRatio = VideoPlayerView.defaultAspectRatio
2022-07-11 03:54:56 +05:30
resetAutoplay()
exitFullScreen()
#if !os(macOS)
2022-08-25 22:39:55 +05:30
if closePlayerOnItemClose { Delay.by(0.2) { self.hide() } }
#endif
2021-12-03 01:49:10 +05:30
}
2022-08-27 01:47:21 +05:30
func startPiP() {
avPlayerBackend.startPictureInPictureOnPlay = false
avPlayerBackend.startPictureInPictureOnSwitch = false
if activeBackend == .appleAVPlayer {
avPlayerBackend.tryStartingPictureInPicture()
return
}
guard let video = currentVideo else { return }
guard let stream = avPlayerBackend.bestPlayable(availableStreams, maxResolution: .hd720p30) else { return }
exitFullScreen()
if avPlayerBackend.video == video {
if activeBackend != .appleAVPlayer {
avPlayerBackend.startPictureInPictureOnSwitch = true
changeActiveBackend(from: activeBackend, to: .appleAVPlayer)
}
} else {
avPlayerBackend.startPictureInPictureOnPlay = true
playStream(stream, of: video, preservingTime: true, upgrading: true, withBackend: avPlayerBackend)
}
controls.objectWillChange.send()
}
var transitioningToPiP: Bool {
avPlayerBackend.startPictureInPictureOnPlay || avPlayerBackend.startPictureInPictureOnSwitch
}
var pipPossible: Bool {
guard activeBackend == .appleAVPlayer else { return !transitioningToPiP }
guard let pipController = pipController else { return false }
guard !pipController.isPictureInPictureActive else { return true }
return pipController.isPictureInPicturePossible && !transitioningToPiP
}
func closePiP() {
guard playingInPictureInPicture else {
return
}
2022-08-27 01:47:21 +05:30
avPlayerBackend.startPictureInPictureOnPlay = false
avPlayerBackend.startPictureInPictureOnSwitch = false
#if os(tvOS)
show()
#endif
2022-08-19 04:10:46 +05:30
backend.closePiP()
2022-06-26 20:16:29 +05:30
}
func handleQueueChange() {
Defaults[.queue] = queue
updateRemoteCommandCenter()
2022-06-26 20:16:29 +05:30
controls.objectWillChange.send()
}
2022-01-09 20:35:05 +05:30
func handleCurrentItemChange() {
2022-01-06 21:05:45 +05:30
#if os(macOS)
Windows.player.window?.title = windowTitle
#endif
2022-01-09 20:35:05 +05:30
2022-06-30 03:42:37 +05:30
DispatchQueue.main.async(qos: .background) { [weak self] in
2022-07-11 03:54:56 +05:30
guard let self = self else { return }
Defaults[.lastPlayed] = self.currentItem
if self.playbackMode == .related,
let video = self.currentVideo,
self.autoplayItemSource.isNil || self.autoplayItemSource?.videoID != video.videoID
{
self.setRelatedAutoplayItem()
}
2022-06-30 03:42:37 +05:30
}
2022-01-06 21:05:45 +05:30
}
2022-07-11 03:54:56 +05:30
func handlePlaybackModeChange() {
Defaults[.playbackMode] = playbackMode
updateRemoteCommandCenter()
2022-07-11 03:54:56 +05:30
guard playbackMode == .related else {
autoplayItem = nil
return
}
setRelatedAutoplayItem()
}
func setRelatedAutoplayItem() {
2022-07-11 23:14:49 +05:30
guard let video = currentVideo else { return }
let related = video.related.filter { $0.videoID != autoplayItem?.video?.videoID }
2022-07-11 03:54:56 +05:30
2022-07-11 23:14:49 +05:30
let watchFetchRequest = Watch.fetchRequest()
watchFetchRequest.predicate = NSPredicate(format: "videoID IN %@", related.map(\.videoID) as [String])
2022-07-11 03:54:56 +05:30
2022-07-11 23:14:49 +05:30
let results = try? context.fetch(watchFetchRequest)
context.perform { [weak self] in
guard let self = self,
let results = results else { return }
let resultsIds = results.map(\.videoID)
guard let autoplayVideo = related.filter({ !resultsIds.contains($0.videoID) }).randomElement() else {
return
}
let item = PlayerQueueItem(autoplayVideo)
self.autoplayItem = item
self.autoplayItemSource = video
DispatchQueue.main.asyncAfter(deadline: .now() + 3) { [weak self] in
guard let self = self else { return }
2022-08-17 02:46:35 +05:30
self.playerAPI.loadDetails(item, completionHandler: { newItem in
2022-07-11 23:14:49 +05:30
guard newItem.videoID == self.autoplayItem?.videoID else { return }
self.autoplayItem = newItem
self.updateRemoteCommandCenter()
self.controls.objectWillChange.send()
})
}
2022-07-11 03:54:56 +05:30
}
}
func updateRemoteCommandCenter() {
let skipForwardCommand = MPRemoteCommandCenter.shared().skipForwardCommand
let skipBackwardCommand = MPRemoteCommandCenter.shared().skipBackwardCommand
let previousTrackCommand = MPRemoteCommandCenter.shared().previousTrackCommand
let nextTrackCommand = MPRemoteCommandCenter.shared().nextTrackCommand
if !remoteCommandCenterConfigured {
remoteCommandCenterConfigured = true
#if !os(macOS)
UIApplication.shared.beginReceivingRemoteControlEvents()
#endif
let preferredIntervals = [NSNumber(10)]
skipForwardCommand.preferredIntervals = preferredIntervals
skipBackwardCommand.preferredIntervals = preferredIntervals
skipForwardCommand.addTarget { [weak self] _ in
self?.backend.seek(relative: .secondsInDefaultTimescale(10), seekType: .userInteracted)
return .success
}
skipBackwardCommand.addTarget { [weak self] _ in
self?.backend.seek(relative: .secondsInDefaultTimescale(-10), seekType: .userInteracted)
return .success
}
previousTrackCommand.addTarget { [weak self] _ in
self?.backend.seek(to: .zero, seekType: .userInteracted)
return .success
}
nextTrackCommand.addTarget { [weak self] _ in
self?.advanceToNextItem()
return .success
}
MPRemoteCommandCenter.shared().playCommand.addTarget { [weak self] _ in
self?.play()
return .success
}
MPRemoteCommandCenter.shared().pauseCommand.addTarget { [weak self] _ in
self?.pause()
return .success
}
MPRemoteCommandCenter.shared().togglePlayPauseCommand.addTarget { [weak self] _ in
self?.togglePlay()
return .success
}
MPRemoteCommandCenter.shared().changePlaybackPositionCommand.addTarget { [weak self] remoteEvent in
guard let event = remoteEvent as? MPChangePlaybackPositionCommandEvent else { return .commandFailed }
self?.backend.seek(to: event.positionTime, seekType: .userInteracted)
return .success
}
}
switch Defaults[.systemControlsCommands] {
case .seek:
previousTrackCommand.isEnabled = false
nextTrackCommand.isEnabled = false
skipForwardCommand.isEnabled = true
skipBackwardCommand.isEnabled = true
case .restartAndAdvanceToNext:
skipForwardCommand.isEnabled = false
skipBackwardCommand.isEnabled = false
previousTrackCommand.isEnabled = true
nextTrackCommand.isEnabled = isAdvanceToNextItemAvailable
}
}
2022-07-11 03:54:56 +05:30
func resetAutoplay() {
autoplayItem = nil
autoplayItemSource = nil
}
#if os(macOS)
var windowTitle: String {
currentVideo.isNil ? "Not Playing" : "\(currentVideo!.title) - \(currentVideo!.author)"
}
#else
func handleEnterForeground() {
setNeedsDrawing(presentingPlayer)
2022-08-21 02:01:03 +05:30
avPlayerBackend.playerLayer.player = avPlayerBackend.avPlayer
2022-06-05 22:42:00 +05:30
guard closePiPAndOpenPlayerOnEnteringForeground, playingInPictureInPicture else {
return
}
show()
closePiP()
}
2022-06-05 22:42:00 +05:30
func handleEnterBackground() {
if Defaults[.pauseOnEnteringBackground], !playingInPictureInPicture, !musicMode {
pause()
2022-08-21 02:01:03 +05:30
} else if !playingInPictureInPicture {
avPlayerBackend.playerLayer.player = nil
}
2022-06-05 22:42:00 +05:30
}
2022-08-08 23:32:46 +05:30
#endif
2022-06-05 22:42:00 +05:30
2022-08-08 23:32:46 +05:30
func enterFullScreen(showControls: Bool = true) {
guard !playingFullScreen else { return }
2022-08-08 23:32:46 +05:30
logger.info("entering fullscreen")
toggleFullscreen(false, showControls: showControls)
}
2022-08-08 23:32:46 +05:30
func exitFullScreen(showControls: Bool = true) {
guard playingFullScreen else { return }
2022-08-08 23:32:46 +05:30
logger.info("exiting fullscreen")
toggleFullscreen(true, showControls: showControls)
}
2022-02-17 02:40:57 +05:30
func updateNowPlayingInfo() {
#if os(tvOS)
guard activeBackend == .mpv else { return }
#endif
guard let video = currentItem?.video else {
MPNowPlayingInfoCenter.default().nowPlayingInfo = .none
return
}
2022-02-17 02:40:57 +05:30
let currentTime = (backend.currentTime?.seconds.isFinite ?? false) ? backend.currentTime!.seconds : 0
var nowPlayingInfo: [String: AnyObject] = [
MPMediaItemPropertyTitle: video.title as AnyObject,
MPMediaItemPropertyArtist: video.author as AnyObject,
MPNowPlayingInfoPropertyIsLiveStream: live as AnyObject,
MPNowPlayingInfoPropertyElapsedPlaybackTime: currentTime as AnyObject,
MPNowPlayingInfoPropertyPlaybackQueueCount: queue.count as AnyObject,
MPNowPlayingInfoPropertyPlaybackQueueIndex: 1 as AnyObject,
MPMediaItemPropertyMediaType: MPMediaType.anyVideo.rawValue as AnyObject
]
2022-08-21 01:58:31 +05:30
if !currentArtwork.isNil {
nowPlayingInfo[MPMediaItemPropertyArtwork] = currentArtwork as AnyObject
}
2022-02-17 02:40:57 +05:30
if !video.live {
let itemDuration = (backend.playerItemDuration ?? .zero).seconds
let duration = itemDuration.isFinite ? Double(itemDuration) : nil
2022-02-17 02:40:57 +05:30
if !duration.isNil {
nowPlayingInfo[MPMediaItemPropertyPlaybackDuration] = duration as AnyObject
2022-02-17 02:40:57 +05:30
}
}
2022-02-17 02:40:57 +05:30
MPNowPlayingInfoCenter.default().nowPlayingInfo = nowPlayingInfo
2022-02-17 02:40:57 +05:30
}
func updateCurrentArtwork() {
guard let video = currentVideo,
2022-06-27 02:58:03 +05:30
let thumbnailURL = video.thumbnailURL(quality: .medium)
2022-02-17 02:40:57 +05:30
else {
return
}
2022-06-27 02:58:03 +05:30
let task = URLSession.shared.dataTask(with: thumbnailURL) { [weak self] thumbnailData, _, _ in
guard let thumbnailData = thumbnailData else {
return
}
2022-02-17 02:40:57 +05:30
2022-06-27 02:58:03 +05:30
#if os(macOS)
guard let image = NSImage(data: thumbnailData) else { return }
#else
guard let image = UIImage(data: thumbnailData) else { return }
#endif
self?.currentArtwork = MPMediaItemArtwork(boundsSize: image.size) { _ in image }
2022-02-17 02:40:57 +05:30
}
2022-06-27 02:58:03 +05:30
task.resume()
2022-02-17 02:40:57 +05:30
}
2022-04-03 17:53:42 +05:30
func toggleFullscreen(_ isFullScreen: Bool, showControls: Bool = true) {
controls.presentingControls = showControls && isFullScreen
2022-04-03 17:53:42 +05:30
#if os(macOS)
2022-08-08 23:32:46 +05:30
Windows.player.toggleFullScreen()
2022-06-16 23:14:39 +05:30
#endif
2022-08-08 23:32:46 +05:30
playingFullScreen = !isFullScreen
2022-07-09 05:51:04 +05:30
#if os(iOS)
if !playingFullScreen {
let rotationOrientation = rotateToPortraitOnExitFullScreen ? UIInterfaceOrientation.portrait : nil
Orientation.lockOrientation(.allButUpsideDown, andRotateTo: rotationOrientation)
2022-04-03 17:53:42 +05:30
}
#endif
}
2022-05-29 23:56:56 +05:30
func setNeedsDrawing(_ needsDrawing: Bool) {
backends.forEach { $0.setNeedsDrawing(needsDrawing) }
}
2022-06-08 02:57:48 +05:30
func toggleMusicMode() {
musicMode.toggle()
if musicMode {
controls.presentingControls = true
controls.removeTimer()
2022-08-21 02:01:03 +05:30
backend.startMusicMode()
2022-06-08 02:57:48 +05:30
} else {
2022-08-21 02:01:03 +05:30
backend.stopMusicMode()
2022-06-08 02:57:48 +05:30
controls.resetTimer()
}
}
func updateAspectRatio() {
2022-08-14 22:29:04 +05:30
#if !os(tvOS)
guard aspectRatio != backend.aspectRatio else { return }
2022-08-14 22:29:04 +05:30
DispatchQueue.main.async { [weak self] in
guard let self = self else { return }
self.aspectRatio = self.backend.aspectRatio
}
#endif
}
2021-06-14 23:35:02 +05:30
}