Files
playlet-piped/playlet-lib/src/components/VideoPlayer/VideoPlayer.bs
T
Brahim Hadriche 1e161e8a77 Use credentialTransferToken to play age restricted videos (#498)
* Use credentialTransferToken to play age restricted videos

* changelog
2024-12-09 20:48:56 -05:00

563 lines
19 KiB
Plaintext

#const DEBUG_LOG_VIDEO_QUALITY = false
import "pkg:/components/Dialog/DialogUtils.bs"
import "pkg:/components/Services/Invidious/InvidiousToContentNode.bs"
import "pkg:/components/VideoPlayer/Lounge.bs"
import "pkg:/components/VideoPlayer/SponsorBlock.bs"
import "pkg:/components/VideoPlayer/VideoPlayerStyle.bs"
import "pkg:/components/VideoQueue/VideoQueueUtils.bs"
import "pkg:/source/AsyncTask/AsyncTask.bs"
import "pkg:/source/AsyncTask/Tasks.bs"
import "pkg:/source/utils/ErrorUtils.bs"
import "pkg:/source/utils/Logging.bs"
import "pkg:/source/utils/RemoteKeys.bs"
function Init()
SetPlayerStyle()
SetupAnimation()
m.fullScreenHint = m.top.findNode("fullScreenHint")
m.fullScreenHintLabel = m.top.findNode("fullScreenHintLabel")
m.fullScreenHintTimer = m.top.findNode("fullScreenHintTimer")
m.fullScreenHintTimer.ObserveField("fire", FuncName(OnFullScreenHintTimer))
m.trickplayUITimer = m.top.findNode("trickplayUITimer")
m.trickplayUITimer.ObserveField("fire", FuncName(OnTrickplayUITimer))
' videoPlayingSuccess indicates if we started playing a video successfully
' We use it to detect if we should try another link for a video, or if another error
' occurred (such as a network error)
m.videoPlayingSuccess = false
' ignoreNextFinishedState indicates if we should ignore the next finished state
' This is used to prevent the video from playing the next video when we are
' still trying to find a working stream url.
' This is also used to prevent playing the next video when we're still displaying
' an error dialog.
m.ignoreNextFinishedState = false
' Indicates that we're currently paused and seeking position
m.isSeekingPosition = false
' Checks if current RokuOS version has showUI field in Video node
m.showUIEnabled = m.top.hasField("showUI")
LogInfo(`Custom OK handler is ${m.showUIEnabled ? "enabled" : "disabled"}`)
' asyncStopSemantics available since Roku OS 12.5
' It is set to true because stopping synchronously causes timeout and crash
' Usually we would need to wait for the video state to move to "stopping" then to "stopped"
' before considering the video node closed, and creating a new one.
' However, since we have a task to load video details, there should be enough time for the
' video node to close before we create a new one.
if m.top.hasField("asyncStopSemantics")
m.top.asyncStopSemantics = true
end if
httpAgent = m.top.getHttpAgent()
httpAgent.AddHeader("User-Agent", "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:126.0) Gecko/20100101 Firefox/126.0")
#if DEBUG_LOG_VIDEO_QUALITY
m.top.addFields({
"_resolution": ""
"_audioFormat": ""
"_videoFormat": ""
})
m.top.observeField("streamingSegment", FuncName(OnStreamingSegmentChangeDebug))
m.top.observeField("audioFormat", FuncName(OnFormatChangeDebug))
m.top.observeField("videoFormat", FuncName(OnFormatChangeDebug))
m.top.observeField("_resolution", FuncName(OnFormatChangeDebug))
m.top.observeField("_audioFormat", FuncName(OnQualityChangeDebug))
m.top.observeField("_videoFormat", FuncName(OnQualityChangeDebug))
#end if
end function
#if DEBUG_LOG_VIDEO_QUALITY
function OnStreamingSegmentChangeDebug()
segment = m.top.streamingSegment
width = segment.width
height = segment.height
if width > 0 and height > 0
m.top._resolution = `${width}x${height}`
end if
end function
function OnFormatChangeDebug()
audioFormat = m.top.audioFormat
videoFormat = m.top.videoFormat
resolution = m.top._resolution
m.top._audioFormat = audioFormat
m.top._videoFormat = `${videoFormat} ${resolution}`
end function
function OnQualityChangeDebug()
LogDebug("Video format:", m.top._videoFormat, "Audio format:", m.top._audioFormat)
end function
#end if
function OnNodeReady()
minRect = m.top.minRect
rect = m.container.fullscreen ? m.top.maxRect : minRect
m.top.width = rect.width
m.top.height = rect.height
m.top.translation = [rect.x, rect.y]
m.fullScreenHint.width = minRect.width
m.fullScreenHintLabel.width = minRect.width
m.fullScreenHint.translation = [0, minRect.height - m.fullScreenHint.height]
' TODO:P2 show a loading spinner if video is loading minimized
' Probably only worth doing after the video player is redone
m.top.enableUI = m.container.fullscreen
m.top.showFullScreenHint = not m.container.fullscreen
m.container.observeFieldScoped("fullscreen", FuncName(OnFullScreenChange))
m.top.ObserveField("state", FuncName(OnVideoPlayerStateChange))
SponsorBlock.SetupSponsorBlock()
end function
function PlayWithContent(contentNode as object)
videoContentNode = CreateObject("roSGNode", "ContentNode")
if not StringUtils.IsNullOrEmpty(contentNode.videoId)
videoContentNode.AddFields({ videoId: contentNode.videoId })
end if
if ValidInt(contentNode.timestamp) <> -1
videoContentNode.AddFields({ timestamp: contentNode.timestamp })
end if
if not StringUtils.IsNullOrEmpty(contentNode.title)
videoContentNode.title = contentNode.title
end if
' NOTE: "_author" not "author". See PlaylistContentNode.xml for explanation.
if not StringUtils.IsNullOrEmpty(contentNode._author)
videoContentNode.secondaryTitle = contentNode._author
end if
StartVideoContentTask(videoContentNode)
Lounge.SendNowPlayingLoading(contentNode.videoId)
end function
function StartVideoContentTask(videoContentNode as object)
if m.videoContentTask <> invalid
m.videoContentTask.cancel = true
end if
MarkVideoWatched(videoContentNode.videoId)
m.top.content = videoContentNode
m.videoContentTask = AsyncTask.Start(Tasks.VideoContentTask, {
content: videoContentNode
invidious: m.top.invidious
preferences: m.top.preferences
loungeService: m.top.loungeService
playletServerPort: m.top.webServer.port
}, OnVideoContentTaskResults)
end function
function OnVideoContentTaskResults(output as object) as void
m.videoContentTask = invalid
if output.cancelled or m.onCloseCalled = true
return
end if
if not output.success or not output.result.success
' output.error for unhandled exception
error = output.error
if error = invalid
' output.result.error for network errors
error = output.result.error
end if
error = ErrorUtils.Format(error)
LogError(error)
videoId = output.task.input.content.videoId
title = Tr(Locale.VideoPlayer.VideoLoadError)
message = Tr(Locale.VideoPlayer.VideoLoadErrorMessage).Replace("%1", videoId) + `\n${error}`
buttons = [Tr(Locale.Buttons.PlayNextVideo), Tr(Locale.Buttons.Cancel)]
dialog = DialogUtils.ShowTimedDialogButtons(message, title, buttons, 0, 10, true)
dialog.observeFieldScoped("wasClosed", FuncName(OnVideoContentTaskErrorDialogResponse))
Lounge.SendOnStateChange()
return
end if
content = m.top.content
SponsorBlock.FetchSponsorBlock(content.metadata)
timestamp = content.timestamp
hasTimestamp = IsInt(timestamp)
if IsLiveVideo() and not hasTimestamp
duration = m.top.duration
if duration > 0
SeekToEndOfStream()
else
m.top.ObserveField("duration", FuncName(SeekToEndOfStream))
end if
end if
PlayAfterPreviousPlayerHasStopped()
if hasTimestamp and timestamp > 0
m.top.seek = content.timestamp
end if
end function
function PlayAfterPreviousPlayerHasStopped() as void
previousPlayer = m.top.previousPlayer
m.top.previousPlayer = invalid
if previousPlayer = invalid
m.top.control = "play"
return
end if
previousPlayerState = previousPlayer.state
LogInfo("Previous player state:", previousPlayerState)
if previousPlayerState = "stopping"
previousPlayer.observeFieldScoped("state", FuncName(OnPreviousPlayerState))
return
end if
m.top.control = "play"
end function
function OnPreviousPlayerState(event as object) as void
previousPlayer = event.getRoSGNode()
if m.onCloseCalled = true
previousPlayer.unobserveFieldScoped("state")
return
end if
previousPlayerState = previousPlayer.state
LogInfo("Previous player state change:", previousPlayerState)
if previousPlayerState = "stopped" or previousPlayerState = "error" or previousPlayerState = "finished" or previousPlayerState = "none"
previousPlayer.unobserveFieldScoped("state")
m.top.control = "play"
end if
end function
function OnVideoContentTaskErrorDialogResponse(event as object)
dialog = event.getRoSGNode()
dialog.unobserveFieldScoped("wasClosed")
shouldPlayNext = dialog.actualButtonSelected = 0
if not shouldPlayNext or not VideoQueueUtils.PlayNext(m.videoQueue, m.invidious, m.preferences)
if m.top.isSameNode(m.videoQueue.player)
m.videoQueue.closePlayer = true
end if
end if
Lounge.SendOnStateChange()
end function
function MarkVideoWatched(videoId as string)
if m.top.invidious.authToken <> invalid
AsyncTask.Start(Tasks.MarkVideoWatchedTask, {
videoId: videoId
invidious: m.top.invidious
})
end if
end function
function OnClose()
m.onCloseCalled = true
m.top.previousPlayer = invalid
if m.videoContentTask <> invalid
m.videoContentTask.cancel = true
m.videoContentTask = invalid
end if
if m.sponsorBlockTask <> invalid
m.sponsorBlockTask.cancel = true
m.sponsorBlockTask = invalid
end if
parent = m.top.getParent()
if parent <> invalid
parent.RemoveChild(m.top)
end if
SponsorBlock.RemoveNotifcation(m.notifications)
' Stopping a video is slow and synchronous, and can lead to execution timeout crashes.
try
m.top.control = "stop"
catch error
errorMessage = ErrorUtils.Format(error)
LogError("Error stopping video:", errorMessage)
DialogUtils.ShowDialog(errorMessage, Tr(Locale.VideoPlayer.ErrorClosingVideo), true)
end try
m.top.content = invalid
end function
function OnVideoPlayerStateChange() as void
Lounge.SendOnStateChange()
state = m.top.state
content = m.top.content
' Reset isSeekingPosition when started to play the video
if state = "playing"
m.isSeekingPosition = false
end if
' If we successfully played the video, then any error that comes later is not due to a 403 (FORBIDDEN).
' This is to reduce false positives, as we do not want retry another link if the first link is working fine.
if state = "playing" and not m.videoPlayingSuccess
LogInfo(`Now playing video ${content.url}`)
m.videoPlayingSuccess = true
end if
if state = "error"
errorInfo = m.top.errorInfo
LogError(`Error playing video ${content.videoId}`, errorInfo)
if m.videoPlayingSuccess <> true
' http for stream format, mediaerror for DASH
if errorInfo.category = "http" or errorInfo.category = "mediaerror"
currentUrl = content.url
playletStreamUrls = content.playletStreamUrls
playletStreamUrlIndex = content.playletStreamUrlIndex
playletStreamUrlIndex++
content.playletStreamUrlIndex = playletStreamUrlIndex
if playletStreamUrlIndex < playletStreamUrls.Count()
nextUrl = playletStreamUrls[playletStreamUrlIndex]
LogError(`Stream ${currentUrl} failed to play. Trying next stream ${nextUrl}`)
' TODO:P2 handle SeekToEndOfStream for live videos on error
m.top.UnobserveField("duration")
content.url = nextUrl
' This video errored, and is about to finish, so don't close the video yet
' That's why we should ignore the next "finished" event
m.ignoreNextFinishedState = true
m.top.control = "play"
timestamp = content.timestamp
hasTimestamp = IsInt(timestamp)
if hasTimestamp and timestamp > 0
m.top.seek = content.timestamp
end if
return
end if
end if
end if
end if
if state = "finished" and m.ignoreNextFinishedState = true
m.ignoreNextFinishedState = false
return
end if
if state = "finished"
OnVideoFinished()
return
end if
if state = "error"
messageLines = []
messageLines.push(`errorMsg: ${m.top.errorMsg}`)
messageLines.push(`errorCode: ${m.top.errorCode}`)
messageLines.push(`errorStr: ${m.top.errorStr}`)
errorInfo = m.top.errorInfo
if errorInfo <> invalid
for each info in errorInfo
messageLines.push(`${info}: ${errorInfo[info]}`)
end for
end if
title = Tr(Locale.VideoPlayer.ErrorPlayingVideo).Replace("%1", content.videoId)
LogError(title, messageLines)
buttons = [Tr(Locale.Buttons.PlayNextVideo), Tr(Locale.Buttons.Cancel)]
dialog = DialogUtils.ShowTimedDialogButtons(messageLines, title, buttons, 0, 10, true)
dialog.observeFieldScoped("wasClosed", FuncName(OnVideoContentTaskErrorDialogResponse))
m.ignoreNextFinishedState = true
end if
end function
function SeekToEndOfStream()
m.top.UnobserveField("duration")
duration = m.top.duration
' If the stream is less than 30 seconds, it's not worth seeking to the end
if duration > 30
LogInfo("Seeking to end of live stream", duration)
m.top.seek = duration
end if
end function
function OnVideoFinished() as void
if not VideoQueueUtils.PlayNext(m.videoQueue, m.invidious, m.preferences)
m.videoQueue.closePlayer = true
end if
end function
function IsLiveVideo() as boolean
content = m.top.content
return content <> invalid and content.Live = true
end function
function ShowUIAndStartTimer()
if m.showUIEnabled
m.top.showUI = { "show": true, "trickPlaybar": true, "titleAndTime": true, "trickplayBackgroundOverlay": true, "focusTrickplayBar": false }
m.trickplayUITimer.control = "start"
end if
end function
function HideUIAndStopTimer()
if m.showUIEnabled
m.top.showUI = { "show": false, "focusTrickplayBar": false }
m.trickplayUITimer.control = "stop"
end if
end function
function HandleOKPress() as boolean
if not m.showUIEnabled
return false
end if
handled = false
state = m.top.state
uiVisible = m.top.trickPlaybar.visible
isLive = IsLiveVideo()
LogInfo(`Handling OK button: state = ${state}, uiVisible = ${uiVisible} isLive = ${isLive}`)
if state = "playing"
if not uiVisible
' Video is playing and UI is not visible, show it
ShowUIAndStartTimer()
else if not isLive
' Trickplay bar is visible and video is currently played, pause it and retain the UI
m.trickplayUITimer.control = "stop"
m.top.control = "pause"
ShowUIAndStartTimer()
else
HideUIAndStopTimer()
end if
handled = true
else if state = "paused"
' Exit early if we're in seeking mode to avoid messing up internal Video node state
if m.isSeekingPosition
return false
end if
if not uiVisible
' Video is paused and UI is not visible, show it
ShowUIAndStartTimer()
else
' Video is currently paused with visible UI, resume it and hide UI
HideUIAndStopTimer()
m.top.control = "resume"
end if
handled = true
end if
return handled
end function
function OnKeyEvent(key as string, press as boolean) as boolean
if press = false
return false
end if
' Unfortunately, a Video node cannot capture the "options" key (because, Roku...)
' https://community.roku.com/t5/Roku-Developer-Program/Bug-in-10-0-1-Options-key-is-not-being-consumed-by-onKeyEvent-when-Video-node-is-in-focus/m-p/709200/highlight/true#M49312
' Because of that, the button "down" is used to shrink the video for picture in picture mode
if key = RemoteKeys.Down
if VideoQueueUtils.ToggleVideoPictureInPicture(m.videoQueue)
return true
end if
end if
if key = RemoteKeys.Back
m.videoQueue.closePlayer = true
return true
end if
if key = RemoteKeys.Ok
return HandleOKPress()
end if
if key = RemoteKeys.Left or key = RemoteKeys.Right or key = RemoteKeys.Rewind or key = RemoteKeys.FastForward
' We're paused and one of the buttons is pressed: left, right ff, rw.
' That means we're seeking position. Check that in HandleOKPress and exit early
m.isSeekingPosition = true
end if
' Always stop UI timer when pressing any button to avoid UI being hidden twice
m.trickplayUITimer.control = "stop"
return false
end function
function SetupAnimation()
m.minimizeAnimation = m.top.findNode("minimizeAnimation")
m.widthInterpolator = m.top.findNode("widthInterpolator")
m.heightInterpolator = m.top.findNode("heightInterpolator")
m.translationInterpolator = m.top.findNode("translationInterpolator")
minRect = m.top.minRect
maxRect = m.top.maxRect
m.widthInterpolator.keyValue = [maxRect.width, (maxRect.width + minRect.width) / 2, minRect.width]
m.heightInterpolator.keyValue = [maxRect.height, (maxRect.height + minRect.height) / 2, minRect.height]
maxTranslation = [maxRect.x, maxRect.y]
minTranslation = [minRect.x, minRect.y]
midTranslation = [(maxRect.x + minRect.x) / 2, (maxRect.y + minRect.y) / 2]
m.translationInterpolator.keyValue = [maxTranslation, midTranslation, minTranslation]
end function
function OnFullScreenChange()
HideUIAndStopTimer()
m.widthInterpolator.reverse = m.container.fullscreen
m.heightInterpolator.reverse = m.container.fullscreen
m.translationInterpolator.reverse = m.container.fullscreen
m.minimizeAnimation.control = "start"
m.top.enableUI = m.container.fullscreen
m.top.showFullScreenHint = not m.container.fullscreen
SponsorBlock.SetVisible(m.notifications, m.container.fullscreen)
end function
function OnShowFullScreenHint() as void
m.fullScreenHintTimer.control = "stop"
if m.container.fullscreen
m.fullScreenHint.visible = false
return
end if
if m.top.showFullScreenHint
' Take 1 second until the shrink animation finishes to show the hint
m.fullScreenHintTimer.duration = 1
else
' Wait 5 seconds then hide the hint
m.fullScreenHintTimer.duration = 5
end if
m.fullScreenHintTimer.control = "start"
end function
function OnTrickplayUITimer()
HideUIAndStopTimer()
end function
function OnFullScreenHintTimer()
showFullScreenHint = m.top.showFullScreenHint
m.fullScreenHint.visible = showFullScreenHint
if showFullScreenHint
m.top.showFullScreenHint = false
end if
end function