ws-video: video/mkv tests (ffprobe packets, ffmpeg audio, lacing / zlib / unknown clusters / subtitles, WebM remux), zlib content compression, codec-delay trimming of non-Opus audio (AudioWrap.trim), video/y4m, containers/Avi + video/avi (WIP tests)

This commit is contained in:
4DBug committed 2026-10-31 09:41:22 -05:00
1 parent 8a905a4510
commit 9411cd97c6
14 files changed
+1862 -20

No files matched your search

+25 -1
View File
@@ -194,18 +194,42 @@ local list: { Entry } = {
return require("@formats/audio/wav")
end,
},
{
name = "avi",
category = "video",
path = "video/avi",
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 },
load = function()
return require("@formats/video/avi")
end,
},
{
name = "mkv",
category = "video",
path = "video/mkv",
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/Video", "codecs/Video/Source" },
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 },
load = function()
return require("@formats/video/mkv")
end,
},
{
name = "y4m",
category = "video",
path = "video/y4m",
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 } },
load = function()
return require("@formats/video/y4m")
end,
},
{
name = "gltf",
category = "model",
+84 -8
View File
@@ -63,31 +63,107 @@ function Video.simpleDecoder(decodeOne: (data: buffer, packet: Types.Packet) ->
return self :: any
end
-- raw video: yuv420p (I420 / IYUV / y4m), yv12 (V before U), rgb24 / bgr24 / bgra (bottom-up AVI DIBs: track.flip)
-- raw video: yuv420p (I420 / IYUV / y4m), yv12 (V before U), yuv422p / yuv444p / yuva444p / gray (chroma averaged
-- down to 4:2:0, alpha dropped), track.bitDepth 9..16 (little-endian 16-bit samples scaled to 8 bits), rgb24 / bgr24 /
-- bgra / rgba (AVI DIBs: track.flip = bottom-up rows, track.stride = padded rows)
local function rawPlanar(data: buffer, pf: string, bits: number, w: number, h: number): Types.Image
local img = Types.Image.new(w, h, "yuv420p")
local px = img.pixels
local cw, ch = (w + 1) // 2, (h + 1) // 2
local bps = if bits > 8 then 2 else 1
local shift = 2 ^ (bits - 8)
local function sample(o: number): number
if bps == 1 then
return buffer.readu8(data, o)
end
return math.min(255, buffer.readu16(data, o) // shift)
end
for i = 0, w * h - 1 do
buffer.writeu8(px, i, sample(i * bps))
end
local scw, sch = w, h -- source chroma plane size
if pf == "yuv420p" then
scw, sch = cw, ch
elseif pf == "yuv422p" then
scw, sch = cw, h
end
local uo, vo = w * h * bps, (w * h + scw * sch) * bps
for cy = 0, ch - 1 do
for cx = 0, cw - 1 do
local i = cy * cw + cx
local u, v
if pf == "gray" then
u, v = 128, 128
elseif pf == "yuv420p" then
u, v = sample(uo + i * bps), sample(vo + i * bps)
elseif pf == "yuv422p" then
local y0, y1 = cy * 2, math.min(cy * 2 + 1, h - 1)
u = (sample(uo + (y0 * scw + cx) * bps) + sample(uo + (y1 * scw + cx) * bps) + 1) // 2
v = (sample(vo + (y0 * scw + cx) * bps) + sample(vo + (y1 * scw + cx) * bps) + 1) // 2
else
local x0, x1 = cx * 2, math.min(cx * 2 + 1, w - 1)
local y0, y1 = cy * 2, math.min(cy * 2 + 1, h - 1)
local a, b, c, d = (y0 * w + x0) * bps, (y0 * w + x1) * bps, (y1 * w + x0) * bps, (y1 * w + x1) * bps
u = (sample(uo + a) + sample(uo + b) + sample(uo + c) + sample(uo + d) + 2) // 4
v = (sample(vo + a) + sample(vo + b) + sample(vo + c) + sample(vo + d) + 2) // 4
end
buffer.writeu8(px, w * h + i, u)
buffer.writeu8(px, w * h + cw * ch + i, v)
end
end
return img
end
local PLANAR_SIZE: { [string]: (w: number, h: number, cw: number, ch: number) -> number } = {
yuv420p = function(w, h, cw, ch)
return w * h + 2 * cw * ch
end,
yv12 = function(w, h, cw, ch)
return w * h + 2 * cw * ch
end,
yuv422p = function(w, h, cw, _ch)
return w * h + 2 * cw * h
end,
yuv444p = function(w, h)
return w * h * 3
end,
yuva444p = function(w, h)
return w * h * 4
end,
gray = function(w, h)
return w * h
end,
}
local function rawDecoder(track: Types.Track, _opts: any?): (Types.VideoCodecDecoder?, Err.Err?)
local w, h = track.width or 0, track.height or 0
if w <= 0 or h <= 0 or w * h > 2 ^ 26 then
return nil, Err.new(Err.CORRUPT, "raw video without a valid size")
end
local pf = track.pixelFormat or "yuv420p"
local bits = track.bitDepth or 8
local cw, ch = (w + 1) // 2, (h + 1) // 2
local flip = track.flip == true
local planar = PLANAR_SIZE[pf]
return Video.simpleDecoder(function(data: buffer): (Types.Image?, Err.Err?)
local n = buffer.len(data)
if pf == "yuv420p" or pf == "yv12" then
local need = w * h + 2 * cw * ch
if planar then
local need = planar(w, h, cw, ch) * (if bits > 8 then 2 else 1)
if n < need then
return nil, Err.new(Err.TRUNCATED, "raw frame: " .. n .. " of " .. need .. " bytes")
end
local img = Types.Image.new(w, h, "yuv420p")
if pf == "yv12" then
if pf == "yuv420p" and bits == 8 then
local img = Types.Image.new(w, h, "yuv420p")
buffer.copy(img.pixels, 0, data, 0, need)
return img
elseif pf == "yv12" then
local img = Types.Image.new(w, h, "yuv420p")
buffer.copy(img.pixels, 0, data, 0, w * h)
buffer.copy(img.pixels, w * h, data, w * h + cw * ch, cw * ch)
buffer.copy(img.pixels, w * h + cw * ch, data, w * h, cw * ch)
else
buffer.copy(img.pixels, 0, data, 0, need)
return img
end
return img
return rawPlanar(data, pf, bits, w, h)
end
local bpp = if pf == "bgra" or pf == "rgba" then 4 else 3
local stride = if track.stride then track.stride else w * bpp
+45 -1
View File
@@ -263,6 +263,50 @@ local function adts(track: Types.Track, packets: { Types.Packet }): (buffer?, Er
return w:finish(), nil
end
-- ------------------------------------------------------------------------------------------------ trim
-- trim(decoder, frames) -> an audio Decoder that drops the first `frames` sample frames (a container's codec delay:
-- Matroska CodecDelay for MP2 / MP3 / AAC, which ffmpeg drops too; Opus handles its pre-skip itself)
function AudioWrap.trim(dec: any, skip: number): any
if skip <= 0 then
return dec
end
local rate = dec.sampleRate
local w: any = setmetatable({}, { __index = dec })
w.frames = math.max(0, (dec.frames or 0) - skip)
w.duration = math.max(0, (dec.duration or 0) - skip / rate)
local function drop()
local left = skip
while left > 0 do
local _, n = dec:read(math.min(left, 4096))
if not n or n <= 0 then
break
end
left -= n
end
end
local started = false
function w.read(_: any, n: number, out: buffer?): (buffer, number)
if not started then
started = true
drop()
end
return dec:read(n, out)
end
function w.seek(_: any, seconds: number)
started = true
if seconds <= 0 then
dec:seek(0)
drop()
else
dec:seek(seconds + skip / rate)
end
end
function w.position(_: any): number
return math.max(0, dec:position() - skip / rate)
end
return w
end
-- ------------------------------------------------------------------------------------------------ wrap
-- wrap(demuxer, track) -> buffer, audio format name | nil, nil, Err
function AudioWrap.wrap(dmx: any, track: Types.Track): (buffer?, string?, Err.Err?)
@@ -277,7 +321,7 @@ function AudioWrap.wrap(dmx: any, track: Types.Track): (buffer?, string?, Err.Er
if #packets == 0 then
return nil, nil, Err.new(Err.CORRUPT, "audio track without packets")
end
if track.waveFormat and (PCM[codec] == nil or codec == "pcm_s16le" or codec == "pcm_u8") then
if track.waveFormat and string.sub(codec, 1, 6) == "adpcm_" then
return wav(track.waveFormat, concat(packets)), "wav", nil
end
if PCM[codec] then
+523
View File
@@ -0,0 +1,523 @@
--!strict
-- containers/Avi: the AVI RIFF form (Microsoft AVI 1.0 + the OpenDML 1.02 extensions). New in formats-luau.
-- Reading: hdrl (avih, strl: strh / strf / strn / indx), every RIFF piece (RIFF AVI + RIFF AVIX ...), and the chunk
-- index of every stream: from the OpenDML super index (indx -> ix## standard / field indexes), else idx1 (offsets
-- relative to the movi list or absolute, detected), else a linear scan of the movi lists (LIST rec included).
-- Writing: AVI 1.0 (avih, strl, LIST movi, idx1) with an OpenDML odml / dmlh header, chunks interleaved as given.
--
-- local avi, err = Avi.read(buf, base, limit)
-- avi.streams[i] = { type = "vids" | "auds" | ..., handler, scale, rate, start, length, sampleSize, strf
-- (buffer), name, chunks = { { offset, size, key } } } -- offsets of the chunk data, absolute
-- local w = Avi.writer({ streams = {...}, avih = {...} }); w:chunk(streamIndex, data, key); local file = w:finish()
--
-- Never throws: malformed data returns nil, Err (a damaged index falls back to scanning).
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local readu8, readu16, readu32, readstring = buffer.readu8, buffer.readu16, buffer.readu32, buffer.readstring
local Avi = {}
export type Chunk = { offset: number, size: number, key: boolean }
export type Stream = {
index: number, -- 0-based stream number (the "##" of the chunk ids)
type: string, -- strh fccType: "vids", "auds", "txts", "mids"
handler: string,
flags: number,
scale: number,
rate: number,
start: number,
length: number,
suggestedBufferSize: number,
sampleSize: number,
frame: { number }, -- rcFrame left, top, right, bottom
strf: buffer, -- the format block (BITMAPINFOHEADER / WAVEFORMATEX ...)
name: string?,
chunks: { Chunk },
}
export type File = {
avih: { microSecPerFrame: number, flags: number, totalFrames: number, streams: number, width: number, height: number },
streams: { Stream },
odml: { totalFrames: number }?,
info: { [string]: string },
index: string, -- "odml" | "idx1" | "scan"
}
local function u32(b: buffer, o: number): number
return readu32(b, o)
end
-- chunk walker over [p, limit): calls fn(id, dataOffset, size, listType?) for each chunk (LIST bodies are not
-- entered); returns where it stopped
local function walk(b: buffer, p: number, limit: number, fn: (id: string, data: number, size: number, ltype: string?) -> boolean?): number
while p + 8 <= limit do
local id = readstring(b, p, 4)
local size = u32(b, p + 4)
local data = p + 8
local ltype: string? = nil
if (id == "LIST" or id == "RIFF") and data + 4 <= limit then
ltype = readstring(b, data, 4)
end
if data + size > limit then
size = limit - data
end
if fn(id, data, size, ltype) == false then
return p
end
p = data + size + (size % 2)
end
return p
end
local function streamNumber(id: string): number?
local a, b = string.byte(id, 1, 2)
if not a or not b then
return nil
end
local function hex(c: number): number?
if c >= 48 and c <= 57 then
return c - 48
elseif c >= 65 and c <= 70 then
return c - 55
elseif c >= 97 and c <= 102 then
return c - 87
end
return nil
end
local h, l = hex(a), hex(b)
if h and l then
return h * 16 + l
end
return nil
end
Avi.streamNumber = streamNumber
local function parseStrl(b: buffer, data: number, size: number, index: number): Stream
local s: Stream = {
index = index,
type = "",
handler = "",
flags = 0,
scale = 1,
rate = 1,
start = 0,
length = 0,
suggestedBufferSize = 0,
sampleSize = 0,
frame = { 0, 0, 0, 0 },
strf = buffer.create(0),
chunks = {},
}
local indx: { number }? = nil
walk(b, data + 4, data + size, function(id: string, d: number, n: number): boolean?
if id == "strh" and n >= 48 then
s.type = readstring(b, d, 4)
s.handler = readstring(b, d + 4, 4)
s.flags = u32(b, d + 8)
s.scale = u32(b, d + 20)
s.rate = u32(b, d + 24)
s.start = u32(b, d + 28)
s.length = u32(b, d + 32)
s.suggestedBufferSize = u32(b, d + 36)
s.sampleSize = u32(b, d + 44)
if n >= 56 then
s.frame = { buffer.readi16(b, d + 48), buffer.readi16(b, d + 50), buffer.readi16(b, d + 52), buffer.readi16(b, d + 54) }
end
elseif id == "strf" then
local f = buffer.create(n)
buffer.copy(f, 0, b, d, n)
s.strf = f
elseif id == "strn" then
local str = readstring(b, d, n)
s.name = string.match(str, "^[^%z]*")
elseif id == "indx" and n >= 24 then
indx = { d, n }
end
return nil
end)
;(s :: any)._indx = indx
return s
end
-- an OpenDML index chunk (indx super index or ix## standard index) at d with n bytes: appends chunks to s
local function readIndex(b: buffer, d: number, n: number, s: Stream, limit: number, depth: number): boolean
if n < 24 or depth > 2 then
return false
end
local longsPerEntry = readu16(b, d)
local subType = readu8(b, d + 2)
local indexType = readu8(b, d + 3)
local entries = u32(b, d + 4)
if indexType == 0 then -- AVI_INDEX_OF_INDEXES: { qwOffset, dwSize, dwDuration }
if longsPerEntry ~= 4 then
return false
end
local p = d + 24
for _ = 1, entries do
if p + 16 > d + n then
break
end
local off = u32(b, p) + u32(b, p + 4) * 4294967296
local size = u32(b, p + 8)
p += 16
if off > 0 and off + 8 <= limit then
local sz = math.min(u32(b, off + 4), limit - off - 8)
readIndex(b, off + 8, if size > 0 then math.min(sz, size) else sz, s, limit, depth + 1)
end
end
return #s.chunks > 0
elseif indexType == 1 then -- AVI_INDEX_OF_CHUNKS: base offset, { dwOffset, dwSize } (or field index: 3 longs)
if n < 24 then
return false
end
local base = u32(b, d + 12) + u32(b, d + 16) * 4294967296
local per = if subType == 1 then 12 else 8 -- AVI_INDEX_2FIELD
local p = d + 24
for _ = 1, entries do
if p + per > d + n then
break
end
local off = u32(b, p)
local size = u32(b, p + 4)
p += per
local key = size < 0x80000000
size %= 0x80000000
local at = base + off
if at >= 0 and at + size <= limit then
table.insert(s.chunks, { offset = at, size = size, key = key })
end
end
return true
end
return false
end
-- read(buf, base, limit) -> File | nil, Err
function Avi.read(b: buffer, base: number, limit: number): (File?, Err.Err?)
if limit - base < 12 or readstring(b, base, 4) ~= "RIFF" or readstring(b, base + 8, 4) ~= "AVI " then
return nil, Err.new(Err.CORRUPT, "not an AVI file", base)
end
local file: File = {
avih = { microSecPerFrame = 0, flags = 0, totalFrames = 0, streams = 0, width = 0, height = 0 },
streams = {},
odml = nil,
info = {},
index = "scan",
}
local movis: { { number } } = {} -- { data offset of the 'movi' fourcc, end }
local idx1: { number }? = nil
local hdrl = false
-- every RIFF piece (AVI, then AVIX for OpenDML files)
walk(b, base, limit, function(id: string, d: number, n: number, ltype: string?): boolean?
if id ~= "RIFF" then
return nil
end
walk(b, d + 4, d + n, function(cid: string, cd: number, cn: number, cltype: string?): boolean?
if cid == "LIST" and cltype == "hdrl" and not hdrl then
hdrl = true
local si = 0
walk(b, cd + 4, cd + cn, function(hid: string, hd: number, hn: number, hltype: string?): boolean?
if hid == "avih" and hn >= 40 then
file.avih = {
microSecPerFrame = u32(b, hd),
flags = u32(b, hd + 12),
totalFrames = u32(b, hd + 16),
streams = u32(b, hd + 24),
width = u32(b, hd + 32),
height = u32(b, hd + 36),
}
elseif hid == "LIST" and hltype == "strl" then
table.insert(file.streams, parseStrl(b, hd, hn, si))
si += 1
elseif hid == "LIST" and hltype == "odml" then
walk(b, hd + 4, hd + hn, function(oid: string, od: number, on: number): boolean?
if oid == "dmlh" and on >= 4 then
file.odml = { totalFrames = u32(b, od) }
end
return nil
end)
end
return nil
end)
elseif cid == "LIST" and cltype == "movi" then
table.insert(movis, { cd, cd + cn })
elseif cid == "LIST" and cltype == "INFO" then
walk(b, cd + 4, cd + cn, function(iid: string, idd: number, inn: number): boolean?
file.info[iid] = string.match(readstring(b, idd, inn), "^[^%z]*") or ""
return nil
end)
elseif cid == "idx1" and not idx1 then
idx1 = { cd, cn }
end
return nil
end)
return nil
end)
if not hdrl then
return nil, Err.new(Err.CORRUPT, "no hdrl list")
end
if #file.streams == 0 then
return nil, Err.new(Err.CORRUPT, "no streams")
end
-- 1. OpenDML indexes
local odml = true
for _, s in file.streams do
local ix = (s :: any)._indx
if not ix or not readIndex(b, ix[1], ix[2], s, limit, 0) then
odml = false
end
end
if odml then
file.index = "odml"
else
for _, s in file.streams do
table.clear(s.chunks)
end
-- 2. idx1
local ok = false
if idx1 and movis[1] then
local d, n = idx1[1], idx1[2]
local count = n // 16
local moviBase = movis[1][1] -- the 'movi' fourcc
-- relative or absolute offsets: check the first entry that points at a chunk id
local rel = true
if count > 0 then
local off = u32(b, d + 8)
local ckid = readstring(b, d, 4)
local relAt, absAt = moviBase + off, base + off
if relAt + 4 <= limit and readstring(b, relAt, 4) == ckid then
rel = true
elseif absAt + 4 <= limit and readstring(b, absAt, 4) == ckid then
rel = false
end
end
for k = 0, count - 1 do
local e = d + k * 16
local ckid = readstring(b, e, 4)
local flags = u32(b, e + 4)
local off = u32(b, e + 8)
local size = u32(b, e + 12)
local sn = streamNumber(ckid)
local s = sn and file.streams[sn + 1]
if s and string.sub(ckid, 3, 4) ~= "pc" then
local at = (if rel then moviBase else base) + off + 8
if at + size <= limit then
table.insert(s.chunks, { offset = at, size = size, key = bit32.band(flags, 0x10) ~= 0 })
ok = true
end
end
end
end
if ok then
file.index = "idx1"
else
for _, s in file.streams do
table.clear(s.chunks)
end
-- 3. scan the movi lists
local function scan(d0: number, e0: number)
walk(b, d0, e0, function(id: string, d: number, n: number, ltype: string?): boolean?
if id == "LIST" and ltype == "rec " then
scan(d + 4, d + n)
return nil
end
local sn = streamNumber(id)
local s = sn and file.streams[sn + 1]
if s and string.sub(id, 1, 2) ~= "ix" and string.sub(id, 3, 4) ~= "pc" then
table.insert(s.chunks, { offset = d, size = n, key = true })
end
return nil
end)
end
for _, m in movis do
scan(m[1] + 4, m[2])
end
file.index = "scan"
end
end
for _, s in file.streams do
(s :: any)._indx = nil
end
return file, nil
end
-- ------------------------------------------------------------------------------------------------ writing
export type WStream = {
type: string, -- "vids" | "auds"
handler: string, -- fccHandler (4 chars)
scale: number,
rate: number,
sampleSize: number, -- 0 = every chunk one sample (video, VBR audio)
strf: buffer,
name: string?,
width: number?,
height: number?,
quality: number?,
ckid: string?, -- the chunk id suffix: "dc" (video), "wb" (audio)
}
export type WOptions = {
streams: { WStream },
microSecPerFrame: number,
width: number,
height: number,
software: string?,
}
-- write(opts, chunks) -> buffer: chunks = { { stream (1-based), data: buffer, key: boolean } } in file order
function Avi.write(opts: WOptions, chunks: { { any } }): buffer
local ns = #opts.streams
local lengths = table.create(ns, 0)
local maxChunk = table.create(ns, 0)
local bytes = table.create(ns, 0)
local total = 0
for _, c in chunks do
local si, data = c[1], c[2]
local n = buffer.len(data)
local s = opts.streams[si]
if s.sampleSize > 0 then
lengths[si] += n // s.sampleSize
else
lengths[si] += 1
end
bytes[si] += n
if n > maxChunk[si] then
maxChunk[si] = n
end
total += n + 8 + (n % 2)
end
local frames = 0
for si, s in opts.streams do
if s.type == "vids" and frames == 0 then
frames = lengths[si]
end
end
local w = Bytes.writer(total + 4096 + #chunks * 16)
w:string("RIFF")
local riffSize = w:tell()
w:u32le(0)
w:string("AVI ")
-- hdrl
w:string("LIST")
local hdrlSize = w:tell()
w:u32le(0)
w:string("hdrl")
w:string("avih")
w:u32le(56)
local duration = if opts.microSecPerFrame > 0 then frames * opts.microSecPerFrame / 1e6 else 1
local maxBytes = 0
for si = 1, ns do
maxBytes += bytes[si]
end
w:u32le(math.floor(opts.microSecPerFrame + 0.5))
w:u32le(if duration > 0 then math.floor(maxBytes / duration) else 0)
w:u32le(0) -- padding granularity
w:u32le(0x10 + 0x100) -- AVIF_HASINDEX | AVIF_ISINTERLEAVED
w:u32le(frames)
w:u32le(0) -- initial frames
w:u32le(ns)
local suggested = 0
for si = 1, ns do
suggested = math.max(suggested, maxChunk[si] + 8)
end
w:u32le(suggested)
w:u32le(opts.width)
w:u32le(opts.height)
for _ = 1, 4 do
w:u32le(0)
end
for si, s in opts.streams do
w:string("LIST")
local strlSize = w:tell()
w:u32le(0)
w:string("strl")
w:string("strh")
w:u32le(56)
w:string(s.type)
w:string(s.handler)
w:u32le(0) -- flags
w:u16le(0) -- priority
w:u16le(0) -- language
w:u32le(0) -- initial frames
w:u32le(s.scale)
w:u32le(s.rate)
w:u32le(0) -- start
w:u32le(lengths[si])
w:u32le(maxChunk[si])
w:u32le(if s.quality then s.quality else 0xFFFFFFFF)
w:u32le(s.sampleSize)
w:u16le(0)
w:u16le(0)
w:u16le(s.width or 0)
w:u16le(s.height or 0)
w:string("strf")
w:u32le(buffer.len(s.strf))
w:bytes(s.strf)
if buffer.len(s.strf) % 2 == 1 then
w:u8(0)
end
if s.name then
local nm = s.name .. "\0"
w:string("strn")
w:u32le(#nm)
w:string(nm)
if #nm % 2 == 1 then
w:u8(0)
end
end
w:setU32le(strlSize, w:tell() - strlSize - 4)
end
-- OpenDML extended header (total frames)
w:string("LIST")
w:u32le(16)
w:string("odml")
w:string("dmlh")
w:u32le(4)
w:u32le(frames)
w:setU32le(hdrlSize, w:tell() - hdrlSize - 4)
-- INFO
local sw = (opts.software or "formats-luau") .. "\0"
if #sw % 2 == 1 then
sw ..= "\0"
end
w:string("LIST")
w:u32le(4 + 8 + #sw)
w:string("INFO")
w:string("ISFT")
w:u32le(#sw)
w:string(sw)
-- movi
w:string("LIST")
local moviSize = w:tell()
w:u32le(0)
local moviBase = w:tell()
w:string("movi")
local index = table.create(#chunks)
for _, c in chunks do
local si, data, key = c[1], c[2], c[3]
local s = opts.streams[si]
local id = string.format("%02d", si - 1) .. (s.ckid or (if s.type == "vids" then "dc" else "wb"))
local at = w:tell()
local n = buffer.len(data)
w:string(id)
w:u32le(n)
w:bytes(data)
if n % 2 == 1 then
w:u8(0)
end
table.insert(index, { id, if key then 0x10 else 0, at - moviBase, n })
end
w:setU32le(moviSize, w:tell() - moviSize - 4)
-- idx1
w:string("idx1")
w:u32le(#index * 16)
for _, e in index do
w:string(e[1])
w:u32le(e[2])
w:u32le(e[3])
w:u32le(e[4])
end
w:setU32le(riffSize, w:tell() - 8)
return w:finish()
end
return Avi
+5 -1
View File
@@ -268,7 +268,11 @@ local function openAudio(demuxer: any, track: any): (any, Err.Err?)
if not buf then
return nil, err
end
return F.open(buf, { format = fmt, category = "audio" })
local dec, oerr = F.open(buf, { format = fmt, category = "audio" })
if dec and fmt ~= "opus" and type(track.codecDelay) == "number" and track.codecDelay > 0 then
dec = AudioWrap.trim(dec, math.floor(track.codecDelay * dec.sampleRate + 0.5))
end
return dec, oerr
end
local function withHooks(o: Options): Options
+331
View File
@@ -0,0 +1,331 @@
--!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 })
end
tick += dur
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
local function rational(fps: number): (number, number)
if math.abs(fps - math.floor(fps + 0.5)) < 1e-6 then
return math.floor(fps + 0.5), 1
end
local ntsc = fps * 1001 / 1000
if math.abs(ntsc - math.floor(ntsc + 0.5)) < 1e-4 then
return math.floor(ntsc + 0.5) * 1000, 1001
end
return math.floor(fps * 1000 + 0.5), 1000
end
-- 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 fd = math.huge
for _, p in s.packets do
if p.duration and p.duration > 0 and p.duration < fd then
fd = p.duration
end
end
local maxFps = o.maxFps or 100
if fd == math.huge then
fd = if s.frameRate and s.frameRate > 0 then 1 / s.frameRate else 0.04
end
fd = math.max(fd, 1 / maxFps)
local num, den = rational(1 / fd)
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: video packets repeated to fill their duration at the constant rate
local order = Source.interleave(streams)
local chunks: { { any } } = {}
local vtime = 0 -- frames written so far (video slots)
for _, item in order do
local si, p = item[1], item[2]
local s = streams[si]
if s.kind == "video" then
local stop = p.pts + (if p.duration and p.duration > 0 then p.duration else frameDur)
local slots = math.max(1, math.floor(stop / frameDur + 0.5) - vtime)
for _ = 1, slots do
table.insert(chunks, { si, p.data, true })
end
vtime += slots
else
table.insert(chunks, { si, p.data, true })
end
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
+28 -5
View File
@@ -9,6 +9,7 @@ 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 = {}
@@ -56,6 +57,7 @@ local ID = {
ContentEncodings = 0x6D80,
ContentEncoding = 0x6240,
ContentEncodingType = 0x5033,
ContentEncodingScope = 0x5032,
ContentCompression = 0x5034,
ContentCompAlgo = 0x4254,
ContentCompSettings = 0x4255,
@@ -182,13 +184,17 @@ local function parseAudio(buf: buffer, off: number, len: number, t: any)
end
end
-- ContentEncodings: header stripping (algo 3) is supported; zlib / bzip / lzo compression and encryption are not
-- 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.ContentEncodingType then
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
@@ -201,6 +207,8 @@ local function parseEncodings(buf: buffer, off: number, len: number, t: any): st
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
@@ -259,6 +267,14 @@ local function parseTracks(buf: buffer, off: number, len: number, scaleNs: numbe
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)
@@ -465,14 +481,21 @@ local function block(ctx: Ctx, off: number, len: number, clusterTime: number, si
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
if strip then
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, key and k == 1, nb)
dmx:addData(tn, pts + (k - 1) * stepTicks, nil, d, kf, nb)
else
dmx:add(tn, pts + (k - 1) * stepTicks, nil, d, key and (k == 1 or t.kind ~= "video"), p, s)
dmx:add(tn, pts + (k - 1) * stepTicks, nil, d, kf, p, s)
end
if discardNs and k == #sizes then
dmx:setExtra("discardPadding", discardNs / 1e9)
+3 -3
View File
@@ -2,14 +2,14 @@
-- 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 compression, unknown-size clusters, Cues and Tags in meta) and returns a VideoDecoder: video
-- 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: zlib / bzip2 / lzo content compression and encryption (the track's packets are left as stored,
-- 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
@@ -27,7 +27,7 @@ local 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/Video", "codecs/Video/Source" },
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 },
}
+222
View File
@@ -0,0 +1,222 @@
--!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). 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 (default: from the source's frame rate)
}
-- ------------------------------------------------------------------------------------------------ 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
local function rational(fps: number): (number, number)
if fps <= 0 or fps ~= fps then
return 25, 1
end
if math.abs(fps - math.floor(fps + 0.5)) < 1e-6 then
return math.floor(fps + 0.5), 1
end
local ntsc = fps * 1001 / 1000
if math.abs(ntsc - math.floor(ntsc + 0.5)) < 1e-4 then
return math.floor(ntsc + 0.5) * 1000, 1001
end
return math.floor(fps * 1000 + 0.5), 1000
end
-- 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
if opts and type(opts.frameRate) == "table" then
fn, fd = opts.frameRate[1], opts.frameRate[2]
else
fn, fd = rational(s.frameRate or 25)
end
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