Files
rosetta/src/Formats/playlist/m3u/init.luau
T
2026-10-31 08:55:44 -05:00

370 lines
13 KiB
Luau

--!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