ws-video: video/mp4 (MP4 / MOV / 3GP on containers/IsoBmff: edit lists, fragments, dOps -> OpusHead, PCM entries, AAC priming as codec delay; writer: copied H.264 / HEVC / AV1 / MJPEG / AAC / ALAC / Opus / FLAC / MP3, MJPEG from frames, PCM in MOV, edit lists for B-frame / codec delays); IsoBmff Mux writes no empty DecoderSpecificInfo (ffmpeg refuses it); writer checks extended to MP4 / MOV / H.264 remux

This commit is contained in:
4DBug committed 2026-10-31 10:02:25 -05:00
1 parent 7165690029
commit 26f4e0cb60
8 files changed
+475 -6

No files matched your search

+12
View File
@@ -302,6 +302,18 @@ local list: { Entry } = {
return require("@formats/video/mkv")
end,
},
{
name = "mp4",
category = "video",
path = "video/mp4",
extensions = { "mp4", "m4v", "mov", "qt", "3gp", "3g2", "mj2" },
mime = { "video/mp4", "video/quicktime", "video/3gpp" },
deps = { "core/Err", "core/Bytes", "Types", "containers/IsoBmff", "containers/Demux", "codecs/Video", "codecs/Video/Source" },
caps = { decode = true, encode = true, streaming = true, remux = true, video = { "mjpeg", "mpeg1", "h264" }, audio = true, fragments = true },
load = function()
return require("@formats/video/mp4")
end,
},
{
name = "mpegps",
category = "video",
+1 -1
View File
@@ -92,7 +92,7 @@ local function esds(w: Bytes.Writer, t: MuxTrack)
c:u24be(0)
c:u32be(t.bitrate or 0)
c:u32be(t.bitrate or 0)
if t.config then
if t.config and buffer.len(t.config) > 0 then -- (MJPEG / MP3 have no decoder-specific info)
descriptor(c, 5, function(s)
s:bytes(t.config :: buffer)
end)
+324
View File
@@ -0,0 +1,324 @@
--!strict
-- video/mp4: MP4 / M4V / QuickTime MOV / 3GP (ISO/IEC 14496-12 / 14496-14, the QuickTime file format), on
-- containers/IsoBmff (ws-m4a's box parser, sample tables, fragments and muxer). New in formats-luau.
-- Read: every track's samples into a Demuxer (pts = dts + composition offset, moved by the edit list: the first
-- edit's media time is subtracted (B-frame delay, AAC priming), an initial empty edit added; sync samples as
-- keyframes; fragmented files too) and open() returns a VideoDecoder: video through the codecs/Video registry (MJPEG
-- 'jpeg' / 'mjpa' / mp4v 0x6C, MPEG-1, raw; H.264 'avc1' with its avcC when a decoder is registered), audio through
-- the api's opts.openAudio hook (AAC, ALAC (audio/m4a), MP3, Opus (dOps -> OpusHead), FLAC, PCM 'sowt' / 'twos' /
-- 'lpcm' / 'ipcm').
-- Write: MP4 (or MOV with opts.format = "mov" / a .mov destination): H.264 / HEVC / AV1 / MJPEG / MPEG-4 video copied
-- from an ISO / Matroska source (their configurations are the same boxes), else MJPEG encoded from the frames (mp4v
-- object type 0x6C in MP4, 'jpeg' in MOV); AAC / ALAC / Opus / FLAC / MP3 audio copied, else PCM s16 ('sowt', MOV
-- only; MP4 drops other audio unless opts.audio = true, which fails).
-- Edit lists are written for a B-frame delay and an audio codec delay (AAC priming). Not supported: fragmented
-- writing, timed text tracks, encrypted tracks.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local IsoBmff = require("@formats/containers/IsoBmff")
local Demux = require("@formats/containers/Demux")
local Video = require("@formats/codecs/Video")
local Source = require("@formats/codecs/Video/Source")
-- ------------------------------------------------------------------------------------------------ contract
local Mp4 = {
name = "mp4",
category = "video",
extensions = { "mp4", "m4v", "mov", "qt", "3gp", "3g2", "mj2" },
mime = { "video/mp4", "video/quicktime", "video/3gpp" },
deps = { "core/Err", "core/Bytes", "Types", "containers/IsoBmff", "containers/Demux", "codecs/Video", "codecs/Video/Source" },
caps = { decode = true, encode = true, streaming = true, remux = true, video = { "mjpeg", "mpeg1", "h264" }, audio = true, fragments = true },
}
-- ------------------------------------------------------------------------------------------------ types
export type OpenOptions = {
rgba: boolean?,
track: number?, -- the video track id (default: the first video track)
audio: boolean?,
maxPixels: number?,
maxSamples: number?,
openAudio: any?, -- set by the api
}
export type EncodeOptions = {
format: string?, -- "mov" writes QuickTime (brand 'qt '); else MP4 (brand 'isom')
quality: number?, -- MJPEG quality when frames are encoded (default 90)
reencode: boolean?, -- encode the frames to MJPEG even when the video could be copied
video: boolean?,
audio: boolean?, -- false: no audio; true: fail when the audio cannot be written
}
-- ------------------------------------------------------------------------------------------------ constants
local IMAGE_BRANDS = { avif = true, avis = true, heic = true, heix = true, mif1 = true, msf1 = true, ["crx "] = true }
local AUDIO_BRANDS = { ["M4A "] = true, ["M4B "] = true, ["M4P "] = true }
-- copied video codecs -> sample entry (MP4 / MOV)
local VIDEO_ENTRY: { [string]: string } = { h264 = "avc1", hevc = "hvc1", av1 = "av01", vp9 = "vp09" }
local AUDIO_ENTRY: { [string]: string } = { aac = "mp4a", alac = "alac", opus = "Opus", flac = "fLaC", mp3 = "mp4a" }
-- ------------------------------------------------------------------------------------------------ sniff
function Mp4.sniff(r: Bytes.Reader): number
local brand = IsoBmff.sniff(r)
if brand == nil or IMAGE_BRANDS[brand] then
return 0
end
if AUDIO_BRANDS[brand] then
return 0.2
end
if brand == "M4V " then
return 0.9
end
return if brand == "" then 0.6 else 0.8
end
-- ------------------------------------------------------------------------------------------------ decode
-- OpusHead (RFC 7845, little-endian) from an ISO dOps box payload (big-endian)
local function opusHead(d: buffer): buffer?
if buffer.len(d) < 11 then
return nil
end
local w = Bytes.writer(19 + buffer.len(d))
w:string("OpusHead")
w:u8(1)
local ch = buffer.readu8(d, 1)
w:u8(ch)
w:u16le(buffer.readu8(d, 2) * 256 + buffer.readu8(d, 3))
w:u32le(((buffer.readu8(d, 4) * 256 + buffer.readu8(d, 5)) * 256 + buffer.readu8(d, 6)) * 256 + buffer.readu8(d, 7))
w:u16le(buffer.readu8(d, 8) * 256 + buffer.readu8(d, 9))
local family = buffer.readu8(d, 10)
w:u8(family)
if family ~= 0 and buffer.len(d) >= 13 + ch then
w:bytes(d, 11, 2 + ch) -- stream count, coupled count, mapping
end
return w:finish()
end
local function pcmCodec(t: any): string
local p = t.pcm
local bits = if p then p.bits else (t.bitsPerSample or 16)
if p and p.float then
return "pcm_f" .. bits .. (if p.little then "le" else "be")
end
if bits == 8 then
return if t.entry == "raw " then "pcm_u8" else "pcm_s8"
end
return "pcm_s" .. bits .. (if p == nil or p.little then "le" else "be")
end
-- demux(r, opts?) -> the Demuxer | nil, Err
function Mp4.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?)
local ok, movie, err = pcall(IsoBmff.parse, r, opts and opts.maxSamples and { maxSamples = opts.maxSamples } or nil)
if not ok then
return nil, Err.new(Err.CORRUPT, "internal error: " .. tostring(movie))
end
if not movie then
return nil, err
end
local tracks: { Types.Track } = {}
local src = {}
for _, it in movie.tracks do
local t: any = {
id = it.id,
kind = it.kind,
codec = it.codec,
codecTag = it.entry,
timescale = it.timescale,
duration = it.duration,
language = it.language,
width = it.width,
height = it.height,
sampleRate = it.sampleRate,
channels = it.channels,
bitsPerSample = it.bitsPerSample,
config = it.config,
default = true,
}
if it.kind == "video" then
if not Video.entry(t.codec) then
t.codec = Video.fromFourcc(it.entry) or t.codec
end
if it.sampleCount > 0 and it.duration > 0 then
t.frameRate = it.sampleCount / it.duration
end
elseif it.kind == "audio" then
if it.codec == "pcm" then
t.codec = pcmCodec(it)
elseif it.codec == "ulaw" then
t.codec = "pcm_mulaw"
elseif it.codec == "alaw" then
t.codec = "pcm_alaw"
elseif it.codec == "opus" and it.config then
t.config = opusHead(it.config)
end
if it.skip and it.skip > 0 then
t.codecDelay = it.skip / it.timescale -- AAC priming: dropped like ffmpeg
end
end
table.insert(tracks, t)
table.insert(src, it)
end
local dmx = Demux.new(if movie.brand == "qt " then "mov" else "mp4", tracks, r.buf, { brand = movie.brand })
-- samples in file order across tracks
local items: { { number } } = {}
for k, it in src do
-- the edit list moves presentation times: minus the first edit's media time (video: the B-frame delay; audio
-- keeps it as its codec delay), plus an initial empty edit (converted to media ticks)
local shift = 0
if it.kind == "video" then
shift = -(it.skip or 0)
end
if it.delay and it.delay > 0 and movie.timescale and movie.timescale > 0 then
shift += it.delay / movie.timescale * it.timescale
end
for i = 1, it.sampleCount do
table.insert(items, { it.offsets[i], k, i, shift })
end
end
table.sort(items, function(a: { number }, b: { number }): boolean
return a[1] < b[1]
end)
for _, e in items do
local it = src[e[2]]
local i = e[3]
local dts = it.dts[i]
local pts = dts + (if it.cts then it.cts[i] or 0 else 0) + e[4]
dmx:add(it.id, pts, dts + e[4], it.durations[i], it.sync == nil or it.sync[i] == true, it.offsets[i], it.sizes[i])
end
dmx:finish()
return dmx, nil
end
-- ------------------------------------------------------------------------------------------------ encode
-- OpusHead -> dOps payload
local function dOps(head: buffer?): buffer?
if not head or buffer.len(head) < 19 then
return nil
end
local w = Bytes.writer(16)
w:u8(0)
local ch = buffer.readu8(head, 9)
w:u8(ch)
w:u16be(buffer.readu16(head, 10))
w:u32be(buffer.readu32(head, 12))
w:u16be(buffer.readu16(head, 16))
local family = buffer.readu8(head, 18)
w:u8(family)
if family ~= 0 and buffer.len(head) >= 21 + ch then
w:bytes(head, 19, 2 + ch)
end
return w:finish()
end
-- encode(video, opts?) -> buffer | nil, Err
function Mp4.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
local o: any = table.clone(opts or {})
o.quality = o.quality or 90
local mov = type(o.format) == "string" and (string.lower(o.format) == "mov" or string.lower(o.format) == "qt")
local vcopy: { [string]: boolean } = { mjpeg = true }
for id in VIDEO_ENTRY do
vcopy[id] = true
end
local acopy: { [string]: boolean } = {}
for id in AUDIO_ENTRY do
acopy[id] = true
end
acopy.pcm_s16le = mov
local streams, err = Source.streams(value, o, {
video = { copy = vcopy, encode = "mjpeg" },
audio = { copy = acopy, pcm = mov },
})
if not streams then
return nil, err
end
local mtracks = {}
for _, s in streams do
local scale = if s.kind == "audio" then math.floor((s.sampleRate or 48000) + 0.5) else 90000
if s.kind == "video" and s.track and s.track.timescale and s.copied and s.track.timescale == math.floor(s.track.timescale) then
scale = s.track.timescale
end
local samples, durations, cts, sync = {}, {}, {}, {}
local anyCts = false
local firstDts = nil :: number?
for i, p in s.packets do
samples[i] = p.data
local dts = p.dts or p.pts
firstDts = firstDts or dts
local nextP = s.packets[i + 1]
local d = if nextP then (nextP.dts or nextP.pts) - dts else p.duration
durations[i] = math.max(0, math.floor(d * scale + 0.5))
local c = math.floor((p.pts - dts) * scale + 0.5)
cts[i] = c
if c ~= 0 then
anyCts = true
end
if p.keyframe then
sync[i] = true
end
end
-- an edit list keeps the source's start: video decode times before 0 (B-frame delay), audio codec delay
local skip = 0
if firstDts and firstDts < 0 then
skip = math.floor(-firstDts * scale + 0.5)
end
if s.kind == "audio" and s.track and s.track.codecDelay and s.copied then
skip = math.floor(s.track.codecDelay * scale + 0.5)
end
local t: any = {
kind = s.kind,
timescale = scale,
skip = if skip > 0 then skip else nil,
samples = samples,
durations = durations,
cts = if anyCts then cts else nil,
sync = sync,
width = s.width,
height = s.height,
sampleRate = s.sampleRate and math.floor(s.sampleRate + 0.5),
channels = s.channels,
}
if s.kind == "video" then
if s.codec == "mjpeg" then
t.entry = if mov then "jpeg" else "mp4v"
if not mov then
t.objectType = 0x6C
t.configBox = "esds"
t.config = buffer.create(0)
end
else
t.entry = VIDEO_ENTRY[s.codec]
t.config = s.config
end
else
if s.codec == "pcm_s16le" then
t.entry = "sowt"
t.bitsPerSample = 16
else
t.entry = AUDIO_ENTRY[s.codec]
t.config = if s.codec == "opus" then dOps(s.config) else s.config
if s.codec == "mp3" then
t.objectType = 0x6B
t.configBox = "esds"
t.config = buffer.create(0)
end
end
end
if not t.entry then
return nil, Err.new(Err.UNSUPPORTED, "no sample entry for " .. s.kind .. " codec " .. s.codec)
end
table.insert(mtracks, t)
end
return IsoBmff.mux({ brand = if mov then "qt " else "isom", compatible = if mov then { "qt " } else { "isom", "iso2", "mp41" }, tracks = mtracks })
end
-- ------------------------------------------------------------------------------------------------ open
-- open(r, opts?) -> a VideoDecoder | nil, Err
function Mp4.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?)
local dmx, err = Mp4.demux(r, opts)
if not dmx then
return nil, err
end
return Video.open(dmx, opts)
end
return Mp4