absorb: playlist/m3u (M3U/M3U8 + HLS) and playlist/pls from playlist-luau 3fc7fd3, + a PLS writer; shared codecs/Url (RFC 3986, locate) and codecs/Text (BOM, CP1252, lines); tests vs urllib.parse.urljoin, Python cp1252, Python-written playlists

Two shared codecs added outside the assigned folders (a format never requires another format): codecs/Url and codecs/Text, used by the three playlist formats.
This commit is contained in:
4DBug committed 2026-10-31 08:55:44 -05:00
1 parent 17778cff1b
commit e3fba1c2ae
11 files changed
+1504

No files matched your search

+24
View File
@@ -98,6 +98,30 @@ local list: { Entry } = {
return require("@formats/archive/zip")
end,
},
{
name = "m3u",
category = "playlist",
path = "playlist/m3u",
extensions = { "m3u", "m3u8" },
mime = { "audio/x-mpegurl", "audio/mpegurl", "application/vnd.apple.mpegurl", "application/x-mpegurl" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Url", "codecs/Text" },
caps = { decode = true, encode = true, hls = true },
load = function()
return require("@formats/playlist/m3u")
end,
},
{
name = "pls",
category = "playlist",
path = "playlist/pls",
extensions = { "pls" },
mime = { "audio/x-scpls", "audio/scpls" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Url", "codecs/Text" },
caps = { decode = true, encode = true },
load = function()
return require("@formats/playlist/pls")
end,
},
}
return list
+53
View File
@@ -0,0 +1,53 @@
--!strict
--!optimize 2
-- codecs/Text: text decoding helpers for the text formats: a UTF-8 BOM is stripped, text that is not valid UTF-8 is
-- read as Windows-1252 (classic .m3u / .pls / .ini / .srt files), lines split on CRLF / CR / LF, trim. Absorbed from
-- playlist-luau 3fc7fd3 (same author, no third-party code). Never throws.
local Text = {}
-- CP1252 bytes 0x80..0x9F (undefined ones map to U+FFFD)
Text.CP1252 = {
[0x80] = 0x20AC, [0x82] = 0x201A, [0x83] = 0x0192, [0x84] = 0x201E, [0x85] = 0x2026, [0x86] = 0x2020,
[0x87] = 0x2021, [0x88] = 0x02C6, [0x89] = 0x2030, [0x8A] = 0x0160, [0x8B] = 0x2039, [0x8C] = 0x0152,
[0x8E] = 0x017D, [0x91] = 0x2018, [0x92] = 0x2019, [0x93] = 0x201C, [0x94] = 0x201D, [0x95] = 0x2022,
[0x96] = 0x2013, [0x97] = 0x2014, [0x98] = 0x02DC, [0x99] = 0x2122, [0x9A] = 0x0161, [0x9B] = 0x203A,
[0x9C] = 0x0153, [0x9E] = 0x017E, [0x9F] = 0x0178,
}
function Text.trim(s: string): string
return (string.match(s, "^%s*(.-)%s*$") :: string)
end
-- toUtf8(text, warnings?) -> text as UTF-8: strips a BOM; text that is not valid UTF-8 is read as Windows-1252
function Text.toUtf8(text: string, warnings: { string }?): string
if string.sub(text, 1, 3) == "\239\187\191" then
text = string.sub(text, 4)
end
if utf8.len(text) then
return text
end
if warnings then
table.insert(warnings, "text is not UTF-8: read as Windows-1252")
end
local out = table.create(#text)
for i = 1, #text do
local b = string.byte(text, i)
if b < 0x80 then
out[i] = string.char(b)
else
out[i] = utf8.char(if b < 0xA0 then Text.CP1252[b] or 0xFFFD else b)
end
end
return table.concat(out)
end
function Text.lines(text: string): { string }
text = string.gsub(text, "\r\n?", "\n")
local out = {}
for line in string.gmatch(text .. "\n", "([^\n]*)\n") do
table.insert(out, line)
end
return out
end
return Text
+216
View File
@@ -0,0 +1,216 @@
--!strict
--!optimize 2
-- codecs/Url: RFC 3986 reference resolution (section 5.2), the classification of a playlist / manifest location (URL,
-- Windows / UNC / POSIX local path, relative reference) and percent-encoding of bytes that may not appear in a URI
-- (raw spaces and UTF-8 in playlists). Shared by the playlist formats (m3u / HLS, pls, xspf); later DASH / glTF URIs.
-- Absorbed from playlist-luau 3fc7fd3 (same author, no third-party code): Url.luau, plus locate / base from its
-- init.luau. Never throws.
local Url = {}
export type Location = { url: string, playable: boolean, reason: string?, [string]: any }
export type Parts = {
scheme: string?,
authority: string?,
path: string,
query: string?,
fragment: string?,
}
-- Splits a URI reference into its five components (RFC 3986 appendix B).
function Url.split(ref: string): Parts
local scheme, rest = string.match(ref, "^([%a][%w+%.%-]*):(.*)$")
if not scheme then
rest = ref
end
local s = rest :: string
local fragment, query, authority
local i = string.find(s, "#", 1, true)
if i then
fragment = string.sub(s, i + 1)
s = string.sub(s, 1, i - 1)
end
i = string.find(s, "?", 1, true)
if i then
query = string.sub(s, i + 1)
s = string.sub(s, 1, i - 1)
end
if string.sub(s, 1, 2) == "//" then
local j = string.find(s, "/", 3, true)
if j then
authority = string.sub(s, 3, j - 1)
s = string.sub(s, j)
else
authority = string.sub(s, 3)
s = ""
end
end
return { scheme = scheme, authority = authority, path = s, query = query, fragment = fragment }
end
-- Recomposes components (RFC 3986 section 5.3).
function Url.join(p: Parts): string
local out = {}
if p.scheme then
table.insert(out, p.scheme .. ":")
end
if p.authority then
table.insert(out, "//" .. p.authority)
end
table.insert(out, p.path)
if p.query then
table.insert(out, "?" .. p.query)
end
if p.fragment then
table.insert(out, "#" .. p.fragment)
end
return table.concat(out)
end
-- RFC 3986 section 5.2.4
function Url.removeDotSegments(path: string): string
local input = path
local output = {}
while input ~= "" do
if string.sub(input, 1, 3) == "../" then
input = string.sub(input, 4)
elseif string.sub(input, 1, 2) == "./" then
input = string.sub(input, 3)
elseif string.sub(input, 1, 3) == "/./" then
input = string.sub(input, 3)
elseif input == "/." then
input = "/"
elseif string.sub(input, 1, 4) == "/../" then
input = string.sub(input, 4)
table.remove(output)
elseif input == "/.." then
input = "/"
table.remove(output)
elseif input == "." or input == ".." then
input = ""
else
-- move the first segment (with its leading "/", up to the next "/") to the output
local j = string.find(input, "/", 2, true)
local seg = if j then string.sub(input, 1, j - 1) else input
table.insert(output, seg)
input = string.sub(input, #seg + 1)
end
end
return table.concat(output)
end
-- Resolves a reference against an absolute base URI (RFC 3986 section 5.2.2, strict).
function Url.resolve(ref: string, base: string): string
local r, b = Url.split(ref), Url.split(base)
local t: Parts = { path = "" }
if r.scheme then
t.scheme, t.authority, t.path, t.query = r.scheme, r.authority, Url.removeDotSegments(r.path), r.query
else
if r.authority then
t.authority, t.path, t.query = r.authority, Url.removeDotSegments(r.path), r.query
else
if r.path == "" then
t.path = b.path
t.query = if r.query then r.query else b.query
else
if string.sub(r.path, 1, 1) == "/" then
t.path = Url.removeDotSegments(r.path)
else
-- merge (5.2.3)
local merged
if b.authority and b.path == "" then
merged = "/" .. r.path
else
local k = string.match(b.path, "^.*()/")
merged = (if k then string.sub(b.path, 1, k) else "") .. r.path
end
t.path = Url.removeDotSegments(merged)
end
t.query = r.query
end
t.authority = b.authority
end
t.scheme = b.scheme
end
t.fragment = r.fragment
return Url.join(t)
end
-- Percent-encodes the bytes that may not appear in a URI (controls, space, non-ASCII, "<>\"^`{|}" and "\\"),
-- leaving existing %XX escapes and the reserved delimiters alone.
function Url.encodeUnsafe(s: string): string
return (string.gsub(s, "[%z\1-\32\127-\255<>\"%^`{|}\\]", function(c: string): string
return string.format("%%%02X", string.byte(c))
end))
end
-- Is a location a local Windows path ("C:\x", "C:/x", "\\server\share", "\x")?
function Url.isWindowsPath(s: string): boolean
return string.match(s, "^%a:[\\/]") ~= nil
or string.match(s, "^%a:$") ~= nil
or string.sub(s, 1, 2) == "\\\\"
or string.sub(s, 1, 1) == "\\"
end
-- The scheme of an absolute URI (lower case), or nil. Windows drive letters are not schemes.
function Url.scheme(s: string): string?
if Url.isWindowsPath(s) then
return nil
end
local scheme = string.match(s, "^([%a][%w+%.%-]*):")
return if scheme then string.lower(scheme) else nil
end
-- locate(raw, base?, baseScheme?) -> { url, playable, reason? }: an entry location resolved against the playlist's
-- base (from Url.base). Windows paths stay as they are and are local; relative paths without a base, file: URLs and
-- schemes other than http(s) are not playable (reason says why).
function Url.locate(raw: string, base: string?, baseScheme: string?): Location
local loc = (string.match(raw, "^%s*(.-)%s*$") :: string)
if Url.isWindowsPath(loc) then
return { url = loc, playable = false, reason = "local path" }
end
local scheme = Url.scheme(loc)
local url = loc
if not scheme and baseScheme == "windows" and base then
-- a playlist on a Windows disk: relative entries are paths next to it
local dir = string.match(base, "^(.*[\\/])") or ""
return { url = dir .. loc, playable = false, reason = "local path" }
end
if scheme then
if scheme == "http" or scheme == "https" then
url = Url.encodeUnsafe(Url.resolve(loc, loc))
end
elseif base and baseScheme then
-- a relative reference: Windows separators become URL ones
url = Url.resolve(Url.encodeUnsafe((string.gsub(loc, "\\", "/"))), base)
scheme = baseScheme
else
return { url = loc, playable = false, reason = "relative path without a base URL" }
end
if scheme == "http" or scheme == "https" then
return { url = url, playable = true }
elseif scheme == "file" then
return { url = url, playable = false, reason = "local path" }
end
return { url = url, playable = false, reason = "scheme " .. tostring(scheme) }
end
-- base(baseUrl?, warnings?) -> base, baseScheme: the base for Url.locate from the playlist's own URL or path ("windows"
-- for a Windows path); a non-absolute base is ignored (with a warning)
function Url.base(baseUrl: string?, warnings: { string }?): (string?, string?)
if type(baseUrl) ~= "string" or baseUrl == "" then
return nil, nil
end
local s = Url.scheme(baseUrl)
if s and Url.split(baseUrl).authority ~= nil or s == "file" then
return Url.encodeUnsafe(baseUrl), s
elseif Url.isWindowsPath(baseUrl) then
return baseUrl, "windows"
end
if warnings then
table.insert(warnings, "base URL is not absolute: " .. baseUrl)
end
return nil, nil
end
return Url
+369
View File
@@ -0,0 +1,369 @@
--!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/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("@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 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/Url", "codecs/Text" },
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 = r:peek(512)
if string.sub(s, 1, 3) == "\239\187\191" then
s = string.sub(s, 4)
end
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
+237
View File
@@ -0,0 +1,237 @@
--!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, titles, lengths = {}, {}, {}
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