From 68a8d61eb050677cb6886cae0c486b3478c08cfc Mon Sep 17 00:00:00 2001 From: Brahim Hadriche Date: Fri, 2 Dec 2022 10:46:48 -0500 Subject: [PATCH] Refactor and fix player (#19) * Refactor and fix player * Rename functions, fix video loading indicator * Hide loading indicator on exit --- .../HomeGridScreen/HomeGridScreen.bs | 20 +- .../HomeGridScreen/HomeGridScreen.xml | 1 + .../LoadingIndicator/LoadingIndicator.xml | 2 +- src/components/MainScene.bs | 41 +-- src/components/MainScene.xml | 1 + src/components/SearchScreen/SearchScreen.bs | 2 +- .../VideoPlayer/SponsorBlockTask.bs | 4 - src/components/VideoPlayer/Video.bs | 223 ++--------------- src/components/VideoPlayer/VideoContainer.xml | 8 + src/components/VideoPlayer/VideoPlayer.bs | 235 ++++++++++++------ src/components/VideoPlayer/VideoPlayer.xml | 11 +- .../VideoPlayer/VideoPlayerCaptions.bs | 24 ++ .../VideoPlayer/VideoPlayerSponsorBlock.bs | 143 +++++++++++ .../WebServer/Middleware/DashRouter.bs | 2 +- 14 files changed, 388 insertions(+), 329 deletions(-) create mode 100644 src/components/VideoPlayer/VideoContainer.xml create mode 100644 src/components/VideoPlayer/VideoPlayerCaptions.bs create mode 100644 src/components/VideoPlayer/VideoPlayerSponsorBlock.bs diff --git a/src/components/HomeGridScreen/HomeGridScreen.bs b/src/components/HomeGridScreen/HomeGridScreen.bs index cbaadb39..a20a98c2 100644 --- a/src/components/HomeGridScreen/HomeGridScreen.bs +++ b/src/components/HomeGridScreen/HomeGridScreen.bs @@ -6,6 +6,7 @@ function Init() m.top.ObserveField("rowItemSelected", "OnHomeGridScreenVideoSelected") m.top.ObserveField("focus", "OnFocusChange") m.top.ObserveField("playvideo", "OnPlayVideoCommand") + m.top.ObserveField("refresh", "OnRefresh") m.top.focus = true @@ -18,6 +19,10 @@ function OnFocusChange() end if end function +function OnRefresh() + InitContent() +end function + function InitContent() m.sortedContent = [] contentNode = CreateObject("roSGNode", "ContentNode") @@ -106,23 +111,12 @@ function OnHomeGridScreenVideoSelected(event as object) as void videoId = itemContent.videoId - CloseVideo() - ShowVideoScreen(videoId, m.top) -end function - -function CloseVideo() - if m.videoPlayer <> invalid - m.videoPlayer.control = "stop" - m.videoPlayer.visible = false - m.videoPlayer.getParent().removeChild(m.videoPlayer) - m.videoPlayer = invalid - end if + PlayVideo(videoId, m.top) end function function OnPlayVideoCommand() videoId = m.top.playvideo - CloseVideo() - ShowVideoScreen(videoId, m.top) + PlayVideo(videoId) end function function OnkeyEvent(key as string, press as boolean) as boolean diff --git a/src/components/HomeGridScreen/HomeGridScreen.xml b/src/components/HomeGridScreen/HomeGridScreen.xml index 75945e92..718a7f10 100644 --- a/src/components/HomeGridScreen/HomeGridScreen.xml +++ b/src/components/HomeGridScreen/HomeGridScreen.xml @@ -9,6 +9,7 @@ + + spinInterval="1" /> \ No newline at end of file diff --git a/src/components/MainScene.bs b/src/components/MainScene.bs index df22dc5c..719850f3 100644 --- a/src/components/MainScene.bs +++ b/src/components/MainScene.bs @@ -1,4 +1,5 @@ import "pkg:/source/roku_modules/log/LogMixin.brs" +import "pkg:/components/VideoPlayer/Video.bs" function Init() log.initializeLogManager(["log_PrintTransport"], 2) @@ -6,9 +7,13 @@ function Init() m.top.backgroundColor = "0x242424FF" m.top.backgroundURI = "" - loadingIndicator = m.top.findNode("LoadingIndicator") - m.global.addFields({ loadingIndicator: loadingIndicator }) - m.global.loadingIndicator.visible = true + m.loadingIndicator = m.top.findNode("LoadingIndicator") + m.videoContainer = m.top.findNode("VideoContainer") + m.global.addFields({ + loadingIndicator: m.loadingIndicator, + videoContainer: m.videoContainer + }) + m.loadingIndicator.visible = true m.homeGridScreen = m.top.findNode("HomeGridScreen") m.homeGridScreen.ObserveField("escape", "OnHomeGridScreenEscape") @@ -76,38 +81,12 @@ function OnNavIndexChange() as void end function function OnWebServerLogin() - ' TODO: refresh same component instead of creating a new one - m.global.loadingIndicator.visible = true - homeIndex = GetIndexOfChild(m.top, m.homeGridScreen.id) - newHomeGridScreen = CreateObject("roSGNode", "HomeGridScreen") - m.top.replaceChild(newHomeGridScreen, homeIndex) - m.homeGridScreen = newHomeGridScreen - m.homeGridScreen.id = "HomeGridScreen" - m.homeGridScreen.ObserveField("escape", "OnHomeGridScreenEscape") - - ' Selecting home - m.navBar.focusIndex = -1 - m.homeGridScreen.focus = true - - m.searchScreen.visible = false - m.homeGridScreen.visible = true - m.settingsScreen.visible = false + m.homeGridScreen.refresh = true end function function OnWebServerCommand() if m.serverTask.command.StartsWith("play:") - ' Selecting home - m.navBar.focusIndex = -1 - m.homeGridScreen.focus = true - - m.searchScreen.visible = false - m.homeGridScreen.visible = true - m.settingsScreen.visible = false - ' Trigger play video from home - ' TODO: allow returning to current screen, instead of home - ' BUG: if current video is playing in search screen, new video does not play - ' TODO: Owner of video player needs to be independant - m.homeGridScreen.playvideo = m.serverTask.command.Mid(5) + PlayVideo(m.serverTask.command.Mid(5)) end if end function diff --git a/src/components/MainScene.xml b/src/components/MainScene.xml index 9eb98a50..5e141219 100644 --- a/src/components/MainScene.xml +++ b/src/components/MainScene.xml @@ -6,6 +6,7 @@ + \ No newline at end of file diff --git a/src/components/SearchScreen/SearchScreen.bs b/src/components/SearchScreen/SearchScreen.bs index ba808109..b7d8b31f 100644 --- a/src/components/SearchScreen/SearchScreen.bs +++ b/src/components/SearchScreen/SearchScreen.bs @@ -141,7 +141,7 @@ function OnSearchVideoSelected(event as object) itemContent = rowContent.GetChild(selectedRowItem) videoId = itemContent.videoId - ShowVideoScreen(videoId, m.top) + PlayVideo(videoId, m.top) end function function OnkeyEvent(key as string, press as boolean) as boolean diff --git a/src/components/VideoPlayer/SponsorBlockTask.bs b/src/components/VideoPlayer/SponsorBlockTask.bs index dde52033..8561e998 100644 --- a/src/components/VideoPlayer/SponsorBlockTask.bs +++ b/src/components/VideoPlayer/SponsorBlockTask.bs @@ -1,9 +1,5 @@ import "pkg:/source/services/SponsorBlock.bs" -function Init() - m.top.functionName = "TaskMain" -end function - function TaskMain() input = m.top.getField("input") videoId = input.videoId diff --git a/src/components/VideoPlayer/Video.bs b/src/components/VideoPlayer/Video.bs index badc0430..43552865 100644 --- a/src/components/VideoPlayer/Video.bs +++ b/src/components/VideoPlayer/Video.bs @@ -1,212 +1,35 @@ import "pkg:/source/services/Invidious.bs" import "pkg:/components/Dialog/DialogUtils.bs" +import "pkg:/source/roku_modules/rokupromise/Promise.brs" -function ShowVideoScreen(videoId as string, sender as object) - m.videoPlayer = CreateObject("roSGNode", "VideoPlayer") - m.videoPlayer.sender = sender - m.videoPlayer.addFields({ - videoPlayingSuccess: false, - ignoreNextFinishedState: false, - videoId: videoId - }) - - m.videoPlayer.getScene().AppendChild(m.videoPlayer) - - m.videoPlayer.trickPlayBar.filledBarBlendColor = "0xFF0000FF" - m.videoPlayer.bufferingBar.filledBarBlendColor = "0xFF0000FF" - m.videoPlayer.retrievingBar.filledBarBlendColor = "0xFF0000FF" - - m.videoPlayer.visible = true - m.videoPlayer.SetFocus(true) - - m.videoPlayer.ObserveField("state", "OnVideoPlayerStateChange") - - StartVideoDetailsTask(videoId) - StartSponsorBlockTask(videoId) +function PlayVideo(videoId as string, sender = invalid as object) + CloseVideo(false) + videoContainer = GetVideoContainer() + if sender <> invalid + videoContainer.sender = sender + end if + videoContainer.videoPlayer = videoContainer.createChild("VideoPlayer") + videoContainer.videoPlayer.videoId = videoId + videoContainer.videoPlayer.SetFocus(true) end function -function OnVideoPlayerStateChange() as void - state = m.videoPlayer.state - - ' If we successfully played the video, then any error that comes later is not due to rate limiting. - ' This is to reduce false positives, as we do not want retry another link if the first link is working fine. - if state = "playing" - m.videoPlayer.videoPlayingSuccess = true - - if m.videoPlayer.visible = false and m.videoPlayer.embedded = true - m.videoPlayer.visible = true - end if +function CloseVideo(setFocus = true as boolean) + videoContainer = GetVideoContainer() + if videoContainer.videoPlayer <> invalid + videoContainer.videoPlayer.control = "stop" + videoContainer.RemoveChild(videoContainer.videoPlayer) + videoContainer.videoPlayer = invalid end if - - if state = "error" - ' A hack to see if we could use the proxy here - if m.videoPlayingSuccess <> true - errorInfo = m.videoPlayer.errorInfo - ' http for stream format, mediaerror for DASH - if errorInfo.category = "http" or errorInfo.category = "mediaerror" - url = m.videoPlayer.content.url - if url.InStr("local=true") = -1 - print(`Video ${url} failed to play. Trying a proxy (local=true)`) - if url.InStr("?") = -1 - url += "?local=true" - else - url += "&local=true" - end if - m.videoPlayer.content.url = url - ' This video errored, and is about to finish, so don't close the video yet - ' TODO: perhaps creating a second player is better? - m.videoPlayer.ignoreNextFinishedState = true - m.videoPlayer.control = "play" - return - end if - end if - end if - end if - - if state = "finished" and m.videoPlayer.ignoreNextFinishedState = true - m.videoPlayer.ignoreNextFinishedState = false - return - end if - - if state = "error" or state = "finished" - CloseVideoPlayer() - end if -end function - -function CloseVideoPlayer() - sender = m.videoPlayer.sender - m.videoPlayer.control = "stop" - m.videoPlayer.visible = false - m.videoPlayer.getParent().RemoveChild(m.videoPlayer) - m.videoPlayer = invalid - sender.focus = true -end function - -function StartVideoDetailsTask(videoId as string) - createTaskPromise("VideoDetailsTask", { - input: { - videoId: videoId - } - }).then(function(task as object) as void - if m.videoPlayer.control = "stop" - return - end if - videoId = task.output.videoId - metadata = task.output.metadata - if metadata <> invalid - contentNode = CreateObject("roSGNode", "ContentNode") - contentNode.addFields({ - videoId: videoId, - metadata: metadata - }) - - if metadata.hlsUrl <> invalid - contentNode.url = metadata.hlsUrl - else if metadata.dashUrl <> invalid - #if DASH_THUMBNAILS - ' Redirect to our server so we can inject thumbnails (storyboards) into the DASH manifest - contentNode.url = `http://${GetLocalIpAddress()}:8888/dash?v=${videoId}` - #else - contentNode.url = metadata.dashUrl - #end if - - else - stream = metadata.formatStreams[metadata.formatStreams.Count() - 1] - itag = stream.itag - ' Use an url relative to the host, so we can proxy(local=true) in case it fails - contentNode.url = Invidious.GetVideoUrl(videoId, itag, false) - end if - - contentNode.title = metadata.title - contentNode.secondaryTitle = metadata.author - SetCaptions(metadata, m.videoPlayer, contentNode) - m.videoPlayer.content = contentNode - m.videoPlayer.control = "play" + if setFocus and videoContainer.sender <> invalid + if videoContainer.sender.hasField("focus") + videoContainer.sender.focus = true else - ErrorMessage(`Failed to load video ${videoId}`, "Video load fail") - CloseVideoPlayer() + videoContainer.sender.SetFocus(true) end if - end function) -end function - -function StartSponsorBlockTask(videoId as string) - createTaskPromise("SponsorBlockTask", { - input: { - videoId: videoId - } - }).then(function(task as object) - skipSegments = task.output.skipSegments - barPath = task.output.barPath - if skipSegments <> invalid - m.videoPlayer.addFields({ skipSegments: skipSegments }) - m.videoPlayer.seekMode = "accurate" - if barPath <> invalid - m.videoPlayer.trickPlayBar.trackImageUri = barPath - m.videoPlayer.trickPlayBar.filledBarBlendColor = "0xFF000080" - end if - - m.videoPlayer.ObserveField("position", "OnPositionChangeSkipSponsorBlockSections") - end if - end function) -end function - -function SetCaptions(metadata as object, videoPlayer as object, contentNode as object) as void - ' TODO: check if we have caption settings ON - ' TODO: read favorate language from system settings - ' TODO: populate list of caption tracks - if metadata.captions.Count() = 0 - return end if - videoPlayer.globalCaptionMode = "ON" - contentNode.ClosedCaptions = True - selectedCaption = metadata.captions[0] - - ' Use favorite caption langauage, or the first one - for each caption in metadata.captions - if caption.language_code = "en" - selectedCaption = caption - exit for - end if - end for - - contentNode.SubtitleConfig = { - ShowSubtitle: 1, - TrackName: InvidiousSettings.GetSelectedInstance() + selectedCaption.url - } + m.global.loadingIndicator.visible = false end function -function OnPositionChangeSkipSponsorBlockSections() as void - shouldMute = false - muteCategory = "" - segments = m.videoPlayer.skipSegments - for each segment in segments - ' TODO: handle other action types - if segment["actionType"] = "skip" - segmentRange = segment["segment"] - segmentStart = segmentRange[0] - segmentEnd = segmentRange[1] - currentPosition = m.videoPlayer.position - if (segmentStart < currentPosition) and ((segmentEnd - 1) > currentPosition) - ' TODO: if segmentEnd is at the end of the video, close video - m.videoPlayer.seek = segmentEnd - print("Skiping section:" + segment["category"]) - return - end if - end if - if segment["actionType"] = "mute" - segmentRange = segment["segment"] - segmentStart = segmentRange[0] - segmentEnd = segmentRange[1] - currentPosition = m.videoPlayer.position - if (segmentStart < currentPosition) and (segmentEnd > currentPosition) - shouldMute = true - muteCategory = segment["category"] - exit for - end if - end if - end for - if m.videoPlayer.mute <> shouldMute - print(`Muting section: ${muteCategory} - ${shouldMute}`) - m.videoPlayer.mute = shouldMute - end if +function GetVideoContainer() as object + return m.global.videoContainer end function diff --git a/src/components/VideoPlayer/VideoContainer.xml b/src/components/VideoPlayer/VideoContainer.xml new file mode 100644 index 00000000..9c2f8787 --- /dev/null +++ b/src/components/VideoPlayer/VideoContainer.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/src/components/VideoPlayer/VideoPlayer.bs b/src/components/VideoPlayer/VideoPlayer.bs index c98d5379..c698901e 100644 --- a/src/components/VideoPlayer/VideoPlayer.bs +++ b/src/components/VideoPlayer/VideoPlayer.bs @@ -1,82 +1,27 @@ import "pkg:/source/utils/TimeUtils.bs" import "pkg:/source/services/SponsorBlock.bs" +import "pkg:/components/VideoPlayer/Video.bs" function Init() - SetChapterLabel() - m.timeLabel = FindTimeLabel() - m.top.trickPlayBar.observeField("visible", "OnTrickPlayBarVisible") - m.chapterLabelTimer = m.top.findNode("chapterLabelTimer") - m.chapterLabelTimer.observeField("fire", "OnChapterLabelTimer") -end function + SetupSponsorBlock() + m.videoDetailsTask = m.top.findNode("VideoDetailsTask") + m.busySpinner = FindChildNodeOfType(m.top, "BusySpinner") + m.busySpinnerLabel = FindChildNodeOfType(m.busySpinner, "Label") + ' TODO: show spinner while fetching video details + SetupBusySpinner() + m.global.loadingIndicator.visible = true -' This is a hack to access the position of the trickplay -function FindTimeLabel() as object - children = m.top.trickPlayBar.getChildren(m.top.trickPlayBar.getChildCount(), 0) - label = invalid - for each child in children - ' It's very unfortunate to have to find a label with 0:00 text, - ' and that's on the left side of the screen. This might need completely custom trickPlayBar - if child.isSubtype("Label") and child.text = "0:00" - if label = invalid - label = child - else - if child.translation[0] < label.translation[0] - label = child - end if - end if - end if - end for - return label -end function + m.videoPlayingSuccess = false + m.ignoreNextFinishedState = false -function OnTrickPlayBarVisible() - if m.top.trickPlayBar.visible - m.top.chapter = "" - m.chapterLabelTimer.control = "start" - else - m.chapterLabelTimer.control = "stop" - end if -end function + m.top.trickPlayBar.filledBarBlendColor = "0xFF0000FF" + m.top.bufferingBar.filledBarBlendColor = "0xFF0000FF" + m.top.retrievingBar.filledBarBlendColor = "0xFF0000FF" -function OnChapterLabelTimer() as void - if m.timeLabel = invalid or m.top.skipSegments = invalid - return - end if + m.top.observeField("control", "OnControlChange") + m.top.observeField("videoId", "StartVideoDetailsTask") - if m.sponsorBlockLastTime = m.timeLabel.text - return - end if - m.sponsorBlockLastTime = m.timeLabel.text - - time = TimeUtils.ParseTime(m.timeLabel.text) - UpdateSponsorBlockChapter(time) -end function - -function UpdateSponsorBlockChapter(time as integer) as void - segments = m.top.skipSegments - for each segment in segments - segmentRange = segment["segment"] - segmentStart = segmentRange[0] - segmentEnd = segmentRange[1] - - if (segmentStart <= time) and (segmentEnd >= time) - m.top.chapter = SponsorBlock.SegmentTitle(segment["category"]) - return - end if - end for - m.top.chapter = "" -end function - -function SetChapterLabel() - m.chapterLabel = m.top.findNode("chapterLabel") - m.chapterLabel.reparent(m.top.trickPlayBar, false) - trickPlayBarWidth = m.top.trickPlayBar.boundingRect().width - #if DASH_THUMBNAILS - yPos = 25 - #else - yPos = 55 - #end if - m.chapterLabel.translation = [trickPlayBarWidth / 2 - m.chapterLabel.width / 2, yPos] + m.top.ObserveField("state", "OnVideoPlayerStateChange") end function function OnkeyEvent(key as string, press as boolean) as boolean @@ -90,10 +35,146 @@ function OnkeyEvent(key as string, press as boolean) as boolean return false end function -function CloseVideo() - sender = m.top.sender - m.top.control = "stop" - m.top.visible = false - m.top.getParent().removeChild(m.videoPlayer) - sender.focus = true +function OnControlChange() + if m.top.control = "stop" + m.sponsorBlockTask.control = "stop" + m.videoDetailsTask.control = "stop" + end if +end function + +function StartVideoDetailsTask() + m.videoDetailsTask.input = { videoId: m.top.videoId } + m.videoDetailsTask.observeField("output", "OnVideoDetailsTaskResults") + m.videoDetailsTask.control = "run" +end function + +function OnVideoDetailsTaskResults() as void + task = m.videoDetailsTask + videoId = task.output.videoId + metadata = task.output.metadata + if videoId <> m.top.videoId + return + end if + if metadata = invalid + m.global.loadingIndicator.visible = false + ErrorMessage(`Failed to load video information for ${videoId}`, "Video load fail") + CloseVideo() + end if + + contentNode = CreateObject("roSGNode", "ContentNode") + contentNode.addFields({ metadata: metadata }) + + if metadata.hlsUrl <> invalid + contentNode.url = metadata.hlsUrl + else if metadata.dashUrl <> invalid + #if DASH_THUMBNAILS + ' Redirect to our server so we can inject thumbnails (storyboards) into the DASH manifest + contentNode.url = `http://${GetLocalIpAddress()}:8888/dash?v=${videoId}` + #else + contentNode.url = metadata.dashUrl + #end if + + else + stream = metadata.formatStreams[metadata.formatStreams.Count() - 1] + itag = stream.itag + ' Use an url relative to the host, so we can proxy(local=true) in case it fails + contentNode.url = Invidious.GetVideoUrl(videoId, itag, false) + end if + + contentNode.title = metadata.title + contentNode.secondaryTitle = metadata.author + SetCaptions(metadata, m.top, contentNode) + m.global.loadingIndicator.visible = false + m.top.content = contentNode + m.top.control = "play" +end function + +function FindChildNodeOfType(node as object, nodeType as string) as object + if node.subtype() = nodeType + return node + end if + + childCount = node.getChildCount() + children = node.getChildren(childCount, 0) + for i = 0 to childCount - 1 + child = FindChildNodeOfType(children[i], nodeType) + if child <> invalid + return child + end if + end for + + return invalid +end function + +function SetupBusySpinner() + m.busySpinner.poster.width = 150 + m.busySpinner.poster.height = 150 + m.busySpinner.poster.uri = "pkg:/images/spinner.png" + m.busySpinner.observeField("translation", "OnSpinnerMoved") + m.busySpinnerLabel.width = 150 + m.busySpinnerLabel.height = 150 + m.busySpinnerLabel.translation = [0, 0] + m.busySpinnerLabel.observeField("translation", "OnSpinnerLabelMoved") +end function + +function OnSpinnerMoved() + currentTranslation = m.busySpinner.translation + parentRect = m.top.boundingRect() + centerx = (parentRect.width - m.busySpinner.poster.width) / 2 + centery = (parentRect.height - m.busySpinner.poster.height) / 2 + + if currentTranslation[0] <> centerx or currentTranslation[1] <> centery + m.busySpinner.translation = [centerx, centery] + end if +end function + +function OnSpinnerLabelMoved() + currentTranslation = m.busySpinnerLabel.translation + if currentTranslation[0] <> 0 or currentTranslation[1] <> 0 + m.busySpinnerLabel.translation = [0, 0] + end if +end function + +function OnVideoPlayerStateChange() as void + state = m.top.state + + ' 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" + m.videoPlayingSuccess = true + end if + + if state = "error" + ' A hack to see if we could use the proxy here + if m.videoPlayingSuccess <> true + errorInfo = m.top.errorInfo + ' http for stream format, mediaerror for DASH + if errorInfo.category = "http" or errorInfo.category = "mediaerror" + url = m.top.content.url + if url.InStr("local=true") = -1 + print(`Video ${url} failed to play. Trying a proxy (local=true)`) + if url.InStr("?") = -1 + url += "?local=true" + else + url += "&local=true" + end if + m.top.content.url = url + ' This video errored, and is about to finish, so don't close the video yet + ' TODO: perhaps creating a second player is better? + m.ignoreNextFinishedState = true + m.top.control = "play" + return + end if + end if + end if + end if + + if state = "finished" and m.ignoreNextFinishedState = true + m.ignoreNextFinishedState = false + return + end if + + if state = "error" or state = "finished" + CloseVideo() + end if end function diff --git a/src/components/VideoPlayer/VideoPlayer.xml b/src/components/VideoPlayer/VideoPlayer.xml index e78c4c43..e8c9b828 100644 --- a/src/components/VideoPlayer/VideoPlayer.xml +++ b/src/components/VideoPlayer/VideoPlayer.xml @@ -1,11 +1,20 @@ +