ws-h264: merge ws/video; codecs/Video registers h264 (avc1/avc3/H264/... FourCCs, V_MPEG4/ISO/AVC) via H264.newVideoDecoder; video/h264 raw Annex B format (demux by access unit, copy-writer from MP4/MKV samples); MMCO 5 resets frame_num (JVT MR2/MR4/MR5); meta.yuv from the VUI

This commit is contained in:
4DBug committed 2026-10-31 10:29:56 -05:00
commit d4486dccce
211 files changed
+43039 -552

No files matched your search

+299
View File
@@ -0,0 +1,299 @@
--!strict
-- video/avi: AVI (Microsoft RIFF AVI 1.0, OpenDML 1.02). New in formats-luau, on containers/Avi.
-- Read: open() indexes every stream (OpenDML super / standard indexes, else idx1, else a movi scan; RIFF AVIX pieces
-- of files over 1 GB) and returns a VideoDecoder: video through the codecs/Video registry by FourCC (MJPEG, MPEG-1,
-- uncompressed BI_RGB 24 / 32-bit bottom-up or top-down, I420 / YV12; H.264 and others when a decoder is
-- registered), audio through the api's opts.openAudio hook (PCM, A-law / mu-law, IMA / MS ADPCM with its WAVEFORMATEX,
-- MP3 / MP2, AAC). Dropped frames (empty video chunks) keep their time slot. Avi.demux(r) gives the Demuxer.
-- Write: MJPEG video (copied from an MJPEG source, else every frame encoded; variable frame delays such as a GIF's
-- become a constant rate with repeated frames) plus PCM s16 audio, AVI 1.0 with idx1 and an odml / dmlh header.
-- Not supported: writing files over 1 GB (no AVIX pieces), palette changes (##pc chunks are skipped), text streams.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Avi = require("@formats/containers/Avi")
local Demux = require("@formats/containers/Demux")
local Video = require("@formats/codecs/Video")
local Source = require("@formats/codecs/Video/Source")
-- ------------------------------------------------------------------------------------------------ contract
local AviFormat = {
name = "avi",
category = "video",
extensions = { "avi" },
mime = { "video/x-msvideo", "video/avi" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Avi", "containers/Demux", "codecs/Video", "codecs/Video/Source" },
caps = { decode = true, encode = true, streaming = true, video = { "mjpeg", "mpeg1", "rawvideo" }, audio = true, odml = true },
}
-- ------------------------------------------------------------------------------------------------ types
export type OpenOptions = {
rgba: boolean?, -- nextFrame returns rgba8 (default false: the codec's native yuv420p; BI_RGB gives rgba8)
track: number?, -- the video track (stream index + 1) to decode
audio: boolean?, -- false: do not open the audio track
maxPixels: number?,
openAudio: any?, -- set by the api
}
export type EncodeOptions = {
quality: number?, -- MJPEG quality 1..100 (default 90)
reencode: boolean?, -- encode the frames even when the source is MJPEG
audio: boolean?, -- false: no audio (default: PCM s16 from the source's audio, when it has one)
video: boolean?,
maxFps: number?, -- the highest frame rate variable delays may need (default 100)
}
-- ------------------------------------------------------------------------------------------------ constants
-- WAVEFORMATEX wFormatTag -> codec id
local AUDIO_TAGS: { [number]: string } = {
[0x0001] = "pcm",
[0x0002] = "adpcm_ms",
[0x0003] = "pcm_f",
[0x0006] = "pcm_alaw",
[0x0007] = "pcm_mulaw",
[0x0011] = "adpcm_ima_wav",
[0x0050] = "mp2",
[0x0055] = "mp3",
[0x00FF] = "aac",
[0x1610] = "aac",
[0x706D] = "aac",
[0x2000] = "ac3",
[0x2001] = "dts",
[0xF1AC] = "flac",
}
-- ------------------------------------------------------------------------------------------------ sniff
function AviFormat.sniff(r: Bytes.Reader): number
if r:peek(4) == "RIFF" and r:peek(4, 8) == "AVI " then
return 1
end
return 0
end
-- ------------------------------------------------------------------------------------------------ decode
local function videoTrack(s: Avi.Stream, id: number): Types.Track
local f = s.strf
local t: any = {
id = id,
kind = "video",
codec = "",
codecTag = s.handler,
timescale = if s.scale > 0 then s.rate / s.scale else 25,
frameRate = if s.scale > 0 then s.rate / s.scale else 0,
default = true,
name = s.name,
frames = s.length,
}
if buffer.len(f) >= 40 then
local w = buffer.readi32(f, 4)
local h = buffer.readi32(f, 8)
local bits = buffer.readu16(f, 14)
local comp = buffer.readstring(f, 16, 4)
t.width = math.abs(w)
t.height = math.abs(h)
t.codecTag = comp
t.bitsPerPixel = bits
if comp == "\0\0\0\0" or comp == "DIB " or comp == "RGB " then
t.codec = "rawvideo"
t.pixelFormat = if bits == 32 then "bgra" else "bgr24"
t.flip = h > 0
t.stride = ((math.abs(w) * bits + 31) // 32) * 4
if bits ~= 24 and bits ~= 32 then
t.codec = "rawvideo_" .. bits
end
else
t.codec = Video.fromFourcc(comp) or Video.fromFourcc(s.handler) or string.lower((string.gsub(comp, "%z", "")))
if comp == "YV12" then
t.pixelFormat = "yv12"
elseif t.codec == "rawvideo" then
t.pixelFormat = "yuv420p"
end
end
local size = buffer.readu32(f, 0)
if size > 40 and buffer.len(f) > 40 then
local c = buffer.create(buffer.len(f) - 40)
buffer.copy(c, 0, f, 40)
t.config = c
end
else
t.codec = Video.fromFourcc(s.handler) or string.lower(s.handler)
local fr = s.frame
t.width, t.height = fr[3] - fr[1], fr[4] - fr[2]
end
return t
end
local function audioTrack(s: Avi.Stream, id: number): Types.Track
local f = s.strf
local t: any = {
id = id,
kind = "audio",
codec = "unknown",
codecTag = s.handler,
timescale = if s.scale > 0 then s.rate / s.scale else 1,
default = true,
name = s.name,
waveFormat = f,
}
if buffer.len(f) >= 16 then
local tag = buffer.readu16(f, 0)
t.channels = buffer.readu16(f, 2)
t.sampleRate = buffer.readu32(f, 4)
t.blockAlign = buffer.readu16(f, 12)
local bits = buffer.readu16(f, 14)
t.bitsPerSample = bits
if tag == 0xFFFE and buffer.len(f) >= 26 then
tag = buffer.readu16(f, 24) -- WAVE_FORMAT_EXTENSIBLE: the sub-format GUID's tag
end
t.formatTag = tag
local c = AUDIO_TAGS[tag] or string.format("wav_0x%04x", tag)
if c == "pcm" then
c = if bits == 8 then "pcm_u8" else "pcm_s" .. bits .. "le"
elseif c == "pcm_f" then
c = "pcm_f" .. bits .. "le"
end
t.codec = c
if buffer.len(f) >= 18 then
local cb = buffer.readu16(f, 16)
if cb > 0 and 18 + cb <= buffer.len(f) and c ~= "mp3" then
local cfg = buffer.create(cb)
buffer.copy(cfg, 0, f, 18, cb)
t.config = cfg
end
end
end
return t
end
-- demux(r, opts?) -> the Demuxer | nil, Err
function AviFormat.demux(r: Bytes.Reader, _opts: OpenOptions?): (any, Err.Err?)
local ok, file, err = pcall(Avi.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 } = {}
local streams: { { any } } = {}
for i, s in file.streams do
local t: Types.Track? = nil
if s.type == "vids" then
t = videoTrack(s, i)
elseif s.type == "auds" then
t = audioTrack(s, i)
elseif s.type == "txts" then
t = { id = i, kind = "subtitle", codec = "text", timescale = if s.scale > 0 then s.rate / s.scale else 1 }
end
if t then
table.insert(tracks, t)
table.insert(streams, { s, t })
end
end
local meta = { info = file.info, index = file.index, odml = file.odml ~= nil }
local dmx = Demux.new("avi", tracks, r.buf, meta)
-- packets in file order across streams: merge by offset
local items: { { number } } = {}
for k, st in streams do
local s: Avi.Stream, t: any = st[1], st[2]
local tick = s.start
for _, c in s.chunks do
local dur = if s.sampleSize > 0 then c.size / s.sampleSize else 1
if t.kind == "audio" and s.sampleSize == 0 and (t.blockAlign or 0) > 0 and t.codec:sub(1, 3) == "pcm" then
dur = c.size / t.blockAlign
end
if c.size > 0 then
table.insert(items, { c.offset, k, tick, dur, if c.key then 1 else 0, c.size })
tick += dur
elseif t.kind == "video" then
tick += 1 -- an empty video chunk: a dropped frame keeps its slot (empty audio chunks are padding)
end
end
end
table.sort(items, function(a: { number }, b: { number }): boolean
return a[1] < b[1]
end)
for _, it in items do
local t: any = streams[it[2]][2]
dmx:add(t.id, it[3], nil, it[4], it[5] == 1 or t.kind ~= "video" or t.codec == "mjpeg" or t.codec == "rawvideo", it[1], it[6])
end
dmx:finish()
return dmx, nil
end
-- ------------------------------------------------------------------------------------------------ encode
-- encode(video, opts?) -> buffer | nil, Err
function AviFormat.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
local o: any = table.clone(opts or {})
o.quality = o.quality or 90
local streams, err = Source.streams(value, o, {
video = { copy = { mjpeg = true }, encode = "mjpeg" },
audio = { copy = { pcm_s16le = true, pcm_u8 = true }, pcm = true },
})
if not streams then
return nil, err
end
local wstreams: { Avi.WStream } = {}
local width, height, usPerFrame = 0, 0, 0
local frameDur = 0
for _, s in streams do
if s.kind == "video" then
-- a constant frame rate: the shortest frame duration (variable delays repeat frames)
local num, den, packets = Source.constantRate(s, o.maxFps)
s.packets = packets
frameDur = den / num
width, height = s.width or 0, s.height or 0
usPerFrame = 1e6 * frameDur
local bih = Bytes.writer(40)
bih:u32le(40)
bih:u32le(width)
bih:u32le(height)
bih:u16le(1)
bih:u16le(24)
bih:string("MJPG")
bih:u32le(width * height * 3)
bih:u32le(0)
bih:u32le(0)
bih:u32le(0)
bih:u32le(0)
table.insert(wstreams, { type = "vids", handler = "MJPG", scale = den, rate = num, sampleSize = 0, strf = bih:finish(), width = width, height = height, ckid = "dc" })
else
local ch = s.channels or 1
local bits = if s.codec == "pcm_u8" then 8 else 16
local align = ch * bits // 8
local rate = math.floor((s.sampleRate or 44100) + 0.5)
local wf = Bytes.writer(18)
wf:u16le(1)
wf:u16le(ch)
wf:u32le(rate)
wf:u32le(rate * align)
wf:u16le(align)
wf:u16le(bits)
wf:u16le(0)
table.insert(wstreams, { type = "auds", handler = "\0\0\0\0", scale = align, rate = rate * align, sampleSize = align, strf = wf:finish(), ckid = "wb" })
end
end
-- chunks in time order (the video packets already repeated to the constant rate)
local chunks: { { any } } = {}
for _, item in Source.interleave(streams) do
table.insert(chunks, { item[1], item[2].data, true })
end
local ok, buf = pcall(Avi.write, { streams = wstreams, microSecPerFrame = usPerFrame, width = width, height = height }, chunks)
if not ok then
return nil, Err.new(Err.ARG, "internal error: " .. tostring(buf))
end
return buf, nil
end
-- ------------------------------------------------------------------------------------------------ open
-- open(r, opts?) -> a VideoDecoder | nil, Err
function AviFormat.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?)
local dmx, err = AviFormat.demux(r, opts)
if not dmx then
return nil, err
end
return Video.open(dmx, opts)
end
return AviFormat
+145
View File
@@ -0,0 +1,145 @@
--!strict
-- video/h264: raw H.264 / AVC elementary streams (ITU-T H.264 Annex B byte stream: .h264 / .264 files, x264 / ffmpeg
-- `-f h264` output, the JVT conformance bitstreams). New in formats-luau.
-- Read: the stream cut into access units (codecs/H264.accessUnits) as a one-track Demuxer; open() returns a
-- VideoDecoder decoding through codecs/H264 (yuv420p frames in display order, numbered in output order since a raw
-- stream has no timestamps; the frame rate comes from the SPS VUI timing, else opts.frameRate, else 25).
-- Write: H.264 tracks copied from any video (MP4 / MKV samples are converted from length-prefixed NAL units to Annex B,
-- the avcC parameter sets put in front of every keyframe). Not supported: re-encoding other codecs to H.264 (there is
-- no H.264 encoder), and whatever codecs/H264 does not decode (interlaced, 4:2:2 / 4:4:4, > 8 bits: UNSUPPORTED).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Demux = require("@formats/containers/Demux")
local Video = require("@formats/codecs/Video")
local Source = require("@formats/codecs/Video/Source")
local H264 = require("@formats/codecs/H264")
-- ------------------------------------------------------------------------------------------------ contract
local Format = {
name = "h264",
category = "video",
extensions = { "h264", "264", "avc", "jsv", "26l", "jvt" },
mime = { "video/h264" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Demux", "codecs/Video", "codecs/Video/Source", "codecs/H264" },
caps = { decode = true, encode = true, streaming = true, video = { "h264" }, depths = { 8 } },
}
-- ------------------------------------------------------------------------------------------------ types
export type OpenOptions = {
rgba: boolean?, -- nextFrame returns rgba8 (default false: yuv420p)
maxPixels: number?, -- largest picture (default 2^22 luma samples)
frameRate: number?, -- frames per second when the stream has no VUI timing (default 25)
deblock: boolean?, -- false skips the deblocking filter (faster, not conformant)
}
-- ------------------------------------------------------------------------------------------------ sniff
-- a start code then an SPS / AUD / SEI / PPS NAL header (forbidden bit 0)
function Format.sniff(r: Bytes.Reader): number
local s = r:peek(5)
if not s or #s < 4 then
return 0
end
local hdr
if string.byte(s, 1) == 0 and string.byte(s, 2) == 0 and string.byte(s, 3) == 1 then
hdr = string.byte(s, 4)
elseif #s >= 5 and string.byte(s, 1) == 0 and string.byte(s, 2) == 0 and string.byte(s, 3) == 0 and string.byte(s, 4) == 1 then
hdr = string.byte(s, 5)
else
return 0
end
if hdr >= 128 then
return 0
end
local t = hdr % 32
if t == 7 then
return 0.8
elseif t == 9 or t == 6 or t == 8 then
return 0.5
elseif t == 5 then
return 0.4
end
return 0
end
-- ------------------------------------------------------------------------------------------------ decode
-- demux(r, opts?) -> the Demuxer (one video track, one packet per access unit) | nil, Err
function Format.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?)
local buf, base, limit = r.buf, r.base, r.limit
local units = H264.accessUnits(buf, base, limit - base)
if #units == 0 then
return nil, Err.new(Err.CORRUPT, "no access units (no slices after a start code)", base)
end
local info = H264.info(buffer.readstring(buf, base, math.min(limit - base, 4096))) or {}
if info.interlaced or (info.chromaFormat and info.chromaFormat ~= 1) or (info.bitDepth and info.bitDepth ~= 8) then
-- still demuxable (remuxing works); decoding reports UNSUPPORTED
info.unsupported = true
end
local fps = info.frameRate or (opts and opts.frameRate) or 25
if fps <= 0 or fps > 1000 then
fps = 25
end
local track: Types.Track = {
id = 1,
kind = "video",
codec = "h264",
timescale = fps,
width = info.width,
height = info.height,
frameRate = fps,
profile = info.profile,
level = info.level,
ptsInOutputOrder = true,
default = true,
}
local dmx = Demux.new("h264", { track }, buf, { profile = info.profile, level = info.level })
local k = 0
for i = 1, #units, 3 do
dmx:add(1, k, k, 1, units[i + 2] or k == 0, units[i], units[i + 1])
k += 1
end
track.frames = k
dmx:finish()
return dmx, nil
end
-- ------------------------------------------------------------------------------------------------ encode
-- encode(video, opts?) -> an Annex B buffer of the source's H.264 track | nil, Err (UNSUPPORTED for other codecs)
function Format.encode(value: any, _opts: any?): (buffer?, Err.Err?)
local streams, err = Source.streams(value, { audio = false }, { video = { copy = { h264 = true } } })
if not streams then
return nil, err
end
local s = streams[1]
if not s or s.codec ~= "h264" then
return nil, Err.new(Err.UNSUPPORTED, "only H.264 tracks can be written as a raw H.264 stream")
end
local parts = {}
for i, p in s.packets do
local data = p.data
if s.config then
local key = i == 1 or p.keyframe
local out, e = H264.toAnnexB(if key then s.config else nil, data)
if not out then
return nil, e
end
data = out
end
table.insert(parts, buffer.tostring(data))
end
return buffer.fromstring(table.concat(parts)), nil
end
-- ------------------------------------------------------------------------------------------------ open
-- open(r, opts?) -> a VideoDecoder | nil, Err
function Format.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?)
local dmx, err = Format.demux(r, opts)
if not dmx then
return nil, err
end
return Video.open(dmx, opts)
end
return Format
+285
View File
@@ -0,0 +1,285 @@
--!strict
-- video/mkv/Mux: the Matroska / WebM muxer: EBML header, Segment with SeekHead, Info (1 ms TimecodeScale, Duration),
-- Tracks (CodecPrivate, DefaultDuration, Video / Audio settings, Opus CodecDelay / SeekPreRoll), Clusters of
-- SimpleBlocks (a new cluster at a video keyframe once the current one spans 2 s, and before the 16-bit relative
-- timestamp would overflow), and Cues (one CuePoint per cluster, on the video track when there is one). Streams come
-- from codecs/Video/Source (copied packets or encoded frames). Interpreted; never throws.
local Err = require("@formats/core/Err")
local Ebml = require("@formats/containers/Ebml")
local Video = require("@formats/codecs/Video")
local Source = require("@formats/codecs/Video/Source")
local Parse = require("@formats/video/mkv/Parse")
local ID = Parse.ID
local Mux = {}
local AUDIO_IDS: { [string]: string } = {
vorbis = "A_VORBIS",
opus = "A_OPUS",
flac = "A_FLAC",
mp3 = "A_MPEG/L3",
mp2 = "A_MPEG/L2",
mp1 = "A_MPEG/L1",
aac = "A_AAC",
ac3 = "A_AC3",
eac3 = "A_EAC3",
alac = "A_ALAC",
pcm_u8 = "A_PCM/INT/LIT",
pcm_s16le = "A_PCM/INT/LIT",
pcm_s24le = "A_PCM/INT/LIT",
pcm_s32le = "A_PCM/INT/LIT",
pcm_s16be = "A_PCM/INT/BIG",
pcm_s24be = "A_PCM/INT/BIG",
pcm_s32be = "A_PCM/INT/BIG",
pcm_f32le = "A_PCM/FLOAT/IEEE",
pcm_f64le = "A_PCM/FLOAT/IEEE",
}
Mux.AUDIO_IDS = AUDIO_IDS
-- codecId(stream) -> the Matroska CodecID | nil
function Mux.codecId(kind: string, codec: string): string?
if kind == "video" then
local e = Video.entry(codec)
local m = e and e.matroska
return m and m[1]
end
return AUDIO_IDS[codec]
end
local function pcmBits(codec: string): number?
local b = string.match(codec, "^pcm_[suf](%d+)")
if b then
return tonumber(b)
end
if codec == "pcm_u8" then
return 8
end
return nil
end
export type Options = {
webm: boolean?,
title: string?,
app: string?,
clusterSeconds: number?, -- default 2
}
-- mux(streams, opts) -> buffer | nil, Err
function Mux.mux(streams: { any }, opts: Options): (buffer?, Err.Err?)
local webm = opts.webm == true
local app = opts.app or "formats-luau"
local clusterSpan = opts.clusterSeconds or 2
-- tracks
local ids: { string } = {}
local videoIndex = 0
for i, s in streams do
local cid = Mux.codecId(s.kind, s.codec)
if not cid then
return nil, Err.new(Err.UNSUPPORTED, "no Matroska CodecID for " .. s.kind .. " codec " .. s.codec)
end
ids[i] = cid
if s.kind == "video" and videoIndex == 0 then
videoIndex = i
end
end
local order = Source.interleave(streams)
local duration = 0
for _, s in streams do
for _, p in s.packets do
local e = p.pts + (p.duration or 0)
if e > duration then
duration = e
end
end
end
-- segment body: Info, Tracks, Clusters, Cues (the SeekHead goes in front once their offsets are known)
local body = Ebml.writer(65536)
local infoAt = body:tell()
local info = body:open(ID.Info)
body:uint(ID.TimecodeScale, 1000000)
body:string(ID.MuxingApp, app)
body:string(ID.WritingApp, app)
if opts.title then
body:string(ID.Title, opts.title)
end
body:float(ID.Duration, duration * 1000)
body:close(info)
local tracksAt = body:tell()
local tracks = body:open(ID.Tracks)
for i, s in streams do
local te = body:open(ID.TrackEntry)
body:uint(ID.TrackNumber, i)
body:uint(ID.TrackUID, i)
body:uint(ID.TrackType, if s.kind == "video" then 1 else 2)
body:uint(ID.FlagLacing, 0)
body:string(ID.Language, "und")
body:string(ID.CodecID, ids[i])
if s.config and buffer.len(s.config) > 0 then
body:binary(ID.CodecPrivate, s.config)
end
if s.kind == "video" then
if s.frameRate and s.frameRate > 0 then
body:uint(ID.DefaultDuration, math.floor(1e9 / s.frameRate + 0.5))
end
local v = body:open(ID.Video)
body:uint(ID.PixelWidth, s.width or 0)
body:uint(ID.PixelHeight, s.height or 0)
body:close(v)
else
if s.codec == "opus" then
local pre = 0
local c = s.config
if c and buffer.len(c) >= 12 then
pre = buffer.readu16(c, 10)
end
body:uint(ID.CodecDelay, math.floor(pre * 1e9 / 48000 + 0.5))
body:uint(ID.SeekPreRoll, 80000000)
end
local a = body:open(ID.Audio)
body:float(ID.SamplingFrequency, s.sampleRate or 48000)
body:uint(ID.Channels, s.channels or 1)
local bits = pcmBits(s.codec) or s.bitsPerSample
if bits and string.sub(s.codec, 1, 4) == "pcm_" then
body:uint(ID.BitDepth, bits)
end
body:close(a)
end
body:close(te)
end
body:close(tracks)
-- clusters
local cues: { { number } } = {} -- { time ms, track, cluster offset in body }
local cl: number? = nil
local clTime = 0
local clStart = 0
for _, item in order do
local si: number, p = item[1], item[2]
local ms = math.floor(p.pts * 1000 + 0.5)
local isVideoKey = si == videoIndex and p.keyframe
local need = cl == nil
or ms - clTime > 30000
or ms < clTime
or (isVideoKey and ms - clStart >= clusterSpan * 1000)
or (videoIndex == 0 and ms - clStart >= clusterSpan * 1000)
if need then
if cl then
body:close(cl)
end
local at = body:tell()
cl = body:open(ID.Cluster)
clTime = ms
clStart = ms
body:uint(ID.Timecode, ms)
if videoIndex == 0 or isVideoKey then
table.insert(cues, { ms, if videoIndex > 0 then videoIndex else si, at })
end
end
local data: buffer = p.data
local hdr = Ebml.vintString(si, 1)
local rel = ms - clTime
local size = #hdr + 3 + buffer.len(data)
body:header(ID.SimpleBlock, size)
body:raw(hdr)
body:raw(string.char(rel // 256, rel % 256, if p.keyframe or streams[si].kind ~= "video" then 0x80 else 0))
body:rawBuffer(data)
end
if cl then
body:close(cl)
end
local cuesAt = body:tell()
if #cues > 0 then
local c = body:open(ID.Cues)
for _, q in cues do
local cp = body:open(ID.CuePoint)
body:uint(ID.CueTime, q[1])
local tp = body:open(ID.CueTrackPositions)
body:uint(ID.CueTrack, q[2])
body:uint(ID.CueClusterPosition, q[3]) -- patched below by the SeekHead length
body:close(tp)
body:close(cp)
end
body:close(c)
end
local bodyBuf = body:finish()
-- the SeekHead: its own length shifts every position, so build it until its size is stable
local function seekHead(shift: number): buffer
local w = Ebml.writer(256)
local sh = w:open(ID.SeekHead)
local entries = { { ID.Info, infoAt }, { ID.Tracks, tracksAt } }
if #cues > 0 then
table.insert(entries, { ID.Cues, cuesAt })
end
for _, e in entries do
local sk = w:open(0x4DBB)
local idv = e[1]
local bytes = {}
while idv > 0 do
table.insert(bytes, 1, idv % 256)
idv = idv // 256
end
w:header(0x53AB, #bytes)
for _, b in bytes do
w:raw(string.char(b))
end
w:uint(0x53AC, e[2] + shift)
w:close(sk)
end
w:close(sh)
return w:finish()
end
local shift = 0
local head = seekHead(0)
for _ = 1, 4 do
local n = buffer.len(head)
if n == shift then
break
end
shift = n
head = seekHead(shift)
end
shift = buffer.len(head)
-- cue cluster positions (relative to the segment data) must include the SeekHead: rewrite the Cues element
-- (its uint widths may grow, but Cues are last, so nothing after them moves)
if #cues > 0 then
local w = Ebml.writer(4096)
local c = w:open(ID.Cues)
for _, q in cues do
local cp = w:open(ID.CuePoint)
w:uint(ID.CueTime, q[1])
local tp = w:open(ID.CueTrackPositions)
w:uint(ID.CueTrack, q[2])
w:uint(ID.CueClusterPosition, q[3] + shift)
w:close(tp)
w:close(cp)
end
w:close(c)
local cuesBuf = w:finish()
local nb = buffer.create(cuesAt + buffer.len(cuesBuf))
buffer.copy(nb, 0, bodyBuf, 0, cuesAt)
buffer.copy(nb, cuesAt, cuesBuf)
bodyBuf = nb
end
-- the file
local out = Ebml.writer(buffer.len(bodyBuf) + 256)
local eb = out:open(ID.EBML)
out:uint(0x4286, 1)
out:uint(0x42F7, 1)
out:uint(0x42F2, 4)
out:uint(0x42F3, 8)
out:string(ID.DocType, if webm then "webm" else "matroska")
out:uint(0x4287, 4)
out:uint(0x4285, 2)
out:close(eb)
local seg = out:open(ID.Segment)
out:rawBuffer(head)
out:rawBuffer(bodyBuf)
out:close(seg)
return out:finish(), nil
end
return Mux
+681
View File
@@ -0,0 +1,681 @@
--!strict
-- video/mkv/Parse: the Matroska / WebM demuxer: EBML header, Segment Info / Tracks / Cues / Tags / Chapters (titles
-- only), and every Cluster into a containers/Demux packet index: SimpleBlock and BlockGroup (BlockDuration,
-- ReferenceBlock -> not a keyframe), the three lacings (Xiph, EBML, fixed), header-stripping content compression,
-- clusters of unknown size (live streams). Times: every track's timescale is 1e9 / TimecodeScale (milliseconds by
-- default). Interpreted (it only walks headers); never throws.
local Err = require("@formats/core/Err")
local Types = require("@formats/Types")
local Ebml = require("@formats/containers/Ebml")
local Demux = require("@formats/containers/Demux")
local Video = require("@formats/codecs/Video")
local Deflate = require("@formats/codecs/Deflate")
local Parse = {}
-- element IDs
local ID = {
EBML = 0x1A45DFA3,
DocType = 0x4282,
Segment = 0x18538067,
SeekHead = 0x114D9B74,
Info = 0x1549A966,
TimecodeScale = 0x2AD7B1,
Duration = 0x4489,
Title = 0x7BA9,
MuxingApp = 0x4D80,
WritingApp = 0x5741,
DateUTC = 0x4461,
Tracks = 0x1654AE6B,
TrackEntry = 0xAE,
TrackNumber = 0xD7,
TrackUID = 0x73C5,
TrackType = 0x83,
FlagEnabled = 0xB9,
FlagDefault = 0x88,
FlagForced = 0x55AA,
FlagLacing = 0x9C,
DefaultDuration = 0x23E383,
Name = 0x536E,
Language = 0x22B59C,
LanguageBCP47 = 0x22B59D,
CodecID = 0x86,
CodecPrivate = 0x63A2,
CodecDelay = 0x56AA,
SeekPreRoll = 0x56BB,
Video = 0xE0,
PixelWidth = 0xB0,
PixelHeight = 0xBA,
DisplayWidth = 0x54B0,
DisplayHeight = 0x54BA,
ColourSpace = 0x2EB524,
Audio = 0xE1,
SamplingFrequency = 0xB5,
OutputSamplingFrequency = 0x78B5,
Channels = 0x9F,
BitDepth = 0x6264,
ContentEncodings = 0x6D80,
ContentEncoding = 0x6240,
ContentEncodingType = 0x5033,
ContentEncodingScope = 0x5032,
ContentCompression = 0x5034,
ContentCompAlgo = 0x4254,
ContentCompSettings = 0x4255,
ContentEncryption = 0x5035,
Cluster = 0x1F43B675,
Timecode = 0xE7,
SimpleBlock = 0xA3,
BlockGroup = 0xA0,
Block = 0xA1,
BlockDuration = 0x9B,
ReferenceBlock = 0xFB,
DiscardPadding = 0x75A2,
Cues = 0x1C53BB6B,
CuePoint = 0xBB,
CueTime = 0xB3,
CueTrackPositions = 0xB7,
CueTrack = 0xF7,
CueClusterPosition = 0xF1,
CueRelativePosition = 0xF0,
Tags = 0x1254C367,
Tag = 0x7373,
SimpleTag = 0x67C8,
TagName = 0x45A3,
TagString = 0x4487,
Targets = 0x63C0,
Chapters = 0x1043A770,
Attachments = 0x1941A469,
Void = 0xEC,
Crc32 = 0xBF,
}
Parse.ID = ID
-- the top-level children of a Segment (an unknown-size Cluster ends where one of these starts)
local TOP: { [number]: boolean } = {
[ID.SeekHead] = true,
[ID.Info] = true,
[ID.Tracks] = true,
[ID.Cluster] = true,
[ID.Cues] = true,
[ID.Tags] = true,
[ID.Chapters] = true,
[ID.Attachments] = true,
[ID.Segment] = true,
[ID.EBML] = true,
}
-- Matroska audio / subtitle CodecIDs -> our codec ids (video ids come from the codecs/Video registry)
local AUDIO: { [string]: string } = {
A_VORBIS = "vorbis",
A_OPUS = "opus",
A_FLAC = "flac",
["A_MPEG/L3"] = "mp3",
["A_MPEG/L2"] = "mp2",
["A_MPEG/L1"] = "mp1",
A_AAC = "aac",
["A_AAC/MPEG4/LC"] = "aac",
["A_AAC/MPEG4/LC/SBR"] = "aac",
["A_AAC/MPEG2/LC"] = "aac",
A_AC3 = "ac3",
A_EAC3 = "eac3",
A_DTS = "dts",
A_ALAC = "alac",
A_TTA1 = "tta",
A_WAVPACK4 = "wavpack",
["A_MS/ACM"] = "acm",
}
local SUBS: { [string]: string } = {
["S_TEXT/UTF8"] = "text",
["S_TEXT/ASCII"] = "text",
["S_TEXT/WEBVTT"] = "webvtt",
["S_TEXT/ASS"] = "ass",
["S_TEXT/SSA"] = "ssa",
["S_ASS"] = "ass",
["S_SSA"] = "ssa",
["S_VOBSUB"] = "dvdsub",
["S_HDMV/PGS"] = "pgs",
}
-- codecFor(CodecID, bitDepth) -> our codec id
local function codecFor(id: string, kind: string, bits: number?): string
if kind == "video" then
return Video.fromMatroska(id) or string.lower((string.gsub(id, "^V_", "")))
end
if id == "A_PCM/INT/LIT" then
return if bits == 8 then "pcm_u8" else "pcm_s" .. (bits or 16) .. "le"
elseif id == "A_PCM/INT/BIG" then
return if bits == 8 then "pcm_u8" else "pcm_s" .. (bits or 16) .. "be"
elseif id == "A_PCM/FLOAT/IEEE" then
return "pcm_f" .. (bits or 32) .. "le"
end
return AUDIO[id] or SUBS[id] or string.lower((string.gsub(id, "^[AS]_", "")))
end
Parse.codecFor = codecFor
type TrackInfo = Types.Track & { strip: buffer?, lacing: boolean?, defaultDurationNs: number? }
local function parseVideo(buf: buffer, off: number, len: number, t: any)
for id, o, n in Ebml.children(buf, off, off + len) do
if id == ID.PixelWidth then
t.width = Ebml.uint(buf, o, n)
elseif id == ID.PixelHeight then
t.height = Ebml.uint(buf, o, n)
elseif id == ID.DisplayWidth then
t.displayWidth = Ebml.uint(buf, o, n)
elseif id == ID.DisplayHeight then
t.displayHeight = Ebml.uint(buf, o, n)
elseif id == ID.ColourSpace then
t.colourSpace = buffer.readstring(buf, o, math.min(n, 4))
end
end
end
local function parseAudio(buf: buffer, off: number, len: number, t: any)
for id, o, n in Ebml.children(buf, off, off + len) do
if id == ID.SamplingFrequency then
t.sampleRate = Ebml.float(buf, o, n)
elseif id == ID.OutputSamplingFrequency then
t.outputSampleRate = Ebml.float(buf, o, n)
elseif id == ID.Channels then
t.channels = Ebml.uint(buf, o, n)
elseif id == ID.BitDepth then
t.bitsPerSample = Ebml.uint(buf, o, n)
end
end
end
-- ContentEncodings: header stripping (algo 3) and zlib (algo 0) are supported; bzip / lzo compression and encryption
-- are not
local function parseEncodings(buf: buffer, off: number, len: number, t: any): string?
for id, o, n in Ebml.children(buf, off, off + len) do
if id == ID.ContentEncoding then
local etype = 0
local scope = 1
for id2, o2, n2 in Ebml.children(buf, o, o + n) do
if id2 == ID.ContentEncodingScope then
scope = Ebml.uint(buf, o2, n2)
elseif id2 == ID.ContentEncodingType then
etype = Ebml.uint(buf, o2, n2)
elseif id2 == ID.ContentCompression then
local algo, settings = 0, nil
for id3, o3, n3 in Ebml.children(buf, o2, o2 + n2) do
if id3 == ID.ContentCompAlgo then
algo = Ebml.uint(buf, o3, n3)
elseif id3 == ID.ContentCompSettings then
settings = Ebml.binary(buf, o3, n3)
end
end
if algo == 3 then
t.strip = settings
elseif algo == 0 then
t.zlib = scope -- 1: frames, 2: CodecPrivate
else
return "content compression algorithm " .. algo
end
elseif id2 == ID.ContentEncryption then
return "encrypted track"
end
end
if etype ~= 0 then
return "encrypted track"
end
end
end
return nil
end
local function parseTracks(buf: buffer, off: number, len: number, scaleNs: number): ({ TrackInfo }, { [number]: string })
local tracks: { TrackInfo } = {}
local problems: { [number]: string } = {}
for id, o, n in Ebml.children(buf, off, off + len) do
if id == ID.TrackEntry then
local t: any = { id = 0, kind = "data", codec = "", timescale = 1e9 / scaleNs, default = true, lacing = true, language = "eng" }
local ttype, codecId = 0, ""
local problem: string? = nil
for id2, o2, n2 in Ebml.children(buf, o, o + n) do
if id2 == ID.TrackNumber then
t.id = Ebml.uint(buf, o2, n2)
elseif id2 == ID.TrackUID then
t.uid = Ebml.uint(buf, o2, n2)
elseif id2 == ID.TrackType then
ttype = Ebml.uint(buf, o2, n2)
elseif id2 == ID.FlagDefault then
t.default = Ebml.uint(buf, o2, n2) ~= 0
elseif id2 == ID.FlagEnabled then
t.enabled = Ebml.uint(buf, o2, n2) ~= 0
elseif id2 == ID.FlagLacing then
t.lacing = Ebml.uint(buf, o2, n2) ~= 0
elseif id2 == ID.DefaultDuration then
t.defaultDurationNs = Ebml.uint(buf, o2, n2)
elseif id2 == ID.Name then
t.name = Ebml.string(buf, o2, n2)
elseif id2 == ID.Language then
t.language = Ebml.string(buf, o2, n2)
elseif id2 == ID.CodecID then
codecId = Ebml.string(buf, o2, n2)
elseif id2 == ID.CodecPrivate then
t.config = Ebml.binary(buf, o2, n2)
elseif id2 == ID.CodecDelay then
t.codecDelay = Ebml.uint(buf, o2, n2) / 1e9
elseif id2 == ID.SeekPreRoll then
t.seekPreRoll = Ebml.uint(buf, o2, n2) / 1e9
elseif id2 == ID.Video then
parseVideo(buf, o2, n2, t)
elseif id2 == ID.Audio then
parseAudio(buf, o2, n2, t)
elseif id2 == ID.ContentEncodings then
problem = parseEncodings(buf, o2, n2, t)
end
end
if t.zlib and bit32.band(t.zlib, 2) ~= 0 and t.config then
local c = Deflate.zlib(t.config)
if c then
t.config = c
else
problem = "bad zlib-compressed CodecPrivate"
end
end
t.kind = if ttype == 1 then "video" elseif ttype == 2 then "audio" elseif ttype == 17 then "subtitle" else "data"
t.codecTag = codecId
t.codec = codecFor(codecId, t.kind, t.bitsPerSample)
if t.kind == "audio" then
t.sampleRate = t.sampleRate or 8000
t.channels = t.channels or 1
end
if t.defaultDurationNs and t.defaultDurationNs > 0 and t.kind == "video" then
t.frameRate = 1e9 / t.defaultDurationNs
end
if t.id > 0 then
table.insert(tracks, t)
if problem then
problems[t.id] = problem
end
end
end
end
return tracks, problems
end
local function parseInfo(buf: buffer, off: number, len: number, meta: { [string]: any }): (number, number?)
local scale, duration = 1000000, nil
for id, o, n in Ebml.children(buf, off, off + len) do
if id == ID.TimecodeScale then
scale = Ebml.uint(buf, o, n)
elseif id == ID.Duration then
duration = Ebml.float(buf, o, n)
elseif id == ID.Title then
meta.title = Ebml.string(buf, o, n)
elseif id == ID.MuxingApp then
meta.muxingApp = Ebml.string(buf, o, n)
elseif id == ID.WritingApp then
meta.writingApp = Ebml.string(buf, o, n)
end
end
if scale <= 0 then
scale = 1000000
end
return scale, duration
end
local function parseCues(buf: buffer, off: number, len: number, segData: number): { { time: number, track: number, position: number } }
local cues = {}
for id, o, n in Ebml.children(buf, off, off + len) do
if id == ID.CuePoint then
local time = 0
local positions = {}
for id2, o2, n2 in Ebml.children(buf, o, o + n) do
if id2 == ID.CueTime then
time = Ebml.uint(buf, o2, n2)
elseif id2 == ID.CueTrackPositions then
local tr, pos = 0, 0
for id3, o3, n3 in Ebml.children(buf, o2, o2 + n2) do
if id3 == ID.CueTrack then
tr = Ebml.uint(buf, o3, n3)
elseif id3 == ID.CueClusterPosition then
pos = Ebml.uint(buf, o3, n3)
end
end
table.insert(positions, { tr, pos })
end
end
for _, p in positions do
table.insert(cues, { time = time, track = p[1], position = segData + p[2] })
end
end
end
return cues
end
local function parseTags(buf: buffer, off: number, len: number, meta: { [string]: any })
local tags = meta.tags or {}
meta.tags = tags
for id, o, n in Ebml.children(buf, off, off + len) do
if id == ID.Tag then
for id2, o2, n2 in Ebml.children(buf, o, o + n) do
if id2 == ID.SimpleTag then
local name, value = nil, nil
for id3, o3, n3 in Ebml.children(buf, o2, o2 + n2) do
if id3 == ID.TagName then
name = Ebml.string(buf, o3, n3)
elseif id3 == ID.TagString then
value = Ebml.string(buf, o3, n3)
end
end
if name and value and tags[string.lower(name)] == nil then
tags[string.lower(name)] = value
end
end
end
end
end
end
type Ctx = {
buf: buffer,
dmx: any,
byNum: { [number]: TrackInfo },
scaleNs: number,
err: string?,
maxPackets: number,
}
-- one Block / SimpleBlock payload at [off, off + len): track, relative timecode, flags, lacing
local function block(ctx: Ctx, off: number, len: number, clusterTime: number, simple: boolean, keyHint: boolean?, durTicks: number?, discardNs: number?)
local buf = ctx.buf
local limit = off + len
local tn, tl = Ebml.vint(buf, off, limit)
if not tn or not tl or tn < 0 or off + tl + 3 > limit then
return
end
local p = off + tl
local rel = buffer.readu8(buf, p) * 256 + buffer.readu8(buf, p + 1)
if rel >= 32768 then
rel -= 65536
end
local flags = buffer.readu8(buf, p + 2)
p += 3
local t = ctx.byNum[tn]
if not t then
return
end
local key = if simple then bit32.band(flags, 0x80) ~= 0 else (keyHint ~= false)
if t.kind == "audio" or t.kind == "subtitle" then
key = true
end
local pts = clusterTime + rel
local lacing = bit32.band(bit32.rshift(flags, 1), 3)
local sizes: { number } = {}
if lacing == 0 then
sizes[1] = limit - p
else
if p >= limit then
return
end
local count = buffer.readu8(buf, p) + 1
p += 1
if lacing == 1 then -- Xiph
local total = 0
for k = 1, count - 1 do
local s = 0
while true do
if p >= limit then
return
end
local b = buffer.readu8(buf, p)
p += 1
s += b
if b ~= 255 then
break
end
end
sizes[k] = s
total += s
end
sizes[count] = limit - p - total
elseif lacing == 3 then -- EBML
local s, l = Ebml.vint(buf, p, limit)
if not s or not l or s < 0 then
return
end
p += l
sizes[1] = s
local total = s
for k = 2, count - 1 do
local d, dl = Ebml.svint(buf, p, limit)
if not d or not dl then
return
end
p += dl
s += d
if s < 0 then
return
end
sizes[k] = s
total += s
end
sizes[count] = limit - p - total
else -- fixed
local each = (limit - p) // count
for k = 1, count do
sizes[k] = each
end
end
if sizes[count] < 0 then
return
end
end
-- frames after the first of a lace: the track's default duration
local stepTicks = 0
if t.defaultDurationNs and t.defaultDurationNs > 0 then
stepTicks = t.defaultDurationNs / ctx.scaleNs
elseif durTicks and #sizes > 0 then
stepTicks = durTicks / #sizes
end
local dmx = ctx.dmx
for k, s in sizes do
if p + s > limit then
return
end
if dmx.n >= ctx.maxPackets then
ctx.err = "too many packets"
return
end
local d = if #sizes == 1 then durTicks else (if stepTicks > 0 then stepTicks else nil)
local kf = key and (k == 1 or t.kind ~= "video")
local strip = t.strip
local z = (t :: any).zlib
if z and bit32.band(z, 1) ~= 0 then
local out = Deflate.zlib(buf, p, s)
if out then
dmx:addData(tn, pts + (k - 1) * stepTicks, nil, d, kf, out)
end
elseif strip then
local nb = buffer.create(buffer.len(strip) + s)
buffer.copy(nb, 0, strip)
buffer.copy(nb, buffer.len(strip), buf, p, s)
dmx:addData(tn, pts + (k - 1) * stepTicks, nil, d, kf, nb)
else
dmx:add(tn, pts + (k - 1) * stepTicks, nil, d, kf, p, s)
end
if discardNs and k == #sizes then
dmx:setExtra("discardPadding", discardNs / 1e9)
end
p += s
end
end
-- a Cluster's children from off to limit (an unknown-size cluster: until a top-level ID); returns where it ended
local function cluster(ctx: Ctx, off: number, limit: number, unknown: boolean): number
local buf = ctx.buf
local pos = off
local time = 0
while pos < limit and not ctx.err do
local id, size, data = Ebml.header(buf, pos, limit)
if not id or not size or not data then
return limit
end
if unknown and TOP[id] then
return pos
end
if size < 0 then
size = limit - data -- an unknown-size child: to the end
end
if data + size > limit then
size = limit - data
end
if id == ID.Timecode then
time = Ebml.uint(buf, data, size)
elseif id == ID.SimpleBlock then
block(ctx, data, size, time, true)
elseif id == ID.BlockGroup then
local bo, bl = -1, 0
local ref, dur, discard = false, nil, nil
for id2, o2, n2 in Ebml.children(buf, data, data + size) do
if id2 == ID.Block then
bo, bl = o2, n2
elseif id2 == ID.ReferenceBlock then
ref = true
elseif id2 == ID.BlockDuration then
dur = Ebml.uint(buf, o2, n2)
elseif id2 == ID.DiscardPadding then
discard = Ebml.int(buf, o2, n2)
end
end
if bo >= 0 then
block(ctx, bo, bl, time, false, not ref, dur, discard)
end
end
pos = data + size
end
return pos
end
export type Options = { maxPackets: number? }
-- parse(buf, base, limit, opts) -> a Demux | nil, Err
function Parse.parse(buf: buffer, base: number, limit: number, opts: Options?): (any, Err.Err?)
local id, size, data = Ebml.header(buf, base, limit)
if id ~= ID.EBML or not size or not data then
return nil, Err.new(Err.CORRUPT, "not an EBML file", base)
end
if size < 0 then
return nil, Err.new(Err.CORRUPT, "EBML header of unknown size", base)
end
local docType = "matroska"
for cid, o, n in Ebml.children(buf, data, math.min(limit, data + size)) do
if cid == ID.DocType then
docType = Ebml.string(buf, o, n)
end
end
if docType ~= "matroska" and docType ~= "webm" then
return nil, Err.new(Err.UNSUPPORTED, "EBML document type " .. docType)
end
local pos = data + size
-- the Segment (skip anything else at the top level)
local segData, segEnd = -1, limit
while pos < limit do
local sid, ssize, sdata = Ebml.header(buf, pos, limit)
if not sid or not ssize or not sdata then
break
end
if sid == ID.Segment then
segData = sdata
segEnd = if ssize < 0 or sdata + ssize > limit then limit else sdata + ssize
break
end
if ssize < 0 then
break
end
pos = sdata + ssize
end
if segData < 0 then
return nil, Err.new(Err.TRUNCATED, "no Segment")
end
local meta: { [string]: any } = { docType = docType }
local scaleNs, duration = 1000000, nil :: number?
local tracks: { TrackInfo } = {}
local problems: { [number]: string } = {}
local cuesAt: { number } = {}
local clusters: { { number } } = {}
-- first pass: the top-level elements (clusters are walked after Info / Tracks, which may come later via SeekHead)
pos = segData
while pos < segEnd do
local cid, csize, cdata = Ebml.header(buf, pos, segEnd)
if not cid or not csize or not cdata then
break
end
local unknown = csize < 0
local cend = if unknown or cdata + csize > segEnd then segEnd else cdata + csize
if cid == ID.Info then
local d
scaleNs, d = parseInfo(buf, cdata, cend - cdata, meta)
duration = d
elseif cid == ID.Tracks then
tracks, problems = parseTracks(buf, cdata, cend - cdata, scaleNs)
elseif cid == ID.Cluster then
if unknown then
-- find its end: walk children until a top-level ID
local p = cdata
while p < segEnd do
local xid, xsize, xdata = Ebml.header(buf, p, segEnd)
if not xid or not xsize or not xdata or TOP[xid] then
break
end
if xsize < 0 then
p = segEnd
break
end
p = math.min(segEnd, xdata + xsize)
end
cend = p
end
table.insert(clusters, { cdata, cend })
elseif cid == ID.Cues then
table.insert(cuesAt, cdata)
table.insert(cuesAt, cend - cdata)
elseif cid == ID.Tags then
parseTags(buf, cdata, cend - cdata, meta)
end
if cend <= pos then
break
end
pos = cend
end
if #tracks == 0 then
return nil, Err.new(Err.CORRUPT, "no tracks")
end
-- track timescales follow the final TimecodeScale (Info may follow Tracks)
local byNum: { [number]: TrackInfo } = {}
for _, t in tracks do
t.timescale = 1e9 / scaleNs
byNum[t.id] = t
end
local dmx = Demux.new(if docType == "webm" then "webm" else "mkv", tracks :: any, buf, meta)
local ctx: Ctx = { buf = buf, dmx = dmx, byNum = byNum, scaleNs = scaleNs, err = nil, maxPackets = opts and opts.maxPackets or 2 ^ 24 }
for _, c in clusters do
cluster(ctx, c[1], c[2], false)
if ctx.err then
return nil, Err.new(Err.LIMIT, ctx.err)
end
end
if duration then
dmx.duration = duration * scaleNs / 1e9
end
local cues = {}
for k = 1, #cuesAt, 2 do
for _, c in parseCues(buf, cuesAt[k], cuesAt[k + 1], segData) do
c.time = c.time * scaleNs / 1e9
table.insert(cues, c)
end
end
meta.cues = cues
meta.timecodeScale = scaleNs
for tid, msg in problems do
local t = byNum[tid]
t.unsupported = msg
end
dmx:finish()
return dmx, nil
end
return Parse
+160
View File
@@ -0,0 +1,160 @@
--!strict
-- video/mkv: Matroska and WebM (the Matroska specification / RFC 9559, the WebM container guidelines). New in
-- formats-luau, on containers/Ebml.
-- Read: open() demuxes the whole file into a packet index (SimpleBlock / BlockGroup, Xiph / EBML / fixed lacing,
-- header-stripping and zlib compression, unknown-size clusters, Cues and Tags in meta) and returns a VideoDecoder: video
-- through the codecs/Video registry (VP8 with inter frames, MJPEG, MPEG-1, raw; H.264 when registered), audio
-- through the api's opts.openAudio hook (Opus, Vorbis, FLAC, MP3, PCM, AAC, ... reach the audio formats), text
-- subtitle tracks as cues (Mkv.subtitles). Mkv.demux(r) gives the Demuxer alone.
-- Write: WebM (opts.format = "webm" or a .webm destination: VP8 / VP9 / AV1 video and Opus / Vorbis audio, copied
-- from the source since VP8 is decode-only) and Matroska (any registered video codec copied, else MJPEG encoded from
-- the frames; audio copied, else PCM s16), with SeekHead, Cues and Duration.
-- Not supported: bzip2 / lzo content compression and encryption (the track's packets are left as stored,
-- track.unsupported says why), chapters / attachments (skipped), writing subtitles.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Video = require("@formats/codecs/Video")
local Source = require("@formats/codecs/Video/Source")
local Parse = require("@formats/video/mkv/Parse")
local Mux = require("@formats/video/mkv/Mux")
-- ------------------------------------------------------------------------------------------------ contract
local Mkv = {
name = "mkv",
category = "video",
extensions = { "mkv", "webm", "mka", "mk3d" },
mime = { "video/x-matroska", "video/webm", "audio/x-matroska", "audio/webm" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Ebml", "containers/Demux", "codecs/Deflate", "codecs/Video", "codecs/Video/Source" },
caps = { decode = true, encode = true, streaming = true, remux = true, video = { "vp8", "mjpeg", "mpeg1", "rawvideo" }, audio = true, subtitles = true },
}
-- ------------------------------------------------------------------------------------------------ types
export type OpenOptions = {
rgba: boolean?, -- nextFrame returns rgba8 images (default false: yuv420p from the codec)
track: number?, -- the video track number to decode (default: the first video track)
audio: boolean?, -- false: do not open the audio track
maxPackets: number?, -- refuse files with more packets (default 2^24)
maxPixels: number?,
openAudio: any?, -- set by the api: (demuxer, track) -> audio Decoder
}
export type EncodeOptions = {
format: string?, -- "webm" writes WebM (DocType webm, WebM codecs only); else Matroska
webm: boolean?, -- the same as format = "webm"
quality: number?, -- MJPEG quality 1..100 when frames are encoded (default 90)
reencode: boolean?, -- encode the frames even when the video track could be copied (Matroska: MJPEG)
video: boolean?, -- false: no video stream
audio: boolean?, -- false: no audio; true: fail if the audio cannot be written (default: dropped)
title: string?,
clusterSeconds: number?, -- target cluster length (default 2)
}
-- ------------------------------------------------------------------------------------------------ constants
local WEBM_VIDEO = { vp8 = true, vp9 = true, av1 = true }
local WEBM_AUDIO = { opus = true, vorbis = true }
-- ------------------------------------------------------------------------------------------------ sniff
function Mkv.sniff(r: Bytes.Reader): number
if r:peek(4) ~= "\26\69\223\163" then
return 0
end
local head = r:peek(math.min(64, r:remaining()))
if string.find(head, "webm", 1, true) or string.find(head, "matroska", 1, true) then
return 1
end
return 0.5
end
-- ------------------------------------------------------------------------------------------------ encode
-- encode(video, opts?) -> buffer | nil, Err: a VideoDecoder (F.load / F.video.open of any video or animated image)
-- or a Demuxer
function Mkv.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
local o: any = opts or {}
local webm = o.webm == true or (type(o.format) == "string" and string.lower(o.format) == "webm")
local want: Source.Want
if webm then
want = { video = { copy = WEBM_VIDEO }, audio = { copy = WEBM_AUDIO } }
else
local copy: { [string]: boolean } = {}
for id, e in Video.codecs do
if e.matroska then
copy[id] = true
end
end
want = { video = { copy = copy, encode = "mjpeg" }, audio = { copy = { ["*"] = true }, pcm = true } }
end
local so = table.clone(o)
so.quality = so.quality or 90
local streams, err = Source.streams(value, so, want)
if not streams then
return nil, err
end
if not webm then
-- audio codecs Matroska cannot name: PCM instead
for i, s in streams do
if s.kind == "audio" and not Mux.codecId("audio", s.codec) then
local alt, aerr = Source.streams(value, { video = false, reencodeAudio = true }, { audio = { pcm = true } })
if alt and alt[1] then
streams[i] = alt[1]
else
return nil, aerr
end
end
end
end
local ok, buf, merr = pcall(Mux.mux, streams, { webm = webm, title = o.title, clusterSeconds = o.clusterSeconds })
if not ok then
return nil, Err.new(Err.ARG, "internal error: " .. tostring(buf))
end
return buf, merr
end
-- ------------------------------------------------------------------------------------------------ open
-- demux(r, opts?) -> the Demuxer (containers/Demux: tracks, packets, read, seek, count / get) | nil, Err
function Mkv.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?)
local ok, dmx, err = pcall(Parse.parse, r.buf, r.base, r.limit, opts)
if not ok then
return nil, Err.new(Err.CORRUPT, "internal error: " .. tostring(dmx))
end
return dmx, err
end
-- open(r, opts?) -> a VideoDecoder (kind "video": nextFrame / seek / audio / demuxer) | nil, Err
function Mkv.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?)
local dmx, err = Mkv.demux(r, opts)
if not dmx then
return nil, err
end
return Video.open(dmx, opts)
end
-- ------------------------------------------------------------------------------------------------ extras
-- subtitles(demuxer, trackId?) -> Types.Subtitles from a text subtitle track (S_TEXT/UTF8, WebVTT, ASS text) | nil
function Mkv.subtitles(dmx: any, trackId: number?): Types.Subtitles?
local track = nil
for _, t in dmx.tracks do
if t.kind == "subtitle" and (trackId == nil or t.id == trackId) then
track = t
break
end
end
if not track then
return nil
end
local subs = Types.Subtitles.new()
subs.meta.codec = track.codec
subs.meta.language = track.language
for k = 1, dmx:count(track.id) do
local p = dmx:get(track.id, k)
if p then
local start = p.pts / track.timescale
local stop = start + (p.duration or 0) / track.timescale
table.insert(subs.cues, { start = start, stop = stop, text = buffer.tostring(p.data) })
end
end
return subs
end
return Mkv
+324
View File
@@ -0,0 +1,324 @@
--!strict
-- video/mp4: MP4 / M4V / QuickTime MOV / 3GP (ISO/IEC 14496-12 / 14496-14, the QuickTime file format), on
-- containers/IsoBmff (ws-m4a's box parser, sample tables, fragments and muxer). New in formats-luau.
-- Read: every track's samples into a Demuxer (pts = dts + composition offset, moved by the edit list: the first
-- edit's media time is subtracted (B-frame delay, AAC priming), an initial empty edit added; sync samples as
-- keyframes; fragmented files too) and open() returns a VideoDecoder: video through the codecs/Video registry (MJPEG
-- 'jpeg' / 'mjpa' / mp4v 0x6C, MPEG-1, raw; H.264 'avc1' with its avcC when a decoder is registered), audio through
-- the api's opts.openAudio hook (AAC, ALAC (audio/m4a), MP3, Opus (dOps -> OpusHead), FLAC, PCM 'sowt' / 'twos' /
-- 'lpcm' / 'ipcm').
-- Write: MP4 (or MOV with opts.format = "mov" / a .mov destination): H.264 / HEVC / AV1 / MJPEG / MPEG-4 video copied
-- from an ISO / Matroska source (their configurations are the same boxes), else MJPEG encoded from the frames (mp4v
-- object type 0x6C in MP4, 'jpeg' in MOV); AAC / ALAC / Opus / FLAC / MP3 audio copied, else PCM s16 ('sowt', MOV
-- only; MP4 drops other audio unless opts.audio = true, which fails).
-- Edit lists are written for a B-frame delay and an audio codec delay (AAC priming). Not supported: fragmented
-- writing, timed text tracks, encrypted tracks.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local IsoBmff = require("@formats/containers/IsoBmff")
local Demux = require("@formats/containers/Demux")
local Video = require("@formats/codecs/Video")
local Source = require("@formats/codecs/Video/Source")
-- ------------------------------------------------------------------------------------------------ contract
local Mp4 = {
name = "mp4",
category = "video",
extensions = { "mp4", "m4v", "mov", "qt", "3gp", "3g2", "mj2" },
mime = { "video/mp4", "video/quicktime", "video/3gpp" },
deps = { "core/Err", "core/Bytes", "Types", "containers/IsoBmff", "containers/Demux", "codecs/Video", "codecs/Video/Source" },
caps = { decode = true, encode = true, streaming = true, remux = true, video = { "mjpeg", "mpeg1", "h264" }, audio = true, fragments = true },
}
-- ------------------------------------------------------------------------------------------------ types
export type OpenOptions = {
rgba: boolean?,
track: number?, -- the video track id (default: the first video track)
audio: boolean?,
maxPixels: number?,
maxSamples: number?,
openAudio: any?, -- set by the api
}
export type EncodeOptions = {
format: string?, -- "mov" writes QuickTime (brand 'qt '); else MP4 (brand 'isom')
quality: number?, -- MJPEG quality when frames are encoded (default 90)
reencode: boolean?, -- encode the frames to MJPEG even when the video could be copied
video: boolean?,
audio: boolean?, -- false: no audio; true: fail when the audio cannot be written
}
-- ------------------------------------------------------------------------------------------------ constants
local IMAGE_BRANDS = { avif = true, avis = true, heic = true, heix = true, mif1 = true, msf1 = true, ["crx "] = true }
local AUDIO_BRANDS = { ["M4A "] = true, ["M4B "] = true, ["M4P "] = true }
-- copied video codecs -> sample entry (MP4 / MOV)
local VIDEO_ENTRY: { [string]: string } = { h264 = "avc1", hevc = "hvc1", av1 = "av01", vp9 = "vp09" }
local AUDIO_ENTRY: { [string]: string } = { aac = "mp4a", alac = "alac", opus = "Opus", flac = "fLaC", mp3 = "mp4a" }
-- ------------------------------------------------------------------------------------------------ sniff
function Mp4.sniff(r: Bytes.Reader): number
local brand = IsoBmff.sniff(r)
if brand == nil or IMAGE_BRANDS[brand] then
return 0
end
if AUDIO_BRANDS[brand] then
return 0.2
end
if brand == "M4V " then
return 0.9
end
return if brand == "" then 0.6 else 0.8
end
-- ------------------------------------------------------------------------------------------------ decode
-- OpusHead (RFC 7845, little-endian) from an ISO dOps box payload (big-endian)
local function opusHead(d: buffer): buffer?
if buffer.len(d) < 11 then
return nil
end
local w = Bytes.writer(19 + buffer.len(d))
w:string("OpusHead")
w:u8(1)
local ch = buffer.readu8(d, 1)
w:u8(ch)
w:u16le(buffer.readu8(d, 2) * 256 + buffer.readu8(d, 3))
w:u32le(((buffer.readu8(d, 4) * 256 + buffer.readu8(d, 5)) * 256 + buffer.readu8(d, 6)) * 256 + buffer.readu8(d, 7))
w:u16le(buffer.readu8(d, 8) * 256 + buffer.readu8(d, 9))
local family = buffer.readu8(d, 10)
w:u8(family)
if family ~= 0 and buffer.len(d) >= 13 + ch then
w:bytes(d, 11, 2 + ch) -- stream count, coupled count, mapping
end
return w:finish()
end
local function pcmCodec(t: any): string
local p = t.pcm
local bits = if p then p.bits else (t.bitsPerSample or 16)
if p and p.float then
return "pcm_f" .. bits .. (if p.little then "le" else "be")
end
if bits == 8 then
return if t.entry == "raw " then "pcm_u8" else "pcm_s8"
end
return "pcm_s" .. bits .. (if p == nil or p.little then "le" else "be")
end
-- demux(r, opts?) -> the Demuxer | nil, Err
function Mp4.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?)
local ok, movie, err = pcall(IsoBmff.parse, r, opts and opts.maxSamples and { maxSamples = opts.maxSamples } or nil)
if not ok then
return nil, Err.new(Err.CORRUPT, "internal error: " .. tostring(movie))
end
if not movie then
return nil, err
end
local tracks: { Types.Track } = {}
local src = {}
for _, it in movie.tracks do
local t: any = {
id = it.id,
kind = it.kind,
codec = it.codec,
codecTag = it.entry,
timescale = it.timescale,
duration = it.duration,
language = it.language,
width = it.width,
height = it.height,
sampleRate = it.sampleRate,
channels = it.channels,
bitsPerSample = it.bitsPerSample,
config = it.config,
default = true,
}
if it.kind == "video" then
if not Video.entry(t.codec) then
t.codec = Video.fromFourcc(it.entry) or t.codec
end
if it.sampleCount > 0 and it.duration > 0 then
t.frameRate = it.sampleCount / it.duration
end
elseif it.kind == "audio" then
if it.codec == "pcm" then
t.codec = pcmCodec(it)
elseif it.codec == "ulaw" then
t.codec = "pcm_mulaw"
elseif it.codec == "alaw" then
t.codec = "pcm_alaw"
elseif it.codec == "opus" and it.config then
t.config = opusHead(it.config)
end
if it.skip and it.skip > 0 then
t.codecDelay = it.skip / it.timescale -- AAC priming: dropped like ffmpeg
end
end
table.insert(tracks, t)
table.insert(src, it)
end
local dmx = Demux.new(if movie.brand == "qt " then "mov" else "mp4", tracks, r.buf, { brand = movie.brand })
-- samples in file order across tracks
local items: { { number } } = {}
for k, it in src do
-- the edit list moves presentation times: minus the first edit's media time (video: the B-frame delay; audio
-- keeps it as its codec delay), plus an initial empty edit (converted to media ticks)
local shift = 0
if it.kind == "video" then
shift = -(it.skip or 0)
end
if it.delay and it.delay > 0 and movie.timescale and movie.timescale > 0 then
shift += it.delay / movie.timescale * it.timescale
end
for i = 1, it.sampleCount do
table.insert(items, { it.offsets[i], k, i, shift })
end
end
table.sort(items, function(a: { number }, b: { number }): boolean
return a[1] < b[1]
end)
for _, e in items do
local it = src[e[2]]
local i = e[3]
local dts = it.dts[i]
local pts = dts + (if it.cts then it.cts[i] or 0 else 0) + e[4]
dmx:add(it.id, pts, dts + e[4], it.durations[i], it.sync == nil or it.sync[i] == true, it.offsets[i], it.sizes[i])
end
dmx:finish()
return dmx, nil
end
-- ------------------------------------------------------------------------------------------------ encode
-- OpusHead -> dOps payload
local function dOps(head: buffer?): buffer?
if not head or buffer.len(head) < 19 then
return nil
end
local w = Bytes.writer(16)
w:u8(0)
local ch = buffer.readu8(head, 9)
w:u8(ch)
w:u16be(buffer.readu16(head, 10))
w:u32be(buffer.readu32(head, 12))
w:u16be(buffer.readu16(head, 16))
local family = buffer.readu8(head, 18)
w:u8(family)
if family ~= 0 and buffer.len(head) >= 21 + ch then
w:bytes(head, 19, 2 + ch)
end
return w:finish()
end
-- encode(video, opts?) -> buffer | nil, Err
function Mp4.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
local o: any = table.clone(opts or {})
o.quality = o.quality or 90
local mov = type(o.format) == "string" and (string.lower(o.format) == "mov" or string.lower(o.format) == "qt")
local vcopy: { [string]: boolean } = { mjpeg = true }
for id in VIDEO_ENTRY do
vcopy[id] = true
end
local acopy: { [string]: boolean } = {}
for id in AUDIO_ENTRY do
acopy[id] = true
end
acopy.pcm_s16le = mov
local streams, err = Source.streams(value, o, {
video = { copy = vcopy, encode = "mjpeg" },
audio = { copy = acopy, pcm = mov },
})
if not streams then
return nil, err
end
local mtracks = {}
for _, s in streams do
local scale = if s.kind == "audio" then math.floor((s.sampleRate or 48000) + 0.5) else 90000
if s.kind == "video" and s.track and s.track.timescale and s.copied and s.track.timescale == math.floor(s.track.timescale) then
scale = s.track.timescale
end
local samples, durations, cts, sync = {}, {}, {}, {}
local anyCts = false
local firstDts = nil :: number?
for i, p in s.packets do
samples[i] = p.data
local dts = p.dts or p.pts
firstDts = firstDts or dts
local nextP = s.packets[i + 1]
local d = if nextP then (nextP.dts or nextP.pts) - dts else p.duration
durations[i] = math.max(0, math.floor(d * scale + 0.5))
local c = math.floor((p.pts - dts) * scale + 0.5)
cts[i] = c
if c ~= 0 then
anyCts = true
end
if p.keyframe then
sync[i] = true
end
end
-- an edit list keeps the source's start: video decode times before 0 (B-frame delay), audio codec delay
local skip = 0
if firstDts and firstDts < 0 then
skip = math.floor(-firstDts * scale + 0.5)
end
if s.kind == "audio" and s.track and s.track.codecDelay and s.copied then
skip = math.floor(s.track.codecDelay * scale + 0.5)
end
local t: any = {
kind = s.kind,
timescale = scale,
skip = if skip > 0 then skip else nil,
samples = samples,
durations = durations,
cts = if anyCts then cts else nil,
sync = sync,
width = s.width,
height = s.height,
sampleRate = s.sampleRate and math.floor(s.sampleRate + 0.5),
channels = s.channels,
}
if s.kind == "video" then
if s.codec == "mjpeg" then
t.entry = if mov then "jpeg" else "mp4v"
if not mov then
t.objectType = 0x6C
t.configBox = "esds"
t.config = buffer.create(0)
end
else
t.entry = VIDEO_ENTRY[s.codec]
t.config = s.config
end
else
if s.codec == "pcm_s16le" then
t.entry = "sowt"
t.bitsPerSample = 16
else
t.entry = AUDIO_ENTRY[s.codec]
t.config = if s.codec == "opus" then dOps(s.config) else s.config
if s.codec == "mp3" then
t.objectType = 0x6B
t.configBox = "esds"
t.config = buffer.create(0)
end
end
end
if not t.entry then
return nil, Err.new(Err.UNSUPPORTED, "no sample entry for " .. s.kind .. " codec " .. s.codec)
end
table.insert(mtracks, t)
end
return IsoBmff.mux({ brand = if mov then "qt " else "isom", compatible = if mov then { "qt " } else { "isom", "iso2", "mp41" }, tracks = mtracks })
end
-- ------------------------------------------------------------------------------------------------ open
-- open(r, opts?) -> a VideoDecoder | nil, Err
function Mp4.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?)
local dmx, err = Mp4.demux(r, opts)
if not dmx then
return nil, err
end
return Video.open(dmx, opts)
end
return Mp4
+192
View File
@@ -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
+245
View File
@@ -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
+209
View File
@@ -0,0 +1,209 @@
--!strict
-- video/y4m: YUV4MPEG2 (the mjpegtools / ffmpeg raw video stream). New in formats-luau.
-- Read: the stream header (W H F I A C X tags) and every FRAME into a raw-video Demuxer; open() returns a VideoDecoder
-- with yuv420p frames (C420 / C420jpeg / C420mpeg2 / C420paldv as they are; C422 / C444 chroma averaged down; Cmono
-- with neutral chroma; 9..16-bit samples (C420p10, ...) scaled to 8 bits). Y4m.demux(r) gives the Demuxer.
-- Write: yuv420p 8-bit frames ("C420jpeg", as ffmpeg writes for yuv420p) from any video or animated image; rgba8
-- frames are converted (BT.601 limited range); uneven frame times (a GIF's) become a constant rate with repeated frames. Not supported: interlaced field handling (the I tag is kept in meta),
-- alpha (C444alpha drops it).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Demux = require("@formats/containers/Demux")
local Video = require("@formats/codecs/Video")
local Source = require("@formats/codecs/Video/Source")
-- ------------------------------------------------------------------------------------------------ contract
local Y4m = {
name = "y4m",
category = "video",
extensions = { "y4m" },
mime = { "video/x-yuv4mpeg" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Demux", "codecs/Video", "codecs/Video/Source" },
caps = { decode = true, encode = true, streaming = true, video = { "rawvideo" }, depths = { 8, 10, 12, 16 } },
}
-- ------------------------------------------------------------------------------------------------ types
export type OpenOptions = {
rgba: boolean?, -- nextFrame returns rgba8 (default false: yuv420p)
maxPixels: number?, -- default 2^26
}
export type EncodeOptions = {
frameRate: { number }?, -- { num, den } for the F tag, one frame per source frame (default: the constant rate of the
-- shortest frame, longer frames repeated)
maxFps: number?, -- the highest rate uneven frame times may need (default 100)
}
-- ------------------------------------------------------------------------------------------------ constants
local MAGIC = "YUV4MPEG2 "
-- C tag -> pixel format, bits
local COLOR: { [string]: { any } } = {
["420jpeg"] = { "yuv420p", 8 },
["420paldv"] = { "yuv420p", 8 },
["420mpeg2"] = { "yuv420p", 8 },
["420"] = { "yuv420p", 8 },
["422"] = { "yuv422p", 8 },
["444"] = { "yuv444p", 8 },
["444alpha"] = { "yuva444p", 8 },
mono = { "gray", 8 },
}
for _, b in { 9, 10, 12, 14, 16 } do
COLOR["420p" .. b] = { "yuv420p", b }
COLOR["422p" .. b] = { "yuv422p", b }
COLOR["444p" .. b] = { "yuv444p", b }
COLOR["mono" .. b] = { "gray", b }
end
-- ------------------------------------------------------------------------------------------------ sniff
function Y4m.sniff(r: Bytes.Reader): number
return if r:peek(10) == MAGIC then 1 else 0
end
-- ------------------------------------------------------------------------------------------------ decode
local function frameSize(pf: string, bits: number, w: number, h: number): number
local bps = if bits > 8 then 2 else 1
local cw, ch = (w + 1) // 2, (h + 1) // 2
if pf == "yuv420p" then
return (w * h + 2 * cw * ch) * bps
elseif pf == "yuv422p" then
return (w * h + 2 * cw * h) * bps
elseif pf == "yuv444p" then
return w * h * 3 * bps
elseif pf == "yuva444p" then
return w * h * 4 * bps
end
return w * h * bps
end
-- demux(r, opts?) -> the raw-video Demuxer | nil, Err
function Y4m.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?)
local buf, base, limit = r.buf, r.base, r.limit
local nl = -1
for i = base, math.min(limit, base + 4096) - 1 do
if buffer.readu8(buf, i) == 10 then
nl = i
break
end
end
if limit - base < 10 or buffer.readstring(buf, base, 10) ~= MAGIC then
return nil, Err.new(Err.CORRUPT, "not a YUV4MPEG2 stream", base)
end
if nl < 0 then
return nil, Err.new(Err.TRUNCATED, "no end of the stream header", base)
end
local header = buffer.readstring(buf, base + 10, nl - base - 10)
local w, h, fn, fd = 0, 0, 25, 1
local ctag, itag, atag = "420jpeg", "p", "0:0"
local extra = {}
for tok in string.gmatch(header, "%S+") do
local k, v = string.sub(tok, 1, 1), string.sub(tok, 2)
if k == "W" then
w = tonumber(v) or 0
elseif k == "H" then
h = tonumber(v) or 0
elseif k == "F" then
local a, b = string.match(v, "^(%d+):(%d+)$")
if a and b and tonumber(a) > 0 and tonumber(b) > 0 then
fn, fd = tonumber(a) :: number, tonumber(b) :: number
end
elseif k == "C" then
ctag = v
elseif k == "I" then
itag = v
elseif k == "A" then
atag = v
elseif k == "X" then
table.insert(extra, v)
end
end
local color = COLOR[ctag]
if not color then
return nil, Err.new(Err.UNSUPPORTED, "colour space C" .. ctag)
end
if w <= 0 or h <= 0 or w > 65535 or h > 65535 then
return nil, Err.new(Err.CORRUPT, "bad frame size " .. w .. "x" .. h)
end
local maxPixels = opts and opts.maxPixels or 2 ^ 26
if w * h > maxPixels then
return nil, Err.new(Err.LIMIT, "frame of " .. w .. "x" .. h .. " pixels")
end
local pf, bits = color[1], color[2]
local size = frameSize(pf, bits, w, h)
local track: Types.Track = {
id = 1,
kind = "video",
codec = "rawvideo",
codecTag = "C" .. ctag,
timescale = fn / fd,
width = w,
height = h,
frameRate = fn / fd,
pixelFormat = pf,
bitDepth = bits,
default = true,
}
local meta = { interlace = itag, aspect = atag, extra = extra, colorTag = ctag }
local dmx = Demux.new("y4m", { track }, buf, meta)
local pos = nl + 1
local k = 0
while pos + 5 <= limit do
if buffer.readstring(buf, pos, 5) ~= "FRAME" then
return nil, Err.new(Err.CORRUPT, "expected FRAME", pos)
end
local e = -1
for i = pos + 5, math.min(limit, pos + 4096) - 1 do
if buffer.readu8(buf, i) == 10 then
e = i
break
end
end
if e < 0 then
break
end
local data = e + 1
if data + size > limit then
break -- a truncated last frame is dropped
end
dmx:add(1, k, k, 1, true, data, size)
k += 1
pos = data + size
end
dmx:finish()
return dmx, nil
end
-- ------------------------------------------------------------------------------------------------ encode
-- encode(video, opts?) -> buffer | nil, Err
function Y4m.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
local streams, err = Source.streams(value, { audio = false }, { video = { copy = nil, encode = "rawvideo" } })
if not streams then
return nil, err
end
local s = streams[1]
local fn, fd, packets = Source.constantRate(s, opts and opts.maxFps)
if opts and type(opts.frameRate) == "table" then
fn, fd, packets = opts.frameRate[1], opts.frameRate[2], s.packets
end
s.packets = packets
local w = Bytes.writer(64 + #s.packets * (buffer.len(s.packets[1].data) + 6))
w:string(string.format("YUV4MPEG2 W%d H%d F%d:%d Ip A1:1 C420jpeg XYSCSS=420JPEG\n", s.width or 0, s.height or 0, fn, fd))
for _, p in s.packets do
w:string("FRAME\n")
w:bytes(p.data)
end
return w:finish(), nil
end
-- ------------------------------------------------------------------------------------------------ open
-- open(r, opts?) -> a VideoDecoder | nil, Err
function Y4m.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?)
local dmx, err = Y4m.demux(r, opts)
if not dmx then
return nil, err
end
return Video.open(dmx, opts)
end
return Y4m