rename: src/Formats -> src/Rosetta, @formats -> @rosetta requires, build/luajit/rosetta + rosetta._compat, build/roblox/Rosetta, ROSETTA_* env/globals, writer vendor strings
This commit is contained in:
1 parent
2956576d7f
commit
22ddcd78fa
941 files changed
+3364
-3364
No files matched your search
@@ -0,0 +1,367 @@
|
||||
--!strict
|
||||
-- playlist/m3u: M3U / M3U8 and HLS (RFC 8216) playlists. Absorbed from playlist-luau 3fc7fd3 (same author, no
|
||||
-- third-party code). Decode: #EXTM3U / #EXTINF (durations, titles with attributes and commas), #PLAYLIST, plain
|
||||
-- location lists, a BOM, CRLF / CR, Windows-1252 text; HLS master playlists (variants with BANDWIDTH / CODECS /
|
||||
-- attributes, EXT-X-MEDIA renditions) and media playlists (segments, durations, byte ranges, target duration, media
|
||||
-- sequence, end list, encryption, the segment format). Locations resolve against opts.baseUrl (RFC 3986,
|
||||
-- codecs/text/Url); Windows / UNC paths stay as they are and are flagged unplayable, as are relative paths without a base
|
||||
-- and non-HTTP schemes (mp3 HLS segments are playable; .ts / .aac / fMP4 are flagged). Encode: M3U8 (#EXTM3U,
|
||||
-- #EXTINF, #PLAYLIST). Not supported: writing HLS tags.
|
||||
--
|
||||
-- local pl = M3u.decode(Bytes.reader(buf), { baseUrl = "https://example.com/music/list.m3u" })
|
||||
-- for _, e in pl.entries do print(e.url, e.title, e.duration, e.playable) end -- pl.format: "m3u" | "hls"
|
||||
-- local out = M3u.encode(pl, { title = "My Mix" })
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@rosetta/core/Err")
|
||||
local Sniff = require("@rosetta/core/Sniff")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
local Types = require("@rosetta/Types")
|
||||
local Url = require("@rosetta/codecs/text/Url")
|
||||
local Text = require("@rosetta/codecs/text/Text")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local M3u = {
|
||||
name = "m3u",
|
||||
category = "playlist",
|
||||
extensions = { "m3u", "m3u8" },
|
||||
mime = { "audio/x-mpegurl", "audio/mpegurl", "application/vnd.apple.mpegurl", "application/x-mpegurl" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Url", "codecs/text/Text", "core/Sniff" },
|
||||
caps = { decode = true, encode = true, hls = true },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type Entry = {
|
||||
url: string,
|
||||
title: string?,
|
||||
duration: number?, -- seconds; nil when unknown (-1 in the file)
|
||||
playable: boolean, -- an http(s) URL the player can fetch
|
||||
reason: string?, -- why not playable: "local path", "relative path without a base URL", "scheme ftp", ...
|
||||
-- HLS
|
||||
bandwidth: number?, -- master: BANDWIDTH
|
||||
codecs: string?, -- master: CODECS
|
||||
attributes: { [string]: string }?, -- master: the whole EXT-X-STREAM-INF / EXT-X-MEDIA attribute list
|
||||
byteRange: { length: number, offset: number? }?, -- media: EXT-X-BYTERANGE
|
||||
}
|
||||
|
||||
export type Hls = {
|
||||
master: boolean,
|
||||
targetDuration: number?,
|
||||
mediaSequence: number?,
|
||||
endList: boolean, -- media playlist: EXT-X-ENDLIST seen (false = live, the playlist grows)
|
||||
encrypted: boolean, -- EXT-X-KEY with a METHOD other than NONE
|
||||
totalDuration: number?, -- media: sum of the segment durations
|
||||
segmentFormat: string?, -- media: the segments' common extension ("mp3", "ts", "aac", ...) or "mixed"
|
||||
}
|
||||
|
||||
export type Result = {
|
||||
kind: "playlist",
|
||||
format: "m3u" | "pls" | "hls" | "xspf",
|
||||
meta: { [string]: any },
|
||||
entries: { Entry },
|
||||
warnings: { string },
|
||||
title: string?, -- #PLAYLIST: / PLS has none
|
||||
hls: Hls?,
|
||||
}
|
||||
|
||||
export type DecodeOptions = {
|
||||
baseUrl: string?, -- the playlist's own URL (or Windows path), for relative entries
|
||||
maxBytes: number?, -- refuse bigger files (default 64 MB)
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
title: string?, -- #PLAYLIST: (default: the playlist's title)
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
local UNSUPPORTED_SEGMENTS = { ts = true, aac = true, m4s = true, mp4 = true, m4a = true, fmp4 = true, cmfa = true }
|
||||
|
||||
-- The extension of a URL's path (lower case), or nil
|
||||
local function extension(url: string): string?
|
||||
local p = Url.split(url).path
|
||||
local ext = string.match(p, "%.([%w]+)$")
|
||||
return if ext then string.lower(ext) else nil
|
||||
end
|
||||
|
||||
local function duration(s: string?): number?
|
||||
local d = tonumber(s and Text.trim(s))
|
||||
if not d or d < 0 or d ~= d or d == math.huge then
|
||||
return nil
|
||||
end
|
||||
return d
|
||||
end
|
||||
|
||||
-- RFC 8216 attribute list: KEY=value pairs, quoted strings may hold commas
|
||||
local function attributes(s: string): { [string]: string }
|
||||
local out = {}
|
||||
local i, n = 1, #s
|
||||
while i <= n do
|
||||
local key, eq = string.match(s, "^%s*([%w%-_]+)%s*()=", i)
|
||||
if not key then
|
||||
break
|
||||
end
|
||||
i = (eq :: number) + 1
|
||||
local value
|
||||
if string.sub(s, i, i) == '"' then
|
||||
local j = string.find(s, '"', i + 1, true) or (n + 1)
|
||||
value = string.sub(s, i + 1, j - 1)
|
||||
i = j + 1
|
||||
else
|
||||
local j = string.find(s, ",", i, true) or (n + 1)
|
||||
value = Text.trim(string.sub(s, i, j - 1))
|
||||
i = j
|
||||
end
|
||||
out[string.upper(key)] = value
|
||||
local c = string.find(s, ",", i, true)
|
||||
if not c then
|
||||
break
|
||||
end
|
||||
i = c + 1
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
-- #EXTINF:<duration>[ attr="v" ...],<title>
|
||||
local function extinf(rest: string): (number?, string?)
|
||||
-- the first comma outside quoted attribute values
|
||||
local comma, quoted = nil, false
|
||||
for i = 1, #rest do
|
||||
local c = string.byte(rest, i)
|
||||
if c == 34 then
|
||||
quoted = not quoted
|
||||
elseif c == 44 and not quoted then
|
||||
comma = i
|
||||
break
|
||||
end
|
||||
end
|
||||
local head = if comma then string.sub(rest, 1, comma - 1) else rest
|
||||
local title = if comma then Text.trim(string.sub(rest, comma + 1)) else nil
|
||||
local d = string.match(head, "^%s*([%-%+]?[%d%.]+)")
|
||||
return duration(d), if title and title ~= "" then title else nil
|
||||
end
|
||||
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function M3u.sniff(r: Bytes.Reader): number
|
||||
local s = Sniff.text(r, 512)
|
||||
s = (string.match(s, "^%s*(.*)$") :: string)
|
||||
if string.sub(s, 1, 7) == "#EXTM3U" then
|
||||
return 0.95
|
||||
end
|
||||
if string.find(s, "^#EXTINF:") or string.find(s, "^#EXT%-X%-") then
|
||||
return 0.8
|
||||
end
|
||||
return 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
local function parseM3u(ls: { string }, base: string?, baseScheme: string?, warnings: { string }): Result
|
||||
local res: Result = { kind = "playlist", format = "m3u", entries = {}, warnings = warnings, meta = {} }
|
||||
local pendingDur, pendingTitle = nil, nil
|
||||
for n, line in ls do
|
||||
local l = Text.trim(line)
|
||||
if l == "" then
|
||||
continue
|
||||
end
|
||||
if string.sub(l, 1, 1) == "#" then
|
||||
local upper = string.upper(string.sub(l, 1, 10))
|
||||
if string.sub(upper, 1, 8) == "#EXTINF:" then
|
||||
pendingDur, pendingTitle = extinf(string.sub(l, 9))
|
||||
elseif string.sub(upper, 1, 10) == "#PLAYLIST:" then
|
||||
res.title = Text.trim(string.sub(l, 11))
|
||||
end
|
||||
-- #EXTM3U, #EXTGRP, #EXTALB, ... and plain comments: ignored
|
||||
continue
|
||||
end
|
||||
local e: Entry = Url.locate(l, base, baseScheme)
|
||||
e.title = pendingTitle
|
||||
e.duration = pendingDur
|
||||
pendingDur, pendingTitle = nil, nil
|
||||
table.insert(res.entries, e)
|
||||
if e.reason and e.reason ~= "local path" then
|
||||
table.insert(warnings, ("line %d: %s: %s"):format(n, e.reason, e.url))
|
||||
end
|
||||
end
|
||||
return res
|
||||
end
|
||||
|
||||
local function parseHls(ls: { string }, base: string?, baseScheme: string?, warnings: { string }): Result
|
||||
local hls: Hls = { master = false, endList = false, encrypted = false }
|
||||
local res: Result = { kind = "playlist", format = "hls", entries = {}, warnings = warnings, hls = hls, meta = {} }
|
||||
local pendingDur, pendingTitle, pendingRange = nil, nil, nil
|
||||
local pendingStream: { [string]: string }? = nil
|
||||
local lastRangeEnd: number? = nil
|
||||
local total = 0
|
||||
local formats = {}
|
||||
local fmp4 = false
|
||||
for n, line in ls do
|
||||
local l = Text.trim(line)
|
||||
if l == "" then
|
||||
continue
|
||||
end
|
||||
if string.sub(l, 1, 1) == "#" then
|
||||
local tag, rest = string.match(l, "^(#[%w%-]+):?(.*)$")
|
||||
tag = if tag then string.upper(tag) else nil
|
||||
if tag == "#EXT-X-STREAM-INF" then
|
||||
hls.master = true
|
||||
pendingStream = attributes(rest :: string)
|
||||
elseif tag == "#EXT-X-MEDIA" then
|
||||
hls.master = true
|
||||
local a = attributes(rest :: string)
|
||||
if a.URI then
|
||||
local e: Entry = Url.locate(a.URI, base, baseScheme)
|
||||
e.title = a.NAME
|
||||
e.attributes = a
|
||||
e.codecs = a.CODECS
|
||||
table.insert(res.entries, e)
|
||||
end
|
||||
elseif tag == "#EXT-X-TARGETDURATION" then
|
||||
hls.targetDuration = tonumber(Text.trim(rest :: string))
|
||||
elseif tag == "#EXT-X-MEDIA-SEQUENCE" then
|
||||
hls.mediaSequence = tonumber(Text.trim(rest :: string))
|
||||
elseif tag == "#EXT-X-ENDLIST" then
|
||||
hls.endList = true
|
||||
elseif tag == "#EXT-X-KEY" then
|
||||
local a = attributes(rest :: string)
|
||||
if a.METHOD and string.upper(a.METHOD) ~= "NONE" then
|
||||
if not hls.encrypted then
|
||||
table.insert(warnings, ("line %d: encrypted segments (METHOD=%s) are not supported"):format(n, a.METHOD))
|
||||
end
|
||||
hls.encrypted = true
|
||||
end
|
||||
elseif tag == "#EXT-X-MAP" then
|
||||
fmp4 = true
|
||||
elseif tag == "#EXTINF" then
|
||||
pendingDur, pendingTitle = extinf(rest :: string)
|
||||
elseif tag == "#EXT-X-BYTERANGE" then
|
||||
local len, off = string.match(rest :: string, "^%s*(%d+)@?(%d*)")
|
||||
if len then
|
||||
local o = tonumber(off) or lastRangeEnd
|
||||
pendingRange = { length = tonumber(len) :: number, offset = o }
|
||||
lastRangeEnd = (o or 0) + (tonumber(len) :: number)
|
||||
end
|
||||
end
|
||||
continue
|
||||
end
|
||||
local e: Entry = Url.locate(l, base, baseScheme)
|
||||
if pendingStream then
|
||||
e.attributes = pendingStream
|
||||
e.bandwidth = tonumber(pendingStream.BANDWIDTH)
|
||||
e.codecs = pendingStream.CODECS
|
||||
e.title = pendingStream.NAME
|
||||
pendingStream = nil
|
||||
else
|
||||
e.title = pendingTitle
|
||||
e.duration = pendingDur
|
||||
e.byteRange = pendingRange
|
||||
if pendingDur then
|
||||
total += pendingDur
|
||||
end
|
||||
local ext = extension(e.url) or "?"
|
||||
formats[ext] = true
|
||||
if e.playable and (UNSUPPORTED_SEGMENTS[ext] or fmp4) then
|
||||
e.playable = false
|
||||
e.reason = "segment format " .. (if fmp4 then "fmp4" else ext)
|
||||
end
|
||||
if e.playable and hls.encrypted then
|
||||
e.playable = false
|
||||
e.reason = "encrypted"
|
||||
end
|
||||
end
|
||||
pendingDur, pendingTitle, pendingRange = nil, nil, nil
|
||||
table.insert(res.entries, e)
|
||||
if e.reason == "relative path without a base URL" or (e.reason and string.sub(e.reason, 1, 7) == "scheme ") then
|
||||
table.insert(warnings, ("line %d: %s: %s"):format(n, e.reason, e.url))
|
||||
end
|
||||
end
|
||||
if not hls.master then
|
||||
hls.totalDuration = total
|
||||
local list = {}
|
||||
for ext in formats do
|
||||
table.insert(list, ext)
|
||||
end
|
||||
table.sort(list)
|
||||
hls.segmentFormat = if #list == 1 then list[1] elseif #list == 0 then nil else "mixed"
|
||||
local bad = {}
|
||||
for _, ext in list do
|
||||
if UNSUPPORTED_SEGMENTS[ext] then
|
||||
table.insert(bad, "." .. ext)
|
||||
end
|
||||
end
|
||||
if fmp4 then
|
||||
table.insert(bad, "fMP4 (EXT-X-MAP)")
|
||||
end
|
||||
if #bad > 0 then
|
||||
table.insert(warnings, "HLS segments are " .. table.concat(bad, ", ")
|
||||
.. ": only mp3 segments can be played (concatenated)")
|
||||
end
|
||||
if not hls.endList then
|
||||
table.insert(warnings, "live HLS playlist (no EXT-X-ENDLIST): it has to be reloaded for new segments")
|
||||
end
|
||||
end
|
||||
return res
|
||||
end
|
||||
|
||||
-- decode(r, opts?) -> Types.Playlist | nil, Err. Bad lines become warnings (pl.warnings), never errors.
|
||||
function M3u.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Playlist?, Err.Err?)
|
||||
local n = r.limit - r.pos
|
||||
if n > (opts and opts.maxBytes or 2 ^ 26) then
|
||||
return nil, Err.new(Err.LIMIT, "playlist over the size limit")
|
||||
end
|
||||
local warnings = {}
|
||||
local base, baseScheme = Url.base(opts and opts.baseUrl, warnings)
|
||||
local t = Text.toUtf8(r:string(n), warnings)
|
||||
local ls = Text.lines(t)
|
||||
local res = if string.find(t, "#EXT%-X%-") then parseHls(ls, base, baseScheme, warnings) else parseM3u(ls, base, baseScheme, warnings)
|
||||
local nLocal = 0
|
||||
for _, e in res.entries do
|
||||
if e.reason == "local path" then
|
||||
nLocal += 1
|
||||
end
|
||||
end
|
||||
if nLocal > 0 then
|
||||
table.insert(warnings, string.format("%d local path%s (not playable)", nLocal, if nLocal == 1 then "" else "s"))
|
||||
end
|
||||
res.meta.source = { format = "m3u", hls = res.format == "hls" }
|
||||
return res :: any, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
-- Writes entries as M3U8 (UTF-8, #EXTM3U, #EXTINF:<seconds>,<title>). Durations are rounded; unknown = -1.
|
||||
-- opts.title adds #PLAYLIST:. Line breaks inside titles and URLs become spaces.
|
||||
local function serialize(entries: { any }, opts: { title: string? }?): string
|
||||
local out = { "#EXTM3U" }
|
||||
local function clean(s: string): string
|
||||
return (string.gsub(s, "[\r\n]+", " "))
|
||||
end
|
||||
if opts and opts.title then
|
||||
table.insert(out, "#PLAYLIST:" .. clean(opts.title))
|
||||
end
|
||||
for _, e in entries or {} do
|
||||
if type(e) ~= "table" or type(e.url) ~= "string" then
|
||||
continue
|
||||
end
|
||||
local d = tonumber(e.duration)
|
||||
local secs = if d and d >= 0 and d == d and d ~= math.huge then math.floor(d + 0.5) else -1
|
||||
if e.title or d then
|
||||
table.insert(out, ("#EXTINF:%d,%s"):format(secs, clean(tostring(e.title or ""))))
|
||||
end
|
||||
table.insert(out, clean(e.url))
|
||||
end
|
||||
return table.concat(out, "\n") .. "\n"
|
||||
end
|
||||
|
||||
-- encode(playlist, opts?) -> buffer | nil, Err: M3U8 text. playlist: a Types.Playlist (any format's) or a list of
|
||||
-- entries ({ url, title?, duration? })
|
||||
function M3u.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
if type(value) ~= "table" then
|
||||
return nil, Err.new(Err.ARG, "encode: needs a Playlist or a list of entries")
|
||||
end
|
||||
local entries = if type(value.entries) == "table" then value.entries else value
|
||||
local title = if opts and opts.title then opts.title else value.title
|
||||
return buffer.fromstring(serialize(entries, { title = if type(title) == "string" then title else nil })), nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ extras
|
||||
M3u.Url = Url
|
||||
|
||||
return M3u
|
||||
@@ -0,0 +1,185 @@
|
||||
--!strict
|
||||
-- playlist/pls: PLS playlists ([playlist], FileN / TitleN / LengthN, NumberOfEntries, Version). Absorbed from
|
||||
-- playlist-luau 3fc7fd3 (same author, no third-party code; the parser), plus a new writer. Decode: keys in any case
|
||||
-- and order, comments, a BOM, CRLF / CR, Windows-1252 text, gaps in the numbering (entries sort by number), a
|
||||
-- NumberOfEntries mismatch as a warning; locations resolve against opts.baseUrl (RFC 3986, codecs/text/Url), local /
|
||||
-- relative / non-HTTP locations are flagged unplayable. Encode: Version=2, Length -1 for unknown durations.
|
||||
--
|
||||
-- local pl = Pls.decode(Bytes.reader(buf), { baseUrl = "https://radio.example/list.pls" })
|
||||
-- local out = Pls.encode(pl)
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@rosetta/core/Err")
|
||||
local Sniff = require("@rosetta/core/Sniff")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
local Types = require("@rosetta/Types")
|
||||
local Url = require("@rosetta/codecs/text/Url")
|
||||
local Text = require("@rosetta/codecs/text/Text")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Pls = {
|
||||
name = "pls",
|
||||
category = "playlist",
|
||||
extensions = { "pls" },
|
||||
mime = { "audio/x-scpls", "audio/scpls" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Url", "codecs/text/Text", "core/Sniff" },
|
||||
caps = { decode = true, encode = true },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type Entry = {
|
||||
url: string,
|
||||
title: string?,
|
||||
duration: number?, -- seconds; nil when unknown (-1 in the file)
|
||||
playable: boolean, -- an http(s) URL the player can fetch
|
||||
reason: string?, -- why not playable: "local path", "relative path without a base URL", "scheme ftp", ...
|
||||
-- HLS
|
||||
bandwidth: number?, -- master: BANDWIDTH
|
||||
codecs: string?, -- master: CODECS
|
||||
attributes: { [string]: string }?, -- master: the whole EXT-X-STREAM-INF / EXT-X-MEDIA attribute list
|
||||
byteRange: { length: number, offset: number? }?, -- media: EXT-X-BYTERANGE
|
||||
}
|
||||
|
||||
export type Hls = {
|
||||
master: boolean,
|
||||
targetDuration: number?,
|
||||
mediaSequence: number?,
|
||||
endList: boolean, -- media playlist: EXT-X-ENDLIST seen (false = live, the playlist grows)
|
||||
encrypted: boolean, -- EXT-X-KEY with a METHOD other than NONE
|
||||
totalDuration: number?, -- media: sum of the segment durations
|
||||
segmentFormat: string?, -- media: the segments' common extension ("mp3", "ts", "aac", ...) or "mixed"
|
||||
}
|
||||
|
||||
export type Result = {
|
||||
kind: "playlist",
|
||||
format: "m3u" | "pls" | "hls" | "xspf",
|
||||
meta: { [string]: any },
|
||||
entries: { Entry },
|
||||
warnings: { string },
|
||||
title: string?, -- #PLAYLIST: / PLS has none
|
||||
hls: Hls?,
|
||||
}
|
||||
|
||||
export type DecodeOptions = {
|
||||
baseUrl: string?, -- the playlist's own URL (or Windows path), for relative entries
|
||||
maxBytes: number?, -- refuse bigger files (default 64 MB)
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
local function duration(s: string?): number?
|
||||
local d = tonumber(s and Text.trim(s))
|
||||
if not d or d < 0 or d ~= d or d == math.huge then
|
||||
return nil
|
||||
end
|
||||
return d
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Pls.sniff(r: Bytes.Reader): number
|
||||
local s = Sniff.text(r, 64)
|
||||
local first = string.match(s, "^%s*([^\r\n]*)")
|
||||
return if first and string.lower(Text.trim(first)) == "[playlist]" then 0.95 else 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
local function parsePls(ls: { string }, base: string?, baseScheme: string?, warnings: { string }): Result
|
||||
local res: Result = { kind = "playlist", format = "pls", entries = {}, warnings = warnings, meta = {} }
|
||||
local files: { [number]: string }, titles: { [number]: string }, lengths: { [number]: string } = {}, {}, {}
|
||||
local declared = nil
|
||||
for _, line in ls do
|
||||
local l = Text.trim(line)
|
||||
if l == "" or string.sub(l, 1, 1) == ";" or string.sub(l, 1, 1) == "#" or string.sub(l, 1, 1) == "[" then
|
||||
continue
|
||||
end
|
||||
local key, value = string.match(l, "^([^=]-)%s*=%s*(.*)$")
|
||||
if not key then
|
||||
continue
|
||||
end
|
||||
local k = string.lower(Text.trim(key :: string))
|
||||
local name, idx = string.match(k, "^(%a+)(%d+)$")
|
||||
local i = tonumber(idx)
|
||||
if name == "file" and i then
|
||||
files[i] = value
|
||||
elseif name == "title" and i then
|
||||
titles[i] = value
|
||||
elseif name == "length" and i then
|
||||
lengths[i] = value
|
||||
elseif k == "numberofentries" then
|
||||
declared = tonumber(value)
|
||||
end
|
||||
end
|
||||
local order = {}
|
||||
for i in files do
|
||||
table.insert(order, i)
|
||||
end
|
||||
table.sort(order)
|
||||
for _, i in order do
|
||||
local e: Entry = Url.locate(files[i], base, baseScheme)
|
||||
local t = titles[i] and Text.trim(titles[i])
|
||||
e.title = if t and t ~= "" then t else nil
|
||||
e.duration = duration(lengths[i])
|
||||
table.insert(res.entries, e)
|
||||
if e.reason and e.reason ~= "local path" then
|
||||
table.insert(warnings, ("File%d: %s: %s"):format(i, e.reason, e.url))
|
||||
end
|
||||
end
|
||||
if declared and declared ~= #order then
|
||||
table.insert(warnings, ("NumberOfEntries=%d but %d files"):format(declared, #order))
|
||||
end
|
||||
return res
|
||||
end
|
||||
|
||||
-- decode(r, opts?) -> Types.Playlist | nil, Err. Bad lines become warnings (pl.warnings), never errors.
|
||||
function Pls.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Playlist?, Err.Err?)
|
||||
local n = r.limit - r.pos
|
||||
if n > (opts and opts.maxBytes or 2 ^ 26) then
|
||||
return nil, Err.new(Err.LIMIT, "playlist over the size limit")
|
||||
end
|
||||
local warnings = {}
|
||||
local base, baseScheme = Url.base(opts and opts.baseUrl, warnings)
|
||||
local t = Text.toUtf8(r:string(n), warnings)
|
||||
local res = parsePls(Text.lines(t), base, baseScheme, warnings)
|
||||
local nLocal = 0
|
||||
for _, e in res.entries do
|
||||
if e.reason == "local path" then
|
||||
nLocal += 1
|
||||
end
|
||||
end
|
||||
if nLocal > 0 then
|
||||
table.insert(warnings, string.format("%d local path%s (not playable)", nLocal, if nLocal == 1 then "" else "s"))
|
||||
end
|
||||
res.meta.source = { format = "pls" }
|
||||
return res :: any, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
-- encode(playlist, opts?) -> buffer | nil, Err: PLS text (Version=2). playlist: a Types.Playlist (any format's) or a
|
||||
-- list of entries ({ url, title?, duration? }). Line breaks inside titles and URLs become spaces.
|
||||
function Pls.encode(value: any, _opts: any?): (buffer?, Err.Err?)
|
||||
if type(value) ~= "table" then
|
||||
return nil, Err.new(Err.ARG, "encode: needs a Playlist or a list of entries")
|
||||
end
|
||||
local entries = if type(value.entries) == "table" then value.entries else value
|
||||
local function clean(s: string): string
|
||||
return (string.gsub(s, "[\r\n]+", " "))
|
||||
end
|
||||
local out = { "[playlist]" }
|
||||
local n = 0
|
||||
for _, e in entries do
|
||||
if type(e) == "table" and type(e.url) == "string" then
|
||||
n += 1
|
||||
table.insert(out, string.format("File%d=%s", n, clean(e.url)))
|
||||
if type(e.title) == "string" then
|
||||
table.insert(out, string.format("Title%d=%s", n, clean(e.title)))
|
||||
end
|
||||
local d = tonumber(e.duration)
|
||||
local secs = if d and d >= 0 and d == d and d ~= math.huge then math.floor(d + 0.5) else -1
|
||||
table.insert(out, string.format("Length%d=%d", n, secs))
|
||||
end
|
||||
end
|
||||
table.insert(out, "NumberOfEntries=" .. n)
|
||||
table.insert(out, "Version=2")
|
||||
return buffer.fromstring(table.concat(out, "\n") .. "\n"), nil
|
||||
end
|
||||
|
||||
return Pls
|
||||
@@ -0,0 +1,214 @@
|
||||
--!strict
|
||||
-- playlist/xspf: XSPF 1 ("spiff", https://xspf.org/spec) playlists on codecs/text/Xml. New in rosetta (playlist-luau
|
||||
-- had no XSPF). Decode: the playlist's title / creator / annotation / info / location / identifier / image / date,
|
||||
-- every track's location (the first one is the entry url, all of them in entry.locations), title, creator, album,
|
||||
-- annotation, info, image, trackNum and duration (milliseconds -> seconds), xml:base on the playlist and on tracks;
|
||||
-- locations resolve against xml:base, then opts.baseUrl (RFC 3986, codecs/text/Url), and are classified like the other
|
||||
-- playlist formats (local / relative / non-HTTP locations are unplayable). Encode: XSPF version 1 with those fields.
|
||||
-- Not supported: extension / link / meta elements (skipped), XSPF version 0 differences.
|
||||
--
|
||||
-- local pl = Xspf.decode(Bytes.reader(buf), { baseUrl = "https://example.com/list.xspf" })
|
||||
-- for _, e in pl.entries do print(e.url, e.title, e.creator, e.duration) end
|
||||
-- local out = Xspf.encode(pl)
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@rosetta/core/Err")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
local Types = require("@rosetta/Types")
|
||||
local Url = require("@rosetta/codecs/text/Url")
|
||||
local Xml = require("@rosetta/codecs/text/Xml")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Xspf = {
|
||||
name = "xspf",
|
||||
category = "playlist",
|
||||
extensions = { "xspf" },
|
||||
mime = { "application/xspf+xml" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Url", "codecs/text/Xml" },
|
||||
caps = { decode = true, encode = true },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = {
|
||||
baseUrl: string?, -- the playlist's own URL (or Windows path), for relative locations
|
||||
maxBytes: number?, -- refuse bigger files (default 64 MB)
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
local NS = "http://xspf.org/ns/0/"
|
||||
local PLAYLIST_FIELDS = { "title", "creator", "annotation", "info", "location", "identifier", "image", "date", "license" }
|
||||
local TRACK_FIELDS = { "title", "creator", "album", "annotation", "info", "image" }
|
||||
|
||||
local function trim(s: string): string
|
||||
return (string.match(s, "^%s*(.-)%s*$") :: string)
|
||||
end
|
||||
|
||||
-- the text of the first child element with this local name, trimmed (nil when missing or empty)
|
||||
local function field(node: any, name: string): string?
|
||||
for _, c in node.children do
|
||||
if type(c) == "table" and Xml.localName(c.name) == name then
|
||||
local s = trim(Xml.text(c))
|
||||
return if s ~= "" then s else nil
|
||||
end
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
local function elements(node: any, name: string): { any }
|
||||
local out = {}
|
||||
for _, c in node.children do
|
||||
if type(c) == "table" and Xml.localName(c.name) == name then
|
||||
table.insert(out, c)
|
||||
end
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Xspf.sniff(r: Bytes.Reader): number
|
||||
local s = r:peek(1024)
|
||||
local i = string.find(s, "<%w*:?playlist[%s>]")
|
||||
if i and string.find(s, NS, 1, true) then
|
||||
return 0.95
|
||||
end
|
||||
return 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
-- decode(r, opts?) -> Types.Playlist | nil, Err (malformed XML or a root that is not <playlist> is an error; odd
|
||||
-- tracks become warnings)
|
||||
function Xspf.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Playlist?, Err.Err?)
|
||||
local n = r.limit - r.pos
|
||||
if n > (opts and opts.maxBytes or 2 ^ 26) then
|
||||
return nil, Err.new(Err.LIMIT, "playlist over the size limit")
|
||||
end
|
||||
local doc, err = Xml.decode(r:string(n))
|
||||
if not doc then
|
||||
return nil, err
|
||||
end
|
||||
local root = (doc :: any).root
|
||||
if not root or Xml.localName(root.name) ~= "playlist" then
|
||||
return nil, Err.new(Err.CORRUPT, "the root element is not <playlist>")
|
||||
end
|
||||
local warnings: { string } = {}
|
||||
local base, baseScheme = Url.base(opts and opts.baseUrl, warnings)
|
||||
local function withXmlBase(node: any, b: string?, s: string?): (string?, string?)
|
||||
local xb = node.attrs and node.attrs["xml:base"]
|
||||
if type(xb) ~= "string" or xb == "" then
|
||||
return b, s
|
||||
end
|
||||
local l = Url.locate(xb, b, s)
|
||||
if Url.scheme(l.url) then
|
||||
return l.url, Url.scheme(l.url)
|
||||
end
|
||||
return b, s
|
||||
end
|
||||
local pbase, pscheme = withXmlBase(root, base, baseScheme)
|
||||
local pl: any = {
|
||||
kind = "playlist",
|
||||
format = "xspf",
|
||||
entries = {},
|
||||
warnings = warnings,
|
||||
title = field(root, "title"),
|
||||
meta = { source = { format = "xspf", version = root.attrs and root.attrs.version } },
|
||||
}
|
||||
for _, k in PLAYLIST_FIELDS do
|
||||
if k ~= "title" then
|
||||
pl.meta[k] = field(root, k)
|
||||
end
|
||||
end
|
||||
local nLocal = 0
|
||||
for _, list in elements(root, "trackList") do
|
||||
for i, track in elements(list, "track") do
|
||||
local tbase, tscheme = withXmlBase(track, pbase, pscheme)
|
||||
local locs: { string } = {}
|
||||
for _, l in elements(track, "location") do
|
||||
local s = trim(Xml.text(l))
|
||||
if s ~= "" then
|
||||
table.insert(locs, s)
|
||||
end
|
||||
end
|
||||
if #locs == 0 then
|
||||
table.insert(warnings, string.format("track %d: no location", i))
|
||||
else
|
||||
local e: any = Url.locate(locs[1], tbase, tscheme)
|
||||
for _, k in TRACK_FIELDS do
|
||||
e[k] = field(track, k)
|
||||
end
|
||||
local d = tonumber(field(track, "duration"))
|
||||
e.duration = if d and d >= 0 and d == d and d ~= math.huge then d / 1000 else nil
|
||||
e.trackNum = tonumber(field(track, "trackNum"))
|
||||
if #locs > 1 then
|
||||
local all = {}
|
||||
for _, l in locs do
|
||||
table.insert(all, Url.locate(l, tbase, tscheme).url)
|
||||
end
|
||||
e.locations = all
|
||||
end
|
||||
if e.reason == "local path" then
|
||||
nLocal += 1
|
||||
elseif e.reason then
|
||||
table.insert(warnings, string.format("track %d: %s: %s", i, e.reason, e.url))
|
||||
end
|
||||
table.insert(pl.entries, e)
|
||||
end
|
||||
end
|
||||
end
|
||||
if nLocal > 0 then
|
||||
table.insert(warnings, string.format("%d local path%s (not playable)", nLocal, if nLocal == 1 then "" else "s"))
|
||||
end
|
||||
return pl, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
-- encode(playlist, opts?) -> buffer | nil, Err: XSPF version 1. playlist: a Types.Playlist (any format's) or a list
|
||||
-- of entries ({ url, title?, duration?, creator?, album?, ... }). opts.indent (default 2) pretty-prints.
|
||||
function Xspf.encode(value: any, opts: { indent: number?, title: string? }?): (buffer?, Err.Err?)
|
||||
if type(value) ~= "table" then
|
||||
return nil, Err.new(Err.ARG, "encode: needs a Playlist or a list of entries")
|
||||
end
|
||||
local entries = if type(value.entries) == "table" then value.entries else value
|
||||
local root = Xml.element("playlist", { version = "1", xmlns = NS })
|
||||
local function add(parent: any, name: string, v: any)
|
||||
if type(v) == "string" and v ~= "" then
|
||||
Xml.append(parent, Xml.element(name, nil, { v }))
|
||||
elseif type(v) == "number" and v == v and v ~= math.huge and v ~= -math.huge then
|
||||
Xml.append(parent, Xml.element(name, nil, { tostring(math.floor(v + 0.5)) }))
|
||||
end
|
||||
end
|
||||
local title = if opts and opts.title then opts.title else value.title
|
||||
add(root, "title", title)
|
||||
local meta = if type(value.meta) == "table" then value.meta else {}
|
||||
for _, k in PLAYLIST_FIELDS do
|
||||
if k ~= "title" then
|
||||
add(root, k, meta[k])
|
||||
end
|
||||
end
|
||||
local list = Xml.append(root, Xml.element("trackList"))
|
||||
for _, e in entries do
|
||||
if type(e) == "table" and type(e.url) == "string" then
|
||||
local tr = Xml.append(list, Xml.element("track"))
|
||||
add(tr, "location", e.url)
|
||||
if type(e.locations) == "table" then
|
||||
for i = 2, #e.locations do
|
||||
add(tr, "location", e.locations[i])
|
||||
end
|
||||
end
|
||||
for _, k in TRACK_FIELDS do
|
||||
add(tr, k, e[k])
|
||||
end
|
||||
local d = tonumber(e.duration)
|
||||
if d and d >= 0 then
|
||||
add(tr, "duration", d * 1000)
|
||||
end
|
||||
add(tr, "trackNum", tonumber(e.trackNum))
|
||||
end
|
||||
end
|
||||
local s = Xml.encode(Xml.document(root), { indent = if opts and opts.indent ~= nil then opts.indent else 2 })
|
||||
if type(s) ~= "string" then
|
||||
return nil, Err.new(Err.ARG, "encode: the XML serializer failed")
|
||||
end
|
||||
return buffer.fromstring(s), nil
|
||||
end
|
||||
|
||||
return Xspf
|
||||
Reference in new issue
Block a user