Files
playlet-piped/playlet-lib/src/components/Web/PlayletWebServer/Middleware/HlsRouter.bs
T

353 lines
13 KiB
Plaintext

import "pkg:/components/Web/WebServer/Http/HttpRouter.bs"
import "pkg:/source/services/HttpClient.bs"
namespace Http
class HlsRouter extends HttpRouter
function new(server as object)
super()
m.videoQueue = server.sceneNodes.videoQueue
end function
@get("/api/hls")
function GenerateHlsManifest(context as object) as boolean
request = context.request
response = context.response
v = request.query.v
url = request.query.url
quality = request.query.quality
if StringUtils.IsNullOrEmpty(url)
response.Default(400, "Missing url")
return true
end if
hlsRequest = HttpClient.Get(url)
headers = request.headers
' Host is probably 127.0.0.1:8888 so we should change it before hitting the server
parsedUrl = UrlUtils.ParseUrl(url)
headers["Host"] = parsedUrl.host + ":" + parsedUrl.port
hlsRequest.Headers(headers)
hlsResponse = hlsRequest.Await()
if not hlsResponse.IsSuccess()
LogError("Failed to fetch HLS manifest:", hlsResponse.ErrorMessage())
response.Redirect(url)
return true
end if
hlsManifest = hlsResponse.Text()
' Some backends (Piped) return master manifests with relative
' variant URIs; since we serve the manifest from 127.0.0.1, the
' player would resolve them against the local server and 404.
' Make them absolute against the original manifest URL.
hlsManifest = m.MakeRelativeUrisAbsolute(hlsManifest, url)
hlsManifest = m.PrependManifestHeader(hlsManifest, v, url)
qualityFilter = m.CreateQualityFilter(quality)
hlsManifest = m.FilterHlsManifest(hlsManifest, qualityFilter)
' For some reason, player hangs on HDR videos...
hlsManifest = m.ReplaceVideoRange(hlsManifest)
hlsManifest = ValidString(m.AppendStoryboardPlaylists(hlsManifest))
response.http_code = hlsResponse.StatusCode()
headers = hlsResponse.Headers()
response.headers["Cache-Control"] = "no-cache, must-revalidate"
response.headers["Content-Type"] = headers["Content-Type"]
response.headers["Cross-Origin-Resource-Policy"] = "cross-origin"
response.headers["Date"] = headers["Date"]
response.headers["Server"] = "HTTP server (unknown)"
response.SetBodyDataString(hlsManifest)
WriteAsciiFile("cachefs:/last_generated_hls.m3u8", hlsManifest)
return true
end function
@get("/api/hls/storyboards")
function GetStoryboardsHls(context as object) as boolean
request = context.request
response = context.response
metadata = m.GetPlayerMetadata()
if metadata = invalid
response.Default(500, "Player metadata is invalid")
return true
end if
storyboards = metadata.storyboards
if not IsArray(storyboards)
response.Default(500, "Player metadata storyboards is invalid")
return true
end if
index = request.query.index
if StringUtils.IsNullOrEmpty(index)
response.Default(400, "Missing index")
return true
end if
index = index.ToInt()
if index < 0 or index >= storyboards.Count()
response.Default(400, "Invalid index")
return true
end if
storyboard = storyboards[index]
hlsManifest = m.GenerateStoryboardManifest(storyboard)
response.http_code = 200
response.SetBodyDataString(hlsManifest)
response.ContentType("application/vnd.apple.mpegurl")
return true
end function
function PrependManifestHeader(hlsManifest as dynamic, v as dynamic, url as dynamic) as dynamic
if StringUtils.IsNullOrEmpty(hlsManifest) or not hlsManifest.StartsWith("#EXTM3U")
return hlsManifest
end if
header = `#EXTM3U\n## Generated by Playlet - Video ID: ${v}\n## Source URL: ${url}`
return header + hlsManifest.Mid(7)
end function
function AppendStoryboardPlaylists(hlsManifest as dynamic) as dynamic
if StringUtils.IsNullOrEmpty(hlsManifest) or not hlsManifest.StartsWith("#EXTM3U")
return hlsManifest
end if
metadata = m.GetPlayerMetadata()
if metadata = invalid
return hlsManifest
end if
' TODO:P2: handle live videos
if ValidBool(metadata.liveNow) or ValidBool(metadata.hasLiveStreamingData)
return hlsManifest
end if
if hlsManifest.InStr("/source/yt_live_broadcast") <> -1 or hlsManifest.InStr("/live/1") <> -1
return hlsManifest
end if
storyboards = metadata.storyboards
if not IsArray(storyboards)
return hlsManifest
end if
' Perhaps this is due to the bandwidth calculation being off, but the
' Video node ends up using the first storyboard, which is the lowest
' quality. That's why we reverse the order here.
for i = storyboards.Count() - 1 to 0 step -1
storyboard = storyboards[i]
' estimate bandwidth based on storyboard size
bandwidth = Cint((storyboard.width * storyboard.height * storyboard.storyboardWidth * storyboard.storyboardHeight * storyboard.storyboardCount / (Cdbl(storyboard.interval) / 1000.0)) * 0.01)
hlsManifest += `\n#EXT-X-IMAGE-STREAM-INF:BANDWIDTH=${bandwidth},RESOLUTION=${storyboard.width}x${storyboard.height},CODECS="jpeg",URI="/api/hls/storyboards?index=${i}"`
end for
hlsManifest += `\n`
return hlsManifest
end function
function FilterHlsManifest(hlsManifest as dynamic, qualityFilter as object) as dynamic
if StringUtils.IsNullOrEmpty(hlsManifest) or qualityFilter.Count() = 0
return hlsManifest
end if
lines = hlsManifest.split(`\n`)
newLines = []
includedQualitiesCount = 0
for i = 0 to lines.Count() - 1
line = lines[i]
if not line.StartsWith("#EXT-X-STREAM-INF:")
newLines.push(line)
continue for
end if
resolution = StringUtils.GetBetween(line, "RESOLUTION=", ",")
if StringUtils.IsNullOrEmpty(resolution)
newLines.push(line)
continue for
end if
resolutionParts = resolution.split("x")
if resolutionParts.Count() <> 2
newLines.push(line)
continue for
end if
if qualityFilter[resolutionParts[1]] = true
newLines.push(line)
includedQualitiesCount += 1
continue for
end if
' skip the next line
i += 1
end for
if includedQualitiesCount = 0
LogWarnNoTelemetry("No video streams found using quality filter:", qualityFilter, "Falling back to all video streams")
return hlsManifest
end if
return newLines.join(`\n`)
end function
function ReplaceVideoRange(hlsManifest as dynamic) as dynamic
if StringUtils.IsNullOrEmpty(hlsManifest)
return hlsManifest
end if
return hlsManifest.Replace("VIDEO-RANGE=HLG", "VIDEO-RANGE=SDR").Replace("VIDEO-RANGE=PQ", "VIDEO-RANGE=SDR")
end function
function GenerateStoryboardManifest(storyboard as object) as string
tileCount = storyboard.storyboardWidth * storyboard.storyboardHeight
intervalSeconds = Cdbl(storyboard.interval) / 1000.0
targetDuration = tileCount * intervalSeconds
hlsManifest = `#EXTM3U
#EXT-X-TARGETDURATION:${targetDuration}
#EXT-X-VERSION:7
#EXT-X-MEDIA-SEQUENCE:1
#EXT-X-PLAYLIST-TYPE:VOD
#EXT-X-IMAGES-ONLY
`
for i = 0 to storyboard.storyboardCount - 1
currentTileCount = tileCount
currentStoryboardWidth = storyboard.storyboardWidth
currentStoryboardHeight = storyboard.storyboardHeight
if i = storyboard.storyboardCount - 1
currentTileCount = storyboard.count mod tileCount
if currentTileCount = 0
currentTileCount = tileCount
end if
if currentTileCount < currentStoryboardWidth
currentStoryboardWidth = currentTileCount
end if
currentStoryboardHeight = Cint(Cdbl(currentTileCount) / Cdbl(currentStoryboardWidth))
if currentStoryboardHeight * currentStoryboardWidth < currentTileCount
currentStoryboardHeight += 1
end if
end if
extinf = currentTileCount * intervalSeconds
' TODO:P2: although we took care of the last storyboard to get the
' correct tile count and layout, and still looks wrong, similar to DASH.
hlsManifest += `#EXTINF:${extinf},
#EXT-X-TILES:RESOLUTION=${storyboard.width}x${storyboard.height},LAYOUT=${currentStoryboardWidth}x${currentStoryboardHeight},DURATION=${intervalSeconds}
${storyboard.templateUrl.replace("$M", `${i}`)}
`
end for
hlsManifest += `#EXT-X-ENDLIST`
return hlsManifest
end function
function MakeRelativeUrisAbsolute(manifest as string, baseUrl as string) as string
if manifest = invalid or manifest = "" or baseUrl = invalid or baseUrl = ""
return manifest
end if
parsedUrl = UrlUtils.ParseUrl(baseUrl)
if parsedUrl = invalid or parsedUrl.host = invalid
return manifest
end if
protocol = parsedUrl.protocol
if protocol = invalid or protocol = ""
protocol = "https"
end if
origin = protocol + "://" + parsedUrl.host
if parsedUrl.port <> invalid and parsedUrl.port <> "" and parsedUrl.port <> "80" and parsedUrl.port <> "443"
origin = origin + ":" + parsedUrl.port
end if
' normalize line endings (CR-only manifests would be one line)
manifest = manifest.Replace(chr(13) + chr(10), chr(10))
manifest = manifest.Replace(chr(13), chr(10))
lines = manifest.Split(chr(10))
for i = 0 to lines.Count() - 1
line = lines[i]
trimmed = line.Trim()
if Left(trimmed, 1) = "/"
' bare relative URI line (variant/media playlist)
lines[i] = origin + trimmed
else if Left(trimmed, 1) = "#" and InStr(UCase(trimmed), "URI=" + chr(34) + "/") > 0
' attribute form: #EXT-X-MEDIA:...URI="/..." etc.
' split on double quotes; rewrite any segment that starts
' with a bare slash. no index math needed.
parts = trimmed.Split(chr(34))
for p = 0 to parts.Count() - 1
if Left(parts[p], 1) = "/"
parts[p] = origin + parts[p]
end if
end for
lines[i] = parts.Join(chr(34))
end if
end for
return lines.Join(chr(10))
end function
function GetPlayerMetadata() as object
player = m.videoQueue.player
if player = invalid
return invalid
end if
content = player.content
if content = invalid
return invalid
end if
metadata = content.metadata
if not IsAssociativeArray(metadata)
return invalid
end if
return metadata
end function
function CreateQualityFilter(quality as dynamic) as object
qualityFilter = {}
if not IsString(quality)
return qualityFilter
end if
includeList = quality.split(",")
for each quality in includeList
if quality = "auto"
continue for
end if
pIndex = quality.InStr("p")
if pIndex <> -1
quality = quality.Mid(0, pIndex)
end if
qualityFilter[quality] = true
end for
return qualityFilter
end function
end class
end namespace