238 lines
8.6 KiB
Luau
238 lines
8.6 KiB
Luau
--!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/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("@formats/core/Err")
|
|
local Bytes = require("@formats/core/Bytes")
|
|
local Types = require("@formats/Types")
|
|
local Url = require("@formats/codecs/Url")
|
|
local Text = require("@formats/codecs/Text")
|
|
|
|
-- ------------------------------------------------------------------------------------------------ contract
|
|
local Pls = {
|
|
name = "pls",
|
|
category = "playlist",
|
|
extensions = { "pls" },
|
|
mime = { "audio/x-scpls", "audio/scpls" },
|
|
deps = { "core/Err", "core/Bytes", "Types", "codecs/Url", "codecs/Text" },
|
|
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
|
|
|
|
-- 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 Pls.sniff(r: Bytes.Reader): number
|
|
local s = r:peek(64)
|
|
if string.sub(s, 1, 3) == "\239\187\191" then
|
|
s = string.sub(s, 4)
|
|
end
|
|
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
|