Piped backend: absolute HLS URI rewrite, roLongInt-safe epoch conversion, /manifest endpoint

This commit is contained in:
spaghet committed 2026-11-23 14:35:27 -05:00
1 parent a30bf73d0f
commit be8c79c3d1
4 files changed
+342 -148

No files matched your search

+1 -1
View File
@@ -40,7 +40,7 @@ requires_widevine_version=1.0
playlet_lib_squashfs_remote_url=https://github.com/iBicha/playlet/releases/latest/download/playlet-lib.squashfs.pkg
playlet_lib_zip_remote_url=https://github.com/iBicha/playlet/releases/latest/download/playlet-lib.zip
playlet_lib_zip_embedded_url=pkg:/lib/playlet-lib.zip
playlet_lib_zip_debug_url=https://gitea.spaghet.io/spaghet/playlet-piped/raw/branch/main/piped/playlet-lib.zip
playlet_lib_zip_debug_url=https://gitea.spaghet.io/spaghet/playlet-piped/raw/branch/main/piped/playlet-lib-1795462373.zip
git_commit_sha=unknown
@@ -9,17 +9,17 @@ namespace PipedToInvidious
function VideoFromPiped(item as object, index = invalid as dynamic) as object
videoId = ExtractVideoId(ValidString(item.url))
video = {
videoId: videoId
title: ValidString(item.title)
author: ValidString(item.uploaderName)
authorId: ExtractChannelId(ValidString(item.uploaderUrl))
lengthSeconds: ValidInt(item.duration)
viewCount: ValidInt(item.views)
published: MillisToSeconds(item.uploaded)
publishedText: ValidString(item.uploadedDate)
videoThumbnails: ThumbnailsFromProxy(ValidString(item.thumbnail), videoId)
type: "video"
genre: []
"videoId": videoId
"title": ValidString(item.title)
"author": ValidString(item.uploaderName)
"authorId": ExtractChannelId(ValidString(item.uploaderUrl))
"lengthSeconds": ValidInt(item.duration)
"viewCount": ValidInt(item.views)
"published": MillisToSeconds(item.uploaded)
"publishedText": ValidString(item.uploadedDate)
"videoThumbnails": ThumbnailsFromProxy(ValidString(item.thumbnail), videoId)
"type": "video"
"genre": []
}
if not StringUtils.IsNullOrEmpty(ValidString(item.uploaderAvatar))
video["authorThumbnails"] = [{ url: item.uploaderAvatar, width: 88, height: 88 }]
@@ -54,13 +54,13 @@ namespace PipedToInvidious
for each item in list
if type(item) = "roAssociativeArray" and item.type = "playlist"
playlists.push({
playlistId: ExtractPlaylistId(ValidString(item.url))
title: ValidString(item.title)
videoCount: ValidInt(item.videosCount)
playlistThumbnail: ValidString(item.thumbnail)
author: ValidString(item.uploaderName)
authorId: ExtractChannelId(ValidString(item.uploaderUrl))
type: "playlist"
"playlistId": ExtractPlaylistId(ValidString(item.url))
"title": ValidString(item.title)
"videoCount": ValidInt(item.videosCount)
"playlistThumbnail": ValidString(item.thumbnail)
"author": ValidString(item.uploaderName)
"authorId": ExtractChannelId(ValidString(item.uploaderUrl))
"type": "playlist"
})
end if
end for
@@ -75,15 +75,15 @@ namespace PipedToInvidious
for each item in list
if type(item) = "roAssociativeArray" and item.type = "channel"
channels.push({
authorId: ExtractChannelId(ValidString(item.url))
author: ValidString(item.title)
authorThumbnail: ValidString(item.avatar)
authorThumbnails: [{ url: ValidString(item.avatar), width: 88, height: 88 }]
description: ValidString(item.description)
subCount: ValidInt(item.subscribers)
handle: ValidString(item.handle)
verified: item.verified = true
type: "channel"
"authorId": ExtractChannelId(ValidString(item.url))
"author": ValidString(item.title)
"authorThumbnail": ValidString(item.avatar)
"authorThumbnails": [{ url: ValidString(item.avatar), width: 88, height: 88 }]
"description": ValidString(item.description)
"subCount": ValidInt(item.subscribers)
"handle": ValidString(item.handle)
"verified": item.verified = true
"type": "channel"
})
end if
end for
@@ -100,17 +100,17 @@ namespace PipedToInvidious
function ChannelFromPiped(data as object, channelId as string) as object
' Piped /channel/{id} -> Invidious /api/v1/channels/{ucid}
result = {
author: ValidString(data.name)
authorId: GetFirstNonEmpty(ValidString(data.id), channelId)
bannerUrl: ValidString(data.bannerUrl)
description: ValidString(data.description)
subCount: ValidInt(data.subscriberCount)
relatedStreams: VideosFromPiped(data.relatedStreams)
videos: VideosFromPiped(data.relatedStreams)
tabs: ["videos"]
tabsParams: { videos: "" }
tabsTitles: {}
authorBanners: []
"author": ValidString(data.name)
"authorId": GetFirstNonEmpty(ValidString(data.id), channelId)
"bannerUrl": ValidString(data.bannerUrl)
"description": ValidString(data.description)
"subCount": ValidInt(data.subscriberCount)
"relatedStreams": VideosFromPiped(data.relatedStreams)
"videos": VideosFromPiped(data.relatedStreams)
"tabs": ["videos"]
"tabsParams": { videos: "" }
"tabsTitles": {}
"authorBanners": []
}
nextpage = ValidString(data.nextpage)
if nextpage <> ""
@@ -142,11 +142,11 @@ namespace PipedToInvidious
for each item in EnsureArray(data.relatedStreams)
if type(item) = "roAssociativeArray"
playlists.push({
playlistId: ExtractPlaylistId(ValidString(item.url))
title: ValidString(item.title)
videoCount: ValidInt(item.videosCount)
playlistThumbnail: ValidString(item.thumbnail)
type: "playlist"
"playlistId": ExtractPlaylistId(ValidString(item.url))
"title": ValidString(item.title)
"videoCount": ValidInt(item.videosCount)
"playlistThumbnail": ValidString(item.thumbnail)
"type": "playlist"
})
end if
end for
@@ -169,13 +169,13 @@ namespace PipedToInvidious
end if
end for
result = {
title: ValidString(data.name)
playlistId: playlistId
videoCount: ValidInt(data.videos)
description: ValidString(data.description)
author: ValidString(data.uploader)
authorId: ExtractChannelId(ValidString(data.uploaderUrl))
videos: videos
"title": ValidString(data.name)
"playlistId": playlistId
"videoCount": ValidInt(data.videos)
"description": ValidString(data.description)
"author": ValidString(data.uploader)
"authorId": ExtractChannelId(ValidString(data.uploaderUrl))
"videos": videos
}
thumb = ValidString(data.thumbnailUrl)
if thumb <> ""
@@ -200,24 +200,24 @@ namespace PipedToInvidious
videos.push(VideoFromPiped(item))
else if t = "playlist"
playlists.push({
playlistId: ExtractPlaylistId(ValidString(item.url))
title: ValidString(item.title)
videoCount: ValidInt(item.videosCount)
playlistThumbnail: ValidString(item.thumbnail)
author: ValidString(item.uploaderName)
type: "playlist"
"playlistId": ExtractPlaylistId(ValidString(item.url))
"title": ValidString(item.title)
"videoCount": ValidInt(item.videosCount)
"playlistThumbnail": ValidString(item.thumbnail)
"author": ValidString(item.uploaderName)
"type": "playlist"
})
else if t = "channel"
channels.push({
authorId: ExtractChannelId(ValidString(item.url))
author: ValidString(item.title)
authorThumbnail: ValidString(item.avatar)
authorThumbnails: [{ url: ValidString(item.avatar), width: 88, height: 88 }]
description: ValidString(item.description)
subCount: ValidInt(item.subscribers)
handle: ValidString(item.handle)
verified: item.verified = true
type: "channel"
"authorId": ExtractChannelId(ValidString(item.url))
"author": ValidString(item.title)
"authorThumbnail": ValidString(item.avatar)
"authorThumbnails": [{ url: ValidString(item.avatar), width: 88, height: 88 }]
"description": ValidString(item.description)
"subCount": ValidInt(item.subscribers)
"handle": ValidString(item.handle)
"verified": item.verified = true
"type": "channel"
})
end if
end for
@@ -234,10 +234,10 @@ namespace PipedToInvidious
merged.push(pl)
end for
result = {
items: merged
videos: videos
playlists: playlists
channels: channels
"items": merged
"videos": videos
"playlists": playlists
"channels": channels
}
nextpage = ValidString(data.nextpage)
if nextpage <> ""
@@ -250,28 +250,28 @@ namespace PipedToInvidious
' Piped /streams/{id} -> Invidious /api/v1/videos/:id (plus Playlet's
' innertube-ish playback fields: adaptiveFormats/formatStreams/hlsUrl/captions)
meta = {
videoId: videoId
title: ValidString(data.title)
author: ValidString(data.uploader)
authorId: ExtractChannelId(ValidString(data.uploaderUrl))
lengthSeconds: ValidInt(data.duration)
viewCount: ValidInt(data.views)
published: MillisToSeconds(data.uploaded)
description: ValidString(data.description)
genre: EnsureArray(data.tags)
videoThumbnails: ThumbnailsFromProxy(ValidString(data.thumbnailUrl), videoId)
adaptiveFormats: []
formatStreams: []
captions: []
relatedVideos: VideosFromPiped(data.relatedStreams)
recommendedVideos: VideosFromPiped(data.relatedStreams)
storyboards: []
type: "video"
"videoId": videoId
"title": ValidString(data.title)
"author": ValidString(data.uploader)
"authorId": ExtractChannelId(ValidString(data.uploaderUrl))
"lengthSeconds": ValidInt(data.duration)
"viewCount": ValidInt(data.views)
"published": MillisToSeconds(data.uploaded)
"description": ValidString(data.description)
"genre": EnsureArray(data.tags)
"videoThumbnails": ThumbnailsFromProxy(ValidString(data.thumbnailUrl), videoId)
"adaptiveFormats": []
"formatStreams": []
"captions": []
"relatedVideos": VideosFromPiped(data.relatedStreams)
"recommendedVideos": VideosFromPiped(data.relatedStreams)
"storyboards": []
"type": "video"
' Mark as our own parser shape so nothing tries innertube-only paths
parser: "piped"
"parser": "piped"
' Piped proxies signed googlevideo URLs already; Playlet can use them directly
hlsUrl: ValidString(data.hls)
dashUrl: ValidString(data.dash)
"hlsUrl": ValidString(data.hls)
"dashUrl": ValidString(data.dash)
}
avatar = ValidString(data.uploaderAvatar)
if avatar <> ""
@@ -312,9 +312,9 @@ namespace PipedToInvidious
label = ValidString(caption.code)
end if
meta.captions.push({
url: url
"url": url
language_code: ValidString(caption.code)
label: label
"label": label
auto_generated: caption.autoGenerated = true
})
end for
@@ -349,14 +349,14 @@ namespace PipedToInvidious
templateUrl = templateUrl.Replace("M0.", "$M.")
end if
meta.storyboards.push({
templateUrl: templateUrl
width: frameW
height: frameH
count: total
interval: interval
storyboardWidth: cols
storyboardHeight: rows
storyboardCount: imagesCount
"templateUrl": templateUrl
"width": frameW
"height": frameH
"count": total
"interval": interval
"storyboardWidth": cols
"storyboardHeight": rows
"storyboardCount": imagesCount
})
end if
end for
@@ -370,25 +370,25 @@ namespace PipedToInvidious
container = ContainerFromMime(mime)
isVideo = ValidInt(stream.height) > 0
format = {
url: ValidString(stream.url)
itag: ValidInt(stream.itag)
container: container
codec: codec
"url": ValidString(stream.url)
"itag": ValidInt(stream.itag)
"container": container
"codec": codec
mime_type: mime
bitrate: ValidInt(stream.bitrate)
contentLength: ValidInt(stream.contentLength)
quality: QualityLabel(stream.quality)
qualityLabel: QualityLabel(stream.quality)
fps: ValidInt(stream.fps)
width: ValidInt(stream.width)
height: ValidInt(stream.height)
init: ""
index: ""
approxDurationMs: ""
audioSampleRate: ""
aspectRatio: ""
projectionType: ""
averageBitrate: ValidInt(stream.bitrate)
"bitrate": ValidInt(stream.bitrate)
"contentLength": ValidInt(stream.contentLength)
"quality": QualityLabel(stream.quality)
"qualityLabel": QualityLabel(stream.quality)
"fps": ValidInt(stream.fps)
"width": ValidInt(stream.width)
"height": ValidInt(stream.height)
"init": ""
"index": ""
"approxDurationMs": ""
"audioSampleRate": ""
"aspectRatio": ""
"projectionType": ""
"averageBitrate": ValidInt(stream.bitrate)
}
if isVideo
format["type"] = `video; codecs="` + codec + `"`
@@ -416,15 +416,15 @@ namespace PipedToInvidious
continue for
end if
comment = {
content: ValidString(item.commentText)
author: ValidString(item.author)
id: ValidString(item.commentId)
published: ValidString(item.commentedTime)
publishedText: ValidString(item.commentedTime)
likeCount: ValidInt(item.likeCount)
isPinned: item.pinned = true
authorThumbnails: [{ url: ValidString(item.thumbnail), width: 88, height: 88 }]
commentorUrl: ValidString(item.commentorUrl)
"content": ValidString(item.commentText)
"author": ValidString(item.author)
"id": ValidString(item.commentId)
"published": ValidString(item.commentedTime)
"publishedText": ValidString(item.commentedTime)
"likeCount": ValidInt(item.likeCount)
"isPinned": item.pinned = true
"authorThumbnails": [{ url: ValidString(item.thumbnail), width: 88, height: 88 }]
"commentorUrl": ValidString(item.commentorUrl)
}
if item.hearted = true
comment["heart"] = true
@@ -434,7 +434,7 @@ namespace PipedToInvidious
end if
if ValidInt(item.replyCount) > 0
replies = {
replyCount: ValidInt(item.replyCount)
"replyCount": ValidInt(item.replyCount)
}
rp = ValidString(item.repliesPage)
if rp <> ""
@@ -445,9 +445,9 @@ namespace PipedToInvidious
comments.push(comment)
end for
result = {
commentCount: ValidInt(data.commentCount)
comments: comments
internalContinuation: ""
"commentCount": ValidInt(data.commentCount)
"comments": comments
"internalContinuation": ""
}
np = ValidString(data.nextpage)
if np <> ""
@@ -571,15 +571,64 @@ namespace PipedToInvidious
end function
function MillisToSeconds(millis as dynamic) as integer
t = type(millis)
if t <> "int" and t <> "longint" and t <> "float" and t <> "double"
' NOTE: on this device CDbl() of a boxed roLongInt behaves like a
' SINGLE-precision float: 1256453853000 -> truncates to low 32 bits,
' then rounds (2323402568 -> 2323402624 -> negative int). So never
' convert the full epoch-millis to float; do string arithmetic:
' seconds = int(str[:-3]) when the value looks like epoch millis,
' keeping every intermediate inside int32.
if millis = invalid
return 0
end if
value = ValidInt(millis)
if value > 100000000000
return value / 1000
s = ""
if getInterface(millis, "ifString") <> invalid
s = ValidString(millis)
else if getInterface(millis, "ifToStr") <> invalid
' boxed roInt/roLongInt/roDouble from roJSONParser: CDbl() on a
' roLongInt silently truncates to 32 bits on this firmware, so
' go through the decimal string instead
s = millis.ToStr()
else
return 0
end if
return value
s = s.Replace(" ", "")
' strip sign/decimals
if Left(s, 1) = "-"
s = s.Mid(2)
end if
dotIdx = InStr(s, ".")
if dotIdx > 0
s = s.Left(dotIdx - 1)
end if
if s = "" or s.Len() > 19
return 0
end if
for each c in s
if c < "0" or c > "9"
return 0
end if
end for
' epoch millis are 13 digits (2001-2286); 12 digits start 2001 too.
if s.Len() >= 12
' dropping the last 3 digits of epoch-millis yields epoch-seconds
' directly, and that value fits int32 until 2038
return Val(s.Left(s.Len() - 3))
end if
' already seconds (10 digits) or smaller
if s.Len() = 10
return Val(s)
end if
value = Val(s)
if value > 1000000000
return value
end if
return value / 1000
end function
function EnsureArray(value as dynamic) as object
@@ -41,6 +41,12 @@ namespace Http
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)
@@ -253,6 +259,54 @@ ${storyboard.templateUrl.replace("$M", `${i}`)}
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
@@ -5,6 +5,7 @@ import "pkg:/source/utils/Types.bs"
import "pkg:/source/utils/UrlUtils.bs"
import "pkg:/source/utils/Logging.bs"
import "pkg:/components/Web/WebServer/Http/HttpRouter.bs"
import "pkg:/components/Web/PlayletWebServer/Middleware/HlsRouter.bs"
' Serves the Invidious /api/v1 JSON shapes that Playlet's client expects,
' translated from a real Piped instance (https://github.com/TeamPiped/Piped).
@@ -38,6 +39,92 @@ namespace Http
return instance
end function
' GET /playlet-piped-backend/api/v1/manifest?url=<piped hls master>
' Fetches the Piped HLS master and rewrites its relative variant and
' media URIs to absolute proxy URLs, so Playlet's /api/hls proxy and
' the Roku player resolve them against the Piped instance, not 127.0.0.1.
function GetRewrittenHlsManifest(context as object) as boolean
request = context.request
response = context.response
url = request.query.url
if StringUtils.IsNullOrEmpty(url)
response.Default(400, "Missing url")
return true
end if
hlsResponse = HttpClient.Get(url).Await()
if not hlsResponse.IsSuccess()
LogWarn("Piped backend: manifest fetch failed", url, hlsResponse.StatusCode())
response.Redirect(url)
return true
end if
manifest = m.MakeRelativeUrisAbsolute(hlsResponse.Text(), url)
response.http_code = 200
response.headers["Content-Type"] = "application/x-mpegURL"
response.headers["Cache-Control"] = "no-cache, must-revalidate"
response.SetBodyDataString(manifest)
return true
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 = ValidString(parsedUrl.protocol)
if protocol = ""
protocol = "https"
end if
origin = protocol + "://" + parsedUrl.host
port = ValidString(parsedUrl.port)
if port <> "" and port <> "80" and port <> "443"
origin = origin + ":" + port
end if
bareCount = 0
attrCount = 0
' normalize line endings: some hosts serve manifests with CR-only
' line terminators, which Split("\n") would leave as 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
trimmed = lines[i].Trim()
if Left(trimmed, 1) = "/"
' bare relative URI line (variant/media playlist)
lines[i] = origin + trimmed
bareCount = bareCount + 1
else if Left(trimmed, 1) = "#" and InStr(UCase(trimmed), "URI=" + chr(34) + "/") > 0
' attribute form: #EXT-X-MEDIA:...URI="/..." etc.
parts = trimmed.Split(chr(34))
for q = 0 to parts.Count() - 1
if Left(parts[q], 1) = "/"
parts[q] = origin + parts[q]
end if
end for
lines[i] = parts.Join(chr(34))
attrCount = attrCount + 1
end if
end for
result = lines.Join("\n")
return result
end function
function LibBuildTag() as string
return "PIPED-LIB-14"
end function
function FetchJson(path as string, params = invalid as object) as dynamic
url = m.GetBaseUrl() + path
@@ -93,7 +180,9 @@ namespace Http
head = parts[0]
end if
if head = "stats"
if tail = "manifest"
return m.GetRewrittenHlsManifest(context)
else if head = "stats"
return m.GetStats(context)
else if head = "trending"
return m.GetTrending(context)
@@ -143,7 +232,7 @@ namespace Http
function UnsupportedAuth(context as object) as boolean
m.SendJson(context.response, {
error: "Piped backend accounts are not supported yet. Browse anonymously, or log in to your Piped instance in a browser."
"error": "Piped backend accounts are not supported yet. Browse anonymously, or log in to your Piped instance in a browser."
}, 400)
return true
end function
@@ -159,13 +248,15 @@ namespace Http
end if
m.SendJson(response, {
software: "piped"
version: ValidString(stats.version)
userCount: ValidInt(stats.userCount)
lastStreamed: ""
videoCountPlaylists: 0
videoCount: 0
usage: {}
"buildTag": m.LibBuildTag()
"software": "piped"
"version": ValidString(stats.version)
"userCount": ValidInt(stats.userCount)
"lastStreamed": ""
"videoCountPlaylists": 0
"videoCount": 0
"usage": {}
})
return true
end function
@@ -212,8 +303,8 @@ namespace Http
end if
m.SendJson(response, {
suggestions: suggestions
params: ""
"suggestions": suggestions
"params": ""
})
return true
end function