From 967703a4d4da0b6359382c79abd52ab1b1970bb4 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 09:31:21 -0500 Subject: [PATCH] ws-video: video foundation: Types video section made concrete (Track / Packet / Demuxer / VideoFrame / VideoDecoder / VideoCodecDecoder), codecs/Video (codec registry by id / FourCC / Matroska id, generic VideoDecoder over a Demuxer, frames-backed videos, Source for writers), codecs/Yuv, containers/Demux (indexed demuxer), containers/Ebml, containers/AudioWrap; video/mkv (Matroska / WebM demux + mux, WIP: tests next) api (init.luau, small, backward compatible): KIND_CATEGORY.video; withHooks adds opts.openAudio (audio tracks of video containers reach the audio formats through AudioWrap); F.load of a video format returns its VideoDecoder instead of draining it as audio; F.open passes the hooks and opens animated images as frames-backed videos (F.video.open(gif)); F.save of an Image to a video format wraps it (F.convert(gif, 'avi')); F.video.fromImage, F.video.codecs. --- docs/FORMATS.md | 3 + src/Formats/Registry.luau | 12 + src/Formats/Types.luau | 81 +++- src/Formats/codecs/Video/Source.luau | 260 ++++++++++ src/Formats/codecs/Video/init.luau | 425 +++++++++++++++++ src/Formats/codecs/Yuv.luau | 191 ++++++++ src/Formats/containers/AudioWrap.luau | 341 +++++++++++++ src/Formats/containers/Demux.luau | 287 +++++++++++ src/Formats/containers/Ebml/init.luau | 335 +++++++++++++ src/Formats/init.luau | 80 +++- src/Formats/video/mkv/Mux.luau | 285 +++++++++++ src/Formats/video/mkv/Parse.luau | 658 ++++++++++++++++++++++++++ src/Formats/video/mkv/init.luau | 160 +++++++ 13 files changed, 3099 insertions(+), 19 deletions(-) create mode 100644 src/Formats/codecs/Video/Source.luau create mode 100644 src/Formats/codecs/Video/init.luau create mode 100644 src/Formats/codecs/Yuv.luau create mode 100644 src/Formats/containers/AudioWrap.luau create mode 100644 src/Formats/containers/Demux.luau create mode 100644 src/Formats/containers/Ebml/init.luau create mode 100644 src/Formats/video/mkv/Mux.luau create mode 100644 src/Formats/video/mkv/Parse.luau create mode 100644 src/Formats/video/mkv/init.luau diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 40e275f..aabd3e9 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -20,6 +20,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | audio | mp3 | .mp3 .mp2 .mp1 .mpga | yes | - | streaming: true, seek: true, layers: 1, 2, 3, channels: 2 | `tests/audio/mp3.luau` | | audio | opus | .opus | yes | - | streaming: true, seek: true, lossy: true, channels: 255, rates: 48000 | `tests/audio/opus.luau` | | audio | wav | .wav .wave .rf64 .bw64 | yes | yes | streaming: true, depths: 8, 16, 24, 32, float: true, rf64: true | `tests/audio/wav.luau` | +| video | mkv | .mkv .webm .mka .mk3d | yes | yes | streaming: true, remux: true, video: "vp8", "mjpeg", "mpeg1", "rawvideo", audio: true, subtitles: true | **missing** | | model | gltf | .gltf .glb | yes | yes | binary: true, materials: true, animation: true, skins: true, morphTargets: true, cameras: true, lights: true | `tests/model/gltf.luau` | | model | obj | .obj | yes | yes | materials: true, polygons: true, vertexColors: true | `tests/model/obj.luau` | | model | off | .off | yes | yes | polygons: true, points: true, colors: true, binary: false | `tests/model/off.luau` | @@ -76,7 +77,9 @@ Codecs (layer 1, shared by formats; not loadable on their own): - codecs/Text: text decoding helpers for the text formats: a UTF-8 BOM is stripped, text that is not valid UTF-8 is - codecs/TrueType: the sfnt font container (TrueType .ttf, OpenType .otf with CFF outlines, collections .ttc) parsed - codecs/Url: RFC 3986 reference resolution (section 5.2), the classification of a playlist / manifest location (URL, +- codecs/Video: the video codec registry and the generic VideoDecoder. New in formats-luau. - codecs/Vp8: the VP8 video codec (RFC 6386), decode only. A codec (layer 1): image/webp uses it for lossy frames, the - codecs/Vp8L: WebP lossless (VP8L, "WebP Lossless Bitstream Specification", RFC 9649 section 3). A codec (layer 1): - codecs/Xml: XML 1.0 parse (DOM and pull events) and serialize, the engine data/xml, SVG, DAE, 3MF, TMX, plist, ... +- codecs/Yuv: planar 4:2:0 Y'CbCr <-> rgba8 for the video codecs and writers (native; never throws). BT.601 or - codecs/Zstd: Zstandard decompression (RFC 8878). A codec (layer 3): archive/zst and anything else carrying zstd diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index d514aa9..2f6e7e8 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -194,6 +194,18 @@ local list: { Entry } = { return require("@formats/audio/wav") end, }, + { + name = "mkv", + category = "video", + path = "video/mkv", + extensions = { "mkv", "webm", "mka", "mk3d" }, + mime = { "video/x-matroska", "video/webm", "audio/x-matroska", "audio/webm" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Ebml", "containers/Demux", "codecs/Video", "codecs/Video/Source" }, + caps = { decode = true, encode = true, streaming = true, remux = true, video = { "vp8", "mjpeg", "mpeg1", "rawvideo" }, audio = true, subtitles = true }, + load = function() + return require("@formats/video/mkv") + end, + }, { name = "gltf", category = "model", diff --git a/src/Formats/Types.luau b/src/Formats/Types.luau index 6464e98..f14a833 100644 --- a/src/Formats/Types.luau +++ b/src/Formats/Types.luau @@ -162,38 +162,89 @@ end Types.Midi = Midi -- ------------------------------------------------------------------------------------------------ Video +-- A video file opens (F.video.open / a video format's open) as a VideoDecoder; F.load returns the same object (kind = +-- "video", decoded lazily). Underneath sits a Demuxer: the container's tracks and their packets. Video tracks decode +-- through the codec registry (codecs/Video: by codec id or FourCC, so other codecs can plug in), audio tracks through +-- the audio formats (the api hook opts.openAudio, since a format never requires another format). +-- +-- Times: Packet pts / dts / duration are integer ticks of the track's timescale (exact, for remuxing); VideoFrame pts +-- / duration and every `duration` / `seek` argument are seconds. export type Track = { - id: number, + id: number, -- the container's track number (Matroska TrackNumber, AVI stream index + 1, TS PID, ...) kind: "video" | "audio" | "subtitle" | "data", - codec: string, -- "h264", "vp8", "mpeg1", "mjpeg", "aac", "mp3", "opus", ... - timescale: number, -- ticks per second for pts / duration + codec: string, -- our codec id: "vp8", "mjpeg", "mpeg1", "h264", "rawvideo"; "pcm_s16le", "mp3", "opus", "vorbis", ... + codecTag: string?, -- the container's own id ("V_VP8", "MJPG", stream_type "0x01", "avc1", ...) + timescale: number, -- ticks per second for pts / dts / duration duration: number?, -- seconds + default: boolean?, + language: string?, + name: string?, + -- video width: number?, height: number?, + frameRate: number?, -- frames per second (nominal; 0 / nil when unknown) + pixelFormat: string?, -- raw video: "yuv420p", "rgb24", "bgr24", ... + -- audio sampleRate: number?, channels: number?, - config: buffer?, -- codec configuration (avcC, CodecPrivate, ...) + bitsPerSample: number?, + config: buffer?, -- codec configuration (CodecPrivate, avcC, OpusHead, Vorbis headers, AVI strf extra, ...) [string]: any, } -export type Packet = { track: number, pts: number, dts: number?, duration: number?, keyframe: boolean, data: buffer } +export type Packet = { + track: number, -- Track.id + pts: number, -- presentation time, ticks + dts: number?, -- decode time, ticks (nil = pts) + duration: number?, -- ticks + keyframe: boolean, + data: buffer, -- the packet's bytes (its own buffer) +} export type Demuxer = { + kind: "demuxer", + format: string, -- the container format name tracks: { Track }, - duration: number, - -- packets(trackId?) -> iterator of Packets in file order (one track, or all) + duration: number, -- seconds (0 = unknown) + meta: { [string]: any }, -- title, tags, ... + -- packets(trackId?) -> iterator of Packets in file order (one track, or all), from the current position packets: (self: any, track: number?) -> () -> Packet?, - seek: ((self: any, seconds: number) -> ())?, + -- read(trackId?) -> the next Packet (one track, or any) | nil at the end + read: (self: any, track: number?) -> Packet?, + -- seek(seconds): every track to its last keyframe at or before the time + seek: (self: any, seconds: number) -> (), + track: (self: any, kind: string) -> Track?, -- the first (default) track of a kind +} +export type VideoFrame = { + image: Image, -- yuv420p (the codecs' native output) or rgba8 (opts.rgba = true, MJPEG without yuv, frames-backed) + pts: number, -- seconds + duration: number, -- seconds + keyframe: boolean?, + index: number, -- 1-based, in output order } -export type VideoFrame = { image: Image, pts: number, duration: number } export type VideoDecoder = { + kind: "video", + format: string, -- the container format name ("mkv", "avi", "gif", ...) + codec: string, -- the video codec id ("vp8", "mjpeg", "frames" for animated images) width: number, height: number, - frameRate: number, - duration: number, + frameRate: number, -- frames per second (nominal) + frames: number, -- frame count when known (0 = unknown) + duration: number, -- seconds + track: Track?, -- the video track decoded nextFrame: (self: any) -> (VideoFrame?, Err?), -- nil, nil at the end - toRGBA: (self: any, frame: VideoFrame) -> Image, - seek: ((self: any, seconds: number) -> ())?, - audio: Decoder?, -- the first audio track, decoded - demuxer: Demuxer?, + toRGBA: (self: any, frame: VideoFrame | Image) -> Image, -- an rgba8 Image (the frame's own image if already rgba8) + seek: (self: any, seconds: number) -> (), -- to the last keyframe at or before the time (frames before it skipped) + reset: (self: any) -> (), -- back to the start + audio: Decoder?, -- the first audio track, decoded (nil if none or its codec is unavailable: see audioError) + audioError: Err?, + demuxer: Demuxer?, -- nil for frames-backed videos (animated images) + meta: { [string]: any }, +} +-- a codec's decoder instance (codecs/Video registry entries create them): packets in, pictures out +export type VideoCodecDecoder = { + decode: (self: any, packet: Packet) -> Err?, -- feed one packet (decode order) + receive: (self: any) -> (Image?, number?, boolean?), -- the next picture, the pts (ticks) it carries, keyframe | nil + flush: (self: any) -> (), -- end of stream: pictures held for reordering become available to receive() + reset: (self: any) -> (), -- after a seek: drop references / held pictures } -- ------------------------------------------------------------------------------------------------ Scene (3D, glTF-shaped) diff --git a/src/Formats/codecs/Video/Source.luau b/src/Formats/codecs/Video/Source.luau new file mode 100644 index 0000000..f8065c6 --- /dev/null +++ b/src/Formats/codecs/Video/Source.luau @@ -0,0 +1,260 @@ +--!strict +-- codecs/Video/Source: what a video writer (Matroska / WebM, AVI, Y4M, MP4) gets to write, from whatever it was given: +-- a VideoDecoder (F.load / F.video.open of any video or animated image) or a Demuxer. Each output stream is either +-- copied (the source track's packets, when the target container takes that codec: remuxing, e.g. VP8 into WebM, +-- since VP8 is decode-only) or produced (decoded frames encoded with a registered encoder such as MJPEG, raw +-- yuv420p frames, PCM audio from the audio Decoder). New in formats-luau. +-- +-- local streams, err = Source.streams(value, opts, { +-- video = { copy = { vp8 = true }, encode = "mjpeg" }, -- copy: codec ids the container takes ("*" = any) +-- audio = { copy = { opus = true, vorbis = true }, pcm = true }, +-- }) +-- -- streams[i] = { kind, codec, copied, width, height, frameRate, sampleRate, channels, bitsPerSample, config, +-- -- track, packets = { { pts, duration (seconds), keyframe, data } } } +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Yuv = require("@formats/codecs/Yuv") + +local Source = {} + +export type OutPacket = { pts: number, dts: number?, duration: number, keyframe: boolean, data: buffer } +export type Stream = { + kind: "video" | "audio", + codec: string, + copied: boolean, + width: number?, + height: number?, + frameRate: number?, + sampleRate: number?, + channels: number?, + bitsPerSample: number?, + config: buffer?, + track: Types.Track?, + packets: { OutPacket }, +} +export type Want = { + video: { copy: { [string]: boolean }?, encode: string? }?, + audio: { copy: { [string]: boolean }?, pcm: boolean? }?, +} + +local function allows(set: { [string]: boolean }?, codec: string): boolean + return set ~= nil and (set[codec] == true or set["*"] == true) +end + +-- the packets of a source track, times in seconds +local function copyPackets(dmx: any, track: Types.Track): { OutPacket } + local out = {} + local scale = if track.timescale and track.timescale > 0 then track.timescale else 1 + local n = dmx:count(track.id) + for k = 1, n do + local p = dmx:get(track.id, k) + if p then + table.insert(out, { pts = p.pts / scale, dts = (p.dts or p.pts) / scale, duration = (p.duration or 0) / scale, keyframe = p.keyframe, data = p.data }) + end + end + return out +end + +local function trackStream(track: Types.Track, packets: { OutPacket }): Stream + return { + kind = track.kind :: any, + codec = track.codec, + copied = true, + width = track.width, + height = track.height, + frameRate = track.frameRate, + sampleRate = track.sampleRate, + channels = track.channels, + bitsPerSample = track.bitsPerSample, + config = track.config, + track = track, + packets = packets, + } +end + +-- encodeFrames(video, codec, opts) -> the video's frames encoded with the registry's encoder for codec ("rawvideo": +-- yuv420p planes) +local function encodeFrames(v: any, codec: string, opts: any): (Stream?, Err.Err?) + local encode: ((img: Types.Image, opts: any) -> (buffer?, Err.Err?))? = nil + if codec ~= "rawvideo" then + local Video = require("@formats/codecs/Video") + local e = Video.entry(codec) + encode = e and e.encode + if not encode then + return nil, Err.new(Err.UNSUPPORTED, "no " .. codec .. " encoder") + end + end + if type(v.reset) == "function" then + v:reset() + end + local packets: { OutPacket } = {} + local w, h = v.width, v.height + local maxFrames = opts.maxFrames or math.huge + while #packets < maxFrames do + local f, err = v:nextFrame() + if not f then + if err then + return nil, err + end + break + end + local img: Types.Image = f.image + if (w == 0 or h == 0) and #packets == 0 then + w, h = img.width, img.height + end + if img.width ~= w or img.height ~= h then + return nil, Err.new(Err.UNSUPPORTED, "frame size changes mid-stream (" .. img.width .. "x" .. img.height .. ")") + end + local data: buffer? + if codec == "rawvideo" then + local y = if img.format == "yuv420p" then img else Yuv.imageFromRgba(img, "limited", "bt601") + if not y then + return nil, Err.new(Err.UNSUPPORTED, "frame format " .. img.format) + end + data = y.pixels + else + local e2 + data, e2 = (encode :: any)(img, opts) + if not data then + return nil, e2 or Err.new(Err.ARG, "frame " .. f.index .. " failed to encode") + end + end + table.insert(packets, { pts = f.pts, duration = f.duration, keyframe = true, data = data :: buffer }) + end + if #packets == 0 then + return nil, Err.new(Err.ARG, "no frames to write") + end + local fr = v.frameRate + if not fr or fr <= 0 then + local d = packets[1].duration + fr = if d > 0 then 1 / d else 25 + end + return { + kind = "video", + codec = codec, + copied = false, + width = w, + height = h, + frameRate = fr, + packets = packets, + } :: Stream, nil +end + +-- pcmFrom(decoder, opts) -> an s16le stream from an audio Decoder (chunks of opts.audioChunk frames, default 4096) +local function pcmFrom(dec: any, opts: any): (Stream?, Err.Err?) + local ch, rate = dec.channels, dec.sampleRate + if type(ch) ~= "number" or ch < 1 or type(rate) ~= "number" or rate <= 0 then + return nil, Err.new(Err.ARG, "audio decoder without channels / sample rate") + end + pcall(dec.seek, dec, 0) + local chunk = opts.audioChunk or 4096 + local packets: { OutPacket } = {} + local pos = 0 + local tmp: buffer? = nil + while true do + local ok, out, n = pcall(dec.read, dec, chunk, tmp) + if not ok or not out or not n or n <= 0 then + break + end + tmp = out + local data = buffer.create(n * ch * 2) + for i = 0, n * ch - 1 do + local s = buffer.readf32(out, i * 4) + local v = math.floor(s * 32768 + 0.5) + if v > 32767 then + v = 32767 + elseif v < -32768 then + v = -32768 + elseif v ~= v then + v = 0 + end + buffer.writei16(data, i * 2, v) + end + table.insert(packets, { pts = pos / rate, duration = n / rate, keyframe = true, data = data }) + pos += n + end + return { + kind = "audio", + codec = "pcm_s16le", + copied = false, + sampleRate = rate, + channels = ch, + bitsPerSample = 16, + packets = packets, + } :: Stream, nil +end + +-- streams(value, opts, want) -> { Stream } | nil, Err +function Source.streams(value: any, opts: any?, want: Want): ({ Stream }?, Err.Err?) + local o = opts or {} + if type(value) ~= "table" or (value.kind ~= "video" and value.kind ~= "demuxer") then + return nil, Err.new(Err.ARG, "expected a video (VideoDecoder) or a Demuxer") + end + local dmx = if value.kind == "demuxer" then value else value.demuxer + local out: { Stream } = {} + -- video + local vt: Types.Track? = if value.kind == "video" then value.track else (dmx and dmx:track("video")) + local wv = want.video + if wv and o.video ~= false then + if vt and dmx and allows(wv.copy, vt.codec) and not o.reencode then + table.insert(out, trackStream(vt, copyPackets(dmx, vt))) + elseif value.kind == "video" and wv.encode then + local s, err = encodeFrames(value, wv.encode, o) + if not s then + return nil, err + end + table.insert(out, s) + elseif vt then + return nil, Err.new(Err.UNSUPPORTED, "cannot write " .. vt.codec .. " video" .. (if wv.encode then "" else " (this container cannot take it and it cannot be re-encoded)")) + end + end + -- audio + local wa = want.audio + if wa and o.audio ~= false then + local at: Types.Track? = dmx and dmx:track("audio") + if at and dmx and allows(wa.copy, at.codec) and not o.reencodeAudio then + table.insert(out, trackStream(at, copyPackets(dmx, at))) + elseif wa.pcm and value.kind == "video" and value.audio then + local s, err = pcmFrom(value.audio, o) + if not s then + return nil, err + end + if #s.packets > 0 then + table.insert(out, s) + end + elseif at and o.audio == true then + return nil, Err.new(Err.UNSUPPORTED, "cannot write " .. at.codec .. " audio to this container") + end + end + if #out == 0 then + return nil, Err.new(Err.ARG, "nothing to write (no video or audio stream)") + end + return out, nil +end + +-- interleave(streams) -> { { stream index, packet } } merged by decode time (dts, else pts); each stream keeps its +-- own order +function Source.interleave(streams: { Stream }): { { any } } + local order = {} + local pos = table.create(#streams, 1) + while true do + local best, bt = 0, math.huge + for si, s in streams do + local p = s.packets[pos[si]] + if p then + local t = p.dts or p.pts + if best == 0 or t < bt then + best, bt = si, t + end + end + end + if best == 0 then + break + end + table.insert(order, { best, streams[best].packets[pos[best]] }) + pos[best] += 1 + end + return order +end + +return Source diff --git a/src/Formats/codecs/Video/init.luau b/src/Formats/codecs/Video/init.luau new file mode 100644 index 0000000..718bd30 --- /dev/null +++ b/src/Formats/codecs/Video/init.luau @@ -0,0 +1,425 @@ +--!strict +-- codecs/Video: the video codec registry and the generic VideoDecoder. New in formats-luau. +-- +-- Registry: our codec ids ("vp8", "mjpeg", "mpeg1", "h264", "rawvideo", ...) with the containers' names for them +-- (AVI / MOV FourCCs, Matroska CodecIDs, MPEG stream types) and, for the codecs we can decode, a constructor of a +-- Types.VideoCodecDecoder (packets in, pictures out). Containers map their own ids through Video.fromFourcc / +-- Video.fromMatroska so a track's codec is known even without a decoder (remuxing still works). Another codec plugs +-- in with one line in BUILTIN (static: Roblox has no dynamic require) or at run time with Video.register(entry). +-- +-- local Video = require("@formats/codecs/Video") +-- Video.fromFourcc("MJPG") --> "mjpeg" Video.fromMatroska("V_VP8") --> "vp8" +-- local dec = Video.decoder(track, opts) -- a VideoCodecDecoder | nil, Err (UNSUPPORTED: no decoder) +-- local v = Video.open(demuxer, opts) -- a Types.VideoDecoder over a Types.Demuxer (formats' open()) +-- local v = Video.fromFrames(images, delays) -- a frames-backed VideoDecoder (animated GIF / APNG / WebP) +-- +-- Never throws: bad data / missing codecs come back as nil, Err. +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Yuv = require("@formats/codecs/Yuv") + +local Video = {} + +export type Entry = { + id: string, -- our codec id + name: string, -- a human name + fourcc: { string }?, -- AVI biCompression / MOV sample entry FourCCs + matroska: { string }?, -- Matroska / WebM CodecIDs + -- new(track, opts) -> a decoder instance (nil = decode not supported) + new: ((track: Types.Track, opts: any?) -> (Types.VideoCodecDecoder?, Err.Err?))?, + [string]: any, +} + +-- ------------------------------------------------------------------------------------------------ simple decoders +-- one picture per packet, no reordering: decodeOne(data, packet) -> Image | nil, Err (nil, nil: a packet with no +-- picture to show, such as a hidden VP8 altref frame) +function Video.simpleDecoder(decodeOne: (data: buffer, packet: Types.Packet) -> (Types.Image?, Err.Err?), resetFn: (() -> ())?): Types.VideoCodecDecoder + local queue: { any } = {} + local self = {} + function self.decode(_: any, packet: Types.Packet): Err.Err? + local ok, img, err = pcall(decodeOne, packet.data, packet) + if not ok then + return Err.new(Err.CORRUPT, "decoder threw: " .. tostring(img)) + end + if img then + table.insert(queue, { img, packet.pts, packet.keyframe }) + end + return err + end + function self.receive(_: any): (Types.Image?, number?, boolean?) + local q = table.remove(queue, 1) + if q then + return q[1], q[2], q[3] + end + return nil + end + function self.flush(_: any) end + function self.reset(_: any) + table.clear(queue) + if resetFn then + resetFn() + end + end + return self :: any +end + +-- raw video: yuv420p (I420 / IYUV / y4m), yv12 (V before U), rgb24 / bgr24 / bgra (bottom-up AVI DIBs: track.flip) +local function rawDecoder(track: Types.Track, _opts: any?): (Types.VideoCodecDecoder?, Err.Err?) + local w, h = track.width or 0, track.height or 0 + if w <= 0 or h <= 0 or w * h > 2 ^ 26 then + return nil, Err.new(Err.CORRUPT, "raw video without a valid size") + end + local pf = track.pixelFormat or "yuv420p" + local cw, ch = (w + 1) // 2, (h + 1) // 2 + local flip = track.flip == true + return Video.simpleDecoder(function(data: buffer): (Types.Image?, Err.Err?) + local n = buffer.len(data) + if pf == "yuv420p" or pf == "yv12" then + local need = w * h + 2 * cw * ch + if n < need then + return nil, Err.new(Err.TRUNCATED, "raw frame: " .. n .. " of " .. need .. " bytes") + end + local img = Types.Image.new(w, h, "yuv420p") + if pf == "yv12" then + buffer.copy(img.pixels, 0, data, 0, w * h) + buffer.copy(img.pixels, w * h, data, w * h + cw * ch, cw * ch) + buffer.copy(img.pixels, w * h + cw * ch, data, w * h, cw * ch) + else + buffer.copy(img.pixels, 0, data, 0, need) + end + return img + end + local bpp = if pf == "bgra" or pf == "rgba" then 4 else 3 + local stride = if track.stride then track.stride else w * bpp + if n < stride * (h - 1) + w * bpp then + return nil, Err.new(Err.TRUNCATED, "raw frame too short") + end + local img = Types.Image.new(w, h, "rgba8") + local px = img.pixels + local bgr = pf == "bgr24" or pf == "bgra" + for y = 0, h - 1 do + local s = (if flip then h - 1 - y else y) * stride + local o = y * w * 4 + for x = 0, w - 1 do + local p = s + x * bpp + local a, b, c = buffer.readu8(data, p), buffer.readu8(data, p + 1), buffer.readu8(data, p + 2) + if bgr then + a, c = c, a + end + buffer.writeu32(px, o + x * 4, a + b * 256 + c * 65536 + 0xff000000) + end + end + return img + end) +end + +local function vp8Decoder(_track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?) + local Vp8 = require("@formats/codecs/Vp8") + local dec = Vp8.newDecoder() + local o = { maxPixels = opts and opts.maxPixels } + return Video.simpleDecoder(function(data: buffer): (Types.Image?, Err.Err?) + local img, err = dec:decodeFrame(data, 0, buffer.len(data), o) + if not img then + return nil, err + end + local src = img.meta.source + if type(src) == "table" and src.show == false then + return nil, nil + end + img.meta.yuv = { range = "limited", matrix = "bt601" } + return img, nil + end, function() + if dec.reset then + dec:reset() + else + dec = Vp8.newDecoder() + end + end) +end + +-- ------------------------------------------------------------------------------------------------ registry +-- the codecs known by name (decoders where `new` is set). FourCCs compare case-sensitively first, then upper-cased. +local BUILTIN: { Entry } = { + { id = "vp8", name = "VP8", fourcc = { "VP80", "vp08" }, matroska = { "V_VP8" }, new = vp8Decoder }, + { id = "mjpeg", name = "Motion JPEG", fourcc = { "MJPG", "mjpa", "mjpb", "jpeg", "AVRn", "AVDJ", "dmb1", "LJPG", "JPGL", "MJLS", "ijpg" }, matroska = { "V_MJPEG" } }, + { id = "mpeg1", name = "MPEG-1 video", fourcc = { "mpg1", "MPG1", "PIM1", "m1v " }, matroska = { "V_MPEG1" } }, + { id = "rawvideo", name = "raw video", fourcc = { "\0\0\0\0", "I420", "IYUV", "YV12", "raw ", "DIB " }, matroska = { "V_UNCOMPRESSED" }, new = rawDecoder }, + { id = "mpeg2", name = "MPEG-2 video", fourcc = { "mpg2", "MPG2", "MPEG", "mp2v" }, matroska = { "V_MPEG2" } }, + { id = "mpeg4", name = "MPEG-4 part 2", fourcc = { "mp4v", "FMP4", "XVID", "DIVX", "DX50", "MP4V" }, matroska = { "V_MPEG4/ISO/SP", "V_MPEG4/ISO/ASP", "V_MPEG4/ISO/AP" } }, + { id = "h264", name = "H.264 / AVC", fourcc = { "avc1", "avc3", "H264", "h264", "X264", "x264" }, matroska = { "V_MPEG4/ISO/AVC" } }, + { id = "hevc", name = "H.265 / HEVC", fourcc = { "hvc1", "hev1", "HEVC", "H265" }, matroska = { "V_MPEGH/ISO/HEVC" } }, + { id = "vp9", name = "VP9", fourcc = { "VP90", "vp09" }, matroska = { "V_VP9" } }, + { id = "av1", name = "AV1", fourcc = { "AV01", "av01" }, matroska = { "V_AV1" } }, + { id = "theora", name = "Theora", matroska = { "V_THEORA" } }, + { id = "png", name = "PNG", fourcc = { "png ", "MPNG" }, matroska = { "V_PNG" } }, +} + +local byId: { [string]: Entry } = {} +local byFourcc: { [string]: string } = {} +local byMatroska: { [string]: string } = {} + +-- register(entry): adds or replaces a codec (by id); its fourcc / matroska names map to it +function Video.register(entry: Entry): (boolean, Err.Err?) + if type(entry) ~= "table" or type(entry.id) ~= "string" then + return false, Err.new(Err.ARG, "register: needs an entry with an id") + end + local old = byId[entry.id] + if old and entry.new == nil then + entry.new = old.new + end + byId[entry.id] = entry + for _, f in entry.fourcc or {} do + byFourcc[f] = entry.id + end + for _, m in entry.matroska or {} do + byMatroska[m] = entry.id + end + return true +end +for _, e in BUILTIN do + Video.register(e) +end + +-- the registry (read only by convention): id -> Entry +Video.codecs = byId + +-- fromFourcc(fourcc) -> codec id | nil +function Video.fromFourcc(fcc: string): string? + return byFourcc[fcc] or byFourcc[string.upper(fcc)] or byFourcc[string.lower(fcc)] +end + +-- fromMatroska(codecId) -> codec id | nil (V_MPEG4/ISO/AVC -> h264, ...) +function Video.fromMatroska(id: string): string? + return byMatroska[id] +end + +-- names(codecId) -> the Entry (FourCCs / Matroska ids for writers) | nil +function Video.entry(id: string): Entry? + return byId[id] +end + +-- canDecode(codecId) -> boolean +function Video.canDecode(id: string): boolean + local e = byId[id] + return e ~= nil and e.new ~= nil +end + +-- decoder(track, opts?) -> a VideoCodecDecoder for the track's codec | nil, Err (UNSUPPORTED when none is registered) +function Video.decoder(track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?) + local e = byId[track.codec] + if not e or not e.new then + return nil, Err.new(Err.UNSUPPORTED, "no decoder for video codec " .. tostring(track.codec)) + end + local ok, dec, err = pcall(e.new :: any, track, opts) + if not ok then + return nil, Err.new(Err.CORRUPT, "codec " .. track.codec .. " failed to start: " .. tostring(dec)) + end + return dec, err +end + +-- ------------------------------------------------------------------------------------------------ VideoDecoder +local function toRGBA(_self: any, f: any): Types.Image + local img = if type(f) == "table" and f.image then f.image else f + local out = Yuv.imageToRgba(img) + return out or img +end + +export type OpenOptions = { + rgba: boolean?, -- nextFrame returns rgba8 images (default false: the codec's native yuv420p) + track: number?, -- the video track id (default: the first video track) + maxPixels: number?, + openAudio: ((demuxer: Types.Demuxer, track: Types.Track) -> (Types.Decoder?, Err.Err?))?, -- the api's audio hook + audio: boolean?, -- false: do not open the audio track + [string]: any, +} + +-- open(demuxer, opts?) -> a Types.VideoDecoder over the demuxer's video track (and audio track through +-- opts.openAudio). A video track without a decoder still opens: nextFrame returns nil, Err.UNSUPPORTED, and +-- the demuxer (remuxing) and audio work. +function Video.open(demuxer: Types.Demuxer, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?) + local o: OpenOptions = opts or {} + local track: Types.Track? = nil + if o.track then + for _, t in demuxer.tracks do + if t.id == o.track then + track = t + end + end + if not track then + return nil, Err.new(Err.ARG, "no track " .. tostring(o.track)) + end + else + track = demuxer:track("video") + end + local codec: Types.VideoCodecDecoder? = nil + local codecErr: Err.Err? = nil + if track then + codec, codecErr = Video.decoder(track, o) + else + codecErr = Err.new(Err.UNSUPPORTED, "no video track") + end + local v: any = { + kind = "video", + format = demuxer.format, + codec = if track then track.codec else "none", + width = if track then track.width or 0 else 0, + height = if track then track.height or 0 else 0, + frameRate = if track then track.frameRate or 0 else 0, + frames = if track then track.frames or 0 else 0, + duration = if track and track.duration and track.duration > 0 then track.duration else demuxer.duration, + track = track, + demuxer = demuxer, + meta = demuxer.meta or {}, + decodeError = codecErr, + toRGBA = toRGBA, + } + if v.frames == 0 and v.frameRate > 0 and v.duration > 0 then + v.frames = math.floor(v.duration * v.frameRate + 0.5) + end + -- audio + if o.audio ~= false then + local at = demuxer:track("audio") + if at then + if o.openAudio then + local ok, dec, err = pcall(o.openAudio, demuxer, at) + if ok and dec then + v.audio = dec + else + v.audioError = if ok then err else Err.new(Err.CORRUPT, "audio: " .. tostring(dec)) + end + else + v.audioError = Err.new(Err.UNSUPPORTED, "no audio hook (open through the api: F.video.open)") + end + end + end + local index, flushed, skipUntil = 0, false, -math.huge + local tid = if track then track.id else -1 + local scale = if track and track.timescale and track.timescale > 0 then track.timescale else 1000 + local defaultDur = if v.frameRate > 0 then 1 / v.frameRate else 0 + local lastPts = nil :: number? + function v.nextFrame(self: any): (Types.VideoFrame?, Err.Err?) + if not codec then + return nil, codecErr + end + local dec = codec :: Types.VideoCodecDecoder + while true do + local img, pts, key = dec:receive() + if img then + local t = (pts or 0) / scale + if t + 1e-9 >= skipUntil then + index += 1 + local d = defaultDur + if lastPts and t > lastPts and defaultDur == 0 then + d = t - lastPts + end + lastPts = t + if o.rgba then + img = Yuv.imageToRgba(img) or img + end + return { image = img, pts = t, duration = d, keyframe = key, index = index }, nil + end + else + local p = demuxer:read(tid) + if p == nil then + if flushed then + return nil, nil + end + flushed = true + dec:flush() + else + local err = dec:decode(p) + if err then + return nil, err + end + end + end + end + end + function v.seek(self: any, seconds: number) + demuxer:seek(seconds) + if codec then + codec:reset() + end + flushed = false + skipUntil = seconds + lastPts = nil + if self.audio then + pcall(self.audio.seek, self.audio, seconds) + end + end + function v.reset(self: any) + self:seek(0) + skipUntil = -math.huge + index = 0 + end + return v, nil +end + +-- ------------------------------------------------------------------------------------------------ frames-backed +-- fromFrames(images, delays, opts?) -> a VideoDecoder over full-canvas images (animated GIF / APNG / WebP after +-- coalescing): delays[i] seconds (a number = every frame). opts.format / opts.loops / opts.meta are recorded. +function Video.fromFrames(images: { Types.Image }, delays: (number | { number })?, opts: any?): (Types.VideoDecoder?, Err.Err?) + if type(images) ~= "table" or #images == 0 or type(images[1]) ~= "table" then + return nil, Err.new(Err.ARG, "fromFrames: needs a list of Images") + end + local w, h = images[1].width, images[1].height + local pts: { number } = {} + local durs: { number } = {} + local t = 0 + for i, img in images do + if type(img) ~= "table" or img.width ~= w or img.height ~= h then + return nil, Err.new(Err.ARG, "fromFrames: frame " .. i .. " is not a " .. w .. "x" .. h .. " Image") + end + local d = if type(delays) == "table" then delays[i] or 0.1 else (delays or 0.1) + if type(d) ~= "number" or d ~= d or d < 0 then + d = 0.1 + end + pts[i] = t + durs[i] = d + t += d + end + local n = #images + local o = opts or {} + local v: any = { + kind = "video", + format = o.format or "frames", + codec = "frames", + width = w, + height = h, + frameRate = if t > 0 then n / t else 10, + frames = n, + duration = t, + loops = o.loops, + meta = o.meta or {}, + toRGBA = toRGBA, + images = images, + } + local i = 0 + function v.nextFrame(self: any): (Types.VideoFrame?, Err.Err?) + i += 1 + if i > n then + i = n + return nil, nil + end + local img = images[i] + if o.rgba then + img = Yuv.imageToRgba(img) or img + end + return { image = img, pts = pts[i], duration = durs[i], keyframe = true, index = i }, nil + end + function v.seek(self: any, seconds: number) + local k = 0 + for j = 1, n do + if pts[j] <= seconds + 1e-9 then + k = j - 1 + end + end + i = k + end + function v.reset(self: any) + i = 0 + end + return v, nil +end + +return Video diff --git a/src/Formats/codecs/Yuv.luau b/src/Formats/codecs/Yuv.luau new file mode 100644 index 0000000..e4a86d8 --- /dev/null +++ b/src/Formats/codecs/Yuv.luau @@ -0,0 +1,191 @@ +--!strict +--!native +--!optimize 2 +-- codecs/Yuv: planar 4:2:0 Y'CbCr <-> rgba8 for the video codecs and writers (native; never throws). BT.601 or +-- BT.709 matrices, limited ("tv", 16..235 / 16..240: VP8, MPEG-1, H.264) or full ("pc", 0..255: MJPEG / JPEG) range. +-- yuv -> rgb uses nearest chroma and 16-bit fixed point with swscale's default (non-accurate) coefficients, so the +-- result is within about one level of `ffmpeg -pix_fmt rgba`; rgb -> yuv averages each 2x2 block for the chroma +-- (ffmpeg's default rgb -> yuv420p chroma siting is close to this). +-- +-- Yuv.toRgba(planes, w, h, uo, vo, cw, range?, matrix?, out?) -> rgba8 buffer (alpha 255) +-- Yuv.fromRgba(rgba, w, h, range?, matrix?, out?) -> yuv420p buffer (Y, then U, then V; ceil(w/2) x ceil(h/2)) +-- Yuv.imageToRgba(img) / Yuv.imageFromRgba(img, range?, matrix?) -> Types.Image +local Types = require("@formats/Types") + +local readu8, writeu8, writeu32 = buffer.readu8, buffer.writeu8, buffer.writeu32 +local bcreate = buffer.create +local floor = math.floor + +local Yuv = {} + +-- coefficients (x 65536): r = y' + crv * v; g = y' - cgu * u - cgv * v; b = y' + cbu * u +-- limited: y' = (y - 16) * 255 / 219, chroma scaled by 255 / 224 +local MATRIX = { + bt601 = { kr = 0.299, kb = 0.114 }, + bt709 = { kr = 0.2126, kb = 0.0722 }, +} + +type Coeffs = { ys: number, yo: number, crv: number, cgu: number, cgv: number, cbu: number, cs: number } + +local cache: { [string]: Coeffs } = {} +local function coeffs(range: string?, matrix: string?): Coeffs + local key = (range or "limited") .. (matrix or "bt601") + local c = cache[key] + if c then + return c + end + local m = MATRIX[matrix or "bt601"] or MATRIX.bt601 + local kr, kb = m.kr, m.kb + local kg = 1 - kr - kb + local full = range == "full" + local ys = if full then 1 else 255 / 219 + local cs = if full then 1 else 255 / 224 + c = { + ys = floor(ys * 65536 + 0.5), + yo = if full then 0 else 16, + crv = floor(2 * (1 - kr) * cs * 65536 + 0.5), + cbu = floor(2 * (1 - kb) * cs * 65536 + 0.5), + cgu = floor(2 * (1 - kb) * kb / kg * cs * 65536 + 0.5), + cgv = floor(2 * (1 - kr) * kr / kg * cs * 65536 + 0.5), + cs = cs, + } + cache[key] = c + return c +end + +-- CLIP[v + 1024] = clamp(v, 0, 255) for v in -1024..1279 +local CLIP = bcreate(2304) +for i = 0, 2303 do + writeu8(CLIP, i, math.clamp(i - 1024, 0, 255)) +end + +-- toRgba(src, w, h, uo, vo, cw, range?, matrix?, out?) -> rgba8 (w * h * 4) from planes in one buffer: Y at 0 with +-- stride w, U at uo and V at vo with stride cw (ceil(w/2) rows of ceil(h/2)) +function Yuv.toRgba(src: buffer, w: number, h: number, uo: number, vo: number, cw: number, range: string?, matrix: string?, out: buffer?): buffer + local dst = out or bcreate(w * h * 4) + local c = coeffs(range, matrix) + local ys, yo, crv, cgu, cgv, cbu = c.ys, c.yo, c.crv, c.cgu, c.cgv, c.cbu + local ch = (h + 1) // 2 + if buffer.len(src) < vo + cw * ch or buffer.len(dst) < w * h * 4 or uo + cw * ch > buffer.len(src) then + return dst + end + for y = 0, h - 1 do + local yrow = y * w + local crow = (y // 2) * cw + local o = yrow * 4 + for x = 0, w - 1, 2 do + local ci = crow + (x // 2) + local u = readu8(src, uo + ci) - 128 + local v = readu8(src, vo + ci) - 128 + local rv = (crv * v + 32768) // 65536 + local gv = (cgu * u + cgv * v + 32768) // 65536 + local bu = (cbu * u + 32768) // 65536 + local yy = (ys * (readu8(src, yrow + x) - yo) + 32768) // 65536 + 1024 + writeu32(dst, o, readu8(CLIP, yy + rv) + readu8(CLIP, yy - gv) * 256 + readu8(CLIP, yy + bu) * 65536 + 0xff000000) + if x + 1 < w then + yy = (ys * (readu8(src, yrow + x + 1) - yo) + 32768) // 65536 + 1024 + writeu32(dst, o + 4, readu8(CLIP, yy + rv) + readu8(CLIP, yy - gv) * 256 + readu8(CLIP, yy + bu) * 65536 + 0xff000000) + end + o += 8 + end + end + return dst +end + +-- fromRgba(rgba, w, h, range?, matrix?, out?) -> yuv420p +function Yuv.fromRgba(src: buffer, w: number, h: number, range: string?, matrix: string?, out: buffer?): buffer + local cw, ch = (w + 1) // 2, (h + 1) // 2 + local uo, vo = w * h, w * h + cw * ch + local dst = out or bcreate(w * h + 2 * cw * ch) + if buffer.len(src) < w * h * 4 or buffer.len(dst) < w * h + 2 * cw * ch then + return dst + end + local m = MATRIX[matrix or "bt601"] or MATRIX.bt601 + local kr, kb = m.kr, m.kb + local kg = 1 - kr - kb + local full = range == "full" + local ysc = if full then 1 else 219 / 255 + local csc = if full then 1 else 224 / 255 + local yof = if full then 0.5 else 16.5 + -- fixed point x 65536 + local yr, yg, yb = floor(kr * ysc * 65536 + 0.5), floor(kg * ysc * 65536 + 0.5), floor(kb * ysc * 65536 + 0.5) + local yoff = floor(yof * 65536) + local ur = floor(-kr / (2 * (1 - kb)) * csc * 65536 + 0.5) + local ug = floor(-kg / (2 * (1 - kb)) * csc * 65536 + 0.5) + local ub = floor(0.5 * csc * 65536 + 0.5) + local vr = ub + local vg = floor(-kg / (2 * (1 - kr)) * csc * 65536 + 0.5) + local vb = floor(-kb / (2 * (1 - kr)) * csc * 65536 + 0.5) + local coff4 = floor(128.5 * 65536) * 4 + for i = 0, w * h - 1 do + local o = i * 4 + local r, g, b = readu8(src, o), readu8(src, o + 1), readu8(src, o + 2) + writeu8(dst, i, readu8(CLIP, (yr * r + yg * g + yb * b + yoff) // 65536 + 1024)) + end + for cy = 0, ch - 1 do + local y0 = cy * 2 + local y1 = if y0 + 1 < h then y0 + 1 else y0 + for cx = 0, cw - 1 do + local x0 = cx * 2 + local x1 = if x0 + 1 < w then x0 + 1 else x0 + local a, b2, c2, d = (y0 * w + x0) * 4, (y0 * w + x1) * 4, (y1 * w + x0) * 4, (y1 * w + x1) * 4 + local r = readu8(src, a) + readu8(src, b2) + readu8(src, c2) + readu8(src, d) + local g = readu8(src, a + 1) + readu8(src, b2 + 1) + readu8(src, c2 + 1) + readu8(src, d + 1) + local b = readu8(src, a + 2) + readu8(src, b2 + 2) + readu8(src, c2 + 2) + readu8(src, d + 2) + local i = cy * cw + cx + writeu8(dst, uo + i, readu8(CLIP, (ur * r + ug * g + ub * b + coff4) // 262144 + 1024)) + writeu8(dst, vo + i, readu8(CLIP, (vr * r + vg * g + vb * b + coff4) // 262144 + 1024)) + end + end + return dst +end + +-- the range / matrix an Image's meta records (meta.yuv = { range, matrix }); limited BT.601 when absent +local function info(img: Types.Image): (string, string) + local y = img.meta and img.meta.yuv + if type(y) == "table" then + return y.range or "limited", y.matrix or "bt601" + end + return "limited", "bt601" +end +Yuv.info = info + +-- planes(w, h) -> uo, vo, cw, ch of a yuv420p buffer +function Yuv.planes(w: number, h: number): (number, number, number, number) + local cw, ch = (w + 1) // 2, (h + 1) // 2 + return w * h, w * h + cw * ch, cw, ch +end + +-- imageToRgba(img) -> an rgba8 Image (yuv420p converted; rgba8 returned as is; nil for other formats) +function Yuv.imageToRgba(img: Types.Image): Types.Image? + if img.format == "rgba8" then + return img + end + if img.format ~= "yuv420p" then + return nil + end + local w, h = img.width, img.height + local uo, vo, cw = Yuv.planes(w, h) + local range, matrix = info(img) + local out = Types.Image.new(w, h, "rgba8") + Yuv.toRgba(img.pixels, w, h, uo, vo, cw, range, matrix, out.pixels) + out.meta.source = img.meta.source + return out +end + +-- imageFromRgba(img, range?, matrix?) -> a yuv420p Image (meta.yuv records the range / matrix) +function Yuv.imageFromRgba(img: Types.Image, range: string?, matrix: string?): Types.Image? + if img.format == "yuv420p" then + return img + end + if img.format ~= "rgba8" then + return nil + end + local out = Types.Image.new(img.width, img.height, "yuv420p") + Yuv.fromRgba(img.pixels, img.width, img.height, range, matrix, out.pixels) + out.meta.yuv = { range = range or "limited", matrix = matrix or "bt601" } + out.meta.source = img.meta.source + return out +end + +return Yuv diff --git a/src/Formats/containers/AudioWrap.luau b/src/Formats/containers/AudioWrap.luau new file mode 100644 index 0000000..b6a50f0 --- /dev/null +++ b/src/Formats/containers/AudioWrap.luau @@ -0,0 +1,341 @@ +--!strict +-- containers/AudioWrap: an audio track of a video container (a Types.Demuxer track and its packets) as a standalone +-- stream that an audio format reads, so the api can open it with the audio formats (a format never requires another +-- format). New in formats-luau. +-- PCM (pcm_u8 / s16 / s24 / s32 le and be, f32 / f64, alaw, mulaw) -> WAV (big-endian samples byte-swapped); +-- an AVI audio track with its WAVEFORMATEX (track.waveFormat: IMA / MS ADPCM, ...) -> WAV with that fmt chunk; +-- mp3 / mp2 / mp1 -> the frames back to back (format "mp3"); +-- flac -> "fLaC" + the metadata blocks (CodecPrivate / dfLa) + the frames; +-- opus -> Ogg Opus (OpusHead from the config or made up, OpusTags, packets with granules from their TOC durations); +-- vorbis -> Ogg Vorbis (the three headers from Matroska's Xiph-laced CodecPrivate or MP4's esds-less layout); +-- aac -> ADTS (from the AudioSpecificConfig) for audio/aac. +-- +-- local buf, format, err = AudioWrap.wrap(demuxer, track) -- then F.open(buf, { format = format }) +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Mux = require("@formats/containers/Ogg/Mux") + +local AudioWrap = {} + +local function allPackets(dmx: any, track: Types.Track): { Types.Packet } + local out = {} + local n = if dmx.count then dmx:count(track.id) else 0 + if n > 0 and dmx.get then + for k = 1, n do + local p = dmx:get(track.id, k) + if p then + table.insert(out, p) + end + end + end + return out +end + +local function concat(packets: { Types.Packet }, prefix: buffer?): buffer + local total = if prefix then buffer.len(prefix) else 0 + for _, p in packets do + total += buffer.len(p.data) + end + local out = buffer.create(total) + local o = 0 + if prefix then + buffer.copy(out, 0, prefix) + o = buffer.len(prefix) + end + for _, p in packets do + buffer.copy(out, o, p.data) + o += buffer.len(p.data) + end + return out +end + +-- ------------------------------------------------------------------------------------------------ WAV +local PCM: { [string]: { number } } = { -- tag, bits, bytes swapped (big-endian source) + pcm_u8 = { 1, 8, 0 }, + pcm_s8 = { 1, 8, 0 }, + pcm_s16le = { 1, 16, 0 }, + pcm_s24le = { 1, 24, 0 }, + pcm_s32le = { 1, 32, 0 }, + pcm_s16be = { 1, 16, 1 }, + pcm_s24be = { 1, 24, 1 }, + pcm_s32be = { 1, 32, 1 }, + pcm_f32le = { 3, 32, 0 }, + pcm_f64le = { 3, 64, 0 }, + pcm_f32be = { 3, 32, 1 }, + pcm_f64be = { 3, 64, 1 }, + pcm_alaw = { 6, 8, 0 }, + pcm_mulaw = { 7, 8, 0 }, +} + +local function wav(fmt: buffer, data: buffer): buffer + local w = Bytes.writer(buffer.len(data) + buffer.len(fmt) + 64) + local fl = buffer.len(fmt) + local dl = buffer.len(data) + w:string("RIFF") + w:u32le(4 + 8 + fl + (fl % 2) + 8 + dl + (dl % 2)) + w:string("WAVE") + w:string("fmt ") + w:u32le(fl) + w:bytes(fmt) + if fl % 2 == 1 then + w:u8(0) + end + w:string("data") + w:u32le(dl) + w:bytes(data) + if dl % 2 == 1 then + w:u8(0) + end + return w:finish() +end + +local function pcmWav(track: Types.Track, packets: { Types.Packet }): (buffer?, Err.Err?) + local spec = PCM[track.codec] + local ch = track.channels or 1 + local rate = math.floor((track.sampleRate or 0) + 0.5) + if ch < 1 or rate <= 0 then + return nil, Err.new(Err.CORRUPT, "PCM track without channels / sample rate") + end + local bits = spec[2] + local data = concat(packets) + if spec[3] == 1 then + local bps = bits // 8 + for i = 0, buffer.len(data) - bps, bps do + for k = 0, bps // 2 - 1 do + local a, b = buffer.readu8(data, i + k), buffer.readu8(data, i + bps - 1 - k) + buffer.writeu8(data, i + k, b) + buffer.writeu8(data, i + bps - 1 - k, a) + end + end + end + if track.codec == "pcm_s8" then + for i = 0, buffer.len(data) - 1 do + buffer.writeu8(data, i, (buffer.readu8(data, i) + 128) % 256) + end + end + local f = Bytes.writer(16) + local align = ch * bits // 8 + f:u16le(spec[1]) + f:u16le(ch) + f:u32le(rate) + f:u32le(rate * align) + f:u16le(align) + f:u16le(bits) + return wav(f:finish(), data), nil +end + +-- ------------------------------------------------------------------------------------------------ Ogg +-- the number of 48 kHz samples in an Opus packet (RFC 6716 section 3.1) +local function opusSamples(b: buffer): number + local n = buffer.len(b) + if n < 1 then + return 0 + end + local toc = buffer.readu8(b, 0) + local config = toc // 8 + local fs: number + if config < 12 then + fs = ({ 480, 960, 1920, 2880 })[config % 4 + 1] + elseif config < 16 then + fs = if config % 2 == 0 then 480 else 960 + else + fs = ({ 120, 240, 480, 960 })[config % 4 + 1] + end + local c = toc % 4 + local frames = if c == 0 then 1 elseif c == 3 then (if n >= 2 then buffer.readu8(b, 1) % 64 else 0) else 2 + return fs * frames +end + +local function opusHead(track: Types.Track): buffer + local c = track.config + if c and buffer.len(c) >= 19 and buffer.readstring(c, 0, 8) == "OpusHead" then + return c + end + local w = Bytes.writer(19) + w:string("OpusHead") + w:u8(1) + w:u8(math.clamp(track.channels or 2, 1, 2)) + w:u16le(math.floor((track.codecDelay or 0) * 48000 + 0.5)) + w:u32le(math.floor(track.sampleRate or 48000)) + w:u16le(0) + w:u8(0) + return w:finish() +end + +local function opusTags(): buffer + local w = Bytes.writer(32) + w:string("OpusTags") + local vendor = "formats-luau" + w:u32le(#vendor) + w:string(vendor) + w:u32le(0) + return w:finish() +end + +local function ogg(headers: { buffer }, packets: { Types.Packet }, granuleOf: (p: Types.Packet, i: number) -> number): buffer + local mux = Mux.new({ pageSize = 4096 }) + local s = mux:stream(1) + for i, h in headers do + s:packet(h, 0, { flush = i == 1 or i == #headers }) + end + for i, p in packets do + s:packet(p.data, granuleOf(p, i), { eos = i == #packets }) + end + return mux:finish() +end + +-- Matroska's Vorbis CodecPrivate: Xiph-laced headers (count - 1, sizes, data) +local function xiphHeaders(c: buffer): { buffer }? + local n = buffer.len(c) + if n < 3 then + return nil + end + local count = buffer.readu8(c, 0) + 1 + local p = 1 + local sizes = {} + local total = 0 + for k = 1, count - 1 do + local s = 0 + while true do + if p >= n then + return nil + end + local b = buffer.readu8(c, p) + p += 1 + s += b + if b ~= 255 then + break + end + end + sizes[k] = s + total += s + end + sizes[count] = n - p - total + if sizes[count] < 0 then + return nil + end + local out = {} + for k = 1, count do + local b = buffer.create(sizes[k]) + buffer.copy(b, 0, c, p, sizes[k]) + p += sizes[k] + out[k] = b + end + return out +end + +-- ------------------------------------------------------------------------------------------------ ADTS +local function adts(track: Types.Track, packets: { Types.Packet }): (buffer?, Err.Err?) + local c = track.config + local profile, rateIndex, chanConfig + if c and buffer.len(c) >= 2 then + local b0, b1 = buffer.readu8(c, 0), buffer.readu8(c, 1) + profile = b0 // 8 -- audio object type + rateIndex = (b0 % 8) * 2 + b1 // 128 + chanConfig = (b1 // 8) % 16 + else + local rates = { 96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350 } + profile = 2 + rateIndex = 4 + for i, r in rates do + if r == math.floor((track.sampleRate or 44100) + 0.5) then + rateIndex = i - 1 + end + end + chanConfig = track.channels or 2 + end + if profile < 1 or profile > 4 or rateIndex > 12 then + return nil, Err.new(Err.UNSUPPORTED, "AAC object type " .. tostring(profile) .. " in ADTS") + end + local w = Bytes.writer(64) + for _, p in packets do + local len = buffer.len(p.data) + 7 + w:u8(0xFF) + w:u8(0xF1) + w:u8((profile - 1) * 64 + rateIndex * 4 + chanConfig // 4) + w:u8((chanConfig % 4) * 64 + (len // 2048) % 4) + w:u8((len // 8) % 256) + w:u8((len % 8) * 32 + 0x1F) + w:u8(0xFC) + w:bytes(p.data) + end + return w:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ wrap +-- wrap(demuxer, track) -> buffer, audio format name | nil, nil, Err +function AudioWrap.wrap(dmx: any, track: Types.Track): (buffer?, string?, Err.Err?) + if type(track) ~= "table" or track.kind ~= "audio" then + return nil, nil, Err.new(Err.ARG, "not an audio track") + end + if track.unsupported then + return nil, nil, Err.new(Err.UNSUPPORTED, track.unsupported) + end + local codec = track.codec + local packets = allPackets(dmx, track) + if #packets == 0 then + return nil, nil, Err.new(Err.CORRUPT, "audio track without packets") + end + if track.waveFormat and (PCM[codec] == nil or codec == "pcm_s16le" or codec == "pcm_u8") then + return wav(track.waveFormat, concat(packets)), "wav", nil + end + if PCM[codec] then + local b, err = pcmWav(track, packets) + return b, if b then "wav" else nil, err + end + if codec == "mp3" or codec == "mp2" or codec == "mp1" then + return concat(packets), "mp3", nil + end + if codec == "flac" then + local c = track.config + local prefix: buffer? = nil + if c and buffer.len(c) >= 4 and buffer.readstring(c, 0, 4) == "fLaC" then + prefix = c + elseif c and buffer.len(c) >= 34 then + -- metadata blocks without the marker (MP4 dfLa payload after version / flags) + local start = if buffer.len(c) >= 38 and buffer.readu8(c, 0) == 0 and buffer.readu8(c, 4) % 128 == 0 then 4 else 0 + local b = buffer.create(4 + buffer.len(c) - start) + buffer.writestring(b, 0, "fLaC") + buffer.copy(b, 4, c, start) + prefix = b + else + return nil, nil, Err.new(Err.CORRUPT, "FLAC track without its STREAMINFO") + end + return concat(packets, prefix), "flac", nil + end + if codec == "opus" then + local head = opusHead(track) + local pre = buffer.readu16(head, 10) + local g = pre + local out = ogg({ head, opusTags() }, packets, function(p: Types.Packet): number + g += opusSamples(p.data) + local d = (p :: any).discardPadding + if type(d) == "number" and d > 0 then + return g - math.floor(d * 48000 + 0.5) -- the end trimming (WebM DiscardPadding) + end + return g + end) + return out, "opus", nil + end + if codec == "vorbis" then + local c = track.config + local headers = c and xiphHeaders(c) + if not headers or #headers ~= 3 then + return nil, nil, Err.new(Err.CORRUPT, "Vorbis track without its three headers") + end + local rate = track.sampleRate or 44100 + local scale = track.timescale + local out = ogg(headers, packets, function(p: Types.Packet): number + return math.floor((p.pts + (p.duration or 0)) / scale * rate + 0.5) + end) + return out, "vorbis", nil + end + if codec == "aac" then + local b, err = adts(track, packets) + return b, if b then "aac" else nil, err + end + return nil, nil, Err.new(Err.UNSUPPORTED, "no audio format for codec " .. tostring(codec)) +end + +return AudioWrap diff --git a/src/Formats/containers/Demux.luau b/src/Formats/containers/Demux.luau new file mode 100644 index 0000000..dac5579 --- /dev/null +++ b/src/Formats/containers/Demux.luau @@ -0,0 +1,287 @@ +--!strict +-- containers/Demux: the indexed Types.Demuxer every video container builds (Matroska, AVI, MPEG-TS / PS, Y4M, MP4). +-- New in formats-luau. A container parses its file once into an index of packets (track, pts, dts, duration, +-- keyframe, and the bytes as an offset + length into the source buffer or a buffer of their own); this module gives +-- that index the Demuxer interface: per-track cursors (a video decoder and an audio decoder read the same file +-- independently), a file-order cursor, keyframe seeking, packet copies on demand. +-- +-- local d = Demux.new("mkv", tracks, src, meta) +-- d:add(trackId, pts, dts, duration, keyframe, offset, length) -- in file order +-- d:addData(trackId, pts, dts, duration, keyframe, buffer) -- bytes that are not one range of src +-- d:finish() -- durations, per-track indexes +-- for p in d:packets(1) do ... end; d:read(); d:seek(12.5); d:count(1); d:get(1, i) +local Types = require("@formats/Types") + +local Demux = {} +local D = {} +D.__index = D + +export type Demux = typeof(setmetatable( + {} :: { + kind: "demuxer", + format: string, + tracks: { Types.Track }, + duration: number, + meta: { [string]: any }, + src: buffer, + n: number, + tr: { number }, + pts: { number }, + dts: { number }, + dur: { number }, + key: { boolean }, + off: { number }, + len: { number }, + data: { [number]: buffer }, + extra: { [number]: { [string]: any } }, + byTrack: { [number]: { number } }, + cur: { [number]: number }, + gcur: number, + }, + D +)) + +-- new(format, tracks, src, meta?) -> an empty index +function Demux.new(format: string, tracks: { Types.Track }, src: buffer, meta: { [string]: any }?): Demux + return setmetatable({ + kind = "demuxer" :: "demuxer", + format = format, + tracks = tracks, + duration = 0, + meta = meta or {}, + src = src, + n = 0, + tr = {}, + pts = {}, + dts = {}, + dur = {}, + key = {}, + off = {}, + len = {}, + data = {}, + extra = {}, + byTrack = {}, + cur = {}, + gcur = 1, + }, D) +end + +-- add(track, pts, dts?, duration?, keyframe, offset, length): a packet whose bytes are src[offset, offset + length) +function D.add(self: Demux, track: number, pts: number, dts: number?, duration: number?, keyframe: boolean, offset: number, length: number) + local i = self.n + 1 + self.n = i + self.tr[i] = track + self.pts[i] = pts + self.dts[i] = dts or pts + self.dur[i] = duration or 0 + self.key[i] = keyframe + self.off[i] = offset + self.len[i] = length +end + +-- addData(track, pts, dts?, duration?, keyframe, data): a packet with its own bytes +function D.addData(self: Demux, track: number, pts: number, dts: number?, duration: number?, keyframe: boolean, data: buffer) + self:add(track, pts, dts, duration, keyframe, -1, buffer.len(data)) + self.data[self.n] = data +end + +-- setExtra(key, value): a field for the last packet added (Packet[key] = value: discardPadding, ...) +function D.setExtra(self: Demux, key: string, value: any) + local e = self.extra[self.n] + if not e then + e = {} + self.extra[self.n] = e + end + e[key] = value +end + +-- finish(): builds the per-track indexes, fills missing packet durations from the next packet's pts (or the track's +-- frame rate), and the track / file durations (seconds) where the container gave none +function D.finish(self: Demux) + local byTrack: { [number]: { number } } = {} + for _, t in self.tracks do + byTrack[t.id] = {} + end + for i = 1, self.n do + local list = byTrack[self.tr[i]] + if list then + table.insert(list, i) + end + end + self.byTrack = byTrack + local total = self.duration + for _, t in self.tracks do + local list = byTrack[t.id] + local scale = if t.timescale and t.timescale > 0 then t.timescale else 1 + t.timescale = scale + local frameTicks = if t.frameRate and t.frameRate > 0 then scale / t.frameRate else 0 + -- durations from the next packet in presentation order + if #list > 0 then + local order = table.clone(list) + table.sort(order, function(a: number, b: number): boolean + return self.pts[a] < self.pts[b] + end) + for k = 1, #order do + local i = order[k] + if self.dur[i] <= 0 then + local nx = order[k + 1] + if nx and self.pts[nx] > self.pts[i] then + self.dur[i] = self.pts[nx] - self.pts[i] + elseif frameTicks > 0 then + self.dur[i] = frameTicks + elseif k > 1 then + self.dur[i] = self.dur[order[k - 1]] + end + end + end + local first, last = order[1], order[#order] + local d = (self.pts[last] + self.dur[last] - math.min(0, self.pts[first])) / scale + if not t.duration or t.duration <= 0 then + t.duration = d + end + t.frames = t.frames or #list + end + if t.duration and t.duration > total then + total = t.duration + end + self.cur[t.id] = 1 + end + self.duration = total +end + +-- the Packet for index entry i (a copy of its bytes) +function D._packet(self: Demux, i: number): Types.Packet + local data = self.data[i] + if not data then + local o, l = self.off[i], self.len[i] + local src = self.src + local n = buffer.len(src) + if o < 0 or o > n then + o, l = n, 0 + elseif o + l > n then + l = n - o + end + data = buffer.create(l) + buffer.copy(data, 0, src, o, l) + end + local p: any = { + track = self.tr[i], + pts = self.pts[i], + dts = self.dts[i], + duration = self.dur[i], + keyframe = self.key[i], + data = data :: buffer, + } + local e = self.extra[i] + if e then + for k, v in e do + p[k] = v + end + end + return p +end + +-- read(track?) -> the next Packet of the track (or of any track, in file order) | nil at the end +function D.read(self: Demux, track: number?): Types.Packet? + if track == nil then + local i = self.gcur + if i > self.n then + return nil + end + self.gcur = i + 1 + return self:_packet(i) + end + local list = self.byTrack[track] + if not list then + return nil + end + local c = self.cur[track] or 1 + local i = list[c] + if not i then + return nil + end + self.cur[track] = c + 1 + return self:_packet(i) +end + +-- packets(track?) -> an iterator of Packets from the current position (advancing it) +function D.packets(self: Demux, track: number?): () -> Types.Packet? + return function(): Types.Packet? + return self:read(track) + end +end + +-- count(track) -> number of packets; get(track, k) -> the k-th packet (1-based) without moving cursors +function D.count(self: Demux, track: number): number + local list = self.byTrack[track] + return if list then #list else 0 +end +function D.get(self: Demux, track: number, k: number): Types.Packet? + local list = self.byTrack[track] + local i = list and list[k] + if not i then + return nil + end + return self:_packet(i) +end + +-- info(track, k) -> pts, dts, duration, keyframe, length of the k-th packet (no copy) +function D.info(self: Demux, track: number, k: number): (number?, number?, number?, boolean?, number?) + local list = self.byTrack[track] + local i = list and list[k] + if not i then + return nil + end + return self.pts[i], self.dts[i], self.dur[i], self.key[i], self.len[i] +end + +-- rewind(track?): a track's cursor (or every cursor) back to the start +function D.rewind(self: Demux, track: number?) + if track then + self.cur[track] = 1 + return + end + for id in self.cur do + self.cur[id] = 1 + end + self.gcur = 1 +end + +-- seek(seconds): each track to its last keyframe at or before the time (the file-order cursor to the earliest) +function D.seek(self: Demux, seconds: number) + local g = self.n + 1 + for _, t in self.tracks do + local list = self.byTrack[t.id] + if list and #list > 0 then + local target = seconds * t.timescale + local best = 1 + for k = 1, #list do + local i = list[k] + if self.key[i] and self.pts[i] <= target + 1e-6 then + best = k + end + end + self.cur[t.id] = best + if list[best] < g then + g = list[best] + end + end + end + self.gcur = if g > self.n then 1 else g +end + +-- track(kind) -> the first default track of the kind, else the first of the kind +function D.track(self: Demux, kind: string): Types.Track? + local first = nil + for _, t in self.tracks do + if t.kind == kind then + if t.default then + return t + end + first = first or t + end + end + return first +end + +return Demux diff --git a/src/Formats/containers/Ebml/init.luau b/src/Formats/containers/Ebml/init.luau new file mode 100644 index 0000000..2efc113 --- /dev/null +++ b/src/Formats/containers/Ebml/init.luau @@ -0,0 +1,335 @@ +--!strict +-- containers/Ebml: EBML (RFC 8794), the binary structure under Matroska and WebM. New in formats-luau. +-- Reading: element headers (IDs keep their length marker bits, as the specs write them: 0x1A45DFA3; sizes drop it; +-- an all-ones size is "unknown"), children iteration, and the value types (unsigned / signed integers, floats, +-- strings, binary). Writing: a byte builder with nested master elements whose 8-byte sizes are patched on close, and +-- minimal-length value elements. +-- +-- local id, size, data = Ebml.header(buf, pos, limit) -- size = -1: unknown; nil when malformed / truncated +-- for id, off, size in Ebml.children(buf, off, limit) do ... end +-- local w = Ebml.writer(); local m = w:open(0x18538067); w:uint(0xD7, 1); w:close(m); local out = w:finish() +-- +-- Never throws: malformed input gives nil (readers) or stops iteration. +local Bytes = require("@formats/core/Bytes") + +local readu8 = buffer.readu8 + +local Ebml = {} + +Ebml.UNKNOWN = -1 + +-- vint(buf, pos, limit) -> value (marker removed), length | nil. All-ones values (unknown sizes) return -1. +function Ebml.vint(buf: buffer, pos: number, limit: number): (number?, number?) + if pos >= limit then + return nil + end + local b = readu8(buf, pos) + if b == 0 then + return nil + end + local len = 1 + local mask = 0x80 + while bit32.band(b, mask) == 0 do + len += 1 + mask = mask // 2 + end + if pos + len > limit then + return nil + end + local v = bit32.band(b, mask - 1) + local allOnes = v == mask - 1 + for i = 1, len - 1 do + local c = readu8(buf, pos + i) + v = v * 256 + c + if c ~= 255 then + allOnes = false + end + end + if allOnes then + return -1, len + end + return v, len +end + +-- svint(buf, pos, limit) -> a signed vint (EBML lacing deltas) | nil +function Ebml.svint(buf: buffer, pos: number, limit: number): (number?, number?) + local v, len = Ebml.vint(buf, pos, limit) + if v == nil or len == nil then + return nil + end + if v == -1 then + return nil + end + return v - (2 ^ (7 * len - 1) - 1), len +end + +-- id(buf, pos, limit) -> the element ID with its marker bits, length | nil (IDs are 1..4 bytes) +function Ebml.id(buf: buffer, pos: number, limit: number): (number?, number?) + if pos >= limit then + return nil + end + local b = readu8(buf, pos) + local len = if b >= 0x80 then 1 elseif b >= 0x40 then 2 elseif b >= 0x20 then 3 elseif b >= 0x10 then 4 else 0 + if len == 0 or pos + len > limit then + return nil + end + local v = b + for i = 1, len - 1 do + v = v * 256 + readu8(buf, pos + i) + end + return v, len +end + +-- header(buf, pos, limit) -> id, size (-1 = unknown), data offset | nil +function Ebml.header(buf: buffer, pos: number, limit: number): (number?, number?, number?) + local id, il = Ebml.id(buf, pos, limit) + if not id or not il then + return nil + end + local size, sl = Ebml.vint(buf, pos + il, limit) + if not size or not sl then + return nil + end + return id, size, pos + il + sl +end + +-- children(buf, off, limit) -> iterator of id, data offset, size (an unknown size runs to limit; a size past the +-- limit is clipped; a malformed header ends the iteration) +function Ebml.children(buf: buffer, off: number, limit: number): () -> (number?, number, number) + local pos = off + return function(): (number?, number, number) + if pos >= limit then + return nil, 0, 0 + end + local id, size, data = Ebml.header(buf, pos, limit) + if not id or not size or not data then + pos = limit + return nil, 0, 0 + end + if size < 0 or data + size > limit then + size = limit - data + end + pos = data + size + return id, data, size + end +end + +-- uint(buf, off, len) / int / float / string: element values (0 / "" for empty elements) +function Ebml.uint(buf: buffer, off: number, len: number): number + local v = 0 + for i = 0, math.min(len, 8) - 1 do + v = v * 256 + readu8(buf, off + i) + end + return v +end +function Ebml.int(buf: buffer, off: number, len: number): number + if len <= 0 then + return 0 + end + local v = Ebml.uint(buf, off, len) + local n = math.min(len, 8) + if readu8(buf, off) >= 0x80 then + v -= 2 ^ (8 * n) + end + return v +end +function Ebml.float(buf: buffer, off: number, len: number): number + local r = Bytes.reader(buf, off, len) + if len == 4 then + return r:f32be() + elseif len == 8 then + return r:f64be() + end + return 0 +end +function Ebml.string(buf: buffer, off: number, len: number): string + local s = buffer.readstring(buf, off, len) + local z = string.find(s, "\0", 1, true) + if z then + s = string.sub(s, 1, z - 1) + end + return s +end +function Ebml.binary(buf: buffer, off: number, len: number): buffer + local b = buffer.create(len) + buffer.copy(b, 0, buf, off, len) + return b +end + +-- ------------------------------------------------------------------------------------------------ writing +local W = {} +W.__index = W + +export type Writer = typeof(setmetatable({} :: { w: Bytes.Writer }, W)) + +-- writer(capacity?) -> an EBML byte builder +function Ebml.writer(capacity: number?): Writer + return setmetatable({ w = Bytes.writer(capacity or 65536) }, W) +end + +-- idBytes(id) -> the ID's bytes as written +local function writeId(w: Bytes.Writer, id: number) + if id >= 0x1000000 then + w:u32be(id) + elseif id >= 0x10000 then + w:u24be(id) + elseif id >= 0x100 then + w:u16be(id) + else + w:u8(id) + end +end + +-- size as a minimal vint (n bytes: force a length) +local function writeSize(w: Bytes.Writer, size: number, n: number?) + local len = n or 1 + if not n then + while size >= 2 ^ (7 * len) - 1 do + len += 1 + end + end + local v = size + 2 ^ (7 * len) -- the marker bit + local bytes = table.create(len, 0) + for i = len, 1, -1 do + bytes[i] = v % 256 + v = v // 256 + end + for i = 1, len do + w:u8(bytes[i]) + end +end +Ebml.writeSize = writeSize + +-- vintBytes(v, n?) -> the vint encoding of v as a string (lacing, block track numbers) +function Ebml.vintString(v: number, n: number?): string + local w = Bytes.writer(8) + writeSize(w, v, n) + return buffer.readstring(w:finish(), 0, w:tell()) +end + +function W.tell(self: Writer): number + return self.w:tell() +end + +-- open(id) -> a handle for close(): writes the ID and an 8-byte size placeholder +function W.open(self: Writer, id: number): number + writeId(self.w, id) + local at = self.w:tell() + for _ = 1, 8 do + self.w:u8(0) + end + return at +end + +-- close(handle): patches the size of the element opened at handle +function W.close(self: Writer, at: number) + local w = self.w + local v = w:tell() - at - 8 + w:setU8(at, 0x01) + for i = 7, 1, -1 do + w:setU8(at + i, v % 256) + v = v // 256 + end +end + +-- unknownSize(id): a master element with an unknown size (live streams) +function W.openUnknown(self: Writer, id: number) + writeId(self.w, id) + self.w:u8(0x01) + for _ = 1, 7 do + self.w:u8(0xFF) + end +end + +function W.uint(self: Writer, id: number, v: number) + local n = 1 + while v >= 2 ^ (8 * n) and n < 8 do + n += 1 + end + writeId(self.w, id) + writeSize(self.w, n) + local bytes = table.create(n, 0) + local x = v + for i = n, 1, -1 do + bytes[i] = x % 256 + x = x // 256 + end + for i = 1, n do + self.w:u8(bytes[i]) + end +end + +function W.int(self: Writer, id: number, v: number) + local n = 1 + while (v < -(2 ^ (8 * n - 1)) or v >= 2 ^ (8 * n - 1)) and n < 8 do + n += 1 + end + local u = if v < 0 then v + 2 ^ (8 * n) else v + writeId(self.w, id) + writeSize(self.w, n) + local bytes = table.create(n, 0) + for i = n, 1, -1 do + bytes[i] = u % 256 + u = u // 256 + end + for i = 1, n do + self.w:u8(bytes[i]) + end +end + +function W.float(self: Writer, id: number, v: number) + writeId(self.w, id) + writeSize(self.w, 8) + self.w:f64be(v) +end + +function W.string(self: Writer, id: number, s: string) + writeId(self.w, id) + writeSize(self.w, #s) + self.w:string(s) +end + +-- binary(id, buf, off?, len?) +function W.binary(self: Writer, id: number, b: buffer, off: number?, len: number?) + local o = off or 0 + local n = len or (buffer.len(b) - o) + writeId(self.w, id) + writeSize(self.w, n) + self.w:bytes(b, o, n) +end + +-- raw bytes (a pre-built element, block headers) +function W.raw(self: Writer, s: string) + self.w:string(s) +end +function W.rawBuffer(self: Writer, b: buffer, off: number?, len: number?) + local o = off or 0 + self.w:bytes(b, o, len or (buffer.len(b) - o)) +end +-- element header for a binary element whose payload follows in pieces: id + size +function W.header(self: Writer, id: number, size: number) + writeId(self.w, id) + writeSize(self.w, size) +end + +-- void(n): an EBML Void element of exactly n bytes (n >= 2), for reserved space +function W.void(self: Writer, n: number) + self.w:u8(0xEC) + if n - 2 < 127 then + writeSize(self.w, n - 2, 1) + for _ = 1, n - 2 do + self.w:u8(0) + end + else + writeSize(self.w, n - 9, 8) + for _ = 1, n - 9 do + self.w:u8(0) + end + end +end + +function W.finish(self: Writer): buffer + return self.w:finish() +end + +return Ebml diff --git a/src/Formats/init.luau b/src/Formats/init.luau index 19fd6c7..a87e3e8 100644 --- a/src/Formats/init.luau +++ b/src/Formats/init.luau @@ -19,6 +19,9 @@ local Bytes = require("@formats/core/Bytes") local Input = require("@formats/core/Input") local Types = require("@formats/Types") local Registry = require("@formats/Registry") +local Video = require("@formats/codecs/Video") +local AudioWrap = require("@formats/containers/AudioWrap") +local ImageOps = require("@formats/ops/ImageOps") local host = require("@formats/host") local F = {} @@ -35,6 +38,7 @@ F.plugins = {} :: { [string]: any } -- injected optional dependencies (plugins.b local KIND_CATEGORY: { [string]: string } = { image = "image", audio = "audio", + video = "video", scene = "model", cad = "cad", font = "font", @@ -255,11 +259,26 @@ end -- so the api hands decoders opts.decodeImage(buf) -> Image | nil, Err and encoders opts.encodeImage(img, format) -> -- buffer | nil, Err (unless the caller passed its own). Formats work without them (returning Err.UNSUPPORTED for -- the embedded parts) when called directly. +-- +-- Audio tracks of video containers: opts.openAudio(demuxer, track) -> audio Decoder | nil, Err. The track's packets +-- become a stream an audio format reads (containers/AudioWrap: PCM -> WAV, Opus / Vorbis -> Ogg, AAC -> ADTS, MP3 / +-- FLAC as they are), opened through F.open with that format. +local function openAudio(demuxer: any, track: any): (any, Err.Err?) + local buf, fmt, err = AudioWrap.wrap(demuxer, track) + if not buf then + return nil, err + end + return F.open(buf, { format = fmt, category = "audio" }) +end + local function withHooks(o: Options): Options - if o.decodeImage ~= nil and o.encodeImage ~= nil then + if o.decodeImage ~= nil and o.encodeImage ~= nil and o.openAudio ~= nil then return o end local c = table.clone(o) + if c.openAudio == nil then + c.openAudio = openAudio + end if c.decodeImage == nil then c.decodeImage = function(b: buffer): (any, Err.Err?) return F.load(b, { category = "image" }) @@ -305,12 +324,12 @@ function F.load(src: any, opts: Options?): (any, Err.Err?) end value, err = v, e elseif m.open then - local ok, dec, e = pcall(m.open, Bytes.reader(buf), o) + local ok, dec, e = pcall(m.open, Bytes.reader(buf), withHooks(o)) if not ok then return nil, Err.wrap(Err.new(Err.CORRUPT, "decoder threw: " .. tostring(dec)), entry.name) end if dec then - value = drain(dec) + value = if type(dec) == "table" and dec.kind == "video" then dec else drain(dec) end err = e else @@ -333,6 +352,9 @@ function F.open(src: any, opts: Options?): (any, Err.Err?) return nil, ierr end local entry, derr = detect(buf, name, o.category, o.format) + if not entry and o.category == "video" and o.format == nil then + entry = detect(buf, name, "image", nil) -- animated images open as frames-backed videos + end if not entry then return nil, derr end @@ -340,10 +362,20 @@ function F.open(src: any, opts: Options?): (any, Err.Err?) if not m then return nil, merr end + if not m.open and entry.category == "image" and (o.category == nil or o.category == "video") then + local io = table.clone(o) + io.category = "image" + io.format = entry.name + local img, lerr = F.load(buf, io) + if not img then + return nil, lerr + end + return F.video.fromImage(img, o) + end if not m.open then return nil, Err.wrap(Err.new(Err.UNSUPPORTED, "no streaming decoder (use load)"), entry.name) end - local ok, dec, e = pcall(m.open, Bytes.reader(buf), o) + local ok, dec, e = pcall(m.open, Bytes.reader(buf), withHooks(o)) if not ok then return nil, Err.wrap(Err.new(Err.CORRUPT, "decoder threw: " .. tostring(dec)), entry.name) end @@ -369,6 +401,9 @@ local function encoderFor(value: any, dest: string?, o: Options): (Registry.Entr return nil, nil, Err.new(Err.ARG, "save: no format (pass opts.format or a destination with an extension)") end local entry = find(key, category) + if not entry and category == "image" and type(value) == "table" and value.kind == "image" then + entry = find(key, "video") -- an (animated) image written as a video: F.convert(gif, "avi") + end if not entry then return nil, nil, Err.new(Err.UNKNOWN_FORMAT, "no format named " .. key .. (if category then " for " .. category else "")) end @@ -423,6 +458,13 @@ function F.save(value: any, dest: string?, opts: Options?): (any, Err.Err?) o.files = {} end end + if entry.category == "video" and type(value) == "table" and value.kind == "image" then + local v, verr = F.video.fromImage(value) + if not v then + return nil, verr + end + value = v + end if type(value) == "table" and value.kind == "scene" then local terr = encodeTextures(value) if terr then @@ -539,6 +581,36 @@ for category in Types.CATEGORIES do end F.data.null = Types.null +-- F.video.fromImage(img, opts?) -> a frames-backed VideoDecoder: an animated GIF / APNG / WebP (img.frames, composited +-- onto full canvases by ImageOps.coalesce) or a still image (one frame). opts.rgba is accepted (frames are rgba8). +F.video.fromImage = function(img: any, opts: Options?): (any, Err.Err?) + if type(img) ~= "table" or img.kind ~= "image" then + return nil, Err.new(Err.ARG, "fromImage: expected an Image") + end + local frames, delays = { img }, { 0.1 } + if type(img.frames) == "table" and #img.frames > 0 then + local list, cerr = ImageOps.coalesce(img) + if not list then + return nil, cerr + end + frames = list + delays = {} + for i, f in img.frames do + delays[i] = if type(f.delay) == "number" and f.delay > 0 then f.delay else 0.1 + end + elseif img.format ~= "rgba8" and img.format ~= "yuv420p" then + local c, cerr = ImageOps.convert(img, "rgba8") + if not c then + return nil, cerr + end + frames = { c } + end + local src = type(img.meta) == "table" and img.meta.source + return Video.fromFrames(frames, delays, { format = type(src) == "table" and src.format or "image", loops = img.loops, meta = img.meta }) +end +-- F.video.codecs: the video codec registry (codecs/Video: register / entry / fromFourcc / fromMatroska / decoder) +F.video.codecs = Video + -- F.model.loadTextures(scene, opts?) -> scene, { [index]: Err }: decodes each texture's encoded bytes (texture.data, or -- texture.uri through opts.resolve) into texture.image with F.image.load. Model formats never decode images -- themselves (a format does not require another format); this is the lazy step at the api layer. Textures whose diff --git a/src/Formats/video/mkv/Mux.luau b/src/Formats/video/mkv/Mux.luau new file mode 100644 index 0000000..6eed3cc --- /dev/null +++ b/src/Formats/video/mkv/Mux.luau @@ -0,0 +1,285 @@ +--!strict +-- video/mkv/Mux: the Matroska / WebM muxer: EBML header, Segment with SeekHead, Info (1 ms TimecodeScale, Duration), +-- Tracks (CodecPrivate, DefaultDuration, Video / Audio settings, Opus CodecDelay / SeekPreRoll), Clusters of +-- SimpleBlocks (a new cluster at a video keyframe once the current one spans 2 s, and before the 16-bit relative +-- timestamp would overflow), and Cues (one CuePoint per cluster, on the video track when there is one). Streams come +-- from codecs/Video/Source (copied packets or encoded frames). Interpreted; never throws. +local Err = require("@formats/core/Err") +local Ebml = require("@formats/containers/Ebml") +local Video = require("@formats/codecs/Video") +local Source = require("@formats/codecs/Video/Source") +local Parse = require("@formats/video/mkv/Parse") + +local ID = Parse.ID +local Mux = {} + +local AUDIO_IDS: { [string]: string } = { + vorbis = "A_VORBIS", + opus = "A_OPUS", + flac = "A_FLAC", + mp3 = "A_MPEG/L3", + mp2 = "A_MPEG/L2", + mp1 = "A_MPEG/L1", + aac = "A_AAC", + ac3 = "A_AC3", + eac3 = "A_EAC3", + alac = "A_ALAC", + pcm_u8 = "A_PCM/INT/LIT", + pcm_s16le = "A_PCM/INT/LIT", + pcm_s24le = "A_PCM/INT/LIT", + pcm_s32le = "A_PCM/INT/LIT", + pcm_s16be = "A_PCM/INT/BIG", + pcm_s24be = "A_PCM/INT/BIG", + pcm_s32be = "A_PCM/INT/BIG", + pcm_f32le = "A_PCM/FLOAT/IEEE", + pcm_f64le = "A_PCM/FLOAT/IEEE", +} +Mux.AUDIO_IDS = AUDIO_IDS + +-- codecId(stream) -> the Matroska CodecID | nil +function Mux.codecId(kind: string, codec: string): string? + if kind == "video" then + local e = Video.entry(codec) + local m = e and e.matroska + return m and m[1] + end + return AUDIO_IDS[codec] +end + +local function pcmBits(codec: string): number? + local b = string.match(codec, "^pcm_[suf](%d+)") + if b then + return tonumber(b) + end + if codec == "pcm_u8" then + return 8 + end + return nil +end + +export type Options = { + webm: boolean?, + title: string?, + app: string?, + clusterSeconds: number?, -- default 2 +} + +-- mux(streams, opts) -> buffer | nil, Err +function Mux.mux(streams: { any }, opts: Options): (buffer?, Err.Err?) + local webm = opts.webm == true + local app = opts.app or "formats-luau" + local clusterSpan = opts.clusterSeconds or 2 + -- tracks + local ids: { string } = {} + local videoIndex = 0 + for i, s in streams do + local cid = Mux.codecId(s.kind, s.codec) + if not cid then + return nil, Err.new(Err.UNSUPPORTED, "no Matroska CodecID for " .. s.kind .. " codec " .. s.codec) + end + ids[i] = cid + if s.kind == "video" and videoIndex == 0 then + videoIndex = i + end + end + local order = Source.interleave(streams) + local duration = 0 + for _, s in streams do + for _, p in s.packets do + local e = p.pts + (p.duration or 0) + if e > duration then + duration = e + end + end + end + + -- segment body: Info, Tracks, Clusters, Cues (the SeekHead goes in front once their offsets are known) + local body = Ebml.writer(65536) + local infoAt = body:tell() + local info = body:open(ID.Info) + body:uint(ID.TimecodeScale, 1000000) + body:string(ID.MuxingApp, app) + body:string(ID.WritingApp, app) + if opts.title then + body:string(ID.Title, opts.title) + end + body:float(ID.Duration, duration * 1000) + body:close(info) + + local tracksAt = body:tell() + local tracks = body:open(ID.Tracks) + for i, s in streams do + local te = body:open(ID.TrackEntry) + body:uint(ID.TrackNumber, i) + body:uint(ID.TrackUID, i) + body:uint(ID.TrackType, if s.kind == "video" then 1 else 2) + body:uint(ID.FlagLacing, 0) + body:string(ID.Language, "und") + body:string(ID.CodecID, ids[i]) + if s.config and buffer.len(s.config) > 0 then + body:binary(ID.CodecPrivate, s.config) + end + if s.kind == "video" then + if s.frameRate and s.frameRate > 0 then + body:uint(ID.DefaultDuration, math.floor(1e9 / s.frameRate + 0.5)) + end + local v = body:open(ID.Video) + body:uint(ID.PixelWidth, s.width or 0) + body:uint(ID.PixelHeight, s.height or 0) + body:close(v) + else + if s.codec == "opus" then + local pre = 0 + local c = s.config + if c and buffer.len(c) >= 12 then + pre = buffer.readu16(c, 10) + end + body:uint(ID.CodecDelay, math.floor(pre * 1e9 / 48000 + 0.5)) + body:uint(ID.SeekPreRoll, 80000000) + end + local a = body:open(ID.Audio) + body:float(ID.SamplingFrequency, s.sampleRate or 48000) + body:uint(ID.Channels, s.channels or 1) + local bits = pcmBits(s.codec) or s.bitsPerSample + if bits and string.sub(s.codec, 1, 4) == "pcm_" then + body:uint(ID.BitDepth, bits) + end + body:close(a) + end + body:close(te) + end + body:close(tracks) + + -- clusters + local cues: { { number } } = {} -- { time ms, track, cluster offset in body } + local cl: number? = nil + local clTime = 0 + local clStart = 0 + for _, item in order do + local si: number, p = item[1], item[2] + local ms = math.floor(p.pts * 1000 + 0.5) + local isVideoKey = si == videoIndex and p.keyframe + local need = cl == nil + or ms - clTime > 30000 + or ms < clTime + or (isVideoKey and ms - clStart >= clusterSpan * 1000) + or (videoIndex == 0 and ms - clStart >= clusterSpan * 1000) + if need then + if cl then + body:close(cl) + end + local at = body:tell() + cl = body:open(ID.Cluster) + clTime = ms + clStart = ms + body:uint(ID.Timecode, ms) + if videoIndex == 0 or isVideoKey then + table.insert(cues, { ms, if videoIndex > 0 then videoIndex else si, at }) + end + end + local data: buffer = p.data + local hdr = Ebml.vintString(si, 1) + local rel = ms - clTime + local size = #hdr + 3 + buffer.len(data) + body:header(ID.SimpleBlock, size) + body:raw(hdr) + body:raw(string.char(rel // 256, rel % 256, if p.keyframe or streams[si].kind ~= "video" then 0x80 else 0)) + body:rawBuffer(data) + end + if cl then + body:close(cl) + end + local cuesAt = body:tell() + if #cues > 0 then + local c = body:open(ID.Cues) + for _, q in cues do + local cp = body:open(ID.CuePoint) + body:uint(ID.CueTime, q[1]) + local tp = body:open(ID.CueTrackPositions) + body:uint(ID.CueTrack, q[2]) + body:uint(ID.CueClusterPosition, q[3]) -- patched below by the SeekHead length + body:close(tp) + body:close(cp) + end + body:close(c) + end + local bodyBuf = body:finish() + + -- the SeekHead: its own length shifts every position, so build it until its size is stable + local function seekHead(shift: number): buffer + local w = Ebml.writer(256) + local sh = w:open(ID.SeekHead) + local entries = { { ID.Info, infoAt }, { ID.Tracks, tracksAt } } + if #cues > 0 then + table.insert(entries, { ID.Cues, cuesAt }) + end + for _, e in entries do + local sk = w:open(0x4DBB) + local idv = e[1] + local bytes = {} + while idv > 0 do + table.insert(bytes, 1, idv % 256) + idv = idv // 256 + end + w:header(0x53AB, #bytes) + for _, b in bytes do + w:raw(string.char(b)) + end + w:uint(0x53AC, e[2] + shift) + w:close(sk) + end + w:close(sh) + return w:finish() + end + local shift = 0 + local head = seekHead(0) + for _ = 1, 4 do + local n = buffer.len(head) + if n == shift then + break + end + shift = n + head = seekHead(shift) + end + shift = buffer.len(head) + -- cue cluster positions (relative to the segment data) must include the SeekHead: rewrite the Cues element + -- (its uint widths may grow, but Cues are last, so nothing after them moves) + if #cues > 0 then + local w = Ebml.writer(4096) + local c = w:open(ID.Cues) + for _, q in cues do + local cp = w:open(ID.CuePoint) + w:uint(ID.CueTime, q[1]) + local tp = w:open(ID.CueTrackPositions) + w:uint(ID.CueTrack, q[2]) + w:uint(ID.CueClusterPosition, q[3] + shift) + w:close(tp) + w:close(cp) + end + w:close(c) + local cuesBuf = w:finish() + local nb = buffer.create(cuesAt + buffer.len(cuesBuf)) + buffer.copy(nb, 0, bodyBuf, 0, cuesAt) + buffer.copy(nb, cuesAt, cuesBuf) + bodyBuf = nb + end + + -- the file + local out = Ebml.writer(buffer.len(bodyBuf) + 256) + local eb = out:open(ID.EBML) + out:uint(0x4286, 1) + out:uint(0x42F7, 1) + out:uint(0x42F2, 4) + out:uint(0x42F3, 8) + out:string(ID.DocType, if webm then "webm" else "matroska") + out:uint(0x4287, 4) + out:uint(0x4285, 2) + out:close(eb) + local seg = out:open(ID.Segment) + out:rawBuffer(head) + out:rawBuffer(bodyBuf) + out:close(seg) + return out:finish(), nil +end + +return Mux diff --git a/src/Formats/video/mkv/Parse.luau b/src/Formats/video/mkv/Parse.luau new file mode 100644 index 0000000..4c8b0ce --- /dev/null +++ b/src/Formats/video/mkv/Parse.luau @@ -0,0 +1,658 @@ +--!strict +-- video/mkv/Parse: the Matroska / WebM demuxer: EBML header, Segment Info / Tracks / Cues / Tags / Chapters (titles +-- only), and every Cluster into a containers/Demux packet index: SimpleBlock and BlockGroup (BlockDuration, +-- ReferenceBlock -> not a keyframe), the three lacings (Xiph, EBML, fixed), header-stripping content compression, +-- clusters of unknown size (live streams). Times: every track's timescale is 1e9 / TimecodeScale (milliseconds by +-- default). Interpreted (it only walks headers); never throws. +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Ebml = require("@formats/containers/Ebml") +local Demux = require("@formats/containers/Demux") +local Video = require("@formats/codecs/Video") + +local 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, + ContentCompression = 0x5034, + ContentCompAlgo = 0x4254, + ContentCompSettings = 0x4255, + ContentEncryption = 0x5035, + Cluster = 0x1F43B675, + Timecode = 0xE7, + SimpleBlock = 0xA3, + BlockGroup = 0xA0, + Block = 0xA1, + BlockDuration = 0x9B, + ReferenceBlock = 0xFB, + DiscardPadding = 0x75A2, + Cues = 0x1C53BB6B, + CuePoint = 0xBB, + CueTime = 0xB3, + CueTrackPositions = 0xB7, + CueTrack = 0xF7, + CueClusterPosition = 0xF1, + CueRelativePosition = 0xF0, + Tags = 0x1254C367, + Tag = 0x7373, + SimpleTag = 0x67C8, + TagName = 0x45A3, + TagString = 0x4487, + Targets = 0x63C0, + Chapters = 0x1043A770, + Attachments = 0x1941A469, + Void = 0xEC, + Crc32 = 0xBF, +} +Parse.ID = ID + +-- the top-level children of a Segment (an unknown-size Cluster ends where one of these starts) +local TOP: { [number]: boolean } = { + [ID.SeekHead] = true, + [ID.Info] = true, + [ID.Tracks] = true, + [ID.Cluster] = true, + [ID.Cues] = true, + [ID.Tags] = true, + [ID.Chapters] = true, + [ID.Attachments] = true, + [ID.Segment] = true, + [ID.EBML] = true, +} + +-- Matroska audio / subtitle CodecIDs -> our codec ids (video ids come from the codecs/Video registry) +local AUDIO: { [string]: string } = { + A_VORBIS = "vorbis", + A_OPUS = "opus", + A_FLAC = "flac", + ["A_MPEG/L3"] = "mp3", + ["A_MPEG/L2"] = "mp2", + ["A_MPEG/L1"] = "mp1", + A_AAC = "aac", + ["A_AAC/MPEG4/LC"] = "aac", + ["A_AAC/MPEG4/LC/SBR"] = "aac", + ["A_AAC/MPEG2/LC"] = "aac", + A_AC3 = "ac3", + A_EAC3 = "eac3", + A_DTS = "dts", + A_ALAC = "alac", + A_TTA1 = "tta", + A_WAVPACK4 = "wavpack", + ["A_MS/ACM"] = "acm", +} +local SUBS: { [string]: string } = { + ["S_TEXT/UTF8"] = "text", + ["S_TEXT/ASCII"] = "text", + ["S_TEXT/WEBVTT"] = "webvtt", + ["S_TEXT/ASS"] = "ass", + ["S_TEXT/SSA"] = "ssa", + ["S_ASS"] = "ass", + ["S_SSA"] = "ssa", + ["S_VOBSUB"] = "dvdsub", + ["S_HDMV/PGS"] = "pgs", +} + +-- codecFor(CodecID, bitDepth) -> our codec id +local function codecFor(id: string, kind: string, bits: number?): string + if kind == "video" then + return Video.fromMatroska(id) or string.lower((string.gsub(id, "^V_", ""))) + end + if id == "A_PCM/INT/LIT" then + return if bits == 8 then "pcm_u8" else "pcm_s" .. (bits or 16) .. "le" + elseif id == "A_PCM/INT/BIG" then + return if bits == 8 then "pcm_u8" else "pcm_s" .. (bits or 16) .. "be" + elseif id == "A_PCM/FLOAT/IEEE" then + return "pcm_f" .. (bits or 32) .. "le" + end + return AUDIO[id] or SUBS[id] or string.lower((string.gsub(id, "^[AS]_", ""))) +end +Parse.codecFor = codecFor + +type TrackInfo = Types.Track & { strip: buffer?, lacing: boolean?, defaultDurationNs: number? } + +local function parseVideo(buf: buffer, off: number, len: number, t: any) + for id, o, n in Ebml.children(buf, off, off + len) do + if id == ID.PixelWidth then + t.width = Ebml.uint(buf, o, n) + elseif id == ID.PixelHeight then + t.height = Ebml.uint(buf, o, n) + elseif id == ID.DisplayWidth then + t.displayWidth = Ebml.uint(buf, o, n) + elseif id == ID.DisplayHeight then + t.displayHeight = Ebml.uint(buf, o, n) + elseif id == ID.ColourSpace then + t.colourSpace = buffer.readstring(buf, o, math.min(n, 4)) + end + end +end + +local function parseAudio(buf: buffer, off: number, len: number, t: any) + for id, o, n in Ebml.children(buf, off, off + len) do + if id == ID.SamplingFrequency then + t.sampleRate = Ebml.float(buf, o, n) + elseif id == ID.OutputSamplingFrequency then + t.outputSampleRate = Ebml.float(buf, o, n) + elseif id == ID.Channels then + t.channels = Ebml.uint(buf, o, n) + elseif id == ID.BitDepth then + t.bitsPerSample = Ebml.uint(buf, o, n) + end + end +end + +-- ContentEncodings: header stripping (algo 3) is supported; zlib / 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 + for id2, o2, n2 in Ebml.children(buf, o, o + n) do + if 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 + 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 + t.kind = if ttype == 1 then "video" elseif ttype == 2 then "audio" elseif ttype == 17 then "subtitle" else "data" + t.codecTag = codecId + t.codec = codecFor(codecId, t.kind, t.bitsPerSample) + if t.kind == "audio" then + t.sampleRate = t.sampleRate or 8000 + t.channels = t.channels or 1 + end + if t.defaultDurationNs and t.defaultDurationNs > 0 and t.kind == "video" then + t.frameRate = 1e9 / t.defaultDurationNs + end + if t.id > 0 then + table.insert(tracks, t) + if problem then + problems[t.id] = problem + end + end + end + end + return tracks, problems +end + +local function parseInfo(buf: buffer, off: number, len: number, meta: { [string]: any }): (number, number?) + local scale, duration = 1000000, nil + for id, o, n in Ebml.children(buf, off, off + len) do + if id == ID.TimecodeScale then + scale = Ebml.uint(buf, o, n) + elseif id == ID.Duration then + duration = Ebml.float(buf, o, n) + elseif id == ID.Title then + meta.title = Ebml.string(buf, o, n) + elseif id == ID.MuxingApp then + meta.muxingApp = Ebml.string(buf, o, n) + elseif id == ID.WritingApp then + meta.writingApp = Ebml.string(buf, o, n) + end + end + if scale <= 0 then + scale = 1000000 + end + return scale, duration +end + +local function parseCues(buf: buffer, off: number, len: number, segData: number): { { time: number, track: number, position: number } } + local cues = {} + for id, o, n in Ebml.children(buf, off, off + len) do + if id == ID.CuePoint then + local time = 0 + local positions = {} + for id2, o2, n2 in Ebml.children(buf, o, o + n) do + if id2 == ID.CueTime then + time = Ebml.uint(buf, o2, n2) + elseif id2 == ID.CueTrackPositions then + local tr, pos = 0, 0 + for id3, o3, n3 in Ebml.children(buf, o2, o2 + n2) do + if id3 == ID.CueTrack then + tr = Ebml.uint(buf, o3, n3) + elseif id3 == ID.CueClusterPosition then + pos = Ebml.uint(buf, o3, n3) + end + end + table.insert(positions, { tr, pos }) + end + end + for _, p in positions do + table.insert(cues, { time = time, track = p[1], position = segData + p[2] }) + end + end + end + return cues +end + +local function parseTags(buf: buffer, off: number, len: number, meta: { [string]: any }) + local tags = meta.tags or {} + meta.tags = tags + for id, o, n in Ebml.children(buf, off, off + len) do + if id == ID.Tag then + for id2, o2, n2 in Ebml.children(buf, o, o + n) do + if id2 == ID.SimpleTag then + local name, value = nil, nil + for id3, o3, n3 in Ebml.children(buf, o2, o2 + n2) do + if id3 == ID.TagName then + name = Ebml.string(buf, o3, n3) + elseif id3 == ID.TagString then + value = Ebml.string(buf, o3, n3) + end + end + if name and value and tags[string.lower(name)] == nil then + tags[string.lower(name)] = value + end + end + end + end + end +end + +type Ctx = { + buf: buffer, + dmx: any, + byNum: { [number]: TrackInfo }, + scaleNs: number, + err: string?, + maxPackets: number, +} + +-- one Block / SimpleBlock payload at [off, off + len): track, relative timecode, flags, lacing +local function block(ctx: Ctx, off: number, len: number, clusterTime: number, simple: boolean, keyHint: boolean?, durTicks: number?, discardNs: number?) + local buf = ctx.buf + local limit = off + len + local tn, tl = Ebml.vint(buf, off, limit) + if not tn or not tl or tn < 0 or off + tl + 3 > limit then + return + end + local p = off + tl + local rel = buffer.readu8(buf, p) * 256 + buffer.readu8(buf, p + 1) + if rel >= 32768 then + rel -= 65536 + end + local flags = buffer.readu8(buf, p + 2) + p += 3 + local t = ctx.byNum[tn] + if not t then + return + end + local key = if simple then bit32.band(flags, 0x80) ~= 0 else (keyHint ~= false) + if t.kind == "audio" or t.kind == "subtitle" then + key = true + end + local pts = clusterTime + rel + local lacing = bit32.band(bit32.rshift(flags, 1), 3) + local sizes: { number } = {} + if lacing == 0 then + sizes[1] = limit - p + else + if p >= limit then + return + end + local count = buffer.readu8(buf, p) + 1 + p += 1 + if lacing == 1 then -- Xiph + local total = 0 + for k = 1, count - 1 do + local s = 0 + while true do + if p >= limit then + return + end + local b = buffer.readu8(buf, p) + p += 1 + s += b + if b ~= 255 then + break + end + end + sizes[k] = s + total += s + end + sizes[count] = limit - p - total + elseif lacing == 3 then -- EBML + local s, l = Ebml.vint(buf, p, limit) + if not s or not l or s < 0 then + return + end + p += l + sizes[1] = s + local total = s + for k = 2, count - 1 do + local d, dl = Ebml.svint(buf, p, limit) + if not d or not dl then + return + end + p += dl + s += d + if s < 0 then + return + end + sizes[k] = s + total += s + end + sizes[count] = limit - p - total + else -- fixed + local each = (limit - p) // count + for k = 1, count do + sizes[k] = each + end + end + if sizes[count] < 0 then + return + end + end + -- frames after the first of a lace: the track's default duration + local stepTicks = 0 + if t.defaultDurationNs and t.defaultDurationNs > 0 then + stepTicks = t.defaultDurationNs / ctx.scaleNs + elseif durTicks and #sizes > 0 then + stepTicks = durTicks / #sizes + end + local dmx = ctx.dmx + for k, s in sizes do + if p + s > limit then + return + end + if dmx.n >= ctx.maxPackets then + ctx.err = "too many packets" + return + end + local d = if #sizes == 1 then durTicks else (if stepTicks > 0 then stepTicks else nil) + local strip = t.strip + if strip then + local nb = buffer.create(buffer.len(strip) + s) + buffer.copy(nb, 0, strip) + buffer.copy(nb, buffer.len(strip), buf, p, s) + dmx:addData(tn, pts + (k - 1) * stepTicks, nil, d, key and k == 1, nb) + else + dmx:add(tn, pts + (k - 1) * stepTicks, nil, d, key and (k == 1 or t.kind ~= "video"), p, s) + end + if discardNs and k == #sizes then + dmx:setExtra("discardPadding", discardNs / 1e9) + end + p += s + end +end + +-- a Cluster's children from off to limit (an unknown-size cluster: until a top-level ID); returns where it ended +local function cluster(ctx: Ctx, off: number, limit: number, unknown: boolean): number + local buf = ctx.buf + local pos = off + local time = 0 + while pos < limit and not ctx.err do + local id, size, data = Ebml.header(buf, pos, limit) + if not id or not size or not data then + return limit + end + if unknown and TOP[id] then + return pos + end + if size < 0 then + size = limit - data -- an unknown-size child: to the end + end + if data + size > limit then + size = limit - data + end + if id == ID.Timecode then + time = Ebml.uint(buf, data, size) + elseif id == ID.SimpleBlock then + block(ctx, data, size, time, true) + elseif id == ID.BlockGroup then + local bo, bl = -1, 0 + local ref, dur, discard = false, nil, nil + for id2, o2, n2 in Ebml.children(buf, data, data + size) do + if id2 == ID.Block then + bo, bl = o2, n2 + elseif id2 == ID.ReferenceBlock then + ref = true + elseif id2 == ID.BlockDuration then + dur = Ebml.uint(buf, o2, n2) + elseif id2 == ID.DiscardPadding then + discard = Ebml.int(buf, o2, n2) + end + end + if bo >= 0 then + block(ctx, bo, bl, time, false, not ref, dur, discard) + end + end + pos = data + size + end + return pos +end + +export type Options = { maxPackets: number? } + +-- parse(buf, base, limit, opts) -> a Demux | nil, Err +function Parse.parse(buf: buffer, base: number, limit: number, opts: Options?): (any, Err.Err?) + local id, size, data = Ebml.header(buf, base, limit) + if id ~= ID.EBML or not size or not data then + return nil, Err.new(Err.CORRUPT, "not an EBML file", base) + end + if size < 0 then + return nil, Err.new(Err.CORRUPT, "EBML header of unknown size", base) + end + local docType = "matroska" + for cid, o, n in Ebml.children(buf, data, math.min(limit, data + size)) do + if cid == ID.DocType then + docType = Ebml.string(buf, o, n) + end + end + if docType ~= "matroska" and docType ~= "webm" then + return nil, Err.new(Err.UNSUPPORTED, "EBML document type " .. docType) + end + local pos = data + size + -- the Segment (skip anything else at the top level) + local segData, segEnd = -1, limit + while pos < limit do + local sid, ssize, sdata = Ebml.header(buf, pos, limit) + if not sid or not ssize or not sdata then + break + end + if sid == ID.Segment then + segData = sdata + segEnd = if ssize < 0 or sdata + ssize > limit then limit else sdata + ssize + break + end + if ssize < 0 then + break + end + pos = sdata + ssize + end + if segData < 0 then + return nil, Err.new(Err.TRUNCATED, "no Segment") + end + local meta: { [string]: any } = { docType = docType } + local scaleNs, duration = 1000000, nil :: number? + local tracks: { TrackInfo } = {} + local problems: { [number]: string } = {} + local cuesAt: { number } = {} + local clusters: { { number } } = {} + -- first pass: the top-level elements (clusters are walked after Info / Tracks, which may come later via SeekHead) + pos = segData + while pos < segEnd do + local cid, csize, cdata = Ebml.header(buf, pos, segEnd) + if not cid or not csize or not cdata then + break + end + local unknown = csize < 0 + local cend = if unknown or cdata + csize > segEnd then segEnd else cdata + csize + if cid == ID.Info then + local d + scaleNs, d = parseInfo(buf, cdata, cend - cdata, meta) + duration = d + elseif cid == ID.Tracks then + tracks, problems = parseTracks(buf, cdata, cend - cdata, scaleNs) + elseif cid == ID.Cluster then + if unknown then + -- find its end: walk children until a top-level ID + local p = cdata + while p < segEnd do + local xid, xsize, xdata = Ebml.header(buf, p, segEnd) + if not xid or not xsize or not xdata or TOP[xid] then + break + end + if xsize < 0 then + p = segEnd + break + end + p = math.min(segEnd, xdata + xsize) + end + cend = p + end + table.insert(clusters, { cdata, cend }) + elseif cid == ID.Cues then + table.insert(cuesAt, cdata) + table.insert(cuesAt, cend - cdata) + elseif cid == ID.Tags then + parseTags(buf, cdata, cend - cdata, meta) + end + if cend <= pos then + break + end + pos = cend + end + if #tracks == 0 then + return nil, Err.new(Err.CORRUPT, "no tracks") + end + -- track timescales follow the final TimecodeScale (Info may follow Tracks) + local byNum: { [number]: TrackInfo } = {} + for _, t in tracks do + t.timescale = 1e9 / scaleNs + byNum[t.id] = t + end + local dmx = Demux.new(if docType == "webm" then "webm" else "mkv", tracks :: any, buf, meta) + local ctx: Ctx = { buf = buf, dmx = dmx, byNum = byNum, scaleNs = scaleNs, err = nil, maxPackets = opts and opts.maxPackets or 2 ^ 24 } + for _, c in clusters do + cluster(ctx, c[1], c[2], false) + if ctx.err then + return nil, Err.new(Err.LIMIT, ctx.err) + end + end + if duration then + dmx.duration = duration * scaleNs / 1e9 + end + local cues = {} + for k = 1, #cuesAt, 2 do + for _, c in parseCues(buf, cuesAt[k], cuesAt[k + 1], segData) do + c.time = c.time * scaleNs / 1e9 + table.insert(cues, c) + end + end + meta.cues = cues + meta.timecodeScale = scaleNs + for tid, msg in problems do + local t = byNum[tid] + t.unsupported = msg + end + dmx:finish() + return dmx, nil +end + +return Parse diff --git a/src/Formats/video/mkv/init.luau b/src/Formats/video/mkv/init.luau new file mode 100644 index 0000000..18cd8c8 --- /dev/null +++ b/src/Formats/video/mkv/init.luau @@ -0,0 +1,160 @@ +--!strict +-- video/mkv: Matroska and WebM (the Matroska specification / RFC 9559, the WebM container guidelines). New in +-- formats-luau, on containers/Ebml. +-- Read: open() demuxes the whole file into a packet index (SimpleBlock / BlockGroup, Xiph / EBML / fixed lacing, +-- header-stripping compression, unknown-size clusters, Cues and Tags in meta) and returns a VideoDecoder: video +-- through the codecs/Video registry (VP8 with inter frames, MJPEG, MPEG-1, raw; H.264 when registered), audio +-- through the api's opts.openAudio hook (Opus, Vorbis, FLAC, MP3, PCM, AAC, ... reach the audio formats), text +-- subtitle tracks as cues (Mkv.subtitles). Mkv.demux(r) gives the Demuxer alone. +-- Write: WebM (opts.format = "webm" or a .webm destination: VP8 / VP9 / AV1 video and Opus / Vorbis audio, copied +-- from the source since VP8 is decode-only) and Matroska (any registered video codec copied, else MJPEG encoded from +-- the frames; audio copied, else PCM s16), with SeekHead, Cues and Duration. +-- Not supported: zlib / bzip2 / lzo content compression and encryption (the track's packets are left as stored, +-- track.unsupported says why), chapters / attachments (skipped), writing subtitles. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Video = require("@formats/codecs/Video") +local Source = require("@formats/codecs/Video/Source") +local Parse = require("@formats/video/mkv/Parse") +local Mux = require("@formats/video/mkv/Mux") + +-- ------------------------------------------------------------------------------------------------ contract +local Mkv = { + name = "mkv", + category = "video", + extensions = { "mkv", "webm", "mka", "mk3d" }, + mime = { "video/x-matroska", "video/webm", "audio/x-matroska", "audio/webm" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Ebml", "containers/Demux", "codecs/Video", "codecs/Video/Source" }, + caps = { decode = true, encode = true, streaming = true, remux = true, video = { "vp8", "mjpeg", "mpeg1", "rawvideo" }, audio = true, subtitles = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type OpenOptions = { + rgba: boolean?, -- nextFrame returns rgba8 images (default false: yuv420p from the codec) + track: number?, -- the video track number to decode (default: the first video track) + audio: boolean?, -- false: do not open the audio track + maxPackets: number?, -- refuse files with more packets (default 2^24) + maxPixels: number?, + openAudio: any?, -- set by the api: (demuxer, track) -> audio Decoder +} +export type EncodeOptions = { + format: string?, -- "webm" writes WebM (DocType webm, WebM codecs only); else Matroska + webm: boolean?, -- the same as format = "webm" + quality: number?, -- MJPEG quality 1..100 when frames are encoded (default 90) + reencode: boolean?, -- encode the frames even when the video track could be copied (Matroska: MJPEG) + video: boolean?, -- false: no video stream + audio: boolean?, -- false: no audio; true: fail if the audio cannot be written (default: dropped) + title: string?, + clusterSeconds: number?, -- target cluster length (default 2) +} + +-- ------------------------------------------------------------------------------------------------ constants +local WEBM_VIDEO = { vp8 = true, vp9 = true, av1 = true } +local WEBM_AUDIO = { opus = true, vorbis = true } + +-- ------------------------------------------------------------------------------------------------ sniff +function Mkv.sniff(r: Bytes.Reader): number + if r:peek(4) ~= "\26\69\223\163" then + return 0 + end + local head = r:peek(math.min(64, r:remaining())) + if string.find(head, "webm", 1, true) or string.find(head, "matroska", 1, true) then + return 1 + end + return 0.5 +end + +-- ------------------------------------------------------------------------------------------------ encode +-- encode(video, opts?) -> buffer | nil, Err: a VideoDecoder (F.load / F.video.open of any video or animated image) +-- or a Demuxer +function Mkv.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local o: any = opts or {} + local webm = o.webm == true or (type(o.format) == "string" and string.lower(o.format) == "webm") + local want: Source.Want + if webm then + want = { video = { copy = WEBM_VIDEO }, audio = { copy = WEBM_AUDIO } } + else + local copy: { [string]: boolean } = {} + for id, e in Video.codecs do + if e.matroska then + copy[id] = true + end + end + want = { video = { copy = copy, encode = "mjpeg" }, audio = { copy = { ["*"] = true }, pcm = true } } + end + local so = table.clone(o) + so.quality = so.quality or 90 + local streams, err = Source.streams(value, so, want) + if not streams then + return nil, err + end + if not webm then + -- audio codecs Matroska cannot name: PCM instead + for i, s in streams do + if s.kind == "audio" and not Mux.codecId("audio", s.codec) then + local alt, aerr = Source.streams(value, { video = false, reencodeAudio = true }, { audio = { pcm = true } }) + if alt and alt[1] then + streams[i] = alt[1] + else + return nil, aerr + end + end + end + end + local ok, buf, merr = pcall(Mux.mux, streams, { webm = webm, title = o.title, clusterSeconds = o.clusterSeconds }) + if not ok then + return nil, Err.new(Err.ARG, "internal error: " .. tostring(buf)) + end + return buf, merr +end + +-- ------------------------------------------------------------------------------------------------ open +-- demux(r, opts?) -> the Demuxer (containers/Demux: tracks, packets, read, seek, count / get) | nil, Err +function Mkv.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) + local ok, dmx, err = pcall(Parse.parse, r.buf, r.base, r.limit, opts) + if not ok then + return nil, Err.new(Err.CORRUPT, "internal error: " .. tostring(dmx)) + end + return dmx, err +end + +-- open(r, opts?) -> a VideoDecoder (kind "video": nextFrame / seek / audio / demuxer) | nil, Err +function Mkv.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?) + local dmx, err = Mkv.demux(r, opts) + if not dmx then + return nil, err + end + return Video.open(dmx, opts) +end + +-- ------------------------------------------------------------------------------------------------ extras +-- subtitles(demuxer, trackId?) -> Types.Subtitles from a text subtitle track (S_TEXT/UTF8, WebVTT, ASS text) | nil +function Mkv.subtitles(dmx: any, trackId: number?): Types.Subtitles? + local track = nil + for _, t in dmx.tracks do + if t.kind == "subtitle" and (trackId == nil or t.id == trackId) then + track = t + break + end + end + if not track then + return nil + end + local subs = Types.Subtitles.new() + subs.meta.codec = track.codec + subs.meta.language = track.language + for k = 1, dmx:count(track.id) do + local p = dmx:get(track.id, k) + if p then + local start = p.pts / track.timescale + local stop = start + (p.duration or 0) / track.timescale + table.insert(subs.cues, { start = start, stop = stop, text = buffer.tostring(p.data) }) + end + end + return subs +end + +return Mkv