From fd2d9441a9d108901d1138fcd08c2bb9646265c0 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 09:50:42 -0500 Subject: [PATCH] ws-video: video/mpegts (containers/MpegTs absorbed from mpegts-luau 6e16197, its unit queue fixed for LuaJIT; M2TS, resync before the first packet, private stream types by PES id), video/mpegps (containers/MpegPs: MPEG-1 / MPEG-2 packs, PSM, private stream 1; pictures cut from the joined ES, PTS from PES / GOP temporal references; raw .m1v), containers/MpegEs; tests vs ffprobe / ffmpeg --- docs/FORMATS.md | 2 + src/Formats/Registry.luau | 24 + src/Formats/containers/MpegEs.luau | 145 +++++ src/Formats/containers/MpegPs/init.luau | 224 +++++++ src/Formats/containers/MpegTs/init.luau | 831 ++++++++++++++++++++++++ src/Formats/video/mpegps/init.luau | 192 ++++++ src/Formats/video/mpegts/init.luau | 245 +++++++ tests/video/_common.luau | 33 +- tests/video/mpegps.luau | 48 ++ tests/video/mpegts.luau | 64 ++ tools/fixtures/mpegts.py | 59 ++ 11 files changed, 1852 insertions(+), 15 deletions(-) create mode 100644 src/Formats/containers/MpegEs.luau create mode 100644 src/Formats/containers/MpegPs/init.luau create mode 100644 src/Formats/containers/MpegTs/init.luau create mode 100644 src/Formats/video/mpegps/init.luau create mode 100644 src/Formats/video/mpegts/init.luau create mode 100644 tests/video/mpegps.luau create mode 100644 tests/video/mpegts.luau create mode 100644 tools/fixtures/mpegts.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 4c878ce..0ff9719 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -22,6 +22,8 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | audio | wav | .wav .wave .rf64 .bw64 | yes | yes | streaming: true, depths: 8, 16, 24, 32, float: true, rf64: true | `tests/audio/wav.luau` | | video | avi | .avi | yes | yes | streaming: true, video: "mjpeg", "mpeg1", "rawvideo", audio: true, odml: true | `tests/video/avi.luau` | | video | mkv | .mkv .webm .mka .mk3d | yes | yes | streaming: true, remux: true, video: "vp8", "mjpeg", "mpeg1", "rawvideo", audio: true, subtitles: true | `tests/video/mkv.luau` | +| video | mpegps | .mpg .mpeg .vob .m1v .mpv .dat | yes | - | streaming: true, video: "mpeg1", audio: true | `tests/video/mpegps.luau` | +| video | mpegts | .ts .m2ts .mts .tsv | yes | - | streaming: true, video: "mpeg1", "h264", audio: true | `tests/video/mpegts.luau` | | video | y4m | .y4m | yes | yes | streaming: true, video: "rawvideo", depths: 8, 10, 12, 16 | `tests/video/y4m.luau` | | model | gltf | .gltf .glb | yes | yes | binary: true, materials: true, animation: true, skins: true, morphTargets: true, cameras: true, lights: true | `tests/model/gltf.luau` | | model | obj | .obj | yes | yes | materials: true, polygons: true, vertexColors: true | `tests/model/obj.luau` | diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index 5e2e97c..186a6b9 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -218,6 +218,30 @@ local list: { Entry } = { return require("@formats/video/mkv") end, }, + { + name = "mpegps", + category = "video", + path = "video/mpegps", + extensions = { "mpg", "mpeg", "vob", "m1v", "mpv", "dat" }, + mime = { "video/mpeg" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/MpegPs", "containers/MpegEs", "containers/Demux", "codecs/Video" }, + caps = { decode = true, encode = false, streaming = true, video = { "mpeg1" }, audio = true }, + load = function() + return require("@formats/video/mpegps") + end, + }, + { + name = "mpegts", + category = "video", + path = "video/mpegts", + extensions = { "ts", "m2ts", "mts", "tsv" }, + mime = { "video/mp2t" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/MpegTs", "containers/MpegEs", "containers/Demux", "codecs/Video" }, + caps = { decode = true, encode = false, streaming = true, video = { "mpeg1", "h264" }, audio = true }, + load = function() + return require("@formats/video/mpegts") + end, + }, { name = "y4m", category = "video", diff --git a/src/Formats/containers/MpegEs.luau b/src/Formats/containers/MpegEs.luau new file mode 100644 index 0000000..f84a0bf --- /dev/null +++ b/src/Formats/containers/MpegEs.luau @@ -0,0 +1,145 @@ +--!strict +-- containers/MpegEs: helpers over MPEG video elementary streams for the MPEG-TS / PS demuxers. New in formats-luau. +-- Start-code scanning, MPEG-1 / MPEG-2 video access units (a picture with the sequence / GOP headers before it, +-- picture type and temporal reference, the sequence's frame rate and size, MPEG-2 detection by its sequence +-- extension) and H.264 Annex B keyframes (an IDR slice, or a recovery-point SEI). Interpreted; never throws. +local readu8 = buffer.readu8 + +local MpegEs = {} + +-- next start code (00 00 01 xx) at or after p, before limit: position of the 00 00 01 | nil +function MpegEs.findStart(b: buffer, p: number, limit: number): number? + local i = p + while i + 3 <= limit do + local c = readu8(b, i + 2) + if c > 1 then + i += 3 + elseif c == 1 then + if readu8(b, i) == 0 and readu8(b, i + 1) == 0 then + return i + end + i += 3 + else -- c == 0: the start code may begin at i + 1 or i + 2 + i += 1 + end + end + return nil +end + +local FRAME_RATES = { 24000 / 1001, 24, 25, 30000 / 1001, 30, 50, 60000 / 1001, 60 } + +export type Picture = { + offset: number, -- start of the access unit (its first header's start code) + size: number, + type: number, -- 1 I, 2 P, 3 B, 4 D (0 unknown) + temporal: number, -- temporal_reference + gop: boolean, -- a GOP header precedes the picture + sequence: boolean, -- a sequence header precedes the picture +} +export type Info = { width: number, height: number, frameRate: number, mpeg2: boolean } + +-- info(b, off, limit) -> the first sequence header's facts | nil +function MpegEs.info(b: buffer, off: number, limit: number): Info? + local p = MpegEs.findStart(b, off, limit) + local info: Info? = nil + local count = 0 + while p and count < 64 do + count += 1 + local code = if p + 3 < limit then readu8(b, p + 3) else -1 + if code == 0xB3 and p + 11 < limit and not info then + local w = readu8(b, p + 4) * 16 + readu8(b, p + 5) // 16 + local h = (readu8(b, p + 5) % 16) * 256 + readu8(b, p + 6) + local fr = readu8(b, p + 7) % 16 + info = { width = w, height = h, frameRate = FRAME_RATES[fr] or 0, mpeg2 = false } + elseif code == 0xB5 and info then + info.mpeg2 = true + return info + elseif code == 0x00 and info then + return info + end + p = MpegEs.findStart(b, p + 4, limit) + end + return info +end + +-- pictureType(b, off, limit) -> the type (1 I, 2 P, 3 B) and temporal reference of the first picture header | 0 +function MpegEs.pictureType(b: buffer, off: number, limit: number): (number, number) + local p = MpegEs.findStart(b, off, limit) + local count = 0 + while p and count < 32 do + count += 1 + if p + 5 < limit and readu8(b, p + 3) == 0x00 then + local x = readu8(b, p + 4) * 256 + readu8(b, p + 5) + return (x // 8) % 8, x // 64 + end + p = MpegEs.findStart(b, p + 4, limit) + end + return 0, 0 +end + +-- pictures(b, off, limit) -> access units of an MPEG-1 / 2 video elementary stream: each picture starts at its +-- sequence / GOP header when one precedes it and runs to the next unit's start +function MpegEs.pictures(b: buffer, off: number, limit: number): { Picture } + local out: { Picture } = {} + local unitStart: number? = nil + local seq, gop = false, false + local cur: Picture? = nil + local p = MpegEs.findStart(b, off, limit) + while p do + local code = if p + 3 < limit then readu8(b, p + 3) else -1 + if code == 0xB3 or code == 0xB8 or code == 0x00 or code == 0xB7 then + -- a sequence / GOP header or a picture after a picture closes it + if cur and (code ~= 0xB7) then + cur.size = p - cur.offset + table.insert(out, cur) + cur = nil + end + if code == 0xB3 then + unitStart = unitStart or p + seq = true + elseif code == 0xB8 then + unitStart = unitStart or p + gop = true + elseif code == 0x00 then + local t, tr = 0, 0 + if p + 5 < limit then + local x = readu8(b, p + 4) * 256 + readu8(b, p + 5) + t, tr = (x // 8) % 8, x // 64 + end + cur = { offset = unitStart or p, size = 0, type = t, temporal = tr, gop = gop, sequence = seq } + unitStart, seq, gop = nil, false, false + elseif code == 0xB7 and cur then + cur.size = p + 4 - cur.offset + table.insert(out, cur) + cur = nil + end + end + p = MpegEs.findStart(b, p + 4, limit) + end + if cur then + cur.size = limit - cur.offset + table.insert(out, cur) + end + return out +end + +-- h264Key(b, off, limit) -> an Annex B access unit holds an IDR slice (NAL type 5) +function MpegEs.h264Key(b: buffer, off: number, limit: number): boolean + local p = MpegEs.findStart(b, off, limit) + local count = 0 + while p and count < 64 do + count += 1 + if p + 3 < limit then + local t = readu8(b, p + 3) % 32 + if t == 5 then + return true + elseif t == 1 then + return false + end + end + p = MpegEs.findStart(b, p + 3, limit) + end + return false +end + +return MpegEs diff --git a/src/Formats/containers/MpegPs/init.luau b/src/Formats/containers/MpegPs/init.luau new file mode 100644 index 0000000..53f75be --- /dev/null +++ b/src/Formats/containers/MpegPs/init.luau @@ -0,0 +1,224 @@ +--!strict +-- containers/MpegPs: the MPEG program stream (ISO/IEC 11172-1 system streams and ISO/IEC 13818-1 program streams: +-- .mpg / .mpeg / .vob). New in formats-luau. Pack headers (MPEG-1 and MPEG-2 layouts), system headers, the program +-- stream map (stream types), padding, and PES packets of the video (0xE0..0xEF), audio (0xC0..0xDF) and private +-- stream 1 (0xBD: AC-3 / DTS / LPCM / subpicture sub-streams) ids with their PTS / DTS (both PES header layouts, +-- 33-bit timestamps unwrapped). Data between packs that is not a start code is skipped (resync). +-- +-- local ps, err = MpegPs.read(buf, base, limit) +-- ps.streams[id] = { id, kind, codec, streamType, pes = { { pts?, dts?, offset, size } } } (id: stream_id, or +-- 0xBD00 + sub-stream id for private stream 1); ps.order = the ids in order of appearance +-- +-- Never throws: malformed packets are skipped and counted in ps.errors. +local Err = require("@formats/core/Err") +local MpegEs = require("@formats/containers/MpegEs") + +local readu8 = buffer.readu8 + +local MpegPs = {} + +export type Pes = { pts: number?, dts: number?, offset: number, size: number } +export type Stream = { id: number, kind: string, codec: string, streamType: number?, pes: { Pes } } +export type File = { streams: { [number]: Stream }, order: { number }, mpeg2: boolean, errors: number } + +local WRAP = 8589934592 -- 2^33 + +-- PSM stream_type -> kind, codec +local TYPES: { [number]: { string } } = { + [0x01] = { "video", "mpeg1" }, + [0x02] = { "video", "mpeg2" }, + [0x03] = { "audio", "mp2" }, + [0x04] = { "audio", "mp2" }, + [0x0F] = { "audio", "aac" }, + [0x10] = { "video", "mpeg4" }, + [0x1B] = { "video", "h264" }, + [0x24] = { "video", "hevc" }, + [0x81] = { "audio", "ac3" }, +} + +local function ts(b: buffer, p: number): number + local a = readu8(b, p) + local v = (a // 2) % 8 + v = v * 32768 + (readu8(b, p + 1) * 256 + readu8(b, p + 2)) // 2 + v = v * 32768 + (readu8(b, p + 3) * 256 + readu8(b, p + 4)) // 2 + return v +end + +-- read(buf, base, limit) -> File | nil, Err +function MpegPs.read(b: buffer, base: number, limit: number): (File?, Err.Err?) + local file: File = { streams = {}, order = {}, mpeg2 = false, errors = 0 } + local types: { [number]: number } = {} + local last: { [number]: number } = {} + local wrap: { [number]: number } = {} + local packs = 0 + local p = MpegEs.findStart(b, base, limit) + local function unwrap(id: number, v: number): number + local off = wrap[id] or 0 + local prev = last[id] + local t = v + off + if prev and t < prev - WRAP / 2 then + off += WRAP + wrap[id] = off + t = v + off + end + last[id] = t + return t + end + while p do + if p + 4 > limit then + break + end + local code = readu8(b, p + 3) + local nextP = p + 4 + if code == 0xBA then + packs += 1 + if p + 5 > limit then + break + end + local m = readu8(b, p + 4) + if m // 64 == 1 then -- MPEG-2 pack: 14 bytes + stuffing + file.mpeg2 = true + if p + 14 > limit then + break + end + nextP = p + 14 + readu8(b, p + 13) % 8 + else + nextP = p + 12 + end + elseif code == 0xB9 then + nextP = p + 4 + elseif code >= 0xBB then + if p + 6 > limit then + break + end + local len = readu8(b, p + 4) * 256 + readu8(b, p + 5) + local stop = p + 6 + len + if stop > limit then + stop = limit + end + nextP = stop + if code == 0xBC and len >= 10 then -- program stream map + local infoLen = readu8(b, p + 8) * 256 + readu8(b, p + 9) + local q = p + 10 + infoLen + if q + 2 <= stop then + local mapLen = readu8(b, q) * 256 + readu8(b, q + 1) + q += 2 + local e = math.min(stop, q + mapLen) + while q + 4 <= e do + local st, sid = readu8(b, q), readu8(b, q + 1) + local il = readu8(b, q + 2) * 256 + readu8(b, q + 3) + types[sid] = st + q += 4 + il + end + end + elseif code == 0xBD or (code >= 0xC0 and code <= 0xEF) then + -- a PES packet + local q = p + 6 + local pts, dts: number? = nil, nil + local ok = true + if q < stop and readu8(b, q) // 64 == 2 then -- MPEG-2 PES header + if q + 3 > stop then + ok = false + else + local flags = readu8(b, q + 1) + local hlen = readu8(b, q + 2) + local h = q + 3 + if flags >= 0x80 and h + 5 <= stop then + pts = ts(b, h) + if flags // 64 == 3 and h + 10 <= stop then + dts = ts(b, h + 5) + end + end + q = h + hlen + end + else -- MPEG-1 packet header + local n = 0 + while q < stop and readu8(b, q) == 0xFF and n < 16 do + q += 1 + n += 1 + end + if q < stop and readu8(b, q) // 64 == 1 then + q += 2 + end + if q < stop then + local c = readu8(b, q) // 16 + if c == 2 and q + 5 <= stop then + pts = ts(b, q) + q += 5 + elseif c == 3 and q + 10 <= stop then + pts = ts(b, q) + dts = ts(b, q + 5) + q += 10 + elseif readu8(b, q) == 0x0F then + q += 1 + else + ok = false + end + end + end + if ok and q <= stop then + local id = code + local kind, codec = "other", "unknown" + if code == 0xBD then + if q >= stop then + ok = false + else + local sub = readu8(b, q) + id = 0xBD00 + sub + if sub >= 0x80 and sub <= 0x87 then + kind, codec = "audio", "ac3" + q += 4 + elseif sub >= 0x88 and sub <= 0x8F then + kind, codec = "audio", "dts" + q += 4 + elseif sub >= 0xA0 and sub <= 0xA7 then + kind, codec = "audio", "pcm_dvd" + q += 7 + elseif sub >= 0x20 and sub <= 0x3F then + kind, codec = "subtitle", "dvdsub" + q += 1 + else + q += 1 + end + end + elseif code >= 0xE0 then + kind, codec = "video", "mpeg1" + else + kind, codec = "audio", "mp2" + end + local st = types[code] + if st and TYPES[st] then + kind, codec = TYPES[st][1], TYPES[st][2] + end + if ok and q <= stop then + local s = file.streams[id] + if not s then + s = { id = id, kind = kind, codec = codec, streamType = st, pes = {} } + file.streams[id] = s + table.insert(file.order, id) + end + table.insert(s.pes, { + pts = if pts then unwrap(id, pts) else nil, + dts = if dts then unwrap(id + 0x10000, dts) else nil, + offset = q, + size = stop - q, + }) + end + end + if not ok then + file.errors += 1 + end + end + else + -- a start code that is not a system one (stray ES data between packets): resync + file.errors += 1 + end + p = MpegEs.findStart(b, nextP, limit) + end + if packs == 0 and #file.order == 0 then + return nil, Err.new(Err.CORRUPT, "no MPEG pack or PES packet", base) + end + return file, nil +end + +return MpegPs diff --git a/src/Formats/containers/MpegTs/init.luau b/src/Formats/containers/MpegTs/init.luau new file mode 100644 index 0000000..693b034 --- /dev/null +++ b/src/Formats/containers/MpegTs/init.luau @@ -0,0 +1,831 @@ +--!strict +--!native +-- containers/MpegTs: an MPEG transport stream demuxer (ISO/IEC 13818-1). Absorbed from mpegts-luau 6e16197 (same +-- author; no third-party code). Changed: this header, and the unit queue keeps an explicit tail (pull() used #q on a +-- table with holes at its front, which LuaJIT's border rule makes lose units). 188-byte packets with resync, PAT / PMT sections +-- (assembled across packets, CRC-checked), adaptation fields (PCR, discontinuity, random access), continuity +-- counter checks (gaps are flagged on the unit, duplicates dropped), PES reassembly with 33-bit PTS / DTS. +-- +-- local units = MpegTs.demux(buf) -- whole segment: { video = {...}, audio = {...}, streams, ... } +-- local d = MpegTs.new(); d:push(chunk); local u = d:pull() ... d:flush() -- streamed +-- +-- Native code must never throw (an error unwinding through native code crashes Roblox Studio), so every read is +-- bounds-checked by construction and bad input is skipped and counted in `stats`, never raised. + +local MpegTs = {} + +export type Stream = { + pid: number, + streamType: number, -- PMT stream_type (0 when the stream was found without a PMT) + kind: string, -- "video" | "audio" | "other" + codec: string, -- "mpeg1video" | "mpeg2video" | "mpegaudio" | "aac" | "h264" | "hevc" | "ac3" | "unknown" ... + program: number, -- program_number (0 without a PMT) + language: string?, -- ISO 639 language descriptor, when present +} + +export type Unit = { + pid: number, + kind: string, + codec: string, + streamType: number, + streamId: number, -- PES stream_id (0xE0.. video, 0xC0.. audio) + pts: number?, -- seconds (33-bit 90 kHz clock, unwrapped per PID) + dts: number?, -- seconds; equals pts when the PES carries no DTS + pts90: number?, -- the same in 90 kHz ticks + dts90: number?, + data: buffer, -- the PES payload (one access unit for video as muxed by ffmpeg; one or more frames for audio) + ccError: boolean, -- a continuity counter gap (lost packets) happened inside this unit + randomAccess: boolean, -- the first packet's adaptation field had random_access_indicator set + discontinuity: boolean, -- the first packet's adaptation field had discontinuity_indicator set +} + +export type Stats = { + packets: number, + syncLosses: number, -- resyncs (bytes skipped to find 0x47 again) + skippedBytes: number, + teiErrors: number, -- transport_error_indicator packets (dropped) + ccErrors: number, -- continuity counter gaps + duplicates: number, -- duplicate packets (same CC), dropped + crcErrors: number, -- PSI sections with a bad CRC (ignored) + pesErrors: number, -- PES units without a valid header (dropped) + scrambled: number, -- scrambled packets (dropped) + pcr: number?, -- last PCR seen, seconds +} + +export type Demuxed = { + video: { Unit }, -- units of the selected video PID (first video stream of the PMT), in stream order + audio: { Unit }, -- units of the selected audio PID + streams: { Stream }, -- every elementary stream, PMT order + units: { Unit }, -- every unit of every PID, in completion order + videoPid: number?, + audioPid: number?, + stats: Stats, +} + +type PesState = { + buf: buffer, + len: number, + active: boolean, + expected: number, -- total PES bytes when PES_packet_length is set, else 0 (ends at the next unit start) + hdrChecked: boolean, + ccError: boolean, + randomAccess: boolean, + discontinuity: boolean, + lastPts: number, -- for 33-bit wrap unwrapping + wrapOffset: number, +} + +type SectionState = { buf: buffer, len: number, active: boolean } + +local TS_SIZE = 188 +local SYNC = 0x47 +local MAX_SECTION = 4096 + 188 +local WRAP = 8589934592 -- 2^33 + +local readu8 = buffer.readu8 +local band = bit32.band +local bor = bit32.bor +local lshift = bit32.lshift +local rshift = bit32.rshift + +local CODECS: { [number]: { string } } = { + [0x01] = { "video", "mpeg1video" }, + [0x02] = { "video", "mpeg2video" }, + [0x03] = { "audio", "mpegaudio" }, + [0x04] = { "audio", "mpegaudio" }, + [0x0F] = { "audio", "aac" }, + [0x10] = { "video", "mpeg4" }, + [0x11] = { "audio", "aac_latm" }, + [0x1B] = { "video", "h264" }, + [0x24] = { "video", "hevc" }, + [0x81] = { "audio", "ac3" }, + [0x87] = { "audio", "eac3" }, +} + +-- CRC-32/MPEG-2 (poly 0x04C11DB7, init 0xFFFFFFFF, MSB first, no final xor): a section including its CRC sums to 0 +local CRC = buffer.create(256 * 4) +for i = 0, 255 do + local c = lshift(i, 24) + for _ = 1, 8 do + if band(c, 0x80000000) ~= 0 then + c = bit32.bxor(lshift(c, 1), 0x04C11DB7) + else + c = lshift(c, 1) + end + end + buffer.writeu32(CRC, i * 4, c) +end + +local function crc32(b: buffer, off: number, n: number): number + local c = 0xFFFFFFFF + for i = off, off + n - 1 do + c = bit32.bxor(lshift(c, 8), buffer.readu32(CRC, band(bit32.bxor(rshift(c, 24), readu8(b, i)), 255) * 4)) + end + return c +end +MpegTs.crc32 = crc32 + +local function u16(b: buffer, p: number): number + return readu8(b, p) * 256 + readu8(b, p + 1) +end + +-- 33-bit timestamp from the 5-byte PES encoding at p +local function readTs(b: buffer, p: number): number + local b0 = readu8(b, p) + local hi = band(rshift(b0, 1), 7) * 1073741824 -- bits 32..30 + local mid = bor(lshift(readu8(b, p + 1), 7), rshift(readu8(b, p + 2), 1)) -- bits 29..15 + local lo = bor(lshift(readu8(b, p + 3), 7), rshift(readu8(b, p + 4), 1)) -- bits 14..0 + return hi + mid * 32768 + lo +end + +local Demuxer = {} +Demuxer.__index = Demuxer + +export type Demuxer = typeof(setmetatable( + {} :: { + _pend: buffer, + _pendLen: number, + _pmtPids: { [number]: number }, + _streams: { [number]: Stream }, + _pes: { [number]: PesState }, + _sections: { [number]: SectionState }, + _cc: { [number]: number }, + _queue: { Unit }, + _qhead: number, + _qtail: number, + streams: { Stream }, + stats: Stats, + }, + Demuxer +)) + +function MpegTs.new(): Demuxer + local self = setmetatable({ + _pend = buffer.create(64 * 1024), + _pendLen = 0, + _pmtPids = {}, + _streams = {}, + _pes = {}, + _sections = {}, + _cc = {}, + _queue = {}, + _qhead = 1, + _qtail = 0, + streams = {}, + stats = { + packets = 0, + syncLosses = 0, + skippedBytes = 0, + teiErrors = 0, + ccErrors = 0, + duplicates = 0, + crcErrors = 0, + pesErrors = 0, + scrambled = 0, + pcr = nil, + } :: Stats, + }, Demuxer) + return self +end + +-- PSI --------------------------------------------------------------------------------------------------------- + +local function addStream(self: Demuxer, pid: number, streamType: number, program: number, language: string?) + local info = CODECS[streamType] + local s = self._streams[pid] + if s == nil then + s = { + pid = pid, + streamType = streamType, + kind = if info then info[1] else "other", + codec = if info then info[2] else "unknown", + program = program, + language = language, + } + self._streams[pid] = s + table.insert(self.streams, s) + else + s.streamType = streamType + s.kind = if info then info[1] else "other" + s.codec = if info then info[2] else "unknown" + s.program = program + s.language = language + end +end + +local function parseSection(self: Demuxer, pid: number, b: buffer, n: number) + -- n >= 3 bytes: table_id, section_length (n = 3 + section_length) + if n < 12 then + return + end + if band(readu8(b, 1), 0x80) == 0 then + return -- no section_syntax_indicator: not a PAT / PMT + end + if crc32(b, 0, n) ~= 0 then + self.stats.crcErrors += 1 + return + end + if band(readu8(b, 5), 1) == 0 then + return -- current_next_indicator = 0: a future table + end + local tid = readu8(b, 0) + local stop = n - 4 + if tid == 0x00 and pid == 0 then + local p = 8 + while p + 4 <= stop do + local prog = u16(b, p) + local pmt = band(u16(b, p + 2), 0x1FFF) + if prog ~= 0 then + self._pmtPids[pmt] = prog + end + p += 4 + end + elseif tid == 0x02 and self._pmtPids[pid] ~= nil then + local program = u16(b, 3) + local p = 12 + band(u16(b, 10), 0x0FFF) + while p + 5 <= stop do + local st = readu8(b, p) + local epid = band(u16(b, p + 1), 0x1FFF) + local esl = band(u16(b, p + 3), 0x0FFF) + local d = p + 5 + local dend = math.min(d + esl, stop) + local language: string? = nil + while d + 2 <= dend do + local tag, len = readu8(b, d), readu8(b, d + 1) + if tag == 0x0A and len >= 3 and d + 5 <= dend then + language = buffer.readstring(b, d + 2, 3) + end + d += 2 + len + end + addStream(self, epid, st, program, language) + p += 5 + esl + end + end +end + +local function sectionBytes(self: Demuxer, pid: number, s: SectionState, src: buffer, from: number, to: number) + local n = to - from + if n <= 0 then + return + end + if s.len + n > MAX_SECTION then + s.active = false + s.len = 0 + return + end + buffer.copy(s.buf, s.len, src, from, n) + s.len += n + -- every complete section in the buffer + while s.active and s.len >= 3 do + if readu8(s.buf, 0) == 0xFF then + s.active = false -- stuffing: no more sections until the next unit start + s.len = 0 + return + end + local need = 3 + band(u16(s.buf, 1), 0x0FFF) + if s.len < need then + return + end + parseSection(self, pid, s.buf, need) + local rest = s.len - need + if rest > 0 then + buffer.copy(s.buf, 0, s.buf, need, rest) + end + s.len = rest + end +end + +local function sectionPayload(self: Demuxer, pid: number, pusi: boolean, b: buffer, pos: number, stop: number) + local s = self._sections[pid] + if s == nil then + s = { buf = buffer.create(MAX_SECTION), len = 0, active = false } + self._sections[pid] = s + end + if pusi then + if pos >= stop then + return + end + local ptr = readu8(b, pos) + pos += 1 + local tail = math.min(pos + ptr, stop) + if s.active then + sectionBytes(self, pid, s, b, pos, tail) -- the end of the previous section + end + s.active = true + s.len = 0 + pos = tail + elseif not s.active then + return + end + sectionBytes(self, pid, s, b, pos, stop) +end + +-- PES --------------------------------------------------------------------------------------------------------- + +local function completePes(self: Demuxer, pid: number, st: PesState) + st.active = false + local b, len = st.buf, st.len + if len < 6 or readu8(b, 0) ~= 0 or readu8(b, 1) ~= 0 or readu8(b, 2) ~= 1 then + self.stats.pesErrors += 1 + return + end + local sid = readu8(b, 3) + local stop = if st.expected > 0 then math.min(st.expected, len) else len + local start = 6 + local pts: number?, dts: number? = nil, nil + if not (sid == 0xBC or sid == 0xBE or sid == 0xBF or sid == 0xF0 or sid == 0xF1 or sid == 0xF2 or sid == 0xF8 or sid == 0xFF) then + if stop < 9 then + self.stats.pesErrors += 1 + return + end + if band(readu8(b, 6), 0xC0) == 0x80 then + -- MPEG-2 PES header + local flags = readu8(b, 7) + local hl = readu8(b, 8) + start = 9 + hl + if band(flags, 0x80) ~= 0 and hl >= 5 and 14 <= stop then + pts = readTs(b, 9) + if band(flags, 0x40) ~= 0 and hl >= 10 and 19 <= stop then + dts = readTs(b, 14) + end + end + else + -- MPEG-1 (ISO 11172-1) packet header: stuffing, STD buffer, PTS / DTS + local p = 6 + local k = 0 + while p < stop and readu8(b, p) == 0xFF and k < 16 do + p += 1 + k += 1 + end + if p < stop and band(readu8(b, p), 0xC0) == 0x40 then + p += 2 + end + if p < stop then + local c = band(readu8(b, p), 0xF0) + if c == 0x20 and p + 5 <= stop then + pts = readTs(b, p) + p += 5 + elseif c == 0x30 and p + 10 <= stop then + pts = readTs(b, p) + dts = readTs(b, p + 5) + p += 10 + else + p += 1 + end + end + start = p + end + end + if start > stop then + self.stats.pesErrors += 1 + return + end + -- unwrap the 33-bit clock (per PID) + if pts ~= nil then + pts += st.wrapOffset + if st.lastPts >= 0 then + if pts < st.lastPts - WRAP / 2 then + st.wrapOffset += WRAP + pts += WRAP + elseif pts > st.lastPts + WRAP / 2 and st.wrapOffset >= WRAP then + st.wrapOffset -= WRAP + pts -= WRAP + end + end + st.lastPts = pts + if dts ~= nil then + dts += st.wrapOffset + if dts > pts + WRAP / 2 then + dts -= WRAP + elseif dts < pts - WRAP / 2 then + dts += WRAP + end + else + dts = pts + end + end + local n = stop - start + local data = buffer.create(n) + if n > 0 then + buffer.copy(data, 0, b, start, n) + end + local s = self._streams[pid] + local kind, codec, streamType + if s then + kind, codec, streamType = s.kind, s.codec, s.streamType + elseif sid >= 0xE0 and sid <= 0xEF then + kind, codec, streamType = "video", "unknown", 0 + elseif sid >= 0xC0 and sid <= 0xDF then + kind, codec, streamType = "audio", "mpegaudio", 0 + else + kind, codec, streamType = "other", "unknown", 0 + end + local unit: Unit = { + pid = pid, + kind = kind, + codec = codec, + streamType = streamType, + streamId = sid, + pts = if pts then pts / 90000 else nil, + dts = if dts then dts / 90000 else nil, + pts90 = pts, + dts90 = dts, + data = data, + ccError = st.ccError, + randomAccess = st.randomAccess, + discontinuity = st.discontinuity, + } + local tail = self._qtail + 1 + self._qtail = tail + self._queue[tail] = unit +end + +local function pesPayload( + self: Demuxer, + pid: number, + pusi: boolean, + b: buffer, + pos: number, + stop: number, + ccError: boolean, + randomAccess: boolean, + discontinuity: boolean +) + local st = self._pes[pid] + -- a unit starts with a PES start code; anything else on a PID outside the PMT (SDT, EIT ...) is ignored + local startCode = pusi + and stop - pos >= 3 + and readu8(b, pos) == 0 + and readu8(b, pos + 1) == 0 + and readu8(b, pos + 2) == 1 + if st == nil then + if not startCode then + return + end + st = { + buf = buffer.create(16 * 1024), + len = 0, + active = false, + expected = 0, + hdrChecked = false, + ccError = false, + randomAccess = false, + discontinuity = false, + lastPts = -1, + wrapOffset = 0, + } + self._pes[pid] = st + end + if ccError and st.active then + st.ccError = true -- packets of the unit in progress were lost + end + if pusi then + if st.active then + completePes(self, pid, st) + end + if not startCode then + if self._streams[pid] ~= nil then + self.stats.pesErrors += 1 + end + return + end + st.active = true + st.len = 0 + st.expected = 0 + st.hdrChecked = false + st.ccError = false + st.randomAccess = randomAccess + st.discontinuity = discontinuity + elseif not st.active then + return + end + local n = stop - pos + if n <= 0 then + return + end + if st.len + n > buffer.len(st.buf) then + local cap = buffer.len(st.buf) * 2 + while cap < st.len + n do + cap *= 2 + end + if cap > 64 * 1024 * 1024 then + st.active = false -- runaway unit (no unit start for 64 MB): drop it + st.len = 0 + self.stats.pesErrors += 1 + return + end + local nb = buffer.create(cap) + buffer.copy(nb, 0, st.buf, 0, st.len) + st.buf = nb + end + buffer.copy(st.buf, st.len, b, pos, n) + st.len += n + if not st.hdrChecked and st.len >= 6 then + st.hdrChecked = true + local plen = u16(st.buf, 4) + if plen > 0 then + st.expected = 6 + plen + end + end + if st.expected > 0 and st.len >= st.expected then + completePes(self, pid, st) + end +end + +-- packets ----------------------------------------------------------------------------------------------------- + +local function packet(self: Demuxer, b: buffer, pk: number) + local stats = self.stats + stats.packets += 1 + local b1 = readu8(b, pk + 1) + if band(b1, 0x80) ~= 0 then + stats.teiErrors += 1 + return + end + local pusi = band(b1, 0x40) ~= 0 + local pid = band(b1, 0x1F) * 256 + readu8(b, pk + 2) + if pid == 0x1FFF then + return + end + local b3 = readu8(b, pk + 3) + if band(b3, 0xC0) ~= 0 then + stats.scrambled += 1 + return + end + local afc = band(rshift(b3, 4), 3) + local cc = band(b3, 15) + if afc == 0 then + return + end + local pos = pk + 4 + local stop = pk + TS_SIZE + local discontinuity, randomAccess = false, false + if afc >= 2 then + local afl = readu8(b, pos) + pos += 1 + if afl > 183 then + return + end + if afl > 0 then + local flags = readu8(b, pos) + discontinuity = band(flags, 0x80) ~= 0 + randomAccess = band(flags, 0x40) ~= 0 + if band(flags, 0x10) ~= 0 and afl >= 7 then + local base = readu8(b, pos + 1) * 33554432 + + readu8(b, pos + 2) * 131072 + + readu8(b, pos + 3) * 512 + + readu8(b, pos + 4) * 2 + + rshift(readu8(b, pos + 5), 7) + local ext = band(readu8(b, pos + 5), 1) * 256 + readu8(b, pos + 6) + stats.pcr = base / 90000 + ext / 27000000 + end + end + pos += afl + if afc == 2 then + if discontinuity then + self._cc[pid] = nil + end + return -- adaptation field only: the counter does not advance + end + end + -- continuity counter + local ccError = false + local last = self._cc[pid] + if last ~= nil and not discontinuity then + if cc == last then + stats.duplicates += 1 + return + elseif cc ~= band(last + 1, 15) then + ccError = true + stats.ccErrors += 1 + end + end + self._cc[pid] = cc + if pid == 0 or self._pmtPids[pid] ~= nil then + sectionPayload(self, pid, pusi, b, pos, stop) + elseif pid >= 0x10 then + pesPayload(self, pid, pusi, b, pos, stop, ccError, randomAccess, discontinuity) + end +end + +-- Appends bytes (a buffer, or a string) and demuxes every whole packet in them. Completed units queue up for +-- pull(). Returns false for a bad argument. +function Demuxer.push(self: Demuxer, data: buffer | string, offset: number?, len: number?): boolean + local src: buffer + if type(data) == "string" then + src = buffer.fromstring(data) + elseif type(data) == "buffer" then + src = data + else + return false + end + local off = math.max(0, math.floor(offset or 0)) + local total = buffer.len(src) + if off > total then + return false + end + local n = math.min(math.floor(len or (total - off)), total - off) + if n < 0 then + return false + end + -- append to the pending bytes + local need = self._pendLen + n + if need > buffer.len(self._pend) then + local cap = buffer.len(self._pend) + while cap < need do + cap *= 2 + end + local nb = buffer.create(cap) + buffer.copy(nb, 0, self._pend, 0, self._pendLen) + self._pend = nb + end + if n > 0 then + buffer.copy(self._pend, self._pendLen, src, off, n) + end + self._pendLen = need + local b, avail = self._pend, self._pendLen + local p = 0 + while p + TS_SIZE <= avail do + if readu8(b, p) ~= SYNC then + -- resync: the next 0x47 that is followed by another one 188 bytes later (or by the end of the data) + self.stats.syncLosses += 1 + local q = p + 1 + local found = -1 + local waitAt = -1 + while q < avail do + if readu8(b, q) == SYNC then + if q + TS_SIZE < avail then + if readu8(b, q + TS_SIZE) == SYNC then + found = q + break + end + elseif q + TS_SIZE == avail then + found = q + break + else + waitAt = q -- not enough bytes to confirm: wait for more + break + end + end + q += 1 + end + if found >= 0 then + self.stats.skippedBytes += found - p + p = found + elseif waitAt >= 0 then + self.stats.skippedBytes += waitAt - p + p = waitAt + break + else + self.stats.skippedBytes += avail - p + p = avail + break + end + else + packet(self, b, p) + p += TS_SIZE + end + end + local rest = avail - p + if rest > 0 and p > 0 then + buffer.copy(b, 0, b, p, rest) + end + self._pendLen = rest + return true +end + +-- The next completed unit (any PID), or nil. +function Demuxer.pull(self: Demuxer): Unit? + local q = self._queue + local h = self._qhead + local u = q[h] + if u == nil then + return nil + end + q[h] = nil :: any + h += 1 + if h > self._qtail then + table.clear(q) + h = 1 + self._qtail = 0 + end + self._qhead = h + return u +end + +-- Ends every unit in progress (call at the end of the data: a video PES with no length only ends at the next +-- unit start). Units still queue up for pull(). +function Demuxer.flush(self: Demuxer) + local pids = {} + for pid, st in self._pes do + if st.active then + table.insert(pids, pid) + end + end + table.sort(pids) + for _, pid in pids do + completePes(self, pid, self._pes[pid]) + end + self._pendLen = 0 +end + +-- Forgets buffered bytes, units in progress and continuity state, but keeps the PAT / PMT (for a seek). +function Demuxer.reset(self: Demuxer) + self._pendLen = 0 + for _, st in self._pes do + st.active = false + st.len = 0 + st.lastPts = -1 + st.wrapOffset = 0 + end + for _, s in self._sections do + s.active = false + s.len = 0 + end + table.clear(self._cc) + table.clear(self._queue) + self._qhead = 1 + self._qtail = 0 +end + +-- Streams by kind: the first video / audio PID in PMT order (or in unit order without a PMT). +function Demuxer.streamFor(self: Demuxer, kind: string): Stream? + for _, s in self.streams do + if s.kind == kind then + return s + end + end + return nil +end + +export type DemuxOptions = { videoPid: number?, audioPid: number? } + +-- Demuxes a whole buffer (one segment). Video and audio are the units of one PID each: opts.videoPid / +-- opts.audioPid, else the first video / audio stream of the PMT, else the first PID whose units look like video / +-- audio (PES stream_id). Never throws; a bad argument gives empty lists. +function MpegTs.demux(data: buffer | string, opts: DemuxOptions?): Demuxed + local d = MpegTs.new() + d:push(data) + d:flush() + local units = {} + while true do + local u = d:pull() + if u == nil then + break + end + table.insert(units, u) + end + local videoPid = opts and opts.videoPid + local audioPid = opts and opts.audioPid + if videoPid == nil then + local s = d:streamFor("video") + videoPid = if s then s.pid else nil + end + if audioPid == nil then + local s = d:streamFor("audio") + audioPid = if s then s.pid else nil + end + for _, u in units do + if videoPid == nil and u.kind == "video" then + videoPid = u.pid + end + if audioPid == nil and u.kind == "audio" then + audioPid = u.pid + end + end + local video, audio = {}, {} + for _, u in units do + if u.pid == videoPid then + table.insert(video, u) + elseif u.pid == audioPid then + table.insert(audio, u) + end + end + return { + video = video, + audio = audio, + streams = d.streams, + units = units, + videoPid = videoPid, + audioPid = audioPid, + stats = d.stats, + } +end + +-- Concatenates the data of a list of units (e.g. a segment's audio access units, for Mp3.open). +function MpegTs.concat(units: { Unit }): buffer + local n = 0 + for _, u in units do + n += buffer.len(u.data) + end + local out = buffer.create(n) + local p = 0 + for _, u in units do + local l = buffer.len(u.data) + buffer.copy(out, p, u.data, 0, l) + p += l + end + return out +end + +return MpegTs diff --git a/src/Formats/video/mpegps/init.luau b/src/Formats/video/mpegps/init.luau new file mode 100644 index 0000000..5ab6dac --- /dev/null +++ b/src/Formats/video/mpegps/init.luau @@ -0,0 +1,192 @@ +--!strict +-- video/mpegps: MPEG program streams (ISO/IEC 11172-1 system streams and 13818-1 program streams: .mpg / .mpeg / +-- .vob / VCD .dat). New in formats-luau, on containers/MpegPs. Video PES payloads are joined into the elementary +-- stream and cut into pictures (containers/MpegEs: one packet per picture with its sequence / GOP headers); a +-- picture takes the PTS of the PES it starts in, pictures without one get theirs from the GOP's temporal references. +-- Audio packets are the PES payloads (MP1 / MP2 / MP3 frames, AC-3, LPCM). open() returns a VideoDecoder: MPEG-1 +-- video through the codecs/Video registry (MPEG-2 detected and reported), audio through the api's opts.openAudio hook. +-- Timescale 90 kHz. Not supported: writing, H.264 in PS (packets are whole PES payloads), DVD navigation packets. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local MpegPs = require("@formats/containers/MpegPs") +local MpegEs = require("@formats/containers/MpegEs") +local Demux = require("@formats/containers/Demux") +local Video = require("@formats/codecs/Video") + +-- ------------------------------------------------------------------------------------------------ contract +local Ps = { + name = "mpegps", + category = "video", + extensions = { "mpg", "mpeg", "vob", "m1v", "mpv", "dat" }, + mime = { "video/mpeg" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/MpegPs", "containers/MpegEs", "containers/Demux", "codecs/Video" }, + caps = { decode = true, encode = false, streaming = true, video = { "mpeg1" }, audio = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type OpenOptions = { + rgba: boolean?, + track: number?, -- the video stream id to decode (0xE0.. ; default: the first video stream) + audio: boolean?, + maxPixels: number?, + openAudio: any?, -- set by the api +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Ps.sniff(r: Bytes.Reader): number + if r:peek(4) == "\0\0\1\186" then + return 0.9 + end + if r:peek(4) == "\0\0\1\179" then + return 0.5 -- an MPEG-1 / 2 video elementary stream (sequence header) + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- the pictures of a video stream as packets: join the PES payloads, cut at pictures, place the timestamps +local function videoPackets(dmx: any, buf: buffer, s: MpegPs.Stream, t: any) + local total = 0 + for _, p in s.pes do + total += p.size + end + local es = buffer.create(total) + local starts: { number } = {} + local o = 0 + for i, p in s.pes do + starts[i] = o + buffer.copy(es, o, buf, p.offset, p.size) + o += p.size + end + local info = MpegEs.info(es, 0, total) + if info then + t.width, t.height, t.frameRate = info.width, info.height, info.frameRate + if info.mpeg2 then + t.codec = "mpeg2" + end + end + local pics = MpegEs.pictures(es, 0, total) + local fd = if t.frameRate and t.frameRate > 0 then 90000 / t.frameRate else 3600 + -- the PTS of the PES each picture starts in (only the first picture starting in a PES takes it) + local k = 1 + local used: { [number]: boolean } = {} + local ptsOf: { [number]: number } = {} + for i, pic in pics do + while k < #s.pes and starts[k + 1] <= pic.offset do + k += 1 + end + -- a PES whose payload starts inside this picture's headers also labels it + local pes = s.pes[k] + if pes and pes.pts and not used[k] then + used[k] = true + ptsOf[i] = pes.pts + end + end + -- fill the rest from the temporal references of each GOP (an elementary stream without any PTS: from 0) + local anchorPts, anchorTr = nil :: number?, 0 + local lastPts = nil :: number? + local timed = next(ptsOf) ~= nil + local count = 0 + for i, pic in pics do + if pic.gop then + anchorPts = nil + if not timed then + anchorPts, anchorTr = count * fd, 0 + end + end + if not timed and anchorPts == nil then + anchorPts, anchorTr = count * fd, pic.temporal + end + count += 1 + local pts = ptsOf[i] + if pts then + anchorPts, anchorTr = pts, pic.temporal + elseif anchorPts then + pts = anchorPts + (pic.temporal - anchorTr) * fd + elseif lastPts then + pts = lastPts + fd + end + if pts then + lastPts = pts + local d = buffer.create(pic.size) + buffer.copy(d, 0, es, pic.offset, pic.size) + dmx:addData(t.id, pts, nil, fd, pic.type == 1, d) + end + end +end + +-- demux(r, opts?) -> the Demuxer | nil, Err +function Ps.demux(r: Bytes.Reader, _opts: OpenOptions?): (any, Err.Err?) + if r:peek(4) == "\0\0\1\179" then + -- an MPEG-1 / 2 video elementary stream (.m1v): one video stream, no timestamps + local t: any = { id = 0xE0, kind = "video", codec = "mpeg1", codecTag = "es", timescale = 90000, streamId = 0xE0 } + local dmx = Demux.new("mpegps", { t }, r.buf, { elementary = true }) + videoPackets(dmx, r.buf, { id = 0xE0, kind = "video", codec = "mpeg1", pes = { { offset = r.base, size = r.limit - r.base } } }, t) + dmx:finish() + return dmx, nil + end + local ok, file, err = pcall(MpegPs.read, r.buf, r.base, r.limit) + if not ok then + return nil, Err.new(Err.CORRUPT, "internal error: " .. tostring(file)) + end + if not file then + return nil, err + end + local tracks: { Types.Track } = {} + for _, id in file.order do + local s = file.streams[id] + table.insert(tracks, { + id = id, + kind = s.kind :: any, + codec = s.codec, + codecTag = string.format("0x%02x", id % 256), + timescale = 90000, + streamId = id, + }) + end + local dmx = Demux.new("mpegps", tracks, r.buf, { mpeg2 = file.mpeg2, errors = file.errors }) + for i, id in file.order do + local s = file.streams[id] + local t: any = tracks[i] + if t.kind == "video" and (t.codec == "mpeg1" or t.codec == "mpeg2") then + videoPackets(dmx, r.buf, s, t) + else + local last = nil :: number? + for _, p in s.pes do + local pts = p.pts or last + if pts and p.size > 0 then + last = pts + dmx:add(id, pts, p.dts, nil, true, p.offset, p.size) + end + end + if t.codec == "mp2" and #s.pes > 0 then + local p = s.pes[1] + local b = r.buf + for i2 = p.offset, math.min(p.offset + p.size, r.limit) - 2 do + if buffer.readu8(b, i2) == 0xFF and buffer.readu8(b, i2 + 1) >= 0xE0 then + local layer = (buffer.readu8(b, i2 + 1) // 2) % 4 + t.codec = if layer == 1 then "mp3" elseif layer == 3 then "mp1" else "mp2" + break + end + end + end + end + end + dmx:finish() -- (read() without a track gives the video packets first, then the audio ones) + return dmx, nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts?) -> a VideoDecoder | nil, Err +function Ps.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?) + local dmx, err = Ps.demux(r, opts) + if not dmx then + return nil, err + end + return Video.open(dmx, opts) +end + +return Ps diff --git a/src/Formats/video/mpegts/init.luau b/src/Formats/video/mpegts/init.luau new file mode 100644 index 0000000..b07bf6f --- /dev/null +++ b/src/Formats/video/mpegts/init.luau @@ -0,0 +1,245 @@ +--!strict +-- video/mpegts: MPEG transport streams (ISO/IEC 13818-1: .ts / .m2ts segments, HLS). The demuxer is containers/MpegTs, +-- absorbed from mpegts-luau (resync, PAT / PMT with CRC, continuity checks, PES reassembly, 33-bit PTS / DTS +-- unwrapped); this format turns its units into a Demuxer (timescale 90 kHz; one PES = one packet: a picture as +-- muxed by ffmpeg, one or more audio frames) and returns a VideoDecoder: MPEG-1 video through the codecs/Video +-- registry (stream type 0x02 checked for an MPEG-2 sequence extension), H.264 when registered, audio (MP1 / MP2 / +-- MP3, AAC in ADTS) through the api's opts.openAudio hook. Keyframes: MPEG-1 / 2 I-pictures, H.264 IDR access units. +-- M2TS (192-byte packets with a 4-byte timestamp prefix) is read too. Not supported: writing, scrambled streams, +-- PES without PTS for video before the first one (dropped). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local MpegTs = require("@formats/containers/MpegTs") +local MpegEs = require("@formats/containers/MpegEs") +local Demux = require("@formats/containers/Demux") +local Video = require("@formats/codecs/Video") + +-- ------------------------------------------------------------------------------------------------ contract +local Ts = { + name = "mpegts", + category = "video", + extensions = { "ts", "m2ts", "mts", "tsv" }, + mime = { "video/mp2t" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/MpegTs", "containers/MpegEs", "containers/Demux", "codecs/Video" }, + caps = { decode = true, encode = false, streaming = true, video = { "mpeg1", "h264" }, audio = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type OpenOptions = { + rgba: boolean?, + track: number?, -- the video PID to decode (default: the first video stream of the PMT) + audio: boolean?, + maxPixels: number?, + openAudio: any?, -- set by the api +} + +-- ------------------------------------------------------------------------------------------------ constants +local CODEC: { [string]: string } = { + mpeg1video = "mpeg1", + mpeg2video = "mpeg2", + mpegaudio = "mp2", + aac = "aac", + aac_latm = "aac_latm", + h264 = "h264", + hevc = "hevc", + mpeg4 = "mpeg4", + ac3 = "ac3", + eac3 = "eac3", +} + +-- ------------------------------------------------------------------------------------------------ sniff +-- packetSize(r) -> 188 | 192 (M2TS) | 0, and the offset of the first sync byte: three sync bytes a packet apart +-- (fewer in a short file) within the first 2 KB +local function packetSize(r: Bytes.Reader): (number, number) + local n = r:remaining() + for start = 0, math.min(n, 2048) - 1 do + if r:peekU8(start) == 0x47 then + for _, size in { 188, 192 } do + local hits, need = 0, math.min(3, (n - start - 1) // size + 1) + for k = 0, 2 do + local at = start + k * size + if at < n and r:peekU8(at) == 0x47 then + hits += 1 + end + end + if hits >= need and (need >= 2 or start == 0) then + if size == 192 and start >= 4 then + return 192, start - 4 + elseif size == 188 then + return 188, start + end + end + end + end + end + return 0, 0 +end + +function Ts.sniff(r: Bytes.Reader): number + local s, off = packetSize(r) + if s == 0 then + return 0 + end + if off > 0 then + return 0.6 + end + return if r:remaining() >= 3 * s then 0.9 else 0.5 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- the 188-byte packets of an M2TS file (192-byte packets: drop the 4-byte timestamps) +local function strip192(b: buffer, base: number, limit: number): buffer + local n = (limit - base) // 192 + local out = buffer.create(n * 188) + for i = 0, n - 1 do + buffer.copy(out, i * 188, b, base + i * 192 + 4, 188) + end + return out +end + +local function mpegAudioCodec(u: any): string + local d: buffer = u.data + for i = 0, math.min(buffer.len(d), 4096) - 2 do + if buffer.readu8(d, i) == 0xFF and buffer.readu8(d, i + 1) >= 0xE0 then + local layer = (buffer.readu8(d, i + 1) // 2) % 4 + return if layer == 1 then "mp3" elseif layer == 3 then "mp1" else "mp2" + end + end + return "mp2" +end + +-- demux(r, opts?) -> the Demuxer | nil, Err +function Ts.demux(r: Bytes.Reader, _opts: OpenOptions?): (any, Err.Err?) + local size, off = packetSize(r) + if size == 0 then + return nil, Err.new(Err.CORRUPT, "no transport stream sync", r.base) + end + local d = MpegTs.new() + if size == 192 then + local b = strip192(r.buf, r.base + off, r.limit) + d:push(b, 0, buffer.len(b)) + else + d:push(r.buf, r.base + off, r.limit - r.base - off) + end + d:flush() + local units = {} + while true do + local u = d:pull() + if u == nil then + break + end + table.insert(units, u) + end + if #units == 0 then + return nil, Err.new(Err.CORRUPT, "no PES units") + end + -- tracks: the PMT's streams, then PIDs found without one + local tracks: { Types.Track } = {} + local byPid: { [number]: any } = {} + local function track(pid: number, kind: string, codec: string, st: number, lang: string?): any + local t = byPid[pid] + if t then + return t + end + t = { + id = pid, + kind = if kind == "other" then "data" else kind, + codec = CODEC[codec] or codec, + codecTag = string.format("0x%02x", st), + timescale = 90000, + language = lang, + streamType = st, + } + byPid[pid] = t + table.insert(tracks, t) + return t + end + for _, s in d.streams do + track(s.pid, s.kind, s.codec, s.streamType, s.language) + end + for _, u in units do + track(u.pid, u.kind, u.codec, u.streamType, nil) + end + -- codec details from the first unit + local seen: { [number]: boolean } = {} + for _, u in units do + local t = byPid[u.pid] + if not seen[u.pid] then + seen[u.pid] = true + if t.codec == "unknown" or t.kind == "data" then + -- a private / unknown stream type: go by the PES stream id and the payload + local sid = u.streamId or 0 + if sid >= 0xE0 and sid <= 0xEF then + t.kind = "video" + local info = MpegEs.info(u.data, 0, buffer.len(u.data)) + t.codec = if info then (if info.mpeg2 then "mpeg2" else "mpeg1") elseif MpegEs.findStart(u.data, 0, math.min(buffer.len(u.data), 8)) then "h264" else "unknown" + elseif sid >= 0xC0 and sid <= 0xDF then + t.kind, t.codec = "audio", "mp2" + end + end + if t.codec == "mpeg1" or t.codec == "mpeg2" then + local info = MpegEs.info(u.data, 0, buffer.len(u.data)) + if info then + t.codec = if info.mpeg2 then "mpeg2" else "mpeg1" + t.width, t.height, t.frameRate = info.width, info.height, info.frameRate + end + elseif t.codec == "mp2" then + t.codec = mpegAudioCodec(u) + elseif t.codec == "aac" then + t.adts = true + local b: buffer = u.data + if buffer.len(b) >= 4 and buffer.readu8(b, 0) == 0xFF then + local rates = { 96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350 } + t.sampleRate = rates[(buffer.readu8(b, 2) // 4) % 16 + 1] + t.channels = (buffer.readu8(b, 2) % 2) * 4 + buffer.readu8(b, 3) // 64 + end + end + end + end + local dmx = Demux.new("mpegts", tracks, r.buf, { stats = d.stats }) + local lastPts: { [number]: number } = {} + for _, u in units do + local t = byPid[u.pid] + local pts = u.pts90 or u.dts90 + if pts == nil then + local prev = lastPts[u.pid] + if prev and t.frameRate and t.frameRate > 0 then + pts = prev + 90000 / t.frameRate + else + pts = prev + end + end + if pts ~= nil then + lastPts[u.pid] = pts + local key = true + local data: buffer = u.data + if t.kind == "video" then + if t.codec == "mpeg1" or t.codec == "mpeg2" then + key = MpegEs.pictureType(data, 0, buffer.len(data)) == 1 + elseif t.codec == "h264" then + key = u.randomAccess or MpegEs.h264Key(data, 0, buffer.len(data)) + else + key = u.randomAccess + end + end + dmx:addData(u.pid, pts, u.dts90 or pts, nil, key, data) + end + end + dmx:finish() + return dmx, nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts?) -> a VideoDecoder | nil, Err +function Ts.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?) + local dmx, err = Ts.demux(r, opts) + if not dmx then + return nil, err + end + return Video.open(dmx, opts) +end + +return Ts diff --git a/tests/video/_common.luau b/tests/video/_common.luau index 58cc21e..8141804 100644 --- a/tests/video/_common.luau +++ b/tests/video/_common.luau @@ -41,45 +41,48 @@ function C.snr(ours: buffer, ref: string, n: number): number return 10 * math.log10(sig / err) end --- packets(t, dmx, c, opts): every packet (file order) against ffprobe's: track, time, size, keyframe, CRC +-- packets(t, dmx, c, label, opts?): every track's packets against ffprobe's (in order): size, CRC, time, keyframe. +-- opts.skipStream(ffprobePacket, track) -> true skips a stream (ffmpeg's parsers re-split some, e.g. MPEG audio in TS) function C.packets(t: any, dmx: any, c: any, label: string, opts: any?) local o = opts or {} local trackOf = {} -- ffprobe stream index -> our track for i, s in c.streams do trackOf[s.index] = o.trackFor and o.trackFor(dmx, s) or dmx.tracks[i] end - dmx:rewind() - local k, bad = 0, 0 + local k: { [number]: number } = {} + local total, bad = 0, 0 local first = nil for _, want in c.packets do local tr = trackOf[want.stream] if not (o.skipStream and o.skipStream(want, tr)) then - local p = dmx:read() - k += 1 - if not p then - t:check(false, label .. ": packet " .. k .. " missing") - return - end - local ok = tr ~= nil and p.track == tr.id and buffer.len(p.data) == want.size and Crc32.of(p.data) == want.crc + total += 1 + local id = if tr then tr.id else -1 + k[id] = (k[id] or 0) + 1 + local p = if tr then dmx:get(id, k[id]) else nil + local ok = p ~= nil and buffer.len(p.data) == want.size and Crc32.of(p.data) == want.crc local s = c.streams[want.stream + 1] - if ok and want.pts and s and not o.noPts then + if ok and p and want.pts and s and not o.noPts then local ours = p.pts / tr.timescale - (tr.codecDelay or 0) -- ffmpeg shifts by Matroska's CodecDelay local theirs = want.pts * s.tbn / s.tbd ok = math.abs(ours - theirs) < 0.0015 end - if ok and not o.noKey and tr and tr.kind == "video" then + if ok and p and not o.noKey and tr and tr.kind == "video" then ok = p.keyframe == want.key end if not ok then bad += 1 if not first then - first = string.format("packet %d: track %s/%s size %d/%d pts %s/%s key %s/%s crc %s", k, tostring(p.track), tostring(tr and tr.id), buffer.len(p.data), want.size, tostring(p.pts), tostring(want.pts), tostring(p.keyframe), tostring(want.key), tostring(Crc32.of(p.data) == want.crc)) + first = string.format("track %s packet %d: size %s/%d pts %s/%s key %s/%s crc %s", tostring(id), k[id], tostring(p and buffer.len(p.data)), want.size, tostring(p and p.pts), tostring(want.pts), tostring(p and p.keyframe), tostring(want.key), tostring(p and Crc32.of(p.data) == want.crc)) end end end end - t:check(bad == 0, label .. ": " .. k .. " packets equal ffprobe's (" .. bad .. " differ" .. (if first then "; first: " .. first else "") .. ")") - t:check(dmx:read() == nil, label .. ": no extra packets") + local extra = 0 + for id, n in k do + extra += math.max(0, dmx:count(id) - n) + end + t:check(bad == 0, label .. ": " .. total .. " packets equal ffprobe's (" .. bad .. " differ" .. (if first then "; first: " .. first else "") .. ")") + t:check(extra == 0, label .. ": no extra packets (" .. extra .. ")") end -- frames(t, v, c, label): every decoded frame against ffmpeg's (CRC for EXACT codecs, else PSNR of the raw ones) diff --git a/tests/video/mpegps.luau b/tests/video/mpegps.luau new file mode 100644 index 0000000..2a4317b --- /dev/null +++ b/tests/video/mpegps.luau @@ -0,0 +1,48 @@ +-- video/mpegps tests: program streams from ffmpeg (MPEG-1 system stream, B-frames, MPEG-2 PS / VOB packs, a raw .m1v +-- elementary stream): tracks, picture packets (count and timestamps against ffmpeg's frames), frames against ffmpeg +-- (PSNR) once an MPEG-1 decoder is registered, audio through the api hook (SNR), seeking, fuzz. Fixtures: +-- tools/fixtures/mpegts.py. +local T = require("@tests/T") +local C = require("@tests/video/_common") +local Ps = require("@formats/video/mpegps") +local Bytes = require("@formats/core/Bytes") +local Fx = require("@tests/gen/mpegps_cases") + +local t = T.suite("mpegps") +t:eq(Ps.name, "mpegps", "name") + +for _, c in Fx do + local label = c.name + t:check(Ps.sniff(Bytes.reader(buffer.fromstring(c.data))) > 0, label .. ": sniff") + local v, err = C.open(c.data) + t:check(v ~= nil, label .. ": open " .. tostring(err)) + if v then + local dmx = v.demuxer + local vt = dmx:track("video") + t:check(vt ~= nil and vt.codec == "mpeg1", label .. ": an MPEG-1 video track") + t:eq(dmx:count(vt.id), #c.frames, label .. ": one packet per picture") + -- presentation times: one per frame slot + local seen, ok = {}, true + for k = 1, dmx:count(vt.id) do + local pts = dmx:info(vt.id, k) + local slot = math.floor((pts - dmx:info(vt.id, 1)) / 3600 + 0.5) + if seen[slot] then + ok = false + end + seen[slot] = true + end + t:check(ok, label .. ": distinct presentation times") + C.frames(t, v, c, label, 36) + if dmx:track("audio") then + C.audio(t, v, c, label, false, 30) + end + C.seek(t, v, c, label, 0.5) + end +end + +local samples = {} +for _, c in Fx do + table.insert(samples, string.sub(c.data, 1, 30000)) +end +t:fuzz("open", C.fuzzOpen(Ps), samples, { mutations = 6, garbage = 100 }) +t:done() diff --git a/tests/video/mpegts.luau b/tests/video/mpegts.luau new file mode 100644 index 0000000..534f154 --- /dev/null +++ b/tests/video/mpegts.luau @@ -0,0 +1,64 @@ +-- video/mpegts tests: transport streams from ffmpeg (MPEG-1 + MP2, B-frames, H.264 + AAC, M2TS, garbage before the +-- first packet, a truncated file): tracks and the video packets against ffprobe (time, size, CRC, keyframe), frames +-- against ffmpeg (PSNR) once an MPEG-1 decoder is registered, audio through the api hook (SNR), seeking, fuzz. +-- Fixtures: tools/fixtures/mpegts.py. +local T = require("@tests/T") +local C = require("@tests/video/_common") +local Ts = require("@formats/video/mpegts") +local Bytes = require("@formats/core/Bytes") +local Fx = require("@tests/gen/mpegts_cases") + +local t = T.suite("mpegts") +t:eq(Ts.name, "mpegts", "name") + +local byName = {} +for _, c in Fx do + byName[c.name] = c +end + +local function audioStream(want: any, tr: any): boolean + return tr == nil or tr.kind ~= "video" -- ffmpeg's parser re-splits PES audio into frames +end + +for _, c in Fx do + local label = c.name + local v, err = C.open(c.data) + if c.truncated then + t:check(v ~= nil or err ~= nil, label .. ": opens or fails cleanly") + else + t:check(Ts.sniff(Bytes.reader(buffer.fromstring(c.data))) > 0 or label == "garbage.ts", label .. ": sniff") + t:check(v ~= nil, label .. ": open " .. tostring(err)) + if v then + local dmx = v.demuxer + t:eq(#dmx.tracks, #c.streams, label .. ": track count") + for i, s in c.streams do + local tr = dmx.tracks[i] + t:check(tr ~= nil and tr.kind == s.kind, label .. ": track " .. i .. " kind") + if tr and s.width and tr.width then -- (H.264 sizes come from its SPS, read by the codec) + t:check(tr.width == s.width and tr.height == s.height, label .. ": track " .. i .. " size") + end + end + if c.packets then + C.packets(t, dmx, c, label, { skipStream = audioStream }) + end + C.frames(t, v, c, label, 36) + if dmx:track("audio") then + C.audio(t, v, c, label, false, 30) + end + C.seek(t, v, c, label, 0.5) + end + end +end +do + local v = C.open(byName["mpeg1_mp2.ts"].data) + t:eq(v.codec, "mpeg1", "stream type 0x02 without a sequence extension is MPEG-1") + t:eq(v.demuxer.tracks[2].codec, "mp2", "MPEG audio layer II") + t:eq(C.open(byName["h264_aac.ts"].data).codec, "h264", "H.264 track") +end + +local samples = {} +for _, n in { "mpeg1_mp2.ts", "bframes.ts", "h264_aac.ts" } do + table.insert(samples, string.sub(byName[n].data, 1, 188 * 120)) +end +t:fuzz("open", C.fuzzOpen(Ts), samples, { mutations = 6, garbage = 100 }) +t:done() diff --git a/tools/fixtures/mpegts.py b/tools/fixtures/mpegts.py new file mode 100644 index 0000000..ad3841e --- /dev/null +++ b/tools/fixtures/mpegts.py @@ -0,0 +1,59 @@ +# MPEG-TS / PS fixtures (tools/fixtures.py): transport streams (MPEG-1 + MP2 as bugtv plays them, with B-frames, +# H.264 + AAC, M2TS 192-byte packets, garbage before the first packet) and program streams (MPEG-1 system stream, +# MPEG-2 PS / VOB layout, B-frames, a raw .m1v elementary stream), made by ffmpeg. For each file: ffprobe's streams +# and packets, ffmpeg's frames (CRC-32 of yuv420p; the first frames raw) and audio (f32). +# tests/gen/mpegts_cases.luau, tests/gen/mpegps_cases.luau +import importlib.util, os, tempfile + +_spec = importlib.util.spec_from_file_location("_video_helpers", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_video.py")) +V = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(V) + +INPUTS = ["tools/fixtures/_video.py"] + +SRC = ["-f", "lavfi", "-i", "testsrc2=size=160x120:rate=25"] +AUD = ["-f", "lavfi", "-i", "sine=frequency=440:sample_rate=44100"] + + +def case(tmp, name, raw_frames=3, pcm_frames=8192, packets=True): + path = os.path.join(tmp, name) + c = {"name": name, "data": open(path, "rb").read(), "streams": V.streams(path)} + if packets: + c["packets"] = V.packets(path) + vs = [s for s in c["streams"] if s["kind"] == "video"] + if vs: + frames = V.yuv_frames(path, vs[0]["width"], vs[0]["height"]) + c["frames"] = [V.crc(f) for f in frames] + c["yuv"] = frames[:raw_frames] + if any(s["kind"] == "audio" for s in c["streams"]): + pcm = V.pcm_f32(path) + c["pcm"] = pcm[:pcm_frames * 4] + c["pcmBytes"] = len(pcm) + return c + + +def generate(ctx): + tmp = tempfile.mkdtemp(prefix="mpegfx_") + ff = lambda *a: V.ffmpeg(list(a), cwd=tmp) + ff(*SRC, *AUD, "-t", "1", "-c:v", "mpeg1video", "-b:v", "600k", "-bf", "0", "-c:a", "mp2", "-b:a", "128k", + "-f", "mpegts", "mpeg1_mp2.ts") + ff(*SRC, *AUD, "-t", "1", "-c:v", "mpeg1video", "-b:v", "600k", "-bf", "2", "-c:a", "mp2", "-f", "mpegts", + "bframes.ts") + ff(*SRC, *AUD, "-t", "1", "-c:v", "libx264", "-preset", "veryfast", "-g", "10", "-c:a", "aac", "-b:a", "96k", + "-f", "mpegts", "h264_aac.ts") + ff(*SRC, "-t", "1", "-c:v", "mpeg1video", "-b:v", "600k", "-f", "mpegts", "-mpegts_m2ts_mode", "1", "m2ts.m2ts") + open(os.path.join(tmp, "garbage.ts"), "wb").write(bytes(ctx.rng(3).randrange(256) for _ in range(333)).replace(b"G", b"g") + + open(os.path.join(tmp, "mpeg1_mp2.ts"), "rb").read()) + ts = [case(tmp, "mpeg1_mp2.ts"), case(tmp, "bframes.ts"), case(tmp, "h264_aac.ts"), case(tmp, "m2ts.m2ts"), + case(tmp, "garbage.ts", packets=False)] + full = ts[0]["data"] + ts.append({"name": "truncated.ts", "data": full[: len(full) // 2 + 77], "truncated": True}) + ctx.emit("mpegts_cases", ts) + + ff(*SRC, *AUD, "-t", "1", "-c:v", "mpeg1video", "-b:v", "600k", "-bf", "0", "-c:a", "mp2", "-f", "mpeg", "system.mpg") + ff(*SRC, *AUD, "-t", "1", "-c:v", "mpeg1video", "-b:v", "600k", "-bf", "2", "-c:a", "mp2", "-f", "mpeg", + "bframes.mpg") + ff(*SRC, *AUD, "-t", "1", "-c:v", "mpeg1video", "-b:v", "600k", "-c:a", "mp2", "-f", "vob", "mpeg2ps.vob") + ff(*SRC, "-t", "1", "-c:v", "mpeg1video", "-b:v", "600k", "-bf", "2", "-f", "mpeg1video", "es.m1v") + ps = [case(tmp, n, packets=False) for n in ("system.mpg", "bframes.mpg", "mpeg2ps.vob", "es.m1v")] + ctx.emit("mpegps_cases", ps)