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:
1 parent
8a905a4510
commit
9411cd97c6
14 files changed
+1862
-20
No files matched your search
@@ -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
|
||||
@@ -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)
|
||||
|
||||
@@ -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 },
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
Reference in new issue
Block a user