rename: src/Formats -> src/Rosetta, @formats -> @rosetta requires, build/luajit/rosetta + rosetta._compat, build/roblox/Rosetta, ROSETTA_* env/globals, writer vendor strings
This commit is contained in:
1 parent
2956576d7f
commit
22ddcd78fa
941 files changed
+3364
-3364
No files matched your search
@@ -0,0 +1,303 @@
|
||||
--!strict
|
||||
-- video/avi: AVI (Microsoft RIFF AVI 1.0, OpenDML 1.02). New in rosetta, 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/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("@rosetta/core/Err")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
local Types = require("@rosetta/Types")
|
||||
local Avi = require("@rosetta/containers/Avi")
|
||||
local Demux = require("@rosetta/containers/Demux")
|
||||
local Video = require("@rosetta/codecs/video/Video")
|
||||
local Source = require("@rosetta/codecs/video/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/Video", "codecs/video/Video/Source" },
|
||||
caps = { decode = true, encode = true, streaming = true, video = { "mjpeg", "mpeg1", "mpeg2", "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 bi = Avi.bitmapInfo(f)
|
||||
if bi and bi.palette then
|
||||
t.palette = bi.palette -- 1..8-bit codecs (Microsoft Video 1, Cinepak, QuickTime RLE / SMC in AVI, ...)
|
||||
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 } :: Avi.WOptions, 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 :: Video.OpenOptions?)
|
||||
end
|
||||
|
||||
return AviFormat
|
||||
@@ -0,0 +1,157 @@
|
||||
--!strict
|
||||
-- video/fli: Autodesk Animator FLI / Animator Pro FLC / FLX animations. New in rosetta, written from the FLIC
|
||||
-- file format description (Jim Kent, "FLC - Animator Pro Flic Files"; MultimediaWiki "FLIC").
|
||||
-- Read: the 128-byte header (FLI 0xAF11: speed in 1/70 s; FLC 0xAF12 / DTA 0xAF44: speed in ms; depth 8, 15, 16, 24:
|
||||
-- an FLC that says 16 bits holds 5-5-5 pixels, as Animator Pro wrote them), prefix and other non-frame chunks skipped,
|
||||
-- every frame chunk (0xF1FA, and 0xF5FA) a packet of a Demuxer; open() returns a VideoDecoder whose frames are rgba8
|
||||
-- (codecs/video/Legacy: palette chunks, BRUN, LC, SS2, BLACK, COPY, the deep-colour DTA chunks). The ring frame (the
|
||||
-- extra frame after `frames` that leads back to the first) is not shown. Fli.demux(r) gives the Demuxer.
|
||||
-- Not supported: writing, 1-bit FLICs, the X-COM / Magic Carpet game variants (audio chunks, 6-bit COLOR_256).
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@rosetta/core/Err")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
local Types = require("@rosetta/Types")
|
||||
local Demux = require("@rosetta/containers/Demux")
|
||||
local Video = require("@rosetta/codecs/video/Video")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Fli = {
|
||||
name = "fli",
|
||||
category = "video",
|
||||
extensions = { "fli", "flc", "flx" },
|
||||
mime = { "video/x-fli", "video/fli", "video/x-flc" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "containers/Demux", "codecs/video/Video" },
|
||||
caps = { decode = true, encode = false, streaming = true, video = { "flic" }, depths = { 8, 15, 16, 24 } },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type OpenOptions = {
|
||||
rgba: boolean?, -- (frames are rgba8 already)
|
||||
maxPixels: number?, -- default 2^26
|
||||
ringFrame: boolean?, -- true: also show the ring frame at the end (as ffmpeg does)
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
local HEADER = 128
|
||||
local FLI, FLC, DTA = 0xAF11, 0xAF12, 0xAF44
|
||||
local FRAME, FRAME2 = 0xF1FA, 0xF5FA
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Fli.sniff(r: Bytes.Reader): number
|
||||
local s = r:peek(18)
|
||||
if #s < 18 then
|
||||
return 0
|
||||
end
|
||||
local magic = string.byte(s, 5) + string.byte(s, 6) * 256
|
||||
if magic ~= FLI and magic ~= FLC and magic ~= DTA then
|
||||
return 0
|
||||
end
|
||||
local w = string.byte(s, 9) + string.byte(s, 10) * 256
|
||||
local h = string.byte(s, 11) + string.byte(s, 12) * 256
|
||||
if w > 4096 or h > 4096 then
|
||||
return 0
|
||||
end
|
||||
return 0.9
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
-- demux(r, opts?) -> the Demuxer | nil, Err
|
||||
function Fli.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?)
|
||||
local b, base, limit = r.buf, r.base, r.limit
|
||||
local n = limit - base
|
||||
if n < HEADER then
|
||||
return nil, Err.new(Err.TRUNCATED, "file shorter than the 128-byte header")
|
||||
end
|
||||
local hr = Bytes.reader(b, base, HEADER)
|
||||
hr:skip(4)
|
||||
local magic = hr:u16le()
|
||||
local frames = hr:u16le()
|
||||
local w, h = hr:u16le(), hr:u16le()
|
||||
local depth = hr:u16le()
|
||||
hr:skip(2)
|
||||
local speed = hr:u32le()
|
||||
if hr.err then
|
||||
return nil, hr.err
|
||||
end
|
||||
if magic ~= FLI and magic ~= FLC and magic ~= DTA then
|
||||
return nil, Err.new(Err.CORRUPT, string.format("bad magic 0x%04x", magic), 4)
|
||||
end
|
||||
if magic == FLI then
|
||||
speed = speed % 65536
|
||||
end
|
||||
if w == 0 or h == 0 then
|
||||
return nil, Err.new(Err.CORRUPT, "no picture size")
|
||||
end
|
||||
local max = (opts and opts.maxPixels) or 2 ^ 26
|
||||
if w * h > max then
|
||||
return nil, Err.new(Err.LIMIT, w .. " x " .. h .. " over maxPixels")
|
||||
end
|
||||
if magic == FLI or depth == 0 then
|
||||
depth = 8
|
||||
elseif magic == FLC and depth == 16 then
|
||||
depth = 15 -- Animator Pro's 16-bit FLCs hold 5-5-5 pixels
|
||||
end
|
||||
if speed == 0 then
|
||||
speed = 5
|
||||
end
|
||||
local scale = if magic == FLI then 70 else 1000
|
||||
local track: Types.Track = {
|
||||
id = 1,
|
||||
kind = "video",
|
||||
codec = "flic",
|
||||
codecTag = string.format("0x%04X", magic),
|
||||
timescale = scale,
|
||||
width = w,
|
||||
height = h,
|
||||
frameRate = scale / speed,
|
||||
default = true,
|
||||
bitsPerPixel = depth,
|
||||
}
|
||||
-- the frame chunks
|
||||
local offs, sizes = {}, {}
|
||||
local p = base + HEADER
|
||||
while p + 6 <= limit do
|
||||
local size = buffer.readu32(b, p)
|
||||
local cm = buffer.readu16(b, p + 4)
|
||||
if size < 6 then
|
||||
break
|
||||
end
|
||||
if (cm == FRAME or cm == FRAME2) and size > 6 then
|
||||
if p + size > limit then
|
||||
break -- a truncated last frame
|
||||
end
|
||||
table.insert(offs, p)
|
||||
table.insert(sizes, size)
|
||||
end
|
||||
p += size
|
||||
end
|
||||
local count = #offs
|
||||
if frames > 0 and count > frames and not (opts and opts.ringFrame) then
|
||||
count = frames -- the ring frame is not a frame of the animation
|
||||
end
|
||||
local dmx = Demux.new("fli", { track }, b, {
|
||||
type = magic,
|
||||
frames = frames,
|
||||
depth = depth,
|
||||
speed = speed,
|
||||
ringFrame = #offs > frames and frames > 0,
|
||||
})
|
||||
for i = 1, count do
|
||||
dmx:add(1, (i - 1) * speed, nil, speed, i == 1, offs[i], sizes[i])
|
||||
end
|
||||
dmx:finish()
|
||||
return dmx, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ open
|
||||
-- open(r, opts?) -> a VideoDecoder | nil, Err
|
||||
function Fli.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?)
|
||||
local dmx, err = Fli.demux(r, opts)
|
||||
if not dmx then
|
||||
return nil, err
|
||||
end
|
||||
return Video.open(dmx, opts :: Video.OpenOptions?)
|
||||
end
|
||||
|
||||
return Fli
|
||||
@@ -0,0 +1,166 @@
|
||||
--!strict
|
||||
-- video/flv/Amf: AMF0 values (Adobe's Action Message Format 0, as FLV script data tags use it). Written from the AMF0
|
||||
-- specification and the FLV specification v10. Read: number, boolean, string, object, null, undefined, reference
|
||||
-- (the referenced object), ECMA array, strict array, date (milliseconds), long string; anything else stops the
|
||||
-- value. Write: numbers, booleans, strings, strict arrays and ECMA arrays (ordered key / value lists). Never throws.
|
||||
--
|
||||
-- local name, value = Amf.script(reader) -- a script tag body: "onMetaData", { duration = 12.3, ... }
|
||||
-- Amf.writeValue(w, v); Amf.writeEcma(w, { { "duration", 12.3 }, ... })
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
|
||||
local Amf = {}
|
||||
|
||||
-- null / undefined inside arrays (dropped from objects)
|
||||
Amf.NULL = table.freeze({})
|
||||
|
||||
local MAX_DEPTH = 32
|
||||
|
||||
local function str(r: Bytes.Reader, long: boolean): string
|
||||
local n = if long then r:u32be() else r:u16be()
|
||||
return r:string(n)
|
||||
end
|
||||
|
||||
local readValue: (r: Bytes.Reader, depth: number, refs: { any }) -> any
|
||||
|
||||
-- object properties up to the end marker (00 00 09) or the end of the data
|
||||
local function props(r: Bytes.Reader, depth: number, refs: { any }, into: { [string]: any }): boolean
|
||||
while not r.err and r:remaining() >= 3 do
|
||||
local key = str(r, false)
|
||||
if key == "" and r:peekU8() == 9 then
|
||||
r:skip(1)
|
||||
return true
|
||||
end
|
||||
local v = readValue(r, depth + 1, refs)
|
||||
if r.err or v == nil then
|
||||
return false
|
||||
end
|
||||
if v ~= Amf.NULL then
|
||||
into[key] = v
|
||||
end
|
||||
end
|
||||
return false
|
||||
end
|
||||
|
||||
readValue = function(r: Bytes.Reader, depth: number, refs: { any }): any
|
||||
if depth > MAX_DEPTH or r:remaining() < 1 then
|
||||
return nil
|
||||
end
|
||||
local t = r:u8()
|
||||
if t == 0 then
|
||||
return r:f64be()
|
||||
elseif t == 1 then
|
||||
return r:u8() ~= 0
|
||||
elseif t == 2 then
|
||||
return str(r, false)
|
||||
elseif t == 12 then
|
||||
return str(r, true)
|
||||
elseif t == 3 or t == 8 then
|
||||
if t == 8 then
|
||||
r:u32be() -- the count (approximate in practice: the end marker ends it)
|
||||
end
|
||||
local o: { [string]: any } = {}
|
||||
table.insert(refs, o)
|
||||
props(r, depth, refs, o)
|
||||
return o
|
||||
elseif t == 10 then
|
||||
local n = r:u32be()
|
||||
local a: { any } = {}
|
||||
table.insert(refs, a)
|
||||
for i = 1, n do
|
||||
if r.err or r:remaining() < 1 then
|
||||
break
|
||||
end
|
||||
local v = readValue(r, depth + 1, refs)
|
||||
if v == nil then
|
||||
break
|
||||
end
|
||||
a[i] = v
|
||||
end
|
||||
return a
|
||||
elseif t == 5 or t == 6 then
|
||||
return Amf.NULL
|
||||
elseif t == 7 then
|
||||
local i = r:u16be()
|
||||
return refs[i + 1] or Amf.NULL
|
||||
elseif t == 11 then
|
||||
local ms = r:f64be()
|
||||
r:i16be()
|
||||
return ms
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
-- value(reader) -> the next AMF0 value | nil (unknown type, truncated, nested too deep)
|
||||
function Amf.value(r: Bytes.Reader): any
|
||||
local ok, v = pcall(readValue, r, 0, {})
|
||||
return if ok and not r.err then v else nil
|
||||
end
|
||||
|
||||
-- script(reader) -> name, value: a script data tag body (an AMF0 string, then its value) | nil
|
||||
function Amf.script(r: Bytes.Reader): (string?, any)
|
||||
local name = Amf.value(r)
|
||||
if type(name) ~= "string" then
|
||||
return nil, nil
|
||||
end
|
||||
return name, Amf.value(r)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ write
|
||||
local function writeString(w: Bytes.Writer, s: string)
|
||||
if #s > 65535 then
|
||||
w:u8(12)
|
||||
w:u32be(#s)
|
||||
else
|
||||
w:u8(2)
|
||||
w:u16be(#s)
|
||||
end
|
||||
w:string(s)
|
||||
end
|
||||
|
||||
-- writeValue(w, v): a number, boolean, string, array (strict array) or Amf.NULL; other values are written as null
|
||||
function Amf.writeValue(w: Bytes.Writer, v: any)
|
||||
local t = type(v)
|
||||
if t == "number" then
|
||||
w:u8(0)
|
||||
w:f64be(v)
|
||||
elseif t == "boolean" then
|
||||
w:u8(1)
|
||||
w:u8(if v then 1 else 0)
|
||||
elseif t == "string" then
|
||||
writeString(w, v)
|
||||
elseif t == "table" and v ~= Amf.NULL and #v > 0 then
|
||||
w:u8(10)
|
||||
w:u32be(#v)
|
||||
for _, x in v do
|
||||
Amf.writeValue(w, x)
|
||||
end
|
||||
else
|
||||
w:u8(5)
|
||||
end
|
||||
end
|
||||
|
||||
-- writeEcma(w, list): an ECMA array of { key, value } pairs (values: as writeValue; a list nested as
|
||||
-- { key, { pairs = { ... } } } becomes an object)
|
||||
function Amf.writeEcma(w: Bytes.Writer, list: { { any } }, object: boolean?)
|
||||
if object then
|
||||
w:u8(3)
|
||||
else
|
||||
w:u8(8)
|
||||
w:u32be(#list)
|
||||
end
|
||||
for _, kv in list do
|
||||
local k: string = kv[1]
|
||||
w:u16be(#k)
|
||||
w:string(k)
|
||||
local v = kv[2]
|
||||
if type(v) == "table" and v.pairs then
|
||||
Amf.writeEcma(w, v.pairs, true)
|
||||
else
|
||||
Amf.writeValue(w, v)
|
||||
end
|
||||
end
|
||||
w:u16be(0)
|
||||
w:u8(9)
|
||||
end
|
||||
|
||||
return Amf
|
||||
@@ -0,0 +1,288 @@
|
||||
--!strict
|
||||
-- video/flv/Mux: the FLV writer (Adobe's Video File Format Specification v10): the header, an onMetaData script tag
|
||||
-- (duration, width, height, data rates, frame rate, codec ids, audio format, encoder, file size), the H.264
|
||||
-- AVCDecoderConfigurationRecord / AAC AudioSpecificConfig sequence headers, the packets of codecs/video/Video/Source
|
||||
-- streams as tags interleaved by decode time (milliseconds, shifted so none is negative; H.264 composition times),
|
||||
-- and H.264's end-of-sequence tag. AAC from ADTS sources (MPEG-TS) is split into raw frames with a configuration made
|
||||
-- from the first ADTS header. Interpreted; never throws (returns nil, Err).
|
||||
local Err = require("@rosetta/core/Err")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
local Amf = require("@rosetta/video/flv/Amf")
|
||||
|
||||
local Mux = {}
|
||||
|
||||
-- the codecs FLV holds (copied from the source)
|
||||
local VIDEO_COPY: { [string]: boolean } = { h264 = true, flv1 = true, vp6f = true, vp6a = true, flashsv = true, flashsv2 = true }
|
||||
local AUDIO_COPY: { [string]: boolean } = { aac = true, mp3 = true, pcm_s16le = true, pcm_u8 = true, pcm_alaw = true, pcm_mulaw = true, adpcm_swf = true, nellymoser = true, speex = true }
|
||||
Mux.VIDEO_COPY = VIDEO_COPY
|
||||
Mux.AUDIO_COPY = AUDIO_COPY
|
||||
|
||||
local VIDEO_IDS: { [string]: number } = { flv1 = 2, flashsv = 3, vp6f = 4, vp6a = 5, flashsv2 = 6, h264 = 7 }
|
||||
local AUDIO_FORMATS: { [string]: number } = { pcm_s16le = 3, pcm_u8 = 3, adpcm_swf = 1, mp3 = 2, nellymoser = 6, pcm_alaw = 7, pcm_mulaw = 8, aac = 10, speex = 11 }
|
||||
local RATE_CODES: { [number]: number } = { [5512] = 0, [5513] = 0, [11025] = 1, [22050] = 2, [44100] = 3 }
|
||||
local AAC_RATES = { 96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350 }
|
||||
|
||||
local function isAdts(s: any): boolean
|
||||
if s.track and s.track.adts then
|
||||
return true
|
||||
end
|
||||
local p = s.packets[1]
|
||||
return s.config == nil and p ~= nil and buffer.len(p.data) >= 7 and buffer.readu8(p.data, 0) == 0xFF and buffer.readu8(p.data, 1) >= 0xF0
|
||||
end
|
||||
|
||||
-- audioProblem(stream) -> why FLV cannot hold this audio stream | nil
|
||||
function Mux.audioProblem(s: any): string?
|
||||
local fmt = AUDIO_FORMATS[s.codec]
|
||||
if not fmt then
|
||||
return "FLV has no audio codec " .. tostring(s.codec)
|
||||
end
|
||||
if (s.channels or 1) > 2 then
|
||||
return "FLV audio has at most 2 channels"
|
||||
end
|
||||
local rate = math.floor((s.sampleRate or 0) + 0.5)
|
||||
if s.codec == "aac" then
|
||||
if not s.config and not isAdts(s) then
|
||||
return "AAC without its AudioSpecificConfig"
|
||||
end
|
||||
elseif (s.codec == "pcm_alaw" or s.codec == "pcm_mulaw") and rate ~= 8000 then
|
||||
return "FLV G.711 audio is 8000 Hz (not " .. rate .. ")"
|
||||
elseif s.codec ~= "mp3" and s.codec ~= "speex" and s.codec ~= "nellymoser" and s.codec ~= "pcm_alaw" and s.codec ~= "pcm_mulaw" and RATE_CODES[rate] == nil then
|
||||
return "FLV " .. s.codec .. " audio is 5512, 11025, 22050 or 44100 Hz (not " .. rate .. ")"
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
local function audioFlags(s: any): number
|
||||
local fmt = AUDIO_FORMATS[s.codec]
|
||||
local rate = math.floor((s.sampleRate or 44100) + 0.5)
|
||||
local rc = RATE_CODES[rate] or 3
|
||||
local size = if s.codec == "pcm_u8" then 0 else 1
|
||||
local stereo = if (s.channels or 1) > 1 then 1 else 0
|
||||
if s.codec == "aac" then
|
||||
rc, stereo = 3, 1
|
||||
elseif s.codec == "mp3" and rate == 8000 then
|
||||
fmt = 14
|
||||
elseif s.codec == "speex" then
|
||||
rc, stereo = 0, 0
|
||||
elseif s.codec == "pcm_alaw" or s.codec == "pcm_mulaw" then
|
||||
rc = 0
|
||||
elseif s.codec == "nellymoser" then
|
||||
if rate == 16000 then
|
||||
fmt = 4
|
||||
elseif rate == 8000 then
|
||||
fmt = 5
|
||||
end
|
||||
stereo = 0
|
||||
end
|
||||
return fmt * 16 + rc * 4 + size * 2 + stereo
|
||||
end
|
||||
|
||||
-- ADTS frames -> raw AAC frames (1024 samples each) and the AudioSpecificConfig of the first header
|
||||
local function fromAdts(s: any): ({ any }?, buffer?)
|
||||
local out = {}
|
||||
local cfg: buffer? = nil
|
||||
local rate = s.sampleRate or 44100
|
||||
for _, p in s.packets do
|
||||
local d: buffer = p.data
|
||||
local n = buffer.len(d)
|
||||
local o = 0
|
||||
local t = p.pts
|
||||
while o + 7 <= n do
|
||||
local b1, b2, b3 = buffer.readu8(d, o + 1), buffer.readu8(d, o + 2), buffer.readu8(d, o + 3)
|
||||
if buffer.readu8(d, o) ~= 0xFF or b1 < 0xF0 then
|
||||
return nil, nil
|
||||
end
|
||||
local len = (b3 % 4) * 2048 + buffer.readu8(d, o + 4) * 8 + buffer.readu8(d, o + 5) // 32
|
||||
local hl = if b1 % 2 == 1 then 7 else 9
|
||||
if len < hl or o + len > n then
|
||||
return nil, nil
|
||||
end
|
||||
if not cfg then
|
||||
local aot = b2 // 64 + 1
|
||||
local sfi = (b2 // 4) % 16
|
||||
local ch = (b2 % 2) * 4 + b3 // 64
|
||||
cfg = buffer.create(2)
|
||||
buffer.writeu8(cfg, 0, aot * 8 + sfi // 2)
|
||||
buffer.writeu8(cfg, 1, (sfi % 2) * 128 + ch * 8)
|
||||
rate = AAC_RATES[sfi + 1] or rate
|
||||
end
|
||||
local f = buffer.create(len - hl)
|
||||
buffer.copy(f, 0, d, o + hl, len - hl)
|
||||
table.insert(out, { pts = t, dts = t, duration = 1024 / rate, keyframe = true, data = f })
|
||||
t += 1024 / rate
|
||||
o += len
|
||||
end
|
||||
end
|
||||
return out, cfg
|
||||
end
|
||||
|
||||
local function f64At(b: buffer, at: number, v: number)
|
||||
local t = buffer.create(8)
|
||||
buffer.writef64(t, 0, v)
|
||||
for i = 0, 7 do
|
||||
buffer.writeu8(b, at + i, buffer.readu8(t, 7 - i))
|
||||
end
|
||||
end
|
||||
|
||||
-- mux(streams) -> buffer | nil, Err
|
||||
function Mux.mux(streams: { any }): (buffer?, Err.Err?)
|
||||
local video, audio = nil :: any, nil :: any
|
||||
for _, s in streams do
|
||||
if s.kind == "video" and not video then
|
||||
if not VIDEO_IDS[s.codec] then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "FLV has no video codec " .. tostring(s.codec))
|
||||
end
|
||||
if s.codec == "h264" and (s.config == nil or buffer.len(s.config) < 7 or buffer.readu8(s.config, 0) ~= 1) then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "H.264 without an avcC (an Annex B source) cannot be written to FLV")
|
||||
end
|
||||
video = s
|
||||
elseif s.kind == "audio" and not audio then
|
||||
audio = s
|
||||
end
|
||||
end
|
||||
if not video and not audio then
|
||||
return nil, Err.new(Err.ARG, "no video or audio stream")
|
||||
end
|
||||
local aConfig: buffer? = audio and audio.config
|
||||
local aPackets: { any } = audio and audio.packets or {}
|
||||
if audio and audio.codec == "aac" and isAdts(audio) then
|
||||
local pk, cfg = fromAdts(audio)
|
||||
if not pk or not cfg then
|
||||
return nil, Err.new(Err.CORRUPT, "bad ADTS AAC audio")
|
||||
end
|
||||
aPackets, aConfig = pk, cfg
|
||||
end
|
||||
local order: { { any } } = {} -- { kind, packet }
|
||||
do
|
||||
local vi, ai = 1, 1
|
||||
local vp: { any } = if video then video.packets else {}
|
||||
while vi <= #vp or ai <= #aPackets do
|
||||
local a, v = aPackets[ai], vp[vi]
|
||||
if v and (not a or (v.dts or v.pts) <= (a.dts or a.pts)) then
|
||||
table.insert(order, { "video", v })
|
||||
vi += 1
|
||||
else
|
||||
table.insert(order, { "audio", a })
|
||||
ai += 1
|
||||
end
|
||||
end
|
||||
end
|
||||
-- times: milliseconds, shifted so the earliest decode time is 0 when any is negative
|
||||
local shift = 0
|
||||
local duration = 0
|
||||
local vBytes, aBytes = 0, 0
|
||||
for _, e in order do
|
||||
local p = e[2]
|
||||
local t = p.dts or p.pts
|
||||
if t < -shift then
|
||||
shift = -t
|
||||
end
|
||||
duration = math.max(duration, p.pts + (p.duration or 0))
|
||||
if e[1] == "video" then
|
||||
vBytes += buffer.len(p.data)
|
||||
else
|
||||
aBytes += buffer.len(p.data)
|
||||
end
|
||||
end
|
||||
local function ms(t: number): number
|
||||
return math.floor((t + shift) * 1000 + 0.5)
|
||||
end
|
||||
|
||||
local w = Bytes.writer(65536 + vBytes + aBytes + #order * 20)
|
||||
w:string("FLV")
|
||||
w:u8(1)
|
||||
w:u8((if audio then 4 else 0) + (if video then 1 else 0))
|
||||
w:u32be(9)
|
||||
w:u32be(0)
|
||||
local function tag(kind: number, ts: number, head: { number }, data: buffer?)
|
||||
local n = #head + (if data then buffer.len(data) else 0)
|
||||
w:u8(kind)
|
||||
w:u24be(n)
|
||||
local t = ts % 0x100000000
|
||||
w:u24be(t % 0x1000000)
|
||||
w:u8(t // 0x1000000)
|
||||
w:u24be(0)
|
||||
for _, x in head do
|
||||
w:u8(x)
|
||||
end
|
||||
if data then
|
||||
w:bytes(data)
|
||||
end
|
||||
w:u32be(11 + n)
|
||||
end
|
||||
|
||||
-- onMetaData
|
||||
local props: { { any } } = { { "duration", duration } }
|
||||
if video then
|
||||
table.insert(props, { "width", video.width or 0 })
|
||||
table.insert(props, { "height", video.height or 0 })
|
||||
table.insert(props, { "videodatarate", if duration > 0 then vBytes * 8 / duration / 1000 else 0 })
|
||||
table.insert(props, { "framerate", video.frameRate or 0 })
|
||||
table.insert(props, { "videocodecid", VIDEO_IDS[video.codec] })
|
||||
end
|
||||
if audio then
|
||||
local flags = audioFlags(audio)
|
||||
table.insert(props, { "audiodatarate", if duration > 0 then aBytes * 8 / duration / 1000 else 0 })
|
||||
table.insert(props, { "audiosamplerate", math.floor((audio.sampleRate or 44100) + 0.5) })
|
||||
table.insert(props, { "audiosamplesize", if audio.codec == "pcm_u8" then 8 else 16 })
|
||||
table.insert(props, { "stereo", (audio.channels or 1) > 1 })
|
||||
table.insert(props, { "audiocodecid", flags // 16 })
|
||||
end
|
||||
table.insert(props, { "encoder", "rosetta" })
|
||||
table.insert(props, { "filesize", 0 })
|
||||
local mw = Bytes.writer(512)
|
||||
Amf.writeValue(mw, "onMetaData")
|
||||
Amf.writeEcma(mw, props)
|
||||
local metaBody = mw:finish()
|
||||
local metaAt = w:tell() + 11
|
||||
tag(18, 0, {}, metaBody)
|
||||
local fileSizeAt = metaAt + buffer.len(metaBody) - 3 - 8 -- the last value (filesize) before the end marker
|
||||
|
||||
-- sequence headers
|
||||
local vid = if video then VIDEO_IDS[video.codec] else 0
|
||||
if video and video.codec == "h264" then
|
||||
tag(9, 0, { 0x10 + vid, 0, 0, 0, 0 }, video.config)
|
||||
end
|
||||
local aflags = if audio then audioFlags(audio) else 0
|
||||
if audio and audio.codec == "aac" then
|
||||
tag(8, 0, { aflags, 0 }, aConfig)
|
||||
end
|
||||
local vp6 = if video and (video.codec == "vp6f" or video.codec == "vp6a") then video.config else nil
|
||||
local vp6Byte = if vp6 and buffer.len(vp6) > 0 then buffer.readu8(vp6, 0) else 0
|
||||
if video and (video.codec == "vp6f" or video.codec == "vp6a") and not vp6 then
|
||||
local wd, ht = video.width or 0, video.height or 0
|
||||
vp6Byte = ((16 - wd % 16) % 16) * 16 + (16 - ht % 16) % 16
|
||||
end
|
||||
local lastVideo = 0
|
||||
for _, e in order do
|
||||
local p = e[2]
|
||||
local dts = ms(p.dts or p.pts)
|
||||
if e[1] == "video" then
|
||||
local ft = (if p.keyframe then 1 else 2) * 16 + vid
|
||||
if video.codec == "h264" then
|
||||
local cts = ms(p.pts) - dts
|
||||
if cts < 0 then
|
||||
cts += 0x1000000
|
||||
end
|
||||
tag(9, dts, { ft, 1, cts // 65536 % 256, cts // 256 % 256, cts % 256 }, p.data)
|
||||
elseif vp6 or video.codec == "vp6f" or video.codec == "vp6a" then
|
||||
tag(9, dts, { ft, vp6Byte }, p.data)
|
||||
else
|
||||
tag(9, dts, { ft }, p.data)
|
||||
end
|
||||
lastVideo = math.max(lastVideo, dts)
|
||||
elseif audio.codec == "aac" then
|
||||
tag(8, dts, { aflags, 1 }, p.data)
|
||||
else
|
||||
tag(8, dts, { aflags }, p.data)
|
||||
end
|
||||
end
|
||||
if video and video.codec == "h264" then
|
||||
tag(9, lastVideo, { 0x10 + vid, 2, 0, 0, 0 }, nil)
|
||||
end
|
||||
local out = w:finish()
|
||||
f64At(out, fileSizeAt, buffer.len(out))
|
||||
return out, nil
|
||||
end
|
||||
|
||||
return Mux
|
||||
@@ -0,0 +1,402 @@
|
||||
--!strict
|
||||
-- video/flv: Flash Video (FLV, Adobe's Video File Format Specification v10, and the Enhanced RTMP / FLV extension's
|
||||
-- FourCC video tags). New in rosetta.
|
||||
-- Read: the header, the tag stream and onMetaData (AMF0: duration, width, height, framerate, codec ids, keyframes, ...
|
||||
-- into meta.metadata) into a Demuxer (times in milliseconds; keyframe flags from the video tags; seeking by
|
||||
-- keyframes) and open() returns a VideoDecoder: video through the codecs/video/Video registry (Sorenson Spark / FLV1
|
||||
-- and H.264 decode; VP6 / VP6 alpha, screen video 1 / 2 and enhanced FourCC codecs (HEVC, AV1, VP9) are known tracks
|
||||
-- whose decoding is UNSUPPORTED); H.264's AVCDecoderConfigurationRecord in track.config, composition time offsets
|
||||
-- in the pts. Audio through the api's opts.openAudio hook: MP3 (also 8 kHz), AAC (AudioSpecificConfig in track.config),
|
||||
-- linear PCM (platform-endian read as little-endian), A-law / mu-law, Flash ADPCM (codecs/audio/Adpcm.swf, through
|
||||
-- containers/AudioWrap); Nellymoser and Speex are known tracks without an audio decoder (UNSUPPORTED). Flv.demux(r) gives the Demuxer.
|
||||
-- Write: H.264 / Sorenson Spark / VP6 / screen video copied from the source (FLV has no codec we encode), AAC / MP3 /
|
||||
-- PCM / A-law / mu-law / ADPCM / Nellymoser / Speex audio copied (AAC from ADTS sources re-framed), else PCM s16 at
|
||||
-- the FLV sample rates (5512 / 11025 / 22050 / 44100 Hz), with onMetaData (duration, sizes, frame rate, data
|
||||
-- rates, codec ids, file size).
|
||||
-- Not supported: encrypted tags (the track's packets are dropped, track.unsupported says so), multitrack and ModEx
|
||||
-- enhanced packets (skipped), writing H.264 from Annex B sources (no avcC).
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@rosetta/core/Err")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
local Types = require("@rosetta/Types")
|
||||
local Demux = require("@rosetta/containers/Demux")
|
||||
local Video = require("@rosetta/codecs/video/Video")
|
||||
local Source = require("@rosetta/codecs/video/Video/Source")
|
||||
local H263 = require("@rosetta/codecs/video/H263")
|
||||
local H264 = require("@rosetta/codecs/video/H264")
|
||||
local Aac = require("@rosetta/codecs/audio/Aac")
|
||||
local Amf = require("@rosetta/video/flv/Amf")
|
||||
local Mux = require("@rosetta/video/flv/Mux")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Flv = {
|
||||
name = "flv",
|
||||
category = "video",
|
||||
extensions = { "flv" },
|
||||
mime = { "video/x-flv", "video/flv" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "containers/Demux", "codecs/video/Video", "codecs/video/Video/Source", "codecs/video/H263", "codecs/video/H264", "codecs/audio/Aac" },
|
||||
caps = { decode = true, encode = true, streaming = true, remux = true, video = { "flv1", "h264" }, audio = true, metadata = true },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type OpenOptions = {
|
||||
rgba: boolean?, -- nextFrame returns rgba8 images (default false: yuv420p from the codec)
|
||||
track: number?, -- the video track id (1 video, 2 audio)
|
||||
audio: boolean?, -- false: do not open the audio track
|
||||
maxPackets: number?, -- refuse files with more tags (default 2^24)
|
||||
maxPixels: number?,
|
||||
openAudio: any?, -- set by the api: (demuxer, track) -> audio Decoder
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
video: boolean?, -- false: no video
|
||||
audio: boolean?, -- false: no audio; true: fail when the audio cannot be written (default: dropped)
|
||||
reencodeAudio: boolean?, -- PCM s16 even when the audio could be copied
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
Flv.VIDEO_ID = 1
|
||||
Flv.AUDIO_ID = 2
|
||||
|
||||
-- SoundFormat -> codec id
|
||||
local AUDIO_CODECS: { [number]: string } = {
|
||||
[0] = "pcm", -- platform-endian (little-endian in practice)
|
||||
[1] = "adpcm_swf",
|
||||
[2] = "mp3",
|
||||
[3] = "pcm",
|
||||
[4] = "nellymoser",
|
||||
[5] = "nellymoser",
|
||||
[6] = "nellymoser",
|
||||
[7] = "pcm_alaw",
|
||||
[8] = "pcm_mulaw",
|
||||
[10] = "aac",
|
||||
[11] = "speex",
|
||||
[14] = "mp3",
|
||||
[15] = "device_specific",
|
||||
}
|
||||
local AUDIO_RATES = { [0] = 5512, 11025, 22050, 44100 }
|
||||
-- the formats with a fixed rate (G.711: 8 kHz as ffmpeg reads them) / always mono
|
||||
local FIXED_RATE: { [number]: number } = { [4] = 16000, [5] = 8000, [7] = 8000, [8] = 8000, [11] = 16000, [14] = 8000 }
|
||||
local MONO: { [number]: boolean } = { [4] = true, [5] = true, [11] = true }
|
||||
|
||||
-- CodecID -> codec id
|
||||
local VIDEO_CODECS: { [number]: string } = {
|
||||
[2] = "flv1",
|
||||
[3] = "flashsv",
|
||||
[4] = "vp6f",
|
||||
[5] = "vp6a",
|
||||
[6] = "flashsv2",
|
||||
[7] = "h264",
|
||||
}
|
||||
|
||||
-- Enhanced FLV audio FourCCs
|
||||
local AUDIO_FOURCC: { [string]: string } = { Opus = "opus", fLaC = "flac", mp4a = "aac", [".mp3"] = "mp3", ["ac-3"] = "ac3", ["ec-3"] = "eac3" }
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Flv.sniff(r: Bytes.Reader): number
|
||||
if r:remaining() >= 9 and r:peek(3) == "FLV" then
|
||||
return if r:peekU8(3) == 1 then 1 else 0.6
|
||||
end
|
||||
return 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
local readu8 = buffer.readu8
|
||||
|
||||
local function u24(b: buffer, p: number): number
|
||||
return readu8(b, p) * 65536 + readu8(b, p + 1) * 256 + readu8(b, p + 2)
|
||||
end
|
||||
|
||||
local function s24(b: buffer, p: number): number
|
||||
local v = u24(b, p)
|
||||
return if v >= 0x800000 then v - 0x1000000 else v
|
||||
end
|
||||
|
||||
local function copy(b: buffer, p: number, n: number): buffer
|
||||
local c = buffer.create(n)
|
||||
buffer.copy(c, 0, b, p, n)
|
||||
return c
|
||||
end
|
||||
|
||||
-- the picture size of a codec's first keyframe (Sorenson, VP6, screen video) | nil
|
||||
local function frameSize(codec: string, b: buffer, p: number, n: number): (number?, number?)
|
||||
if codec == "flv1" then
|
||||
local h = H263.header(b, p, n, true)
|
||||
if h then
|
||||
return h.width, h.height
|
||||
end
|
||||
elseif (codec == "vp6f" or codec == "vp6a") and n >= 8 then
|
||||
-- VP6 key frame header: type / quant / marker, version / profile / interlace, [16-bit offset], MB rows, MB
|
||||
-- cols, display rows, display cols; the FLV adjustment byte (p - 1, before the frame) crops width / height
|
||||
local adj = readu8(b, p - 1)
|
||||
local q = p + (if codec == "vp6a" then 3 else 0)
|
||||
if q + 6 > p + n or readu8(b, q) >= 128 then
|
||||
return nil, nil
|
||||
end
|
||||
local b1 = readu8(b, q + 1)
|
||||
local o = q + 2
|
||||
if readu8(b, q) % 2 == 1 or (b1 // 2) % 4 == 0 then
|
||||
o += 2
|
||||
end
|
||||
if o + 4 > p + n then
|
||||
return nil, nil
|
||||
end
|
||||
local w = readu8(b, o + 3) * 16 - adj // 16
|
||||
local h = readu8(b, o + 2) * 16 - adj % 16
|
||||
if w > 0 and h > 0 then
|
||||
return w, h
|
||||
end
|
||||
elseif (codec == "flashsv" or codec == "flashsv2") and n >= 4 then
|
||||
return (readu8(b, p) % 16) * 256 + readu8(b, p + 1), (readu8(b, p + 2) % 16) * 256 + readu8(b, p + 3)
|
||||
end
|
||||
return nil, nil
|
||||
end
|
||||
|
||||
-- demux(r, opts?) -> the Demuxer (containers/Demux) | nil, Err
|
||||
function Flv.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?)
|
||||
local o: OpenOptions = opts or {}
|
||||
local b, base, limit = r.buf, r.base, r.limit
|
||||
if limit - base < 9 or buffer.readstring(b, base, 3) ~= "FLV" then
|
||||
return nil, Err.new(Err.CORRUPT, "not an FLV file (no FLV signature)", base)
|
||||
end
|
||||
local flags = readu8(b, base + 4)
|
||||
local dataOffset = buffer.readu32(b, base + 5)
|
||||
dataOffset = bit32.byteswap(dataOffset)
|
||||
if dataOffset < 9 or base + dataOffset > limit then
|
||||
return nil, Err.new(Err.CORRUPT, "bad header size " .. dataOffset, base + 5)
|
||||
end
|
||||
local meta: { [string]: any } = { version = readu8(b, base + 3), hasAudio = bit32.band(flags, 4) ~= 0, hasVideo = bit32.band(flags, 1) ~= 0 }
|
||||
local tracks: { Types.Track } = {}
|
||||
local dmx = Demux.new("flv", tracks, b, meta)
|
||||
local vt: any, at: any = nil, nil
|
||||
local keyOff, keyLen = -1, 0 -- the first video keyframe
|
||||
local maxPackets = o.maxPackets or 2 ^ 24
|
||||
local count = 0
|
||||
local p = base + dataOffset + 4 -- after PreviousTagSize0
|
||||
while p + 11 <= limit do
|
||||
local tagType = bit32.band(readu8(b, p), 0x1F)
|
||||
local filtered = bit32.band(readu8(b, p), 0x20) ~= 0
|
||||
local size = u24(b, p + 1)
|
||||
local ts = u24(b, p + 4) + readu8(b, p + 7) * 0x1000000
|
||||
if ts >= 0x80000000 then
|
||||
ts -= 0x100000000
|
||||
end
|
||||
local d = p + 11
|
||||
if d + size > limit then
|
||||
meta.truncated = true
|
||||
break
|
||||
end
|
||||
count += 1
|
||||
if count > maxPackets then
|
||||
return nil, Err.new(Err.LIMIT, "more than " .. maxPackets .. " tags")
|
||||
end
|
||||
if tagType == 8 and size >= 1 then
|
||||
local a = readu8(b, d)
|
||||
local fmt = a // 16
|
||||
if not at then
|
||||
at = { id = Flv.AUDIO_ID, kind = "audio", codec = "unknown", codecTag = "flv audio " .. fmt, timescale = 1000, default = true }
|
||||
table.insert(tracks, at)
|
||||
local bits = if (a // 2) % 2 == 1 then 16 else 8
|
||||
local codec = AUDIO_CODECS[fmt] or ("flv_audio_" .. fmt)
|
||||
if codec == "pcm" then
|
||||
codec = if bits == 16 then "pcm_s16le" else "pcm_u8"
|
||||
end
|
||||
at.codec = codec
|
||||
at.soundFormat = fmt
|
||||
at.sampleRate = FIXED_RATE[fmt] or AUDIO_RATES[(a // 4) % 4]
|
||||
at.channels = if MONO[fmt] then 1 else a % 2 + 1
|
||||
at.bitsPerSample = if codec == "pcm_alaw" or codec == "pcm_mulaw" then 8 else bits
|
||||
end
|
||||
if filtered then
|
||||
at.unsupported = "encrypted audio tags"
|
||||
elseif fmt == 10 and at.soundFormat == 10 then
|
||||
if size >= 2 then
|
||||
if readu8(b, d + 1) == 0 then
|
||||
local c = copy(b, d + 2, size - 2)
|
||||
at.config = c
|
||||
local cfg = Aac.config(c)
|
||||
if cfg then
|
||||
at.sampleRate = cfg.extensionRate or cfg.sampleRate
|
||||
at.channels = cfg.channels
|
||||
end
|
||||
elseif size > 2 then
|
||||
dmx:add(at.id, ts, nil, nil, true, d + 2, size - 2)
|
||||
end
|
||||
end
|
||||
elseif fmt == 9 and at.soundFormat == 9 then
|
||||
-- Enhanced FLV: packet type, FourCC
|
||||
if size >= 5 then
|
||||
local pt = a % 16
|
||||
local fcc = buffer.readstring(b, d + 1, 4)
|
||||
at.codec = AUDIO_FOURCC[fcc] or fcc
|
||||
at.codecTag = fcc
|
||||
if pt == 0 then
|
||||
at.config = copy(b, d + 5, size - 5)
|
||||
elseif pt == 1 and size > 5 then
|
||||
dmx:add(at.id, ts, nil, nil, true, d + 5, size - 5)
|
||||
end
|
||||
end
|
||||
elseif fmt == at.soundFormat and size > 1 then
|
||||
dmx:add(at.id, ts, nil, nil, true, d + 1, size - 1)
|
||||
end
|
||||
elseif tagType == 9 and size >= 1 then
|
||||
local v = readu8(b, d)
|
||||
local enhanced = v >= 128
|
||||
local frameType = if enhanced then (v // 16) % 8 else v // 16
|
||||
if frameType ~= 5 then -- not a video info / command frame
|
||||
local codec: string?, codecTag: string? = nil, nil
|
||||
local pt, cts, q, n = 0, 0, 0, 0
|
||||
if enhanced then
|
||||
if size < 5 then
|
||||
codec = nil
|
||||
else
|
||||
local fcc = buffer.readstring(b, d + 1, 4)
|
||||
codec, codecTag = Video.fromFourcc(fcc) or fcc, fcc
|
||||
pt = v % 16
|
||||
q, n, cts = d + 5, size - 5, 0
|
||||
if pt == 1 and (fcc == "avc1" or fcc == "hvc1") then
|
||||
if n >= 3 then
|
||||
cts = s24(b, q)
|
||||
end
|
||||
q, n = q + 3, n - 3
|
||||
elseif pt == 3 then
|
||||
pt = 1 -- coded frames without a composition time
|
||||
end
|
||||
end
|
||||
else
|
||||
local id = v % 16
|
||||
codec = VIDEO_CODECS[id] or ("flv_video_" .. id)
|
||||
codecTag = "flv video " .. id
|
||||
pt, q, n, cts = 1, d + 1, size - 1, 0
|
||||
if codec == "h264" then
|
||||
if size >= 5 then
|
||||
pt = readu8(b, d + 1)
|
||||
cts = s24(b, d + 2)
|
||||
else
|
||||
pt = 2
|
||||
end
|
||||
q, n = d + 5, size - 5
|
||||
elseif codec == "vp6f" or codec == "vp6a" then
|
||||
q, n = d + 2, size - 2 -- after the adjustment byte (the track's config, as ffmpeg's extradata)
|
||||
end
|
||||
end
|
||||
if codec then
|
||||
if not vt then
|
||||
vt = { id = Flv.VIDEO_ID, kind = "video", codec = codec, codecTag = codecTag, timescale = 1000, default = true }
|
||||
table.insert(tracks, vt)
|
||||
end
|
||||
if (codec == "vp6f" or codec == "vp6a") and not vt.config and size >= 2 then
|
||||
vt.config = copy(b, d + 1, 1) -- the crop (adjustment) byte
|
||||
end
|
||||
if filtered then
|
||||
vt.unsupported = "encrypted video tags"
|
||||
elseif codec == vt.codec then
|
||||
if pt == 0 then
|
||||
if n > 0 then
|
||||
vt.config = copy(b, q, n)
|
||||
end
|
||||
elseif pt == 1 and n > 0 then
|
||||
local key = frameType == 1
|
||||
dmx:add(vt.id, ts + cts, ts, nil, key, q, n)
|
||||
if key and keyOff < 0 then
|
||||
keyOff, keyLen = q, n
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
elseif tagType == 18 and size > 0 then
|
||||
local name, value = Amf.script(Bytes.reader(b, d, size))
|
||||
if name == "onMetaData" and type(value) == "table" and meta.metadata == nil then
|
||||
meta.metadata = value
|
||||
elseif name then
|
||||
meta.scripts = meta.scripts or {}
|
||||
table.insert(meta.scripts, { name = name, time = ts / 1000, value = value })
|
||||
end
|
||||
end
|
||||
p = d + size + 4
|
||||
end
|
||||
-- the track facts onMetaData and the codec headers give
|
||||
local md: { [string]: any } = meta.metadata or {}
|
||||
if type(md.duration) == "number" and md.duration > 0 then
|
||||
meta.duration = md.duration
|
||||
end
|
||||
if vt then
|
||||
if vt.codec == "h264" and vt.config then
|
||||
local ok, info = pcall(H264.info, vt.config)
|
||||
if ok and info then
|
||||
vt.width, vt.height = info.width, info.height
|
||||
end
|
||||
elseif keyOff >= 0 then
|
||||
local w, h = frameSize(vt.codec, b, keyOff, keyLen)
|
||||
vt.width, vt.height = w, h
|
||||
end
|
||||
if not vt.width and type(md.width) == "number" and type(md.height) == "number" then
|
||||
vt.width, vt.height = math.floor(md.width), math.floor(md.height)
|
||||
end
|
||||
local fr = md.framerate or md.videoframerate
|
||||
if type(fr) == "number" and fr > 0 and fr < 1000 then
|
||||
vt.frameRate = fr
|
||||
else
|
||||
-- from the timestamps: the frames over the time they span
|
||||
local n = dmx:count(vt.id)
|
||||
local t0 = if n > 0 then dmx:info(vt.id, 1) else nil
|
||||
local t1 = if n > 1 then dmx:info(vt.id, n) else nil
|
||||
if t0 and t1 and t1 > t0 then
|
||||
vt.frameRate = math.floor((n - 1) / ((t1 - t0) / 1000) * 1000 + 0.5) / 1000
|
||||
end
|
||||
end
|
||||
end
|
||||
if at and at.codec == "aac" and not at.config then
|
||||
at.unsupported = "AAC without its AudioSpecificConfig"
|
||||
end
|
||||
dmx:finish()
|
||||
return dmx, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
-- encode(video, opts?) -> buffer | nil, Err: a VideoDecoder (F.load / F.video.open) or a Demuxer
|
||||
function Flv.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
local o: any = opts or {}
|
||||
local streams, err = Source.streams(value, o, {
|
||||
video = { copy = Mux.VIDEO_COPY },
|
||||
audio = { copy = Mux.AUDIO_COPY, pcm = true },
|
||||
})
|
||||
if not streams then
|
||||
return nil, err
|
||||
end
|
||||
-- audio FLV cannot hold (PCM at other rates): dropped, or an error with opts.audio = true
|
||||
for i = #streams, 1, -1 do
|
||||
local s = streams[i]
|
||||
local why = s.kind == "audio" and Mux.audioProblem(s)
|
||||
if why then
|
||||
if o.audio == true then
|
||||
return nil, Err.new(Err.UNSUPPORTED, why)
|
||||
end
|
||||
table.remove(streams, i)
|
||||
end
|
||||
end
|
||||
if #streams == 0 then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "nothing FLV can hold")
|
||||
end
|
||||
local ok, buf, merr = pcall(Mux.mux, streams)
|
||||
if not ok then
|
||||
return nil, Err.new(Err.ARG, "internal error: " .. tostring(buf))
|
||||
end
|
||||
return buf, merr
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ open
|
||||
-- open(r, opts?) -> a VideoDecoder (kind "video": nextFrame / seek / audio / demuxer) | nil, Err
|
||||
function Flv.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?)
|
||||
local ok, dmx, err = pcall(Flv.demux, r, opts)
|
||||
if not ok then
|
||||
return nil, Err.new(Err.CORRUPT, "internal error: " .. tostring(dmx))
|
||||
end
|
||||
if not dmx then
|
||||
return nil, err
|
||||
end
|
||||
return Video.open(dmx, opts :: Video.OpenOptions?)
|
||||
end
|
||||
|
||||
return Flv
|
||||
@@ -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 rosetta.
|
||||
-- Read: the stream cut into access units (codecs/video/H264.accessUnits) as a one-track Demuxer; open() returns a
|
||||
-- VideoDecoder decoding through codecs/video/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/video/H264 does not decode (interlaced, 4:2:2 / 4:4:4, > 8 bits: UNSUPPORTED).
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@rosetta/core/Err")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
local Types = require("@rosetta/Types")
|
||||
local Demux = require("@rosetta/containers/Demux")
|
||||
local Video = require("@rosetta/codecs/video/Video")
|
||||
local Source = require("@rosetta/codecs/video/Video/Source")
|
||||
local H264 = require("@rosetta/codecs/video/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/Video", "codecs/video/Video/Source", "codecs/video/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
|
||||
@@ -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/Video/Source (copied packets or encoded frames). Interpreted; never throws.
|
||||
local Err = require("@rosetta/core/Err")
|
||||
local Ebml = require("@rosetta/containers/Ebml")
|
||||
local Video = require("@rosetta/codecs/video/Video")
|
||||
local Source = require("@rosetta/codecs/video/Video/Source")
|
||||
local Parse = require("@rosetta/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 "rosetta"
|
||||
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
|
||||
@@ -0,0 +1,730 @@
|
||||
--!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("@rosetta/core/Err")
|
||||
local Types = require("@rosetta/Types")
|
||||
local Ebml = require("@rosetta/containers/Ebml")
|
||||
local Demux = require("@rosetta/containers/Demux")
|
||||
local Video = require("@rosetta/codecs/video/Video")
|
||||
local Avi = require("@rosetta/containers/Avi")
|
||||
local QtPalette = require("@rosetta/containers/IsoBmff/QtPalette")
|
||||
local Deflate = require("@rosetta/codecs/compress/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/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
|
||||
|
||||
-- V_MS/VFW/FOURCC (CodecPrivate = a BITMAPINFOHEADER) and V_QUICKTIME (CodecPrivate = a QuickTime sample
|
||||
-- description, sometimes without its size field): the codec from the FourCC, the depth and palette, the extradata
|
||||
local function vfwOrQuickTime(t: any, codecId: string, priv: buffer)
|
||||
local n = buffer.len(priv)
|
||||
if codecId == "V_MS/VFW/FOURCC" then
|
||||
local bi = Avi.bitmapInfo(priv)
|
||||
if bi then
|
||||
t.codec = Video.fromFourcc(bi.compression) or t.codec
|
||||
t.codecTag = bi.compression
|
||||
t.bitsPerPixel = bi.bits
|
||||
t.palette = bi.palette
|
||||
t.config = bi.extra
|
||||
end
|
||||
elseif codecId == "V_QUICKTIME" and n >= 21 then
|
||||
local desc = priv
|
||||
if Video.fromFourcc(buffer.readstring(priv, 0, 4)) then
|
||||
desc = buffer.create(n + 4)
|
||||
local size = n + 4
|
||||
buffer.writeu8(desc, 0, size // 16777216 % 256)
|
||||
buffer.writeu8(desc, 1, size // 65536 % 256)
|
||||
buffer.writeu8(desc, 2, size // 256 % 256)
|
||||
buffer.writeu8(desc, 3, size % 256)
|
||||
buffer.copy(desc, 4, priv, 0, n)
|
||||
end
|
||||
local fcc = buffer.readstring(desc, 4, 4)
|
||||
t.codec = Video.fromFourcc(fcc) or t.codec
|
||||
t.codecTag = fcc
|
||||
local depth, pal = QtPalette.read(desc, 0, buffer.len(desc), t.codec)
|
||||
t.bitsPerPixel = depth
|
||||
t.palette = pal
|
||||
end
|
||||
end
|
||||
|
||||
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)
|
||||
local cfg: buffer? = t.config
|
||||
if t.kind == "video" and cfg then
|
||||
vfwOrQuickTime(t, codecId, cfg)
|
||||
end
|
||||
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
|
||||
-- docType(buf, base, limit) -> the EBML header's DocType ("matroska" when it has none), the header's size and data
|
||||
-- offset | nil, Err
|
||||
function Parse.docType(buf: buffer, base: number, limit: number): (string?, any, number?)
|
||||
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
|
||||
return docType, size, data
|
||||
end
|
||||
|
||||
function Parse.parse(buf: buffer, base: number, limit: number, opts: Options?): (any, Err.Err?)
|
||||
local docType, size, data = Parse.docType(buf, base, limit)
|
||||
if not docType then
|
||||
return nil, size
|
||||
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
|
||||
@@ -0,0 +1,169 @@
|
||||
--!strict
|
||||
-- video/mkv: Matroska and WebM (the Matroska specification / RFC 9559, the WebM container guidelines). New in
|
||||
-- rosetta, 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/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("@rosetta/core/Err")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
local Types = require("@rosetta/Types")
|
||||
local Video = require("@rosetta/codecs/video/Video")
|
||||
local Source = require("@rosetta/codecs/video/Video/Source")
|
||||
local Parse = require("@rosetta/video/mkv/Parse")
|
||||
local Mux = require("@rosetta/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", "containers/Avi", "containers/IsoBmff/QtPalette", "codecs/compress/Deflate", "codecs/video/Video", "codecs/video/Video/Source" },
|
||||
caps = { decode = true, encode = true, streaming = true, remux = true, video = { "vp8", "mjpeg", "mpeg1", "mpeg2", "theora", "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
|
||||
|
||||
-- variant(r) -> "webm" for a WebM file (DocType webm), else nil: the name F.detect reports (never throws)
|
||||
function Mkv.variant(r: Bytes.Reader): string?
|
||||
local ok, docType = pcall(Parse.docType, r.buf, r.pos, r.limit)
|
||||
if ok and docType == "webm" then
|
||||
return "webm"
|
||||
end
|
||||
return nil
|
||||
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 :: Video.OpenOptions?)
|
||||
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) } :: Types.Cue)
|
||||
end
|
||||
end
|
||||
return subs
|
||||
end
|
||||
|
||||
return Mkv
|
||||
@@ -0,0 +1,341 @@
|
||||
--!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 rosetta.
|
||||
-- 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/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("@rosetta/core/Err")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
local Types = require("@rosetta/Types")
|
||||
local IsoBmff = require("@rosetta/containers/IsoBmff")
|
||||
local Demux = require("@rosetta/containers/Demux")
|
||||
local Video = require("@rosetta/codecs/video/Video")
|
||||
local Source = require("@rosetta/codecs/video/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/Video", "codecs/video/Video/Source" },
|
||||
caps = { decode = true, encode = true, streaming = true, remux = true, video = { "mjpeg", "mpeg1", "mpeg2", "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,
|
||||
bitsPerPixel = it.bitsPerPixel,
|
||||
palette = it.palette,
|
||||
}
|
||||
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
|
||||
if it.playDuration and it.playDuration > 0 and it.timescale > 0 then
|
||||
t.playDuration = it.playDuration / it.timescale -- the edit's length: the end padding is not played
|
||||
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
|
||||
-- video: the skipped decode delay is a composition shift, every frame still plays (ffmpeg drops the frames an
|
||||
-- edit cuts); audio: the codec delay samples are not played
|
||||
local playDuration = nil
|
||||
if s.kind == "video" and skip > 0 then
|
||||
playDuration = 0
|
||||
for _, d in durations do
|
||||
playDuration += d
|
||||
end
|
||||
elseif s.kind == "audio" and s.track and s.copied and type(s.track.playDuration) == "number" then
|
||||
playDuration = math.floor(s.track.playDuration * scale + 0.5) -- keep the source's end trim
|
||||
end
|
||||
local t: any = {
|
||||
kind = s.kind,
|
||||
timescale = scale,
|
||||
skip = if skip > 0 then skip else nil,
|
||||
playDuration = playDuration,
|
||||
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 :: Video.OpenOptions?)
|
||||
end
|
||||
|
||||
return Mp4
|
||||
@@ -0,0 +1,193 @@
|
||||
--!strict
|
||||
-- video/mpegps: MPEG program streams (ISO/IEC 11172-1 system streams and 13818-1 program streams: .mpg / .mpeg /
|
||||
-- .vob / VCD .dat). New in rosetta, 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, both
|
||||
-- fields of a field-coded frame in one); 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 / MPEG-2 video through the codecs/video/Video registry (MPEG-2 told by its
|
||||
-- sequence extension), 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("@rosetta/core/Err")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
local Types = require("@rosetta/Types")
|
||||
local MpegPs = require("@rosetta/containers/MpegPs")
|
||||
local MpegEs = require("@rosetta/containers/MpegEs")
|
||||
local Demux = require("@rosetta/containers/Demux")
|
||||
local Video = require("@rosetta/codecs/video/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/Video" },
|
||||
caps = { decode = true, encode = false, streaming = true, video = { "mpeg1", "mpeg2" }, 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,
|
||||
} :: Types.Track)
|
||||
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 :: Video.OpenOptions?)
|
||||
end
|
||||
|
||||
return Ps
|
||||
@@ -0,0 +1,246 @@
|
||||
--!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 / MPEG-2 video through the
|
||||
-- codecs/video/Video registry (stream types 0x01 / 0x02, and private ones such as 0x80 with a video PES stream id,
|
||||
-- told apart by 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("@rosetta/core/Err")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
local Types = require("@rosetta/Types")
|
||||
local MpegTs = require("@rosetta/containers/MpegTs")
|
||||
local MpegEs = require("@rosetta/containers/MpegEs")
|
||||
local Demux = require("@rosetta/containers/Demux")
|
||||
local Video = require("@rosetta/codecs/video/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/Video" },
|
||||
caps = { decode = true, encode = false, streaming = true, video = { "mpeg1", "mpeg2", "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 :: Types.Track)
|
||||
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 :: Video.OpenOptions?)
|
||||
end
|
||||
|
||||
return Ts
|
||||
@@ -0,0 +1,407 @@
|
||||
--!strict
|
||||
-- video/ogv: Ogg video (.ogv, or .ogg with a Theora stream: the Ogg Theora mapping of the Theora I specification,
|
||||
-- RFC 3533 / 5334). New in rosetta, on containers/Ogg and containers/Demux.
|
||||
-- Read: open() demuxes every logical stream of the first Ogg group into a packet index: Theora video (frame times from
|
||||
-- the granule positions: keyframe number << shift | frames since it; the three headers become track.config,
|
||||
-- Xiph-laced as in Matroska, so codecs/video/Theora decodes it through the codecs/video/Video registry), Vorbis /
|
||||
-- Opus / FLAC audio (headers in track.config, times from the granules) reaching the audio formats through the api's
|
||||
-- opts.openAudio hook; the Theora comment header's tags go to meta.tags. Ogv.demux(r) gives the Demuxer alone.
|
||||
-- Write: remux (encode): a Theora video track copied from the source (ogv / mkv), plus its Vorbis / Opus audio copied
|
||||
-- (the audio pages come from containers/AudioWrap and are interleaved by time).
|
||||
-- Not supported: chained Ogg files (only the first group of streams), Skeleton / Kate / Speex streams (skipped),
|
||||
-- encoding Theora (there is no encoder: other sources cannot be written).
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@rosetta/core/Err")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
local Types = require("@rosetta/Types")
|
||||
local Ogg = require("@rosetta/containers/Ogg")
|
||||
local Demux = require("@rosetta/containers/Demux")
|
||||
local AudioWrap = require("@rosetta/containers/AudioWrap")
|
||||
local Theora = require("@rosetta/codecs/video/Theora")
|
||||
local Video = require("@rosetta/codecs/video/Video")
|
||||
local Source = require("@rosetta/codecs/video/Video/Source")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Ogv = {
|
||||
name = "ogv",
|
||||
category = "video",
|
||||
extensions = { "ogv", "ogg" },
|
||||
mime = { "video/ogg" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "containers/Demux", "containers/AudioWrap", "codecs/video/Theora", "codecs/video/Video", "codecs/video/Video/Source" },
|
||||
caps = { decode = true, encode = true, streaming = true, remux = true, video = { "theora" }, audio = true },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type OpenOptions = {
|
||||
rgba: boolean?, -- nextFrame returns rgba8 images (default false: yuv420p from the codec)
|
||||
track: number?, -- the video track id to decode (default: the first video track)
|
||||
audio: boolean?, -- false: do not open the audio track
|
||||
maxPixels: number?,
|
||||
verify: boolean?, -- false: skip the page CRC checks (default true)
|
||||
openAudio: any?, -- set by the api: (demuxer, track) -> audio Decoder
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
audio: boolean?, -- false: no audio; true: fail when the audio cannot be copied (default: dropped)
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
local AUDIO = { vorbis = true, opus = true, flac = true }
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
-- 1 when one of the beginning-of-stream pages at the start of an Ogg file is a Theora identification header (plain
|
||||
-- Ogg Vorbis / Opus / FLAC files are left to the audio formats)
|
||||
function Ogv.sniff(r: Bytes.Reader): number
|
||||
if r:peek(4) ~= "OggS" then
|
||||
return 0
|
||||
end
|
||||
local b, p, lim = r.buf, r.pos, r.limit
|
||||
for _ = 1, 8 do
|
||||
if p + 27 > lim or buffer.readstring(b, p, 4) ~= "OggS" or buffer.readu8(b, p + 5) % 4 < 2 then
|
||||
return 0
|
||||
end
|
||||
local nseg = buffer.readu8(b, p + 26)
|
||||
local d = p + 27 + nseg
|
||||
if d + 7 <= lim and buffer.readu8(b, d) == 0x80 and buffer.readstring(b, d + 1, 6) == "theora" then
|
||||
return 1
|
||||
end
|
||||
if d > lim then
|
||||
return 0
|
||||
end
|
||||
local size = 0
|
||||
for i = 0, nseg - 1 do
|
||||
size += buffer.readu8(b, p + 27 + i)
|
||||
end
|
||||
p = d + size
|
||||
end
|
||||
return 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
-- the pages of an Ogg buffer: { offset, size, serial, granule, bos }
|
||||
local function pages(b: buffer): { { number } }
|
||||
local out = {}
|
||||
local pos = 0
|
||||
while true do
|
||||
local p = Ogg.Page.find(b, pos, nil, false)
|
||||
if not p then
|
||||
break
|
||||
end
|
||||
table.insert(out, { p.offset, p.size, p.granule, if p.bos then 1 else 0, if p.continued then 1 else 0 })
|
||||
pos = p.offset + p.size
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
-- encode(video, opts?) -> an Ogg file | nil, Err: a VideoDecoder or Demuxer whose video track is Theora (ogv, mkv)
|
||||
function Ogv.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
local o: any = opts or {}
|
||||
local streams, err = Source.streams(value, o, { video = { copy = { theora = true } }, audio = { copy = { vorbis = true, opus = true } } })
|
||||
if not streams then
|
||||
return nil, err
|
||||
end
|
||||
local vs: Source.Stream? = nil
|
||||
local as: Source.Stream? = nil
|
||||
for _, s in streams do
|
||||
if s.kind == "video" and s.codec == "theora" and not vs then
|
||||
vs = s
|
||||
elseif s.kind == "audio" and s.copied and not as then
|
||||
as = s
|
||||
end
|
||||
end
|
||||
if not vs or not vs.config then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "only Theora video can be written (no Theora encoder)")
|
||||
end
|
||||
local v = vs :: Source.Stream
|
||||
local headers = Theora.splitConfig(v.config :: buffer)
|
||||
local info = headers and Theora.info(headers[1])
|
||||
if not headers or not info then
|
||||
return nil, Err.new(Err.CORRUPT, "Theora track without its three headers")
|
||||
end
|
||||
local fps = info.fpsNum / info.fpsDen
|
||||
local scale = 2 ^ info.granuleShift
|
||||
local bias = if info.versionMajor * 65536 + info.versionMinor * 256 + info.versionSub >= 0x030201 then 1 else 0
|
||||
-- video pages (serial 0x7468656F), granules from the frame numbers
|
||||
local mux = Ogg.muxer({ pageSize = 4096 })
|
||||
local s = mux:stream(0x7468656F)
|
||||
s:packet(headers[1], 0, { flush = true })
|
||||
s:packet(headers[2], 0)
|
||||
s:packet(headers[3], 0, { flush = true })
|
||||
local key = 0
|
||||
local start = if #v.packets > 0 then v.packets[1].pts else 0
|
||||
for i, p in v.packets do
|
||||
local frame = math.floor((p.pts - start) * fps + 0.5)
|
||||
if buffer.len(p.data) > 0 and buffer.readu8(p.data, 0) // 64 == 0 then
|
||||
key = frame + bias
|
||||
end
|
||||
s:packet(p.data, key * scale + (frame + bias - key), { eos = i == #v.packets })
|
||||
end
|
||||
local video = mux:finish()
|
||||
-- audio pages: the audio track as its own Ogg stream (containers/AudioWrap), interleaved by time
|
||||
local audio: buffer? = nil
|
||||
local arate, askip = 1, 0
|
||||
if as and o.audio ~= false then
|
||||
local a = as :: Source.Stream
|
||||
local track: any = { id = 1, kind = "audio", codec = a.codec, timescale = 1, config = a.config, sampleRate = a.sampleRate, channels = a.channels }
|
||||
local shim = {
|
||||
count = function(_: any, _t: number): number
|
||||
return #a.packets
|
||||
end,
|
||||
get = function(_: any, _t: number, k: number): any
|
||||
local p = a.packets[k]
|
||||
return p and { track = 1, pts = p.pts, duration = p.duration, keyframe = true, data = p.data }
|
||||
end,
|
||||
}
|
||||
local buf, _, aerr = AudioWrap.wrap(shim, track)
|
||||
if not buf and o.audio == true then
|
||||
return nil, aerr
|
||||
end
|
||||
audio = buf
|
||||
if a.codec == "opus" then
|
||||
arate = 48000
|
||||
local c = a.config
|
||||
askip = if c and buffer.len(c) >= 12 then buffer.readu16(c, 10) else 0
|
||||
else
|
||||
arate = a.sampleRate or 44100
|
||||
end
|
||||
elseif o.audio == true and not as then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "the audio track is not Vorbis / Opus")
|
||||
end
|
||||
local vp = pages(video)
|
||||
local ap = if audio then pages(audio) else {}
|
||||
local out = Bytes.writer(buffer.len(video) + (if audio then buffer.len(audio) else 0))
|
||||
local function put(b: buffer, pg: { number })
|
||||
out:bytes(b, pg[1], pg[2])
|
||||
end
|
||||
-- bos pages first (video, then audio), then the other header pages, then data by time
|
||||
put(video, vp[1])
|
||||
if audio and ap[1] then
|
||||
put(audio :: buffer, ap[1])
|
||||
end
|
||||
local vi, ai = 2, 2
|
||||
local function headerPage(list: { { number } }, i: number): boolean
|
||||
local pg = list[i]
|
||||
return pg ~= nil and pg[3] == 0
|
||||
end
|
||||
while headerPage(vp, vi) do
|
||||
put(video, vp[vi])
|
||||
vi += 1
|
||||
end
|
||||
while audio and headerPage(ap, ai) do
|
||||
put(audio :: buffer, ap[ai])
|
||||
ai += 1
|
||||
end
|
||||
local vt, at = 0, 0
|
||||
while vi <= #vp or ai <= #ap do
|
||||
local nv, na = vp[vi], ap[ai]
|
||||
if nv and nv[3] >= 0 then
|
||||
vt = Theora.granuleFrame(info, nv[3]) / fps
|
||||
end
|
||||
if na and na[3] >= 0 then
|
||||
at = (na[3] - askip) / arate
|
||||
end
|
||||
if nv and (not na or vt <= at) then
|
||||
put(video, nv)
|
||||
vi += 1
|
||||
else
|
||||
put(audio :: buffer, na)
|
||||
ai += 1
|
||||
end
|
||||
end
|
||||
return out:finish(), nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ open
|
||||
-- Xiph lacing of header packets (Matroska's CodecPrivate layout): count - 1, the sizes but the last, the packets
|
||||
local function xiphLace(list: { buffer }): buffer
|
||||
local w = Bytes.writer(64)
|
||||
w:u8(#list - 1)
|
||||
for i = 1, #list - 1 do
|
||||
local n = buffer.len(list[i])
|
||||
while n >= 255 do
|
||||
w:u8(255)
|
||||
n -= 255
|
||||
end
|
||||
w:u8(n)
|
||||
end
|
||||
for _, h in list do
|
||||
w:bytes(h)
|
||||
end
|
||||
return w:finish()
|
||||
end
|
||||
|
||||
type Pending = { track: number, pts: number, key: boolean, page: number, data: buffer, off: number, len: number, own: boolean }
|
||||
|
||||
-- demux(r, opts?) -> the Demuxer (containers/Demux) | nil, Err
|
||||
function Ogv.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?)
|
||||
local ogg, err = Ogg.open(r, { verify = not (opts and opts.verify == false) })
|
||||
if not ogg then
|
||||
return nil, err
|
||||
end
|
||||
local src: buffer = ogg.buf
|
||||
local tracks: { Types.Track } = {}
|
||||
local all: { Pending } = {}
|
||||
local meta: { [string]: any } = {}
|
||||
local function add(track: number, pts: number, key: boolean, p: any)
|
||||
table.insert(all, {
|
||||
track = track,
|
||||
pts = pts,
|
||||
key = key,
|
||||
page = p.pageOffset,
|
||||
data = p.data,
|
||||
off = p.offset,
|
||||
len = p.size,
|
||||
own = p.data ~= src,
|
||||
})
|
||||
end
|
||||
for _, st in ogg:streams() do
|
||||
local codec = st.codec
|
||||
if codec ~= "theora" and not AUDIO[codec] then
|
||||
continue
|
||||
end
|
||||
local rd = ogg:reader(st.serial)
|
||||
local headers: { buffer } = {}
|
||||
local nh = if codec == "theora" or codec == "vorbis" then 3 elseif codec == "opus" then 2 else 1
|
||||
while #headers < nh do
|
||||
local p = rd:nextPacket()
|
||||
if not p then
|
||||
break
|
||||
end
|
||||
table.insert(headers, Ogg.copy(p))
|
||||
if codec == "flac" and #headers == 1 and p.size >= 9 then
|
||||
nh = 1 + buffer.readu16(p.data, p.offset + 7) // 256 + (buffer.readu16(p.data, p.offset + 7) % 256) * 256
|
||||
if nh > 64 then
|
||||
nh = 1
|
||||
end
|
||||
end
|
||||
end
|
||||
if #headers < nh then
|
||||
continue
|
||||
end
|
||||
local id = #tracks + 1
|
||||
local track: any = { id = id, kind = "audio", codec = codec, codecTag = codec, timescale = 1, default = true, serial = st.serial }
|
||||
if codec == "theora" then
|
||||
local info = Theora.info(headers[1])
|
||||
if not info then
|
||||
continue
|
||||
end
|
||||
track.kind = "video"
|
||||
track.width, track.height = info.picWidth, info.picHeight
|
||||
track.timescale = info.fpsNum
|
||||
track.frameRate = info.fpsNum / info.fpsDen
|
||||
track.config = xiphLace(headers)
|
||||
local _, _, tags = Theora.comment(headers[2])
|
||||
meta.tags = tags
|
||||
-- frame k of the stream: granule = keyframe << shift | frames since; bitstream 3.2.1 counts from 1
|
||||
local packets = {}
|
||||
local base: number? = nil
|
||||
while true do
|
||||
local p = rd:nextPacket()
|
||||
if not p then
|
||||
break
|
||||
end
|
||||
if p.size > 0 and buffer.readu8(p.data, p.offset) >= 0x80 then
|
||||
continue -- a stray header
|
||||
end
|
||||
table.insert(packets, p)
|
||||
if base == nil and p.granule >= 0 then
|
||||
base = Theora.granuleFrame(info, p.granule) - (#packets - 1)
|
||||
end
|
||||
end
|
||||
local b0 = base or 0
|
||||
for k, p in packets do
|
||||
local key = p.size > 0 and buffer.readu8(p.data, p.offset) // 64 == 0
|
||||
add(id, (b0 + k - 1) * info.fpsDen, key, p)
|
||||
end
|
||||
track.duration = (b0 + #packets) / track.frameRate
|
||||
else
|
||||
local h = headers[1]
|
||||
local rate, channels, skip = 0, 0, 0
|
||||
if codec == "vorbis" and buffer.len(h) >= 16 then
|
||||
channels, rate = buffer.readu8(h, 11), buffer.readu32(h, 12)
|
||||
track.config = xiphLace(headers)
|
||||
elseif codec == "opus" and buffer.len(h) >= 19 then
|
||||
channels, rate, skip = buffer.readu8(h, 9), 48000, buffer.readu16(h, 10)
|
||||
track.config = h
|
||||
track.codecDelay = skip / 48000
|
||||
elseif codec == "flac" and buffer.len(h) >= 9 + 4 + 4 + 18 then
|
||||
local o = 9 + 4 + 4 + 10 -- "fLaC", the block header, STREAMINFO's sample rate field
|
||||
rate = buffer.readu8(h, o) * 4096 + buffer.readu8(h, o + 1) * 16 + buffer.readu8(h, o + 2) // 16
|
||||
channels = (buffer.readu8(h, o + 2) // 2) % 8 + 1
|
||||
local parts = { buffer.create(buffer.len(h) - 9) }
|
||||
buffer.copy(parts[1], 0, h, 9)
|
||||
for i = 2, #headers do
|
||||
table.insert(parts, headers[i])
|
||||
end
|
||||
local total = 0
|
||||
for _, x in parts do
|
||||
total += buffer.len(x)
|
||||
end
|
||||
local cfg = buffer.create(total)
|
||||
local o2 = 0
|
||||
for _, x in parts do
|
||||
buffer.copy(cfg, o2, x)
|
||||
o2 += buffer.len(x)
|
||||
end
|
||||
track.config = cfg
|
||||
end
|
||||
if rate <= 0 or channels <= 0 then
|
||||
continue
|
||||
end
|
||||
track.sampleRate, track.channels, track.timescale = rate, channels, rate
|
||||
local last = 0
|
||||
while true do
|
||||
local p = rd:nextPacket()
|
||||
if not p then
|
||||
break
|
||||
end
|
||||
add(id, math.max(0, last - skip), true, p)
|
||||
if p.granule >= 0 then
|
||||
last = p.granule
|
||||
end
|
||||
end
|
||||
track.duration = math.max(0, last - skip) / rate
|
||||
end
|
||||
table.insert(tracks, track)
|
||||
end
|
||||
if #tracks == 0 then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "no Theora / Vorbis / Opus / FLAC stream")
|
||||
end
|
||||
-- the index in file order (by the page each packet ends on)
|
||||
local order = table.create(#all, 0)
|
||||
for i = 1, #all do
|
||||
order[i] = i
|
||||
end
|
||||
table.sort(order, function(a: number, c: number): boolean
|
||||
local pa, pc = all[a].page, all[c].page
|
||||
if pa ~= pc then
|
||||
return pa < pc
|
||||
end
|
||||
return a < c
|
||||
end)
|
||||
local dmx = Demux.new("ogv", tracks, src, meta)
|
||||
for _, i in order do
|
||||
local e = all[i]
|
||||
if e.own then
|
||||
dmx:addData(e.track, e.pts, e.pts, nil, e.key, e.data)
|
||||
else
|
||||
dmx:add(e.track, e.pts, e.pts, nil, e.key, e.off, e.len)
|
||||
end
|
||||
end
|
||||
dmx:finish()
|
||||
return dmx, nil
|
||||
end
|
||||
|
||||
-- open(r, opts?) -> a VideoDecoder (kind "video": nextFrame / seek / audio / demuxer) | nil, Err
|
||||
function Ogv.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?)
|
||||
local ok, dmx, err = pcall(Ogv.demux, r, opts)
|
||||
if not ok then
|
||||
return nil, Err.new(Err.CORRUPT, "internal error: " .. tostring(dmx))
|
||||
end
|
||||
if not dmx then
|
||||
return nil, err
|
||||
end
|
||||
return Video.open(dmx, opts :: Video.OpenOptions?)
|
||||
end
|
||||
|
||||
return Ogv
|
||||
@@ -0,0 +1,123 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- video/smk/Audio: Smacker's packed audio (SMKA: DPCM with Huffman-coded deltas), the one audio codec only Smacker
|
||||
-- files carry. Written from the format description (MultimediaWiki "Smacker"). A packet: the unpacked size (u32),
|
||||
-- then LSB-first bits: data flag, stereo, 16-bit, one 8-bit Huffman tree per channel and byte (codecs/video/Legacy/
|
||||
-- Smacker trees: 1, 2 or 4), the first sample(s) raw (16-bit ones byte-swapped, the right channel first), then per
|
||||
-- sample a delta added with wraparound (the low byte's tree, and the high byte's for 16 bits). Raw PCM tracks (u8 /
|
||||
-- s16le) are converted here too. Output: interleaved floats (u8: (v - 128) / 128, s16: v / 32768), as ffmpeg gives
|
||||
-- them. Never throws: trees are bounded and every read past the packet gives zero bits.
|
||||
local Smacker = require("@rosetta/codecs/video/Legacy/Smacker")
|
||||
|
||||
local readu8, readi16 = buffer.readu8, buffer.readi16
|
||||
|
||||
local Audio = {}
|
||||
|
||||
-- decode(data, channels, bits, packed) -> frames, floats (1-based interleaved) | nil, message
|
||||
function Audio.decode(d: buffer, channels: number, bits: number, packed: boolean): (number?, { number } | string)
|
||||
local n = buffer.len(d)
|
||||
if not packed then
|
||||
local bps = bits // 8
|
||||
local frames = n // (bps * channels)
|
||||
local count = frames * channels
|
||||
local out = table.create(count, 0)
|
||||
if bps == 1 then
|
||||
for i = 0, count - 1 do
|
||||
out[i + 1] = (readu8(d, i) - 128) / 128
|
||||
end
|
||||
else
|
||||
for i = 0, count - 1 do
|
||||
out[i + 1] = readi16(d, i * 2) / 32768
|
||||
end
|
||||
end
|
||||
return frames, out
|
||||
end
|
||||
if n <= 4 then
|
||||
return nil, "packet too small"
|
||||
end
|
||||
local size = buffer.readu32(d, 0)
|
||||
if size > 2 ^ 24 then
|
||||
return nil, "packet too big"
|
||||
end
|
||||
local br = Smacker.bits(d, 4, n - 4)
|
||||
local bit, read, walk = Smacker.bit, Smacker.read, Smacker.walk
|
||||
if bit(br) == 0 then
|
||||
return 0, {} -- no data
|
||||
end
|
||||
local stereo = bit(br)
|
||||
local wide = bit(br)
|
||||
if (stereo == 1) ~= (channels == 2) or (wide == 1) ~= (bits == 16) then
|
||||
return nil, "packet does not match the track's format"
|
||||
end
|
||||
local bytes = wide + 1
|
||||
local ch = stereo + 1
|
||||
if size % (ch * bytes) ~= 0 then
|
||||
return nil, "unpacked size is not a whole number of samples"
|
||||
end
|
||||
local trees: { { number } } = {}
|
||||
for k = 1, 2 ^ (wide + stereo) do
|
||||
bit(br)
|
||||
local t, msg = Smacker.tree8(br)
|
||||
if not t then
|
||||
return nil, msg or "bad tree"
|
||||
end
|
||||
bit(br)
|
||||
trees[k] = t
|
||||
end
|
||||
if br.nbits - br.pos < ch * bytes * 8 then
|
||||
return nil, "truncated packet"
|
||||
end
|
||||
-- whether any tree needs bits (else every delta is a constant and no end check applies)
|
||||
local coded = false
|
||||
for _, t in trees do
|
||||
if #t > 1 then
|
||||
coded = true
|
||||
end
|
||||
end
|
||||
local frames = size // (ch * bytes)
|
||||
local total = frames * ch
|
||||
local out = table.create(total, 0)
|
||||
if wide == 1 then
|
||||
local pred = { 0, 0 }
|
||||
for c = ch, 1, -1 do
|
||||
local v = read(br, 16)
|
||||
pred[c] = (v // 256) + (v % 256) * 256
|
||||
end
|
||||
for c = 1, math.min(ch, total) do
|
||||
local v = pred[c]
|
||||
out[c] = (if v >= 32768 then v - 65536 else v) / 32768
|
||||
end
|
||||
for i = ch, total - 1 do
|
||||
local c = if ch == 2 then i % 2 else 0
|
||||
if coded and br.pos > br.nbits then
|
||||
return nil, "truncated packet"
|
||||
end
|
||||
local lo = walk(trees[2 * c + 1], br)
|
||||
local hi = walk(trees[2 * c + 2], br)
|
||||
local v = (pred[c + 1] + lo + hi * 256) % 65536
|
||||
pred[c + 1] = v
|
||||
out[i + 1] = (if v >= 32768 then v - 65536 else v) / 32768
|
||||
end
|
||||
else
|
||||
local pred = { 0, 0 }
|
||||
for c = ch, 1, -1 do
|
||||
pred[c] = read(br, 8)
|
||||
end
|
||||
for c = 1, math.min(ch, total) do
|
||||
out[c] = (pred[c] - 128) / 128
|
||||
end
|
||||
for i = ch, total - 1 do
|
||||
local c = if ch == 2 then i % 2 else 0
|
||||
if br.pos > br.nbits then
|
||||
return nil, "truncated packet"
|
||||
end
|
||||
local v = (pred[c + 1] + walk(trees[c + 1], br)) % 256
|
||||
pred[c + 1] = v
|
||||
out[i + 1] = (v - 128) / 128
|
||||
end
|
||||
end
|
||||
return frames, out
|
||||
end
|
||||
|
||||
return Audio
|
||||
@@ -0,0 +1,320 @@
|
||||
--!strict
|
||||
-- video/smk: RAD Game Tools' Smacker video (SMK2 and SMK4). New in rosetta, written from the format description
|
||||
-- (MultimediaWiki "Smacker").
|
||||
-- Read: the header (size, frame count, frame time: > 0 ms, < 0 units of 10 us; the ring-frame flag), up to 7 audio
|
||||
-- tracks (rate, packed / 16-bit / stereo flags), the frame sizes and flags, the four Huffman trees; per frame a palette
|
||||
-- update (skip / copy-from-old / new 6-bit entries), the audio chunks and the video data, into a Demuxer. open()
|
||||
-- returns a VideoDecoder: rgba8 frames from the Smacker video codec (codecs/video/Legacy/Smacker, through the
|
||||
-- codecs/video/Video registry: the frame's palette rides on each packet as packet.palette), and the first audio
|
||||
-- track as an audio Decoder built here (Smacker's packed DPCM audio has no audio format, so the format decodes it
|
||||
-- itself: video/smk/Audio over codecs/audio/Stream; raw u8 / s16le tracks too). The ring frame (the extra frame that
|
||||
-- leads back to the first) is not shown unless opts.ringFrame. Smk.demux(r) gives the Demuxer; Smk.openAudio(dmx,
|
||||
-- track) the Decoder of any of its audio tracks.
|
||||
-- Not supported: writing, Bink audio tracks (flags 0x08 / 0x04: reported as "binkaudio", no decoder).
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@rosetta/core/Err")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
local Types = require("@rosetta/Types")
|
||||
local Demux = require("@rosetta/containers/Demux")
|
||||
local Video = require("@rosetta/codecs/video/Video")
|
||||
local Stream = require("@rosetta/codecs/audio/Stream")
|
||||
local Audio = require("@rosetta/video/smk/Audio")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Smk = {
|
||||
name = "smk",
|
||||
category = "video",
|
||||
extensions = { "smk" },
|
||||
mime = { "video/vnd.radgamettools.smacker" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "containers/Demux", "codecs/video/Video", "codecs/audio/Stream", "codecs/video/Legacy/Smacker" },
|
||||
caps = { decode = true, encode = false, streaming = true, video = { "smackvid" }, audio = { "smackaudio", "pcm_u8", "pcm_s16le" } },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type OpenOptions = {
|
||||
rgba: boolean?, -- (frames are rgba8 already)
|
||||
maxPixels: number?, -- default 2^26
|
||||
audio: boolean?, -- false: do not open the audio track
|
||||
ringFrame: boolean?, -- true: also show the ring frame at the end (as ffmpeg does)
|
||||
openAudio: any?, -- the api's hook: used only for tracks this format cannot decode (Bink audio)
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
local HEADER = 104
|
||||
local RING = 1
|
||||
-- 6-bit palette components -> 8 bits (bit replication: v << 2 | v >> 4)
|
||||
local PAL6 = table.create(64, 0)
|
||||
for i = 0, 63 do
|
||||
PAL6[i + 1] = i * 4 + i // 16
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Smk.sniff(r: Bytes.Reader): number
|
||||
local s = r:peek(4)
|
||||
if s ~= "SMK2" and s ~= "SMK4" then
|
||||
return 0
|
||||
end
|
||||
return 1
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
-- a frame's palette update over the previous palette (pal: 256 u32 R, G, B, A); false when malformed
|
||||
local function palette(b: buffer, p: number, stop: number, old: buffer): (buffer?)
|
||||
local pal = buffer.create(1024)
|
||||
buffer.copy(pal, 0, old, 0, 1024)
|
||||
local function u8(): number
|
||||
local v = if p < stop then buffer.readu8(b, p) else 0
|
||||
p += 1
|
||||
return v
|
||||
end
|
||||
local sz = 0
|
||||
while sz < 256 do
|
||||
local t = u8()
|
||||
if t >= 0x80 then
|
||||
sz += t - 0x80 + 1
|
||||
elseif t >= 0x40 then
|
||||
local off = u8()
|
||||
local j = t - 0x40 + 1
|
||||
if off + j > 256 then
|
||||
return nil
|
||||
end
|
||||
while j > 0 and sz < 256 do
|
||||
buffer.writeu32(pal, sz * 4, buffer.readu32(old, off * 4))
|
||||
sz += 1
|
||||
off += 1
|
||||
j -= 1
|
||||
end
|
||||
else
|
||||
local r = PAL6[t + 1]
|
||||
local g = PAL6[u8() % 64 + 1]
|
||||
local bl = PAL6[u8() % 64 + 1]
|
||||
buffer.writeu32(pal, sz * 4, r + g * 256 + bl * 65536 + 0xFF000000)
|
||||
sz += 1
|
||||
end
|
||||
end
|
||||
return pal
|
||||
end
|
||||
|
||||
-- demux(r, opts?) -> the Demuxer | nil, Err
|
||||
function Smk.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?)
|
||||
local b, base, limit = r.buf, r.base, r.limit
|
||||
if limit - base < HEADER then
|
||||
return nil, Err.new(Err.TRUNCATED, "file shorter than the header")
|
||||
end
|
||||
local hr = Bytes.reader(b, base, HEADER)
|
||||
local magic = hr:string(4)
|
||||
local w, h, frames = hr:u32le(), hr:u32le(), hr:u32le()
|
||||
local ptsInc = hr:i32le()
|
||||
local flags = hr:u32le()
|
||||
hr:skip(28)
|
||||
local treeSize = hr:u32le()
|
||||
local sizes = { hr:u32le(), hr:u32le(), hr:u32le(), hr:u32le() }
|
||||
local rates, aflags = {}, {}
|
||||
for k = 1, 7 do
|
||||
rates[k] = hr:u24le()
|
||||
aflags[k] = hr:u8()
|
||||
end
|
||||
if hr.err then
|
||||
return nil, hr.err
|
||||
end
|
||||
if magic ~= "SMK2" and magic ~= "SMK4" then
|
||||
return nil, Err.new(Err.CORRUPT, "not a Smacker file")
|
||||
end
|
||||
if w == 0 or h == 0 or w > 32768 or h > 32768 then
|
||||
return nil, Err.new(Err.CORRUPT, "bad picture size")
|
||||
end
|
||||
local max = (opts and opts.maxPixels) or 2 ^ 26
|
||||
if w * h > max then
|
||||
return nil, Err.new(Err.LIMIT, w .. " x " .. h .. " over maxPixels")
|
||||
end
|
||||
local shown = frames
|
||||
if bit32.band(flags, RING) ~= 0 then
|
||||
frames += 1
|
||||
end
|
||||
local p = base + HEADER
|
||||
if frames > 0xFFFFFF or p + frames * 5 + treeSize > limit then
|
||||
return nil, Err.new(Err.TRUNCATED, "frame tables or trees past the end of the file")
|
||||
end
|
||||
-- the trees (with the four sizes in front, as the video codec takes them)
|
||||
local config = buffer.create(16 + treeSize)
|
||||
for k = 1, 4 do
|
||||
buffer.writeu32(config, (k - 1) * 4, sizes[k])
|
||||
end
|
||||
buffer.copy(config, 16, b, p + frames * 5, treeSize)
|
||||
-- frame time: > 0 ms, < 0 units of 10 us (ticks of 1/100000 s)
|
||||
local tick = if ptsInc < 0 then -ptsInc elseif ptsInc > 0 then ptsInc * 100 else 10000
|
||||
local tracks: { Types.Track } = {
|
||||
{
|
||||
id = 1,
|
||||
kind = "video",
|
||||
codec = "smackvid",
|
||||
codecTag = magic,
|
||||
timescale = 100000,
|
||||
width = w,
|
||||
height = h,
|
||||
frameRate = 100000 / tick,
|
||||
default = true,
|
||||
config = config,
|
||||
flags = flags,
|
||||
} :: Types.Track,
|
||||
}
|
||||
local audio: { [number]: Types.Track } = {}
|
||||
for k = 1, 7 do
|
||||
if rates[k] > 0 then
|
||||
local f = aflags[k]
|
||||
local bits = if bit32.band(f, 0x20) ~= 0 then 16 else 8
|
||||
local codec = if bit32.band(f, 0x0C) ~= 0 then "binkaudio"
|
||||
elseif bit32.band(f, 0x80) ~= 0 then "smackaudio"
|
||||
elseif bits == 16 then "pcm_s16le"
|
||||
else "pcm_u8"
|
||||
local t: Types.Track = {
|
||||
id = k + 1,
|
||||
kind = "audio",
|
||||
codec = codec,
|
||||
codecTag = string.format("0x%02X", f),
|
||||
timescale = rates[k],
|
||||
sampleRate = rates[k],
|
||||
channels = if bit32.band(f, 0x10) ~= 0 then 2 else 1,
|
||||
bitsPerSample = bits,
|
||||
default = #tracks == 1,
|
||||
}
|
||||
audio[k] = t
|
||||
table.insert(tracks, t)
|
||||
end
|
||||
end
|
||||
local dmx = Demux.new("smk", tracks, b, { version = magic, flags = flags, frames = shown, ringFrame = frames > shown })
|
||||
local count = if opts and opts.ringFrame then frames else shown
|
||||
local pal = buffer.create(1024)
|
||||
local apts = { 0, 0, 0, 0, 0, 0, 0 }
|
||||
local at = p + frames * 5 + treeSize
|
||||
for i = 0, frames - 1 do
|
||||
local fsize = buffer.readu32(b, p + i * 4)
|
||||
local fflags = buffer.readu8(b, p + frames * 4 + i)
|
||||
local size = fsize - fsize % 4
|
||||
local q, stop = at, math.min(limit, at + size)
|
||||
at += size
|
||||
local ok = true
|
||||
if fflags % 2 == 1 and q < stop then
|
||||
local psize = buffer.readu8(b, q) * 4
|
||||
if psize > size then
|
||||
ok = false
|
||||
else
|
||||
local np = palette(b, q + 1, math.min(stop, q + psize), pal)
|
||||
if np then
|
||||
pal = np
|
||||
else
|
||||
ok = false
|
||||
end
|
||||
q += psize
|
||||
end
|
||||
end
|
||||
for k = 1, 7 do
|
||||
if not ok then
|
||||
break
|
||||
end
|
||||
if bit32.band(fflags, 2 ^ k) ~= 0 then
|
||||
if q + 4 > stop then
|
||||
ok = false
|
||||
break
|
||||
end
|
||||
local asize = buffer.readu32(b, q)
|
||||
local t = audio[k]
|
||||
local min = if t and t.codec ~= "pcm_s16le" then 8 else 4
|
||||
if asize < min or q + asize > stop then
|
||||
ok = false
|
||||
break
|
||||
end
|
||||
if t then
|
||||
local len = asize - 4
|
||||
local frameBytes = (t.channels :: number) * (t.bitsPerSample :: number) // 8
|
||||
local n = if t.codec == "smackaudio" then buffer.readu32(b, q + 4) // frameBytes
|
||||
elseif t.codec == "binkaudio" then 0
|
||||
else len // frameBytes
|
||||
dmx:add(t.id, apts[k], nil, n, true, q + 4, len)
|
||||
apts[k] += n
|
||||
end
|
||||
q += asize
|
||||
end
|
||||
end
|
||||
if ok and i < count then
|
||||
dmx:add(1, i * tick, nil, tick, i == 0 or fsize % 2 == 1, q, math.max(0, stop - q))
|
||||
dmx:setExtra("palette", pal)
|
||||
end
|
||||
end
|
||||
dmx:finish()
|
||||
return dmx, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ open
|
||||
-- openAudio(dmx, track) -> an audio Decoder for one of the demuxer's audio tracks | nil, Err
|
||||
function Smk.openAudio(dmx: any, track: Types.Track): (Types.Decoder?, Err.Err?)
|
||||
local codec = track.codec
|
||||
if codec ~= "smackaudio" and codec ~= "pcm_u8" and codec ~= "pcm_s16le" then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "audio codec " .. codec)
|
||||
end
|
||||
local id = track.id
|
||||
local count = dmx:count(id)
|
||||
local starts: { number } = {}
|
||||
local total = 0
|
||||
for k = 1, count do
|
||||
local pts, _, dur = dmx:info(id, k)
|
||||
starts[k] = pts or total
|
||||
total = (pts or total) + (dur or 0)
|
||||
end
|
||||
starts[count + 1] = total
|
||||
local rate, ch, bits = track.sampleRate :: number, track.channels :: number, track.bitsPerSample :: number
|
||||
local packed = codec == "smackaudio"
|
||||
local floats: { number } = {}
|
||||
local dec: any = {
|
||||
sampleRate = rate,
|
||||
channels = ch,
|
||||
frames = total,
|
||||
duration = total / rate,
|
||||
bitrate = rate * ch * bits,
|
||||
tags = {},
|
||||
}
|
||||
return Stream.packets(dec, {
|
||||
count = count,
|
||||
start = function(i: number): number
|
||||
return starts[math.clamp(i, 1, count + 1)]
|
||||
end,
|
||||
decode = function(i: number): (number?, Err.Err?)
|
||||
local pkt = dmx:get(id, i)
|
||||
if not pkt then
|
||||
return nil, Err.new(Err.TRUNCATED, "no audio packet " .. i)
|
||||
end
|
||||
local n, out = Audio.decode(pkt.data, ch, bits, packed)
|
||||
if not n then
|
||||
return nil, Err.from(out :: string)
|
||||
end
|
||||
floats = out :: { number }
|
||||
return n, nil
|
||||
end,
|
||||
pcm = function(): { number }
|
||||
return floats
|
||||
end,
|
||||
reset = function() end,
|
||||
cumulative = true,
|
||||
})
|
||||
end
|
||||
|
||||
-- open(r, opts?) -> a VideoDecoder | nil, Err
|
||||
function Smk.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?)
|
||||
local dmx, err = Smk.demux(r, opts)
|
||||
if not dmx then
|
||||
return nil, err
|
||||
end
|
||||
local o: any = table.clone(opts or {})
|
||||
type Hook = (any, Types.Track) -> (Types.Decoder?, Err.Err?)
|
||||
local hook = o.openAudio :: Hook?
|
||||
o.openAudio = function(d: any, track: Types.Track): (Types.Decoder?, Err.Err?)
|
||||
if track.codec == "binkaudio" and hook then
|
||||
return hook(d, track)
|
||||
end
|
||||
return Smk.openAudio(d, track)
|
||||
end
|
||||
return Video.open(dmx, o)
|
||||
end
|
||||
|
||||
return Smk
|
||||
@@ -0,0 +1,209 @@
|
||||
--!strict
|
||||
-- video/y4m: YUV4MPEG2 (the mjpegtools / ffmpeg raw video stream). New in rosetta.
|
||||
-- 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("@rosetta/core/Err")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
local Types = require("@rosetta/Types")
|
||||
local Demux = require("@rosetta/containers/Demux")
|
||||
local Video = require("@rosetta/codecs/video/Video")
|
||||
local Source = require("@rosetta/codecs/video/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/Video", "codecs/video/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) :: number) > 0 and (tonumber(b) :: number) > 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 :: Video.OpenOptions?)
|
||||
end
|
||||
|
||||
return Y4m
|
||||
Reference in new issue
Block a user