From e3fba1c2ae528cbc26ae75f7e5ac70ea05f6be0b Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 08:55:44 -0500 Subject: [PATCH] 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. --- docs/FORMATS.md | 4 + licenses/NOTICE.md | 1 + src/Formats/Registry.luau | 24 ++ src/Formats/codecs/Text/init.luau | 53 +++++ src/Formats/codecs/Url/init.luau | 216 +++++++++++++++++ src/Formats/playlist/m3u/init.luau | 369 +++++++++++++++++++++++++++++ src/Formats/playlist/pls/init.luau | 237 ++++++++++++++++++ tests/codecs/url.luau | 108 +++++++++ tests/playlist/m3u.luau | 357 ++++++++++++++++++++++++++++ tests/playlist/pls.luau | 69 ++++++ tools/fixtures/playlist.py | 66 ++++++ 11 files changed, 1504 insertions(+) create mode 100644 src/Formats/codecs/Text/init.luau create mode 100644 src/Formats/codecs/Url/init.luau create mode 100644 src/Formats/playlist/m3u/init.luau create mode 100644 src/Formats/playlist/pls/init.luau create mode 100644 tests/codecs/url.luau create mode 100644 tests/playlist/m3u.luau create mode 100644 tests/playlist/pls.luau create mode 100644 tools/fixtures/playlist.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 37fde15..6d82277 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -12,7 +12,11 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | audio | opus | .opus | yes | - | streaming: true, seek: true, lossy: true, channels: 255, rates: 48000 | `tests/audio/opus.luau` | | audio | wav | .wav .wave .rf64 .bw64 | yes | yes | streaming: true, depths: 8, 16, 24, 32, float: true, rf64: true | `tests/audio/wav.luau` | | archive | zip | .zip .wsz | yes | yes | methods: "store", "deflate", zip64: true | `tests/archive/zip.luau` | +| playlist | m3u | .m3u .m3u8 | yes | yes | hls: true | `tests/playlist/m3u.luau` | +| playlist | pls | .pls | yes | yes | | `tests/playlist/pls.luau` | Codecs (layer 1, shared by formats; not loadable on their own): - codecs/Deflate: DEFLATE (RFC 1951) decoder and compressor, with the zlib (RFC 1950) and gzip (RFC 1952) wrappers. +- codecs/Text: text decoding helpers for the text formats: a UTF-8 BOM is stripped, text that is not valid UTF-8 is +- codecs/Url: RFC 3986 reference resolution (section 5.2), the classification of a playlist / manifest location (URL, diff --git a/licenses/NOTICE.md b/licenses/NOTICE.md index cc2e25f..28d7172 100644 --- a/licenses/NOTICE.md +++ b/licenses/NOTICE.md @@ -13,6 +13,7 @@ | `src/Formats/image/bmp/` | bmp-luau b86aed6 (same author), written from the Microsoft BMP documentation | no licence chosen yet; no third-party code | | `tests/fixtures/bmpsuite/` | BMP Suite 2.8 by Jason Summers (generated images) | public domain: [bmpsuite-NOTICE.txt](bmpsuite-NOTICE.txt) | | `src/Formats/containers/Zip/` (the reader), `src/Formats/archive/zip/` | zip-luau 121d4b0 (same author), written from PKWARE's APPNOTE.TXT 6.3 | no licence chosen yet; no third-party code | +| `src/Formats/playlist/` (m3u, pls), `src/Formats/codecs/Url/`, `src/Formats/codecs/Text/` | playlist-luau 3fc7fd3 (same author), written from RFC 3986 / RFC 8216 | no licence chosen yet; no third-party code | | `tests/fixtures/pngsuite/` | PngSuite by Willem van Schaik | [PngSuite-LICENSE.txt](PngSuite-LICENSE.txt) | Ports of third-party code (minimp3, stb_vorbis, libopus, ...) add a row here and their upstream licence text in this diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index ba721ff..8adbe99 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -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 diff --git a/src/Formats/codecs/Text/init.luau b/src/Formats/codecs/Text/init.luau new file mode 100644 index 0000000..11d9da4 --- /dev/null +++ b/src/Formats/codecs/Text/init.luau @@ -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 diff --git a/src/Formats/codecs/Url/init.luau b/src/Formats/codecs/Url/init.luau new file mode 100644 index 0000000..026ecb5 --- /dev/null +++ b/src/Formats/codecs/Url/init.luau @@ -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 diff --git a/src/Formats/playlist/m3u/init.luau b/src/Formats/playlist/m3u/init.luau new file mode 100644 index 0000000..d023619 --- /dev/null +++ b/src/Formats/playlist/m3u/init.luau @@ -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:[ attr="v" ...], +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 diff --git a/src/Formats/playlist/pls/init.luau b/src/Formats/playlist/pls/init.luau new file mode 100644 index 0000000..ea24213 --- /dev/null +++ b/src/Formats/playlist/pls/init.luau @@ -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 diff --git a/tests/codecs/url.luau b/tests/codecs/url.luau new file mode 100644 index 0000000..82075b3 --- /dev/null +++ b/tests/codecs/url.luau @@ -0,0 +1,108 @@ +-- codecs/Url + codecs/Text tests: every example of RFC 3986 section 5.4 (normal and abnormal), dot-segment removal, +-- splitting, encoding and the location helpers (ported from playlist-luau tests/url.luau); random references against +-- Python's urllib.parse.urljoin; Url.locate / Url.base; Windows-1252 decoding against Python's cp1252 codec; lines, +-- BOM, trim; the fuzz pass. Fixtures: tools/fixtures/playlist.py. +local T = require("@tests/T") +local Url = require("@formats/codecs/Url") +local Text = require("@formats/codecs/Text") +local Ref = require("@tests/gen/playlist_url") +local Cp = require("@tests/gen/playlist_cp1252") + +local t = T.suite("url") +local function eq(got: any, want: any, label: string) + t:eq(got, want, label) +end + +local BASE = "http://a/b/c/d;p?q" +local cases = { + -- 5.4.1 normal + { "g:h", "g:h" }, { "g", "http://a/b/c/g" }, { "./g", "http://a/b/c/g" }, { "g/", "http://a/b/c/g/" }, + { "/g", "http://a/g" }, { "//g", "http://g" }, { "?y", "http://a/b/c/d;p?y" }, { "g?y", "http://a/b/c/g?y" }, + { "#s", "http://a/b/c/d;p?q#s" }, { "g#s", "http://a/b/c/g#s" }, { "g?y#s", "http://a/b/c/g?y#s" }, + { ";x", "http://a/b/c/;x" }, { "g;x", "http://a/b/c/g;x" }, { "g;x?y#s", "http://a/b/c/g;x?y#s" }, + { "", "http://a/b/c/d;p?q" }, { ".", "http://a/b/c/" }, { "./", "http://a/b/c/" }, { "..", "http://a/b/" }, + { "../", "http://a/b/" }, { "../g", "http://a/b/g" }, { "../..", "http://a/" }, { "../../", "http://a/" }, + { "../../g", "http://a/g" }, + -- 5.4.2 abnormal + { "../../../g", "http://a/g" }, { "../../../../g", "http://a/g" }, { "/./g", "http://a/g" }, + { "/../g", "http://a/g" }, { "g.", "http://a/b/c/g." }, { ".g", "http://a/b/c/.g" }, { "g..", "http://a/b/c/g.." }, + { "..g", "http://a/b/c/..g" }, { "./../g", "http://a/b/g" }, { "./g/.", "http://a/b/c/g/" }, + { "g/./h", "http://a/b/c/g/h" }, { "g/../h", "http://a/b/c/h" }, { "g;x=1/./y", "http://a/b/c/g;x=1/y" }, + { "g;x=1/../y", "http://a/b/c/y" }, { "g?y/./x", "http://a/b/c/g?y/./x" }, { "g?y/../x", "http://a/b/c/g?y/../x" }, + { "g#s/./x", "http://a/b/c/g#s/./x" }, { "g#s/../x", "http://a/b/c/g#s/../x" }, { "http:g", "http:g" }, +} +for _, c in cases do + eq(Url.resolve(c[1], BASE), c[2], "resolve " .. c[1]) +end +-- base with an empty path +eq(Url.resolve("g", "http://a"), "http://a/g", "empty base path") +eq(Url.resolve("g", "http://a?x"), "http://a/g", "empty base path with query") + +eq(Url.removeDotSegments("/a/b/c/./../../g"), "/a/g", "remove_dot_segments 1") +eq(Url.removeDotSegments("mid/content=5/../6"), "mid/6", "remove_dot_segments 2") + +local p = Url.split("https://user@host:8080/p/a.mp3?x=1&y#frag") +eq(p.scheme, "https", "split scheme") +eq(p.authority, "user@host:8080", "split authority") +eq(p.path, "/p/a.mp3", "split path") +eq(p.query, "x=1&y", "split query") +eq(p.fragment, "frag", "split fragment") +eq(Url.join(p), "https://user@host:8080/p/a.mp3?x=1&y#frag", "join") +local q = Url.split("a/b") +eq(q.scheme, nil, "relative has no scheme") +eq(q.authority, nil, "relative has no authority") + +eq(Url.encodeUnsafe("a b/ü%20?x=\"1\"#f"), "a%20b/%C3%BC%20?x=%221%22#f", "encodeUnsafe") +eq(Url.isWindowsPath("C:\\Music\\a.mp3"), true, "windows drive") +eq(Url.isWindowsPath("d:/x.mp3"), true, "windows drive with slash") +eq(Url.isWindowsPath("\\\\server\\share\\a.mp3"), true, "UNC") +eq(Url.isWindowsPath("http://x/a"), false, "http is not windows") +eq(Url.scheme("C:\\a.mp3"), nil, "a drive letter is not a scheme") +eq(Url.scheme("HTTPS://x"), "https", "scheme lower-cased") +eq(Url.scheme("music/a.mp3"), nil, "relative has no scheme") + + +-- Python's urljoin +for _, c in Ref do + eq(Url.resolve(c[1], c[2]), c[3], "urljoin " .. c[1] .. " against " .. c[2]) +end +t:note("%d random references resolve as urllib.parse.urljoin", #Ref) + +-- locate / base +do + local w = {} + local base, scheme = Url.base("https://h/a/list.m3u", w) + t:check(base == "https://h/a/list.m3u" and scheme == "https", "base") + local l = Url.locate(" b c.mp3 ", base, scheme) + t:check(l.url == "https://h/a/b%20c.mp3" and l.playable, "locate relative") + t:check(Url.locate("C:\\x.mp3", base, scheme).reason == "local path", "locate windows") + t:check(Url.locate("ftp://x/y", base, scheme).reason == "scheme ftp", "locate ftp") + local nb, ns = Url.base("lists/x.m3u", w) + t:check(nb == nil and ns == nil and #w == 1, "a relative base is ignored with a warning") + t:check(select(2, Url.base("C:\\Music\\l.m3u")) == "windows", "windows base") +end + +-- Text +do + for _, c in Cp do + eq(Text.toUtf8("x" .. string.char(c[1]) .. "y"), "x" .. c[2] .. "y", string.format("cp1252 0x%02x", c[1])) + end + local w = {} + Text.toUtf8("\150", w) + t:check(#w == 1, "cp1252 warning") + eq(Text.toUtf8("\239\187\191abc"), "abc", "BOM stripped") + eq(Text.toUtf8("h\u{e9}"), "h\u{e9}", "UTF-8 kept") + local ls = Text.lines("a\r\nb\rc\nd") + t:check(#ls == 4 and ls[1] == "a" and ls[2] == "b" and ls[3] == "c" and ls[4] == "d", "lines") + eq(Text.trim(" x y \t"), "x y", "trim") +end + +t:fuzz("resolve + locate", function(b: buffer) + local s = buffer.tostring(b) + Url.resolve(s, "http://a/b/c/d;p?q") + Url.resolve("g/../h", s) + Url.locate(s, "http://h/", "http") + return Text.lines(Text.toUtf8(s)) +end, { "http://a/b/../c?x#y", "C:\\a\\b.mp3", "\239\187\191#EXTM3U\r\n" }, { mutations = 30 }) + +t:done() diff --git a/tests/playlist/m3u.luau b/tests/playlist/m3u.luau new file mode 100644 index 0000000..3229e53 --- /dev/null +++ b/tests/playlist/m3u.luau @@ -0,0 +1,357 @@ +-- playlist/m3u tests (+ the PLS parts of the ported suite): M3U / M3U8 (EXTINF, comments, BOM, CRLF / CR, +-- Windows-1252, relative / absolute / local locations), PLS, HLS master and media playlists, detection, serialize round +-- trips, bad input; Python-written playlists (tools/fixtures/playlist.py) decode to their entries, and our M3U8 output +-- decodes back; the api; the fuzz pass. Ported from playlist-luau tests/playlist.luau. Fixtures: +-- tools/fixtures/playlist.py. +local T = require("@tests/T") +local M3u = require("@formats/playlist/m3u") +local Pls = require("@formats/playlist/pls") +local Bytes = require("@formats/core/Bytes") +local F = require("@formats") +local Cases = require("@tests/gen/playlist_cases") + +local t = T.suite("m3u") +local function eq(got: any, want: any, label: string) + t:eq(got, want, label) +end +local function has(list: { string }, pattern: string): boolean + for _, w in list do + if string.find(w, pattern) then + return true + end + end + return false +end + +-- the playlist-luau API on top of the two formats (the ported tests below use it) +local Playlist = {} +function Playlist.detect(text: string): string + if type(text) ~= "string" then + return "m3u" + end + local r = Bytes.reader(buffer.fromstring(text)) + if Pls.sniff(r) > 0 then + return "pls" + end + return if string.find(text, "#EXT%-X%-") then "hls" else "m3u" +end +function Playlist.parse(text: any, baseUrl: string?): any + if type(text) ~= "string" then + return { kind = "m3u", entries = {}, warnings = { "expected a string" } } + end + local kind = Playlist.detect(text) + local mod = if kind == "pls" then Pls else M3u + local pl = mod.decode(Bytes.reader(buffer.fromstring(text)), { baseUrl = baseUrl }) :: any + pl.kind = pl.format -- the old field + return pl +end +function Playlist.serialize(entries: any, opts: any?): string + return buffer.tostring(M3u.encode(entries, opts) :: buffer) +end + +-- M3U8 with EXTINF, comments, blank lines, BOM, CRLF +do + local text = "\239\187\191#EXTM3U\r\n#PLAYLIST:My Mix\r\n\r\n# a comment\r\n#EXTINF:123,Daft Punk - One More Time\r\n" + .. "music/one more time.mp3\r\n#EXTINF:-1,Radio\r\nhttp://radio.example/stream\r\n" + .. "#EXTINF:61.5 tvg-id=\"x\" group-title=\"a,b\",Grouped, with comma\r\n../other/b.mp3\r\n" + .. "#EXTGRP:ignored\r\n/abs/c.mp3\r\n https://cdn.example/d.mp3?x=1 \r\n" + local pl = Playlist.parse(text, "https://host.example/lists/m.m3u8") + eq(pl.kind, "m3u", "kind") + eq(pl.title, "My Mix", "#PLAYLIST") + eq(#pl.entries, 5, "entry count") + local e = pl.entries + eq(e[1].url, "https://host.example/lists/music/one%20more%20time.mp3", "relative resolved + encoded") + eq(e[1].title, "Daft Punk - One More Time", "EXTINF title") + eq(e[1].duration, 123, "EXTINF duration") + eq(e[1].playable, true, "https playable") + eq(e[2].url, "http://radio.example/stream", "absolute kept") + eq(e[2].duration, nil, "duration -1 = unknown") + eq(e[2].title, "Radio", "title 2") + eq(e[3].url, "https://host.example/other/b.mp3", "dot-dot resolved") + eq(e[3].duration, 61.5, "fractional duration with attributes") + eq(e[3].title, "Grouped, with comma", "title after the attributes keeps its commas") + eq(e[4].url, "https://host.example/abs/c.mp3", "absolute path") + eq(e[4].title, nil, "EXTINF does not leak to the next entry") + eq(e[5].url, "https://cdn.example/d.mp3?x=1", "trimmed absolute") + eq(#pl.warnings, 0, "no warnings") +end + +-- plain M3U (no header), CR line endings, Windows paths, relative without base, other schemes +do + local text = "C:\\Music\\Song A.mp3\rD:/Other/b.mp3\r\\\\server\\share\\c.mp3\rsongs\\d.mp3\rftp://x/e.mp3\rfile:///home/u/f.mp3" + local pl = Playlist.parse(text) + eq(#pl.entries, 6, "plain count") + eq(pl.entries[1].url, "C:\\Music\\Song A.mp3", "windows path kept as is") + eq(pl.entries[1].playable, false, "windows path unplayable") + eq(pl.entries[1].reason, "local path", "windows path reason") + eq(pl.entries[2].reason, "local path", "drive with slash") + eq(pl.entries[3].reason, "local path", "UNC") + eq(pl.entries[4].url, "songs\\d.mp3", "relative without base kept") + eq(pl.entries[4].reason, "relative path without a base URL", "relative without base reason") + eq(pl.entries[5].reason, "scheme ftp", "ftp unplayable") + eq(pl.entries[6].reason, "local path", "file: is local") + eq(has(pl.warnings, "relative path without a base URL"), true, "warning for relative") + eq(has(pl.warnings, "4 local paths"), true, "local paths summary") + -- with a URL base, Windows separators in relative entries become slashes; drive paths stay local + local pl2 = Playlist.parse(text, "http://h/x/list.m3u") + eq(pl2.entries[4].url, "http://h/x/songs/d.mp3", "backslash relative resolved") + eq(pl2.entries[4].playable, true, "backslash relative playable") + eq(pl2.entries[1].url, "C:\\Music\\Song A.mp3", "windows path untouched with a base") + -- with a Windows base, relative entries are paths next to the playlist + local pl3 = Playlist.parse("a.mp3\nsub\\b.mp3", "C:\\Music\\list.m3u") + eq(pl3.entries[1].url, "C:\\Music\\a.mp3", "windows base") + eq(pl3.entries[2].url, "C:\\Music\\sub\\b.mp3", "windows base sub") + eq(pl3.entries[1].playable, false, "windows base unplayable") + -- file: base + local pl4 = Playlist.parse("a.mp3", "file:///C:/Music/list.m3u") + eq(pl4.entries[1].url, "file:///C:/Music/a.mp3", "file base") + eq(pl4.entries[1].reason, "local path", "file base local") + -- a relative base is not used + local pl5 = Playlist.parse("a.mp3", "lists/x.m3u") + eq(has(pl5.warnings, "not absolute"), true, "relative base warning") +end + +-- Windows-1252 text (a classic .m3u), and UTF-8 kept +do + local pl = Playlist.parse("#EXTM3U\n#EXTINF:10,Bj\246rk \150 J\243ga\nhttp://x/j.mp3\n") + eq(pl.entries[1].title, "Björk – Jóga", "cp1252 transcoded") + eq(has(pl.warnings, "Windows%-1252"), true, "cp1252 warning") + local pl2 = Playlist.parse("#EXTINF:10,Björk – Jóga\nhttp://x/j.mp3") + eq(pl2.entries[1].title, "Björk – Jóga", "utf-8 kept") + eq(#pl2.warnings, 0, "utf-8 no warning") + local pl3 = Playlist.parse("http://x/Björk.mp3") + eq(pl3.entries[1].url, "http://x/Bj%C3%B6rk.mp3", "utf-8 url encoded") +end + +-- PLS +do + local text = "[playlist]\r\nNumberOfEntries=3\r\nFile2=http://s.example:8000/live\r\nTitle2=(#1) Some Radio\r\nLength2=-1\r\n" + .. "File1=music/a.mp3\r\nTitle1=Artist - Song\r\nLength1=200\r\n; comment\r\nfile10 = http://x/z.mp3\r\nVersion=2\r\n" + local pl = Playlist.parse(text, "http://h/p/list.pls") + eq(pl.kind, "pls", "pls kind") + eq(#pl.entries, 3, "pls count") + eq(pl.entries[1].url, "http://h/p/music/a.mp3", "pls order by index + resolved") + eq(pl.entries[1].title, "Artist - Song", "pls title") + eq(pl.entries[1].duration, 200, "pls length") + eq(pl.entries[2].url, "http://s.example:8000/live", "pls 2") + eq(pl.entries[2].duration, nil, "pls length -1") + eq(pl.entries[3].url, "http://x/z.mp3", "pls key case / spaces / index 10") + eq(pl.entries[3].title, nil, "pls no title") + eq(#pl.warnings, 0, "pls no warnings") + local bad = Playlist.parse("[Playlist]\nNumberOfEntries=2\nFile1=http://a/1.mp3\n") + eq(bad.kind, "pls", "pls case-insensitive header") + eq(has(bad.warnings, "NumberOfEntries=2 but 1"), true, "pls count mismatch warning") +end + +-- HLS master playlist: variants with attributes (quoted commas), EXT-X-MEDIA audio renditions +do + local text = [[#EXTM3U +#EXT-X-VERSION:3 +#EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID="aud",NAME="English",LANGUAGE="en",URI="audio/en.m3u8" +#EXT-X-STREAM-INF:BANDWIDTH=128000,CODECS="mp4a.40.2,avc1.4d401e",RESOLUTION=640x360,AUDIO="aud" +low/index.m3u8 +#EXT-X-STREAM-INF:BANDWIDTH=320000,CODECS="mp4a.40.34" +http://other.example/hi/index.m3u8 +]] + local pl = Playlist.parse(text, "https://cdn.example/show/master.m3u8") + eq(pl.kind, "hls", "hls kind") + assert(pl.hls) + eq(pl.hls.master, true, "master") + eq(#pl.entries, 3, "variants + rendition") + eq(pl.entries[1].url, "https://cdn.example/show/audio/en.m3u8", "rendition url") + eq(pl.entries[1].title, "English", "rendition name") + eq(pl.entries[2].url, "https://cdn.example/show/low/index.m3u8", "variant 1 url") + eq(pl.entries[2].bandwidth, 128000, "variant 1 bandwidth") + eq(pl.entries[2].codecs, "mp4a.40.2,avc1.4d401e", "variant codecs keeps its comma") + eq((pl.entries[2].attributes :: any).RESOLUTION, "640x360", "variant attributes") + eq(pl.entries[3].bandwidth, 320000, "variant 2 bandwidth") + eq(pl.entries[3].url, "http://other.example/hi/index.m3u8", "variant 2 absolute") + eq(#pl.warnings, 0, "master no warnings") +end + +-- HLS media playlist with mp3 segments (VOD) +do + local text = [[#EXTM3U +#EXT-X-VERSION:3 +#EXT-X-TARGETDURATION:10 +#EXT-X-MEDIA-SEQUENCE:7 +#EXTINF:10.0, +seg7.mp3 +#EXTINF:9.5,Part two +seg8.mp3?token=a +#EXT-X-BYTERANGE:1000@0 +#EXTINF:4, +all.mp3 +#EXT-X-BYTERANGE:500 +#EXTINF:2, +all.mp3 +#EXT-X-ENDLIST +]] + local pl = Playlist.parse(text, "https://h/radio/list.m3u8") + assert(pl.hls) + eq(pl.kind, "hls", "media kind") + eq(pl.hls.master, false, "media not master") + eq(pl.hls.targetDuration, 10, "target duration") + eq(pl.hls.mediaSequence, 7, "media sequence") + eq(pl.hls.endList, true, "endlist") + eq(pl.hls.totalDuration, 25.5, "total duration") + eq(pl.hls.segmentFormat, "mp3", "segment format") + eq(#pl.entries, 4, "segments") + eq(pl.entries[1].url, "https://h/radio/seg7.mp3", "segment url") + eq(pl.entries[1].duration, 10, "segment duration") + eq(pl.entries[1].title, nil, "empty title is nil") + eq(pl.entries[2].title, "Part two", "segment title") + eq(pl.entries[2].url, "https://h/radio/seg8.mp3?token=a", "segment query") + eq(pl.entries[2].playable, true, "mp3 segments playable") + eq((pl.entries[3].byteRange :: any).length, 1000, "byterange length") + eq((pl.entries[3].byteRange :: any).offset, 0, "byterange offset") + eq((pl.entries[4].byteRange :: any).offset, 1000, "byterange continues") + eq(#pl.warnings, 0, "mp3 VOD no warnings") +end + +-- HLS media playlists with unsupported segments, live, encrypted, fMP4 +do + local ts = Playlist.parse("#EXTM3U\n#EXT-X-TARGETDURATION:6\n#EXTINF:6,\na.ts\n#EXTINF:6,\nb.ts\n", "http://h/x.m3u8") + assert(ts.hls) + eq(ts.entries[1].playable, false, "ts unplayable") + eq(ts.entries[1].reason, "segment format ts", "ts reason") + eq(ts.hls.segmentFormat, "ts", "ts format") + eq(has(ts.warnings, "HLS segments are %.ts"), true, "ts warning") + eq(has(ts.warnings, "live HLS"), true, "live warning") + local aac = Playlist.parse("#EXTM3U\n#EXT-X-TARGETDURATION:6\n#EXTINF:6,\na.aac\n#EXTINF:6,\nb.mp3\n#EXT-X-ENDLIST\n", "http://h/x.m3u8") + assert(aac.hls) + eq(aac.hls.segmentFormat, "mixed", "mixed format") + eq(has(aac.warnings, "%.aac"), true, "aac warning") + eq(aac.entries[2].playable, true, "mp3 among aac still playable") + local m4s = Playlist.parse("#EXTM3U\n#EXT-X-TARGETDURATION:4\n#EXT-X-MAP:URI=\"init.mp4\"\n#EXTINF:4,\n1.m4s\n#EXT-X-ENDLIST\n", "http://h/x.m3u8") + eq(m4s.entries[1].playable, false, "m4s unplayable") + eq(has(m4s.warnings, "%.m4s") and has(m4s.warnings, "fMP4"), true, "m4s + fmp4 warning") + local enc = Playlist.parse("#EXTM3U\n#EXT-X-TARGETDURATION:4\n#EXT-X-KEY:METHOD=AES-128,URI=\"k\"\n#EXTINF:4,\n1.mp3\n#EXT-X-ENDLIST\n", "http://h/x.m3u8") + assert(enc.hls) + eq(enc.hls.encrypted, true, "encrypted") + eq(enc.entries[1].playable, false, "encrypted unplayable") + eq(has(enc.warnings, "encrypted"), true, "encrypted warning") + local none = Playlist.parse("#EXTM3U\n#EXT-X-TARGETDURATION:4\n#EXT-X-KEY:METHOD=NONE\n#EXTINF:4,\n1.mp3\n#EXT-X-ENDLIST\n", "http://h/x.m3u8") + eq(none.entries[1].playable, true, "METHOD=NONE is clear") +end + +-- detection +do + eq(Playlist.detect("[playlist]\nFile1=a"), "pls", "detect pls") + eq(Playlist.detect("\239\187\191 [PLAYLIST]\r\n"), "pls", "detect pls with BOM / spaces") + eq(Playlist.detect("#EXTM3U\n#EXT-X-STREAM-INF:BANDWIDTH=1\na.m3u8"), "hls", "detect hls master") + eq(Playlist.detect("#EXTM3U\n#EXT-X-TARGETDURATION:5\n"), "hls", "detect hls media") + eq(Playlist.detect("#EXTM3U\n#EXTINF:1,a\na.mp3"), "m3u", "detect m3u") + eq(Playlist.detect("a.mp3"), "m3u", "detect plain") +end + +-- serialize: M3U8, round trip +do + local entries = { + { url = "http://x/a.mp3", title = "A - B", duration = 61.6 }, + { url = "http://x/b.mp3" }, + { url = "http://x/c.mp3", title = "multi\nline" }, + { url = "http://x/d.mp3", duration = 5 }, + { title = "no url" }, + } + local text = Playlist.serialize(entries :: any, { title = "Mix" }) + eq(text, "#EXTM3U\n#PLAYLIST:Mix\n#EXTINF:62,A - B\nhttp://x/a.mp3\nhttp://x/b.mp3\n#EXTINF:-1,multi line\nhttp://x/c.mp3\n" + .. "#EXTINF:5,\nhttp://x/d.mp3\n", "serialize text") + local back = Playlist.parse(text) + eq(#back.entries, 4, "round trip count") + eq(back.title, "Mix", "round trip title") + eq(back.entries[1].title, "A - B", "round trip title 1") + eq(back.entries[1].duration, 62, "round trip duration") + eq(back.entries[2].title, nil, "round trip no title") + eq(back.entries[3].duration, nil, "round trip unknown duration") + eq(Playlist.serialize({}), "#EXTM3U\n", "serialize empty") + -- parse -> serialize -> parse keeps everything of a real playlist + local pl = Playlist.parse("#EXTM3U\n#EXTINF:100,X - Y\nhttp://h/1.mp3\n#EXTINF:-1,Live\nhttp://h/live\n") + local again = Playlist.parse(Playlist.serialize(pl.entries)) + for i, e in pl.entries do + eq(again.entries[i].url, e.url, "rt url " .. i) + eq(again.entries[i].title, e.title, "rt title " .. i) + eq(again.entries[i].duration, e.duration, "rt duration " .. i) + end +end + +-- bad input never throws +do + local inputs: { any } = { "", "\n\n\n", "#EXTM3U", "#EXTINF:abc,\n", "[playlist]\n=\nFile=\nFilex1=y", "#EXT-X-STREAM-INF:\n", + "#EXT-X-STREAM-INF:BANDWIDTH=\"unterminated\n", "#EXT-X-BYTERANGE:x\n#EXT-X-TARGETDURATION:\n", "\255\254\0\0", 42, nil } + for i = 1, 11 do + local ok, pl = pcall(Playlist.parse, inputs[i], "http://h/") + eq(ok, true, "bad input " .. i .. " threw " .. tostring(pl)) + eq(type(pl.entries), "table", "bad input " .. i .. " entries") + end + eq(#Playlist.parse("").entries, 0, "empty text") + eq(has(Playlist.parse(42 :: any).warnings, "expected a string"), true, "non-string warning") + local ok = pcall(Playlist.serialize, { 1, "x", { url = 5 } } :: any) + eq(ok, true, "serialize skips junk") + -- random bytes + local state = 7 + for _ = 1, 300 do + local t = table.create(80) + for k = 1, 80 do + state = (state * 1103515245 + 12345) % 2147483648 + t[k] = string.char(({ 10, 13, 35, 44, 58, 61, 34, 92, 47, 46, 65, 120, 200 })[state % 13 + 1]) + end + local s = "#EXTM3U\n#EXT-X-" .. table.concat(t) + local ok2, err = pcall(Playlist.parse, s, "http://h/a/") + eq(ok2, true, "fuzz threw " .. tostring(err)) + local ok3, err3 = pcall(Playlist.parse, "[playlist]\n" .. table.concat(t), "http://h/a/") + eq(ok3, true, "fuzz pls threw " .. tostring(err3)) + end +end + + +-- Python-written playlists +for _, c in Cases do + local pl = M3u.decode(Bytes.reader(buffer.fromstring(c.m3u))) :: any + eq(#pl.entries, #c.entries, c.name .. ": entries") + for i, e in c.entries do + local g = pl.entries[i] + eq(g.url, e.url, c.name .. ": url " .. i) + eq(g.duration, e.duration, c.name .. ": duration " .. i) + if e.title then + eq(g.title, e.title, c.name .. ": title " .. i) + end + end + local back = M3u.decode(Bytes.reader(M3u.encode(pl, { title = c.title }) :: buffer)) :: any + eq(back.title, c.title, c.name .. ": #PLAYLIST round trip") + for i, e in pl.entries do + eq(back.entries[i].url, e.url, c.name .. ": round trip url " .. i) + eq(back.entries[i].title, e.title, c.name .. ": round trip title " .. i) + end +end +t:note("%d Python-written M3U8 files decode to their entries", #Cases) + +-- the contract and the api +do + eq(M3u.name, "m3u", "name") + eq(M3u.category, "playlist", "category") + local c = Cases[1] + eq(F.detect(c.m3u), "m3u", "F.detect") + local pl = F.playlist.load(c.m3u, { baseUrl = "http://x/" }) + t:check(pl and pl.kind == "playlist" and pl.format == "m3u" and #pl.entries == #c.entries, "F.playlist.load") + local saved = F.save(pl, nil, { format = "m3u8" }) + t:check(saved and string.sub(buffer.tostring(saved), 1, 7) == "#EXTM3U", "F.save m3u8") + local hls = F.playlist.load("#EXTM3U\n#EXT-X-TARGETDURATION:4\n#EXTINF:4,\n1.mp3\n#EXT-X-ENDLIST\n", { baseUrl = "http://h/x.m3u8" }) + t:check(hls and hls.format == "hls" and hls.hls.endList, "F.playlist.load HLS") + t:eq(M3u.sniff(Bytes.reader(buffer.fromstring("\239\187\191 #EXTM3U\n"))), 0.95, "sniff with BOM") + t:eq(M3u.sniff(Bytes.reader(buffer.fromstring("a.mp3\n"))), 0, "plain lists are found by extension") + local _, e = M3u.encode(5 :: any) + t:check(e ~= nil, "encode a number") +end + +local samples = {} +for _, c in Cases do + table.insert(samples, c.m3u) +end +table.insert(samples, "#EXTM3U\n#EXT-X-STREAM-INF:BANDWIDTH=128000,CODECS=\"mp4a.40.2\"\nlo.m3u8\n#EXT-X-MEDIA:TYPE=AUDIO,URI=\"a.m3u8\",NAME=\"x\"\n") +table.insert(samples, "#EXTM3U\n#EXT-X-TARGETDURATION:6\n#EXT-X-BYTERANGE:100@0\n#EXTINF:6,\na.mp3\n#EXT-X-KEY:METHOD=AES-128\n#EXT-X-ENDLIST\n") +t:fuzz("decode", function(b: buffer) + return M3u.decode(Bytes.reader(b), { baseUrl = "http://h/a/" }) +end, samples, { mutations = 20 }) + +t:done() diff --git a/tests/playlist/pls.luau b/tests/playlist/pls.luau new file mode 100644 index 0000000..39ddd5c --- /dev/null +++ b/tests/playlist/pls.luau @@ -0,0 +1,69 @@ +-- playlist/pls tests: Python-written PLS files (tools/fixtures/playlist.py) decode to their entries; keys in any case +-- and order, gaps in the numbering, comments, NumberOfEntries mismatches, Windows-1252, relative locations; the +-- writer round-trips (titles, unknown lengths, line breaks); the api; the fuzz pass. (The playlist-luau PLS cases run +-- in tests/playlist/m3u.luau.) Fixtures: tools/fixtures/playlist.py. +local T = require("@tests/T") +local Pls = require("@formats/playlist/pls") +local Bytes = require("@formats/core/Bytes") +local F = require("@formats") +local Cases = require("@tests/gen/playlist_cases") + +local t = T.suite("pls") +local function decode(s: string, base: string?): any + return Pls.decode(Bytes.reader(buffer.fromstring(s)), { baseUrl = base }) +end + +for _, c in Cases do + local pl = decode(c.pls) + t:eq(#pl.entries, #c.entries, c.name .. ": entries") + t:eq(#pl.warnings, 0, c.name .. ": no warnings") + for i, e in c.entries do + local g = pl.entries[i] + t:eq(g.url, e.url, c.name .. ": url " .. i) + t:eq(g.title, e.title, c.name .. ": title " .. i) + t:eq(g.duration, e.duration, c.name .. ": duration " .. i) + t:check(g.playable, c.name .. ": playable " .. i) + end + local back = decode(buffer.tostring(Pls.encode(pl) :: buffer)) + t:eq(#back.entries, #pl.entries, c.name .. ": round trip count") + for i, e in pl.entries do + local g = back.entries[i] + t:check(g.url == e.url and g.title == e.title and g.duration == e.duration, c.name .. ": round trip " .. i) + end +end +t:note("%d Python-written PLS files decode to their entries and round-trip", #Cases) + +do + local pl = decode("; comment\n[PlayList]\nversion=2\nTITLE2=Second\nfile2=b.mp3\nFile10=http://x/ten.mp3\nLength2=7\nFile1=a.mp3\nnumberofentries=4\n", "http://h/dir/list.pls") + t:eq(#pl.entries, 3, "entries sorted by number") + t:eq(pl.entries[1].url, "http://h/dir/a.mp3", "relative resolved") + t:check(pl.entries[2].title == "Second" and pl.entries[2].duration == 7, "case-insensitive keys") + t:eq(pl.entries[3].url, "http://x/ten.mp3", "gap in numbering") + t:check(string.find(pl.warnings[1], "NumberOfEntries=4", 1, true) ~= nil, "count mismatch warning") + local cp = decode("[playlist]\nFile1=http://x/a.mp3\nTitle1=Bj\246rk\nNumberOfEntries=1\n") + t:eq(cp.entries[1].title, "Bj\u{f6}rk", "Windows-1252 text") + local loc = decode("[playlist]\nFile1=C:\\Music\\a.mp3\nNumberOfEntries=1\n") + t:check(not loc.entries[1].playable and loc.entries[1].reason == "local path", "local path") + -- the writer + local out = buffer.tostring(Pls.encode({ { url = "http://a/1.mp3", title = "One\nTwo", duration = 61.6 }, { url = "http://a/2.mp3" }, { url = 5 } } :: any) :: buffer) + t:eq(out, "[playlist]\nFile1=http://a/1.mp3\nTitle1=One Two\nLength1=62\nFile2=http://a/2.mp3\nLength2=-1\nNumberOfEntries=2\nVersion=2\n", "writer output") + t:check(select(2, Pls.encode(5 :: any)) ~= nil, "encode a number") + t:eq(Pls.sniff(Bytes.reader(buffer.fromstring("\239\187\191 [playlist]\r\nFile1=a"))), 0.95, "sniff") + t:eq(Pls.sniff(Bytes.reader(buffer.fromstring("#EXTM3U"))), 0, "sniff m3u") + -- the api + t:eq(F.detect(Cases[1].pls), "pls", "F.detect") + local a = F.playlist.load(Cases[1].pls) + t:check(a and a.format == "pls", "F.playlist.load") + local m = F.convert(Cases[1].pls, "m3u") + t:check(m and string.sub(buffer.tostring(m), 1, 7) == "#EXTM3U", "F.convert pls -> m3u") +end + +local samples = {} +for _, c in Cases do + table.insert(samples, c.pls) +end +t:fuzz("decode", function(b: buffer) + return Pls.decode(Bytes.reader(b), { baseUrl = "http://h/a/" }) +end, samples, { mutations = 20 }) + +t:done() diff --git a/tools/fixtures/playlist.py b/tools/fixtures/playlist.py new file mode 100644 index 0000000..4af9918 --- /dev/null +++ b/tools/fixtures/playlist.py @@ -0,0 +1,66 @@ +# Playlist fixtures (tools/fixtures.py): playlist/m3u, playlist/pls, playlist/xspf, codecs/Url, codecs/Text. +# tests/gen/playlist_url.luau random relative references resolved by Python's urllib.parse.urljoin (RFC 3986) +# tests/gen/playlist_cp1252.luau every Windows-1252 byte decoded by Python's cp1252 codec (undefined bytes: U+FFFD) +# tests/gen/playlist_cases.luau playlists written here (M3U8 with EXTINF, PLS via configparser-style lines, XSPF via +# xml.etree.ElementTree) with the entries they hold: { url, title?, duration? } +import random, urllib.parse, xml.etree.ElementTree as ET + +BASES = ["http://a/b/c/d;p?q", "https://host.example/lists/m.m3u8", "http://h/x/", "https://cdn.example/a/b/c/list.pls", + "http://a"] +SEGS = ["g", "h", "..", ".", "music", "a b", "x.mp3", "s;p", "%41", "ü"] + + +def ref(rng): + parts = [rng.choice(SEGS) for _ in range(rng.randrange(1, 5))] + r = "/".join(parts) + k = rng.randrange(6) + if k == 0: + r = "/" + r + elif k == 1: + r = "./" + r + if rng.random() < 0.2: + r += "?y=" + rng.choice(SEGS) + if rng.random() < 0.15: + r += "#" + rng.choice(["s", "f/../x"]) + return r + + +def generate(ctx): + rng = random.Random(8) + cases = [] + for _ in range(400): + base = rng.choice(BASES) + r = ref(rng) + if " " in r or "ü" in r or (base == "http://a" and r.startswith(".")): + continue # raw spaces / UTF-8 are encoded first by the playlist code; urljoin keeps a leading "." here + cases.append([r, base, urllib.parse.urljoin(base, r)]) + ctx.emit("playlist_url", cases) + ctx.emit("playlist_cp1252", [[b, bytes([b]).decode("cp1252", errors="replace")] for b in range(0x80, 0x100)]) + + out = [] + for n in range(12): + ents = [] + for i in range(rng.randrange(1, 9)): + e = {"url": "http://media.example/%d/track%d.mp3" % (n, i)} + if rng.random() < 0.8: + e["title"] = rng.choice(["Song %d" % i, "Björk – Jóga", "A, B & C", "x <y> \"z\""]) + if rng.random() < 0.7: + e["duration"] = rng.randrange(1, 600) + ents.append(e) + m3u = "#EXTM3U\n" + "".join(("#EXTINF:%d,%s\n" % (e.get("duration", -1), e.get("title", "")) if ("title" in e or "duration" in e) else "") + e["url"] + "\n" for e in ents) + pls = "[playlist]\n" + "".join("File%d=%s\n" % (i + 1, e["url"]) + ("Title%d=%s\n" % (i + 1, e["title"]) if "title" in e else "") + ("Length%d=%d\n" % (i + 1, e.get("duration", -1))) for i, e in enumerate(ents)) + "NumberOfEntries=%d\nVersion=2\n" % len(ents) + root = ET.Element("playlist", {"version": "1", "xmlns": "http://xspf.org/ns/0/"}) + ET.SubElement(root, "title").text = "List %d" % n + tl = ET.SubElement(root, "trackList") + for e in ents: + t = ET.SubElement(tl, "track") + ET.SubElement(t, "location").text = e["url"] + if "title" in e: + ET.SubElement(t, "title").text = e["title"] + if "duration" in e: + ET.SubElement(t, "duration").text = str(e["duration"] * 1000) + xspf = ET.tostring(root, encoding="UTF-8", xml_declaration=True) + expect = [{k: v for k, v in e.items()} for e in ents] + # M3U loses a title when there is no EXTINF text; PLS keeps only what it wrote + out.append({"name": "list%d" % n, "m3u": m3u, "pls": pls, "xspf": xspf, "title": "List %d" % n, "entries": expect}) + ctx.emit("playlist_cases", out)