From 151cac4ed410a755c9550b888a92697edc03b9ec Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sun, 1 Nov 2026 01:54:41 -0500 Subject: [PATCH] video formats: comments are specs only --- src/Rosetta/video/avi/init.luau | 31 +++++++-------------- src/Rosetta/video/fli/init.luau | 20 +++++--------- src/Rosetta/video/flv/Amf.luau | 14 ++-------- src/Rosetta/video/flv/Mux.luau | 13 ++------- src/Rosetta/video/flv/init.luau | 42 ++++++++--------------------- src/Rosetta/video/h264/init.luau | 22 +++++---------- src/Rosetta/video/mkv/Mux.luau | 12 ++------- src/Rosetta/video/mkv/Parse.luau | 19 +++---------- src/Rosetta/video/mkv/init.luau | 43 ++++++++++-------------------- src/Rosetta/video/mp4/init.luau | 31 ++++++--------------- src/Rosetta/video/mpegps/init.luau | 16 +++-------- src/Rosetta/video/mpegts/init.luau | 20 ++++---------- src/Rosetta/video/ogv/init.luau | 34 +++++++---------------- src/Rosetta/video/smk/Audio.luau | 13 +++------ src/Rosetta/video/smk/init.luau | 27 +++++-------------- src/Rosetta/video/y4m/init.luau | 22 +++++---------- 16 files changed, 103 insertions(+), 276 deletions(-) diff --git a/src/Rosetta/video/avi/init.luau b/src/Rosetta/video/avi/init.luau index 60b37da..0196896 100644 --- a/src/Rosetta/video/avi/init.luau +++ b/src/Rosetta/video/avi/init.luau @@ -1,13 +1,7 @@ --!strict --- video/avi: AVI (Microsoft RIFF AVI 1.0, OpenDML 1.02). New in rosetta, on containers/Avi. --- Read: open() indexes every stream (OpenDML super / standard indexes, else idx1, else a movi scan; RIFF AVIX pieces --- of files over 1 GB) and returns a VideoDecoder: video through the codecs/video/Video registry by FourCC (MJPEG, MPEG-1, --- uncompressed BI_RGB 24 / 32-bit bottom-up or top-down, I420 / YV12; H.264 and others when a decoder is --- registered), audio through the api's opts.openAudio hook (PCM, A-law / mu-law, IMA / MS ADPCM with its WAVEFORMATEX, --- MP3 / MP2, AAC). Dropped frames (empty video chunks) keep their time slot. Avi.demux(r) gives the Demuxer. --- Write: MJPEG video (copied from an MJPEG source, else every frame encoded; variable frame delays such as a GIF's --- become a constant rate with repeated frames) plus PCM s16 audio, AVI 1.0 with idx1 and an odml / dmlh header. --- Not supported: writing files over 1 GB (no AVIX pieces), palette changes (##pc chunks are skipped), text streams. +-- video/avi: AVI (RIFF AVI 1.0, OpenDML 1.02: super / standard indexes, idx1, AVIX pieces). Reads video through the +-- codecs/video/Video registry by FourCC and audio through opts.openAudio; dropped frames keep their slot. Writes +-- MJPEG + PCM s16 (AVI 1.0, idx1, odml). Not supported: writing over 1 GB, palette changes (##pc), text streams. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -30,18 +24,18 @@ local AviFormat = { -- ------------------------------------------------------------------------------------------------ types export type OpenOptions = { - rgba: boolean?, -- nextFrame returns rgba8 (default false: the codec's native yuv420p; BI_RGB gives rgba8) - track: number?, -- the video track (stream index + 1) to decode - audio: boolean?, -- false: do not open the audio track + rgba: boolean?, -- default false: yuv420p; BI_RGB gives rgba8 + track: number?, -- stream index + 1 + audio: boolean?, maxPixels: number?, openAudio: any?, -- set by the api } export type EncodeOptions = { - quality: number?, -- MJPEG quality 1..100 (default 90) - reencode: boolean?, -- encode the frames even when the source is MJPEG - audio: boolean?, -- false: no audio (default: PCM s16 from the source's audio, when it has one) + quality: number?, -- 1..100, default 90 + reencode: boolean?, + audio: boolean?, -- default: PCM s16 from the source's audio video: boolean?, - maxFps: number?, -- the highest frame rate variable delays may need (default 100) + maxFps: number?, -- default 100 } -- ------------------------------------------------------------------------------------------------ constants @@ -170,7 +164,6 @@ local function audioTrack(s: Avi.Stream, id: number): Types.Track return t end --- demux(r, opts?) -> the Demuxer | nil, Err function AviFormat.demux(r: Bytes.Reader, _opts: OpenOptions?): (any, Err.Err?) local ok, file, err = pcall(Avi.read, r.buf, r.base, r.limit) if not ok then @@ -197,7 +190,6 @@ function AviFormat.demux(r: Bytes.Reader, _opts: OpenOptions?): (any, Err.Err?) end local meta = { info = file.info, index = file.index, odml = file.odml ~= nil } local dmx = Demux.new("avi", tracks, r.buf, meta) - -- packets in file order across streams: merge by offset local items: { { number } } = {} for k, st in streams do local s: Avi.Stream, t: any = st[1], st[2] @@ -227,7 +219,6 @@ function AviFormat.demux(r: Bytes.Reader, _opts: OpenOptions?): (any, Err.Err?) end -- ------------------------------------------------------------------------------------------------ encode --- encode(video, opts?) -> buffer | nil, Err function AviFormat.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) local o: any = table.clone(opts or {}) o.quality = o.quality or 90 @@ -278,7 +269,6 @@ function AviFormat.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) table.insert(wstreams, { type = "auds", handler = "\0\0\0\0", scale = align, rate = rate * align, sampleSize = align, strf = wf:finish(), ckid = "wb" }) end end - -- chunks in time order (the video packets already repeated to the constant rate) local chunks: { { any } } = {} for _, item in Source.interleave(streams) do table.insert(chunks, { item[1], item[2].data, true }) @@ -291,7 +281,6 @@ function AviFormat.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts?) -> a VideoDecoder | nil, Err function AviFormat.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?) local dmx, err = AviFormat.demux(r, opts) if not dmx then diff --git a/src/Rosetta/video/fli/init.luau b/src/Rosetta/video/fli/init.luau index ac01974..f34ed25 100644 --- a/src/Rosetta/video/fli/init.luau +++ b/src/Rosetta/video/fli/init.luau @@ -1,12 +1,7 @@ --!strict --- video/fli: Autodesk Animator FLI / Animator Pro FLC / FLX animations. New in rosetta, written from the FLIC --- file format description (Jim Kent, "FLC - Animator Pro Flic Files"; MultimediaWiki "FLIC"). --- Read: the 128-byte header (FLI 0xAF11: speed in 1/70 s; FLC 0xAF12 / DTA 0xAF44: speed in ms; depth 8, 15, 16, 24: --- an FLC that says 16 bits holds 5-5-5 pixels, as Animator Pro wrote them), prefix and other non-frame chunks skipped, --- every frame chunk (0xF1FA, and 0xF5FA) a packet of a Demuxer; open() returns a VideoDecoder whose frames are rgba8 --- (codecs/video/Legacy: palette chunks, BRUN, LC, SS2, BLACK, COPY, the deep-colour DTA chunks). The ring frame (the --- extra frame after `frames` that leads back to the first) is not shown. Fli.demux(r) gives the Demuxer. --- Not supported: writing, 1-bit FLICs, the X-COM / Magic Carpet game variants (audio chunks, 6-bit COLOR_256). +-- video/fli: Autodesk FLI / FLC / FLX animations, from Jim Kent's "FLC - Animator Pro Flic Files" (MultimediaWiki +-- "FLIC"): magics 0xAF11 (speed in 1/70 s), 0xAF12 / 0xAF44 (ms); frame chunks 0xF1FA / 0xF5FA, rgba8 through +-- codecs/video/Legacy; the ring frame is not shown. Not supported: writing, 1-bit FLICs, X-COM / Magic Carpet variants. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -27,9 +22,9 @@ local Fli = { -- ------------------------------------------------------------------------------------------------ types export type OpenOptions = { - rgba: boolean?, -- (frames are rgba8 already) + rgba: boolean?, -- frames are rgba8 already maxPixels: number?, -- default 2^26 - ringFrame: boolean?, -- true: also show the ring frame at the end (as ffmpeg does) + ringFrame: boolean?, -- also show the ring frame (as ffmpeg) } -- ------------------------------------------------------------------------------------------------ constants @@ -56,7 +51,6 @@ function Fli.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- demux(r, opts?) -> the Demuxer | nil, Err function Fli.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) local b, base, limit = r.buf, r.base, r.limit local n = limit - base @@ -108,7 +102,6 @@ function Fli.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) default = true, bitsPerPixel = depth, } - -- the frame chunks local offs, sizes = {}, {} local p = base + HEADER while p + 6 <= limit do @@ -119,7 +112,7 @@ function Fli.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) end if (cm == FRAME or cm == FRAME2) and size > 6 then if p + size > limit then - break -- a truncated last frame + break end table.insert(offs, p) table.insert(sizes, size) @@ -145,7 +138,6 @@ function Fli.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts?) -> a VideoDecoder | nil, Err function Fli.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?) local dmx, err = Fli.demux(r, opts) if not dmx then diff --git a/src/Rosetta/video/flv/Amf.luau b/src/Rosetta/video/flv/Amf.luau index 98fe321..4c30ece 100644 --- a/src/Rosetta/video/flv/Amf.luau +++ b/src/Rosetta/video/flv/Amf.luau @@ -1,11 +1,6 @@ --!strict --- video/flv/Amf: AMF0 values (Adobe's Action Message Format 0, as FLV script data tags use it). Written from the AMF0 --- specification and the FLV specification v10. Read: number, boolean, string, object, null, undefined, reference --- (the referenced object), ECMA array, strict array, date (milliseconds), long string; anything else stops the --- value. Write: numbers, booleans, strings, strict arrays and ECMA arrays (ordered key / value lists). Never throws. --- --- local name, value = Amf.script(reader) -- a script tag body: "onMetaData", { duration = 12.3, ... } --- Amf.writeValue(w, v); Amf.writeEcma(w, { { "duration", 12.3 }, ... }) +-- video/flv/Amf: AMF0 values (AMF0 spec, FLV spec v10 script tags). Read: number, boolean, string, object, null, +-- undefined, reference, ECMA / strict array, date (ms), long string. Write: numbers, booleans, strings, arrays. local Bytes = require("@rosetta/core/Bytes") local Amf = {} @@ -90,13 +85,11 @@ readValue = function(r: Bytes.Reader, depth: number, refs: { any }): any return nil end --- value(reader) -> the next AMF0 value | nil (unknown type, truncated, nested too deep) function Amf.value(r: Bytes.Reader): any local ok, v = pcall(readValue, r, 0, {}) return if ok and not r.err then v else nil end --- script(reader) -> name, value: a script data tag body (an AMF0 string, then its value) | nil function Amf.script(r: Bytes.Reader): (string?, any) local name = Amf.value(r) if type(name) ~= "string" then @@ -117,7 +110,6 @@ local function writeString(w: Bytes.Writer, s: string) w:string(s) end --- writeValue(w, v): a number, boolean, string, array (strict array) or Amf.NULL; other values are written as null function Amf.writeValue(w: Bytes.Writer, v: any) local t = type(v) if t == "number" then @@ -139,8 +131,6 @@ function Amf.writeValue(w: Bytes.Writer, v: any) end end --- writeEcma(w, list): an ECMA array of { key, value } pairs (values: as writeValue; a list nested as --- { key, { pairs = { ... } } } becomes an object) function Amf.writeEcma(w: Bytes.Writer, list: { { any } }, object: boolean?) if object then w:u8(3) diff --git a/src/Rosetta/video/flv/Mux.luau b/src/Rosetta/video/flv/Mux.luau index b3f7749..8e4da8a 100644 --- a/src/Rosetta/video/flv/Mux.luau +++ b/src/Rosetta/video/flv/Mux.luau @@ -1,10 +1,6 @@ --!strict --- video/flv/Mux: the FLV writer (Adobe's Video File Format Specification v10): the header, an onMetaData script tag --- (duration, width, height, data rates, frame rate, codec ids, audio format, encoder, file size), the H.264 --- AVCDecoderConfigurationRecord / AAC AudioSpecificConfig sequence headers, the packets of codecs/video/Video/Source --- streams as tags interleaved by decode time (milliseconds, shifted so none is negative; H.264 composition times), --- and H.264's end-of-sequence tag. AAC from ADTS sources (MPEG-TS) is split into raw frames with a configuration made --- from the first ADTS header. Interpreted; never throws (returns nil, Err). +-- video/flv/Mux: the FLV writer (FLV spec v10): header, onMetaData, AVC / AAC sequence headers, tags interleaved by +-- decode time (ms, shifted so none is negative), H.264 end of sequence; ADTS AAC split into raw frames. local Err = require("@rosetta/core/Err") local Bytes = require("@rosetta/core/Bytes") local Amf = require("@rosetta/video/flv/Amf") @@ -30,7 +26,6 @@ local function isAdts(s: any): boolean return s.config == nil and p ~= nil and buffer.len(p.data) >= 7 and buffer.readu8(p.data, 0) == 0xFF and buffer.readu8(p.data, 1) >= 0xF0 end --- audioProblem(stream) -> why FLV cannot hold this audio stream | nil function Mux.audioProblem(s: any): string? local fmt = AUDIO_FORMATS[s.codec] if not fmt then @@ -124,7 +119,6 @@ local function f64At(b: buffer, at: number, v: number) end end --- mux(streams) -> buffer | nil, Err function Mux.mux(streams: { any }): (buffer?, Err.Err?) local video, audio = nil :: any, nil :: any for _, s in streams do @@ -167,7 +161,6 @@ function Mux.mux(streams: { any }): (buffer?, Err.Err?) end end end - -- times: milliseconds, shifted so the earliest decode time is 0 when any is negative local shift = 0 local duration = 0 local vBytes, aBytes = 0, 0 @@ -211,7 +204,6 @@ function Mux.mux(streams: { any }): (buffer?, Err.Err?) w:u32be(11 + n) end - -- onMetaData local props: { { any } } = { { "duration", duration } } if video then table.insert(props, { "width", video.width or 0 }) @@ -238,7 +230,6 @@ function Mux.mux(streams: { any }): (buffer?, Err.Err?) tag(18, 0, {}, metaBody) local fileSizeAt = metaAt + buffer.len(metaBody) - 3 - 8 -- the last value (filesize) before the end marker - -- sequence headers local vid = if video then VIDEO_IDS[video.codec] else 0 if video and video.codec == "h264" then tag(9, 0, { 0x10 + vid, 0, 0, 0, 0 }, video.config) diff --git a/src/Rosetta/video/flv/init.luau b/src/Rosetta/video/flv/init.luau index fc4c95d..c42d473 100644 --- a/src/Rosetta/video/flv/init.luau +++ b/src/Rosetta/video/flv/init.luau @@ -1,20 +1,7 @@ --!strict --- video/flv: Flash Video (FLV, Adobe's Video File Format Specification v10, and the Enhanced RTMP / FLV extension's --- FourCC video tags). New in rosetta. --- Read: the header, the tag stream and onMetaData (AMF0: duration, width, height, framerate, codec ids, keyframes, ... --- into meta.metadata) into a Demuxer (times in milliseconds; keyframe flags from the video tags; seeking by --- keyframes) and open() returns a VideoDecoder: video through the codecs/video/Video registry (Sorenson Spark / FLV1 --- and H.264 decode; VP6 / VP6 alpha, screen video 1 / 2 and enhanced FourCC codecs (HEVC, AV1, VP9) are known tracks --- whose decoding is UNSUPPORTED); H.264's AVCDecoderConfigurationRecord in track.config, composition time offsets --- in the pts. Audio through the api's opts.openAudio hook: MP3 (also 8 kHz), AAC (AudioSpecificConfig in track.config), --- linear PCM (platform-endian read as little-endian), A-law / mu-law, Flash ADPCM (codecs/audio/Adpcm.swf, through --- containers/AudioWrap); Nellymoser and Speex are known tracks without an audio decoder (UNSUPPORTED). Flv.demux(r) gives the Demuxer. --- Write: H.264 / Sorenson Spark / VP6 / screen video copied from the source (FLV has no codec we encode), AAC / MP3 / --- PCM / A-law / mu-law / ADPCM / Nellymoser / Speex audio copied (AAC from ADTS sources re-framed), else PCM s16 at --- the FLV sample rates (5512 / 11025 / 22050 / 44100 Hz), with onMetaData (duration, sizes, frame rate, data --- rates, codec ids, file size). --- Not supported: encrypted tags (the track's packets are dropped, track.unsupported says so), multitrack and ModEx --- enhanced packets (skipped), writing H.264 from Annex B sources (no avcC). +-- video/flv: Flash Video (Adobe FLV spec v10, Enhanced RTMP FourCC tags). Reads the tags and onMetaData (AMF0) into a +-- Demuxer; decodes Sorenson Spark and H.264 (other codecs are UNSUPPORTED tracks), audio through opts.openAudio. +-- Writes copied packets, else PCM s16 at 5512..44100 Hz. Not supported: encrypted tags, multitrack / ModEx packets. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -41,17 +28,17 @@ local Flv = { -- ------------------------------------------------------------------------------------------------ types export type OpenOptions = { - rgba: boolean?, -- nextFrame returns rgba8 images (default false: yuv420p from the codec) - track: number?, -- the video track id (1 video, 2 audio) - audio: boolean?, -- false: do not open the audio track - maxPackets: number?, -- refuse files with more tags (default 2^24) + rgba: boolean?, -- default false: yuv420p + track: number?, -- 1 video, 2 audio + audio: boolean?, + maxPackets: number?, -- default 2^24 maxPixels: number?, openAudio: any?, -- set by the api: (demuxer, track) -> audio Decoder } export type EncodeOptions = { - video: boolean?, -- false: no video - audio: boolean?, -- false: no audio; true: fail when the audio cannot be written (default: dropped) - reencodeAudio: boolean?, -- PCM s16 even when the audio could be copied + video: boolean?, + audio: boolean?, -- true: fail when the audio cannot be written (default: dropped) + reencodeAudio: boolean?, } -- ------------------------------------------------------------------------------------------------ constants @@ -118,7 +105,6 @@ local function copy(b: buffer, p: number, n: number): buffer return c end --- the picture size of a codec's first keyframe (Sorenson, VP6, screen video) | nil local function frameSize(codec: string, b: buffer, p: number, n: number): (number?, number?) if codec == "flv1" then local h = H263.header(b, p, n, true) @@ -152,7 +138,6 @@ local function frameSize(codec: string, b: buffer, p: number, n: number): (numbe return nil, nil end --- demux(r, opts?) -> the Demuxer (containers/Demux) | nil, Err function Flv.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) local o: OpenOptions = opts or {} local b, base, limit = r.buf, r.base, r.limit @@ -169,7 +154,7 @@ function Flv.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) local tracks: { Types.Track } = {} local dmx = Demux.new("flv", tracks, b, meta) local vt: any, at: any = nil, nil - local keyOff, keyLen = -1, 0 -- the first video keyframe + local keyOff, keyLen = -1, 0 local maxPackets = o.maxPackets or 2 ^ 24 local count = 0 local p = base + dataOffset + 4 -- after PreviousTagSize0 @@ -316,7 +301,6 @@ function Flv.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) end p = d + size + 4 end - -- the track facts onMetaData and the codec headers give local md: { [string]: any } = meta.metadata or {} if type(md.duration) == "number" and md.duration > 0 then meta.duration = md.duration @@ -338,7 +322,6 @@ function Flv.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) if type(fr) == "number" and fr > 0 and fr < 1000 then vt.frameRate = fr else - -- from the timestamps: the frames over the time they span local n = dmx:count(vt.id) local t0 = if n > 0 then dmx:info(vt.id, 1) else nil local t1 = if n > 1 then dmx:info(vt.id, n) else nil @@ -355,7 +338,6 @@ function Flv.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) end -- ------------------------------------------------------------------------------------------------ encode --- encode(video, opts?) -> buffer | nil, Err: a VideoDecoder (F.load / F.video.open) or a Demuxer function Flv.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) local o: any = opts or {} local streams, err = Source.streams(value, o, { @@ -365,7 +347,6 @@ function Flv.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) if not streams then return nil, err end - -- audio FLV cannot hold (PCM at other rates): dropped, or an error with opts.audio = true for i = #streams, 1, -1 do local s = streams[i] local why = s.kind == "audio" and Mux.audioProblem(s) @@ -387,7 +368,6 @@ function Flv.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts?) -> a VideoDecoder (kind "video": nextFrame / seek / audio / demuxer) | nil, Err function Flv.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?) local ok, dmx, err = pcall(Flv.demux, r, opts) if not ok then diff --git a/src/Rosetta/video/h264/init.luau b/src/Rosetta/video/h264/init.luau index 30811c3..ee08e6b 100644 --- a/src/Rosetta/video/h264/init.luau +++ b/src/Rosetta/video/h264/init.luau @@ -1,12 +1,7 @@ --!strict --- video/h264: raw H.264 / AVC elementary streams (ITU-T H.264 Annex B byte stream: .h264 / .264 files, x264 / ffmpeg --- `-f h264` output, the JVT conformance bitstreams). New in rosetta. --- Read: the stream cut into access units (codecs/video/H264.accessUnits) as a one-track Demuxer; open() returns a --- VideoDecoder decoding through codecs/video/H264 (yuv420p frames in display order, numbered in output order since a raw --- stream has no timestamps; the frame rate comes from the SPS VUI timing, else opts.frameRate, else 25). --- Write: H.264 tracks copied from any video (MP4 / MKV samples are converted from length-prefixed NAL units to Annex B, --- the avcC parameter sets put in front of every keyframe). Not supported: re-encoding other codecs to H.264 (there is --- no H.264 encoder), and whatever codecs/video/H264 does not decode (interlaced, 4:2:2 / 4:4:4, > 8 bits: UNSUPPORTED). +-- video/h264: raw H.264 Annex B byte streams (.h264 / .264), cut into access units and decoded by codecs/video/H264 +-- (frame rate: the SPS VUI, else opts.frameRate, else 25). Writes H.264 tracks copied from any video (avcC to Annex B). +-- Not supported: encoding other codecs, what codecs/video/H264 does not decode (interlaced, 4:2:2 / 4:4:4, > 8 bits). -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -29,10 +24,10 @@ local Format = { -- ------------------------------------------------------------------------------------------------ types export type OpenOptions = { - rgba: boolean?, -- nextFrame returns rgba8 (default false: yuv420p) - maxPixels: number?, -- largest picture (default 2^22 luma samples) - frameRate: number?, -- frames per second when the stream has no VUI timing (default 25) - deblock: boolean?, -- false skips the deblocking filter (faster, not conformant) + rgba: boolean?, -- default false: yuv420p + maxPixels: number?, -- default 2^22 luma samples + frameRate: number?, -- default 25 + deblock: boolean?, -- false: faster, not conformant } -- ------------------------------------------------------------------------------------------------ sniff @@ -65,7 +60,6 @@ function Format.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- demux(r, opts?) -> the Demuxer (one video track, one packet per access unit) | nil, Err function Format.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) local buf, base, limit = r.buf, r.base, r.limit local units = H264.accessUnits(buf, base, limit - base) @@ -106,7 +100,6 @@ function Format.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) end -- ------------------------------------------------------------------------------------------------ encode --- encode(video, opts?) -> an Annex B buffer of the source's H.264 track | nil, Err (UNSUPPORTED for other codecs) function Format.encode(value: any, _opts: any?): (buffer?, Err.Err?) local streams, err = Source.streams(value, { audio = false }, { video = { copy = { h264 = true } } }) if not streams then @@ -133,7 +126,6 @@ function Format.encode(value: any, _opts: any?): (buffer?, Err.Err?) end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts?) -> a VideoDecoder | nil, Err function Format.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?) local dmx, err = Format.demux(r, opts) if not dmx then diff --git a/src/Rosetta/video/mkv/Mux.luau b/src/Rosetta/video/mkv/Mux.luau index 5c7408b..5e367f2 100644 --- a/src/Rosetta/video/mkv/Mux.luau +++ b/src/Rosetta/video/mkv/Mux.luau @@ -1,9 +1,6 @@ --!strict --- video/mkv/Mux: the Matroska / WebM muxer: EBML header, Segment with SeekHead, Info (1 ms TimecodeScale, Duration), --- Tracks (CodecPrivate, DefaultDuration, Video / Audio settings, Opus CodecDelay / SeekPreRoll), Clusters of --- SimpleBlocks (a new cluster at a video keyframe once the current one spans 2 s, and before the 16-bit relative --- timestamp would overflow), and Cues (one CuePoint per cluster, on the video track when there is one). Streams come --- from codecs/video/Video/Source (copied packets or encoded frames). Interpreted; never throws. +-- video/mkv/Mux: the Matroska / WebM muxer: EBML header, Segment (SeekHead, Info with a 1 ms TimecodeScale, Tracks, +-- Clusters of SimpleBlocks cut at keyframes after 2 s or before the 16-bit timestamp overflows, a CuePoint each). local Err = require("@rosetta/core/Err") local Ebml = require("@rosetta/containers/Ebml") local Video = require("@rosetta/codecs/video/Video") @@ -36,7 +33,6 @@ local AUDIO_IDS: { [string]: string } = { } 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) @@ -64,12 +60,10 @@ export type Options = { clusterSeconds: number?, -- default 2 } --- mux(streams, opts) -> buffer | nil, Err function Mux.mux(streams: { any }, opts: Options): (buffer?, Err.Err?) local webm = opts.webm == true local app = opts.app or "rosetta" local clusterSpan = opts.clusterSeconds or 2 - -- tracks local ids: { string } = {} local videoIndex = 0 for i, s in streams do @@ -150,7 +144,6 @@ function Mux.mux(streams: { any }, opts: Options): (buffer?, Err.Err?) end body:close(tracks) - -- clusters local cues: { { number } } = {} -- { time ms, track, cluster offset in body } local cl: number? = nil local clTime = 0 @@ -264,7 +257,6 @@ function Mux.mux(streams: { any }, opts: Options): (buffer?, Err.Err?) bodyBuf = nb end - -- the file local out = Ebml.writer(buffer.len(bodyBuf) + 256) local eb = out:open(ID.EBML) out:uint(0x4286, 1) diff --git a/src/Rosetta/video/mkv/Parse.luau b/src/Rosetta/video/mkv/Parse.luau index 1a64348..ecc0964 100644 --- a/src/Rosetta/video/mkv/Parse.luau +++ b/src/Rosetta/video/mkv/Parse.luau @@ -1,9 +1,6 @@ --!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. +-- video/mkv/Parse: the Matroska / WebM demuxer: EBML header, Info / Tracks / Cues / Tags / chapter titles, Clusters +-- (SimpleBlock, BlockGroup, Xiph / EBML / fixed lacing, unknown sizes); timescale 1e9 / TimecodeScale. local Err = require("@rosetta/core/Err") local Types = require("@rosetta/Types") local Ebml = require("@rosetta/containers/Ebml") @@ -138,7 +135,6 @@ local SUBS: { [string]: string } = { ["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_", ""))) @@ -219,8 +215,7 @@ local function parseAudio(buf: buffer, off: number, len: number, t: any) end end --- ContentEncodings: header stripping (algo 3) and zlib (algo 0) are supported; bzip / lzo compression and encryption --- are not +-- ContentEncodings: header stripping (algo 3) and zlib (algo 0); not bzip / lzo or encryption 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 @@ -418,7 +413,7 @@ type Ctx = { maxPackets: number, } --- one Block / SimpleBlock payload at [off, off + len): track, relative timecode, flags, lacing +-- Block / SimpleBlock: 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 @@ -543,7 +538,6 @@ local function block(ctx: Ctx, off: number, len: number, clusterTime: number, si 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 @@ -591,9 +585,6 @@ end export type Options = { maxPackets: number? } --- parse(buf, base, limit, opts) -> a Demux | nil, Err --- docType(buf, base, limit) -> the EBML header's DocType ("matroska" when it has none), the header's size and data --- offset | nil, Err function Parse.docType(buf: buffer, base: number, limit: number): (string?, any, number?) local id, size, data = Ebml.header(buf, base, limit) if id ~= ID.EBML or not size or not data then @@ -620,7 +611,6 @@ function Parse.parse(buf: buffer, base: number, limit: number, opts: Options?): 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) @@ -663,7 +653,6 @@ function Parse.parse(buf: buffer, base: number, limit: number, opts: Options?): 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) diff --git a/src/Rosetta/video/mkv/init.luau b/src/Rosetta/video/mkv/init.luau index db5e356..430f9af 100644 --- a/src/Rosetta/video/mkv/init.luau +++ b/src/Rosetta/video/mkv/init.luau @@ -1,16 +1,7 @@ --!strict --- video/mkv: Matroska and WebM (the Matroska specification / RFC 9559, the WebM container guidelines). New in --- rosetta, on containers/Ebml. --- Read: open() demuxes the whole file into a packet index (SimpleBlock / BlockGroup, Xiph / EBML / fixed lacing, --- header-stripping and zlib compression, unknown-size clusters, Cues and Tags in meta) and returns a VideoDecoder: video --- through the codecs/video/Video registry (VP8 with inter frames, MJPEG, MPEG-1, raw; H.264 when registered), audio --- through the api's opts.openAudio hook (Opus, Vorbis, FLAC, MP3, PCM, AAC, ... reach the audio formats), text --- subtitle tracks as cues (Mkv.subtitles). Mkv.demux(r) gives the Demuxer alone. --- Write: WebM (opts.format = "webm" or a .webm destination: VP8 / VP9 / AV1 video and Opus / Vorbis audio, copied --- from the source since VP8 is decode-only) and Matroska (any registered video codec copied, else MJPEG encoded from --- the frames; audio copied, else PCM s16), with SeekHead, Cues and Duration. --- Not supported: bzip2 / lzo content compression and encryption (the track's packets are left as stored, --- track.unsupported says why), chapters / attachments (skipped), writing subtitles. +-- video/mkv: Matroska / WebM (RFC 9559, the WebM guidelines), on containers/Ebml. Reads every packet (all lacings, +-- header stripping and zlib, unknown-size clusters, Cues, Tags) into a Demuxer, text subtitle tracks as cues. Writes +-- WebM or Matroska (copied, else MJPEG + PCM s16). Not supported: bzip2 / lzo, encryption, chapters, attachments. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -33,22 +24,22 @@ local Mkv = { -- ------------------------------------------------------------------------------------------------ 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) + rgba: boolean?, -- default false: yuv420p + track: number?, -- default: the first video track + audio: boolean?, + maxPackets: number?, -- 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) + format: string?, -- "webm": DocType webm, WebM codecs only; else Matroska + webm: boolean?, -- as format = "webm" + quality: number?, -- 1..100, default 90 + reencode: boolean?, + video: boolean?, + audio: boolean?, -- true: fail if the audio cannot be written (default: dropped) title: string?, - clusterSeconds: number?, -- target cluster length (default 2) + clusterSeconds: number?, -- seconds, default 2 } -- ------------------------------------------------------------------------------------------------ constants @@ -67,7 +58,6 @@ function Mkv.sniff(r: Bytes.Reader): number return 0.5 end --- variant(r) -> "webm" for a WebM file (DocType webm), else nil: the name F.detect reports (never throws) function Mkv.variant(r: Bytes.Reader): string? local ok, docType = pcall(Parse.docType, r.buf, r.pos, r.limit) if ok and docType == "webm" then @@ -77,8 +67,6 @@ function Mkv.variant(r: Bytes.Reader): string? 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") @@ -121,7 +109,6 @@ function Mkv.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) 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 @@ -130,7 +117,6 @@ function Mkv.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) 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 @@ -140,7 +126,6 @@ function Mkv.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Er 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 diff --git a/src/Rosetta/video/mp4/init.luau b/src/Rosetta/video/mp4/init.luau index 1d76faa..4358c59 100644 --- a/src/Rosetta/video/mp4/init.luau +++ b/src/Rosetta/video/mp4/init.luau @@ -1,18 +1,7 @@ --!strict --- video/mp4: MP4 / M4V / QuickTime MOV / 3GP (ISO/IEC 14496-12 / 14496-14, the QuickTime file format), on --- containers/IsoBmff (ws-m4a's box parser, sample tables, fragments and muxer). New in rosetta. --- Read: every track's samples into a Demuxer (pts = dts + composition offset, moved by the edit list: the first --- edit's media time is subtracted (B-frame delay, AAC priming), an initial empty edit added; sync samples as --- keyframes; fragmented files too) and open() returns a VideoDecoder: video through the codecs/video/Video registry (MJPEG --- 'jpeg' / 'mjpa' / mp4v 0x6C, MPEG-1, raw; H.264 'avc1' with its avcC when a decoder is registered), audio through --- the api's opts.openAudio hook (AAC, ALAC (audio/m4a), MP3, Opus (dOps -> OpusHead), FLAC, PCM 'sowt' / 'twos' / --- 'lpcm' / 'ipcm'). --- Write: MP4 (or MOV with opts.format = "mov" / a .mov destination): H.264 / HEVC / AV1 / MJPEG / MPEG-4 video copied --- from an ISO / Matroska source (their configurations are the same boxes), else MJPEG encoded from the frames (mp4v --- object type 0x6C in MP4, 'jpeg' in MOV); AAC / ALAC / Opus / FLAC / MP3 audio copied, else PCM s16 ('sowt', MOV --- only; MP4 drops other audio unless opts.audio = true, which fails). --- Edit lists are written for a B-frame delay and an audio codec delay (AAC priming). Not supported: fragmented --- writing, timed text tracks, encrypted tracks. +-- video/mp4: MP4 / M4V / MOV / 3GP (ISO/IEC 14496-12 / 14496-14, QuickTime), on containers/IsoBmff. Reads every +-- track into a Demuxer (pts = dts + composition offset, moved by the edit list; fragments too). Writes MP4 or MOV: +-- video copied, else MJPEG; audio copied, else PCM s16 (MOV). Not supported: fragmented writing, timed text, DRM. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -36,18 +25,18 @@ local Mp4 = { -- ------------------------------------------------------------------------------------------------ types export type OpenOptions = { rgba: boolean?, - track: number?, -- the video track id (default: the first video track) + track: number?, -- default: the first video track audio: boolean?, maxPixels: number?, maxSamples: number?, openAudio: any?, -- set by the api } export type EncodeOptions = { - format: string?, -- "mov" writes QuickTime (brand 'qt '); else MP4 (brand 'isom') - quality: number?, -- MJPEG quality when frames are encoded (default 90) - reencode: boolean?, -- encode the frames to MJPEG even when the video could be copied + format: string?, -- "mov": QuickTime (brand 'qt '); else MP4 (brand 'isom') + quality: number?, -- default 90 + reencode: boolean?, video: boolean?, - audio: boolean?, -- false: no audio; true: fail when the audio cannot be written + audio: boolean?, -- true: fail when the audio cannot be written } -- ------------------------------------------------------------------------------------------------ constants @@ -106,7 +95,6 @@ local function pcmCodec(t: any): string return "pcm_s" .. bits .. (if p == nil or p.little then "le" else "be") end --- demux(r, opts?) -> the Demuxer | nil, Err function Mp4.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) local ok, movie, err = pcall(IsoBmff.parse, r, opts and opts.maxSamples and { maxSamples = opts.maxSamples } or nil) if not ok then @@ -164,7 +152,6 @@ function Mp4.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) table.insert(src, it) end local dmx = Demux.new(if movie.brand == "qt " then "mov" else "mp4", tracks, r.buf, { brand = movie.brand }) - -- samples in file order across tracks local items: { { number } } = {} for k, it in src do -- the edit list moves presentation times: minus the first edit's media time (video: the B-frame delay; audio @@ -215,7 +202,6 @@ local function dOps(head: buffer?): buffer? return w:finish() end --- encode(video, opts?) -> buffer | nil, Err function Mp4.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) local o: any = table.clone(opts or {}) o.quality = o.quality or 90 @@ -329,7 +315,6 @@ function Mp4.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts?) -> a VideoDecoder | nil, Err function Mp4.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?) local dmx, err = Mp4.demux(r, opts) if not dmx then diff --git a/src/Rosetta/video/mpegps/init.luau b/src/Rosetta/video/mpegps/init.luau index 9cca184..f722a41 100644 --- a/src/Rosetta/video/mpegps/init.luau +++ b/src/Rosetta/video/mpegps/init.luau @@ -1,12 +1,7 @@ --!strict --- video/mpegps: MPEG program streams (ISO/IEC 11172-1 system streams and 13818-1 program streams: .mpg / .mpeg / --- .vob / VCD .dat). New in rosetta, on containers/MpegPs. Video PES payloads are joined into the elementary --- stream and cut into pictures (containers/MpegEs: one packet per picture with its sequence / GOP headers, both --- fields of a field-coded frame in one); a picture takes the PTS of the PES it starts in, pictures without one get --- theirs from the GOP's temporal references. Audio packets are the PES payloads (MP1 / MP2 / MP3 frames, AC-3, LPCM). --- open() returns a VideoDecoder: MPEG-1 / MPEG-2 video through the codecs/video/Video registry (MPEG-2 told by its --- sequence extension), audio through the api's opts.openAudio hook. --- Timescale 90 kHz. Not supported: writing, H.264 in PS (packets are whole PES payloads), DVD navigation packets. +-- video/mpegps: MPEG program streams (ISO/IEC 11172-1, 13818-1: .mpg / .vob / VCD .dat), on containers/MpegPs and +-- containers/MpegEs: a packet per picture (the PTS of the PES it starts in, else from the GOP's temporal references), +-- audio packets = PES payloads; 90 kHz. Not supported: writing, H.264 in PS, DVD navigation packets. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -30,7 +25,7 @@ local Ps = { -- ------------------------------------------------------------------------------------------------ types export type OpenOptions = { rgba: boolean?, - track: number?, -- the video stream id to decode (0xE0.. ; default: the first video stream) + track: number?, -- 0xE0..; default: the first video stream audio: boolean?, maxPixels: number?, openAudio: any?, -- set by the api @@ -48,7 +43,6 @@ function Ps.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- the pictures of a video stream as packets: join the PES payloads, cut at pictures, place the timestamps local function videoPackets(dmx: any, buf: buffer, s: MpegPs.Stream, t: any) local total = 0 for _, p in s.pes do @@ -119,7 +113,6 @@ local function videoPackets(dmx: any, buf: buffer, s: MpegPs.Stream, t: any) end end --- demux(r, opts?) -> the Demuxer | nil, Err function Ps.demux(r: Bytes.Reader, _opts: OpenOptions?): (any, Err.Err?) if r:peek(4) == "\0\0\1\179" then -- an MPEG-1 / 2 video elementary stream (.m1v): one video stream, no timestamps @@ -181,7 +174,6 @@ function Ps.demux(r: Bytes.Reader, _opts: OpenOptions?): (any, Err.Err?) end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts?) -> a VideoDecoder | nil, Err function Ps.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?) local dmx, err = Ps.demux(r, opts) if not dmx then diff --git a/src/Rosetta/video/mpegts/init.luau b/src/Rosetta/video/mpegts/init.luau index 07c703b..cabffea 100644 --- a/src/Rosetta/video/mpegts/init.luau +++ b/src/Rosetta/video/mpegts/init.luau @@ -1,13 +1,7 @@ --!strict --- video/mpegts: MPEG transport streams (ISO/IEC 13818-1: .ts / .m2ts segments, HLS). The demuxer is containers/MpegTs, --- absorbed from mpegts-luau (resync, PAT / PMT with CRC, continuity checks, PES reassembly, 33-bit PTS / DTS --- unwrapped); this format turns its units into a Demuxer (timescale 90 kHz; one PES = one packet: a picture as --- muxed by ffmpeg, one or more audio frames) and returns a VideoDecoder: MPEG-1 / MPEG-2 video through the --- codecs/video/Video registry (stream types 0x01 / 0x02, and private ones such as 0x80 with a video PES stream id, --- told apart by an MPEG-2 sequence extension), H.264 when registered, audio (MP1 / MP2 / --- MP3, AAC in ADTS) through the api's opts.openAudio hook. Keyframes: MPEG-1 / 2 I-pictures, H.264 IDR access units. --- M2TS (192-byte packets with a 4-byte timestamp prefix) is read too. Not supported: writing, scrambled streams, --- PES without PTS for video before the first one (dropped). +-- video/mpegts: MPEG transport streams (ISO/IEC 13818-1: .ts, .m2ts, HLS) over containers/MpegTs (from mpegts-luau); +-- one PES = one packet, 90 kHz; MPEG-1 / 2 (types 0x01 / 0x02, private ones told by an MPEG-2 sequence extension), +-- H.264, MP1-3 / ADTS AAC. Not supported: writing, scrambled streams, video PES before the first PTS (dropped). -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -31,7 +25,7 @@ local Ts = { -- ------------------------------------------------------------------------------------------------ types export type OpenOptions = { rgba: boolean?, - track: number?, -- the video PID to decode (default: the first video stream of the PMT) + track: number?, -- default: the first video stream of the PMT audio: boolean?, maxPixels: number?, openAudio: any?, -- set by the api @@ -52,8 +46,7 @@ local CODEC: { [string]: string } = { } -- ------------------------------------------------------------------------------------------------ sniff --- packetSize(r) -> 188 | 192 (M2TS) | 0, and the offset of the first sync byte: three sync bytes a packet apart --- (fewer in a short file) within the first 2 KB +-- 188 or 192 (M2TS): three sync bytes a packet apart (fewer in a short file) within the first 2 KB local function packetSize(r: Bytes.Reader): (number, number) local n = r:remaining() for start = 0, math.min(n, 2048) - 1 do @@ -112,7 +105,6 @@ local function mpegAudioCodec(u: any): string return "mp2" end --- demux(r, opts?) -> the Demuxer | nil, Err function Ts.demux(r: Bytes.Reader, _opts: OpenOptions?): (any, Err.Err?) local size, off = packetSize(r) if size == 0 then @@ -164,7 +156,6 @@ function Ts.demux(r: Bytes.Reader, _opts: OpenOptions?): (any, Err.Err?) for _, u in units do track(u.pid, u.kind, u.codec, u.streamType, nil) end - -- codec details from the first unit local seen: { [number]: boolean } = {} for _, u in units do local t = byPid[u.pid] @@ -234,7 +225,6 @@ function Ts.demux(r: Bytes.Reader, _opts: OpenOptions?): (any, Err.Err?) end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts?) -> a VideoDecoder | nil, Err function Ts.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?) local dmx, err = Ts.demux(r, opts) if not dmx then diff --git a/src/Rosetta/video/ogv/init.luau b/src/Rosetta/video/ogv/init.luau index 8a12660..6e5dbab 100644 --- a/src/Rosetta/video/ogv/init.luau +++ b/src/Rosetta/video/ogv/init.luau @@ -1,15 +1,7 @@ --!strict --- video/ogv: Ogg video (.ogv, or .ogg with a Theora stream: the Ogg Theora mapping of the Theora I specification, --- RFC 3533 / 5334). New in rosetta, on containers/Ogg and containers/Demux. --- Read: open() demuxes every logical stream of the first Ogg group into a packet index: Theora video (frame times from --- the granule positions: keyframe number << shift | frames since it; the three headers become track.config, --- Xiph-laced as in Matroska, so codecs/video/Theora decodes it through the codecs/video/Video registry), Vorbis / --- Opus / FLAC audio (headers in track.config, times from the granules) reaching the audio formats through the api's --- opts.openAudio hook; the Theora comment header's tags go to meta.tags. Ogv.demux(r) gives the Demuxer alone. --- Write: remux (encode): a Theora video track copied from the source (ogv / mkv), plus its Vorbis / Opus audio copied --- (the audio pages come from containers/AudioWrap and are interleaved by time). --- Not supported: chained Ogg files (only the first group of streams), Skeleton / Kate / Speex streams (skipped), --- encoding Theora (there is no encoder: other sources cannot be written). +-- video/ogv: Ogg Theora video (Theora I spec, RFC 3533 / 5334), on containers/Ogg: Theora (granule = keyframe << shift +-- | frames since; the headers Xiph-laced into track.config) and Vorbis / Opus / FLAC streams of the first group. Writes +-- copied Theora + audio. Not supported: chained files, Skeleton / Kate / Speex streams, encoding Theora. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -34,23 +26,22 @@ local Ogv = { -- ------------------------------------------------------------------------------------------------ types export type OpenOptions = { - rgba: boolean?, -- nextFrame returns rgba8 images (default false: yuv420p from the codec) - track: number?, -- the video track id to decode (default: the first video track) - audio: boolean?, -- false: do not open the audio track + rgba: boolean?, -- default false: yuv420p + track: number?, -- default: the first video track + audio: boolean?, maxPixels: number?, - verify: boolean?, -- false: skip the page CRC checks (default true) + verify: boolean?, -- default true openAudio: any?, -- set by the api: (demuxer, track) -> audio Decoder } export type EncodeOptions = { - audio: boolean?, -- false: no audio; true: fail when the audio cannot be copied (default: dropped) + audio: boolean?, -- true: fail when the audio cannot be copied (default: dropped) } -- ------------------------------------------------------------------------------------------------ constants local AUDIO = { vorbis = true, opus = true, flac = true } -- ------------------------------------------------------------------------------------------------ sniff --- 1 when one of the beginning-of-stream pages at the start of an Ogg file is a Theora identification header (plain --- Ogg Vorbis / Opus / FLAC files are left to the audio formats) +-- a Theora identification header in a bos page (plain Ogg audio is left to the audio formats) function Ogv.sniff(r: Bytes.Reader): number if r:peek(4) ~= "OggS" then return 0 @@ -78,7 +69,6 @@ function Ogv.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ encode --- the pages of an Ogg buffer: { offset, size, serial, granule, bos } local function pages(b: buffer): { { number } } local out = {} local pos = 0 @@ -93,7 +83,6 @@ local function pages(b: buffer): { { number } } return out end --- encode(video, opts?) -> an Ogg file | nil, Err: a VideoDecoder or Demuxer whose video track is Theora (ogv, mkv) function Ogv.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) local o: any = opts or {} local streams, err = Source.streams(value, o, { video = { copy = { theora = true } }, audio = { copy = { vorbis = true, opus = true } } }) @@ -137,7 +126,6 @@ function Ogv.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) s:packet(p.data, key * scale + (frame + bias - key), { eos = i == #v.packets }) end local video = mux:finish() - -- audio pages: the audio track as its own Ogg stream (containers/AudioWrap), interleaved by time local audio: buffer? = nil local arate, askip = 1, 0 if as and o.audio ~= false then @@ -232,7 +220,6 @@ end type Pending = { track: number, pts: number, key: boolean, page: number, data: buffer, off: number, len: number, own: boolean } --- demux(r, opts?) -> the Demuxer (containers/Demux) | nil, Err function Ogv.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) local ogg, err = Ogg.open(r, { verify = not (opts and opts.verify == false) }) if not ogg then @@ -301,7 +288,7 @@ function Ogv.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) break end if p.size > 0 and buffer.readu8(p.data, p.offset) >= 0x80 then - continue -- a stray header + continue end table.insert(packets, p) if base == nil and p.granule >= 0 then @@ -392,7 +379,6 @@ function Ogv.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) return dmx, nil end --- open(r, opts?) -> a VideoDecoder (kind "video": nextFrame / seek / audio / demuxer) | nil, Err function Ogv.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?) local ok, dmx, err = pcall(Ogv.demux, r, opts) if not ok then diff --git a/src/Rosetta/video/smk/Audio.luau b/src/Rosetta/video/smk/Audio.luau index bde9edd..615a74a 100644 --- a/src/Rosetta/video/smk/Audio.luau +++ b/src/Rosetta/video/smk/Audio.luau @@ -1,20 +1,15 @@ --!strict --!native --!optimize 2 --- video/smk/Audio: Smacker's packed audio (SMKA: DPCM with Huffman-coded deltas), the one audio codec only Smacker --- files carry. Written from the format description (MultimediaWiki "Smacker"). A packet: the unpacked size (u32), --- then LSB-first bits: data flag, stereo, 16-bit, one 8-bit Huffman tree per channel and byte (codecs/video/Legacy/ --- Smacker trees: 1, 2 or 4), the first sample(s) raw (16-bit ones byte-swapped, the right channel first), then per --- sample a delta added with wraparound (the low byte's tree, and the high byte's for 16 bits). Raw PCM tracks (u8 / --- s16le) are converted here too. Output: interleaved floats (u8: (v - 128) / 128, s16: v / 32768), as ffmpeg gives --- them. Never throws: trees are bounded and every read past the packet gives zero bits. +-- video/smk/Audio: Smacker packed audio (SMKA, MultimediaWiki "Smacker"): u32 unpacked size, then LSB-first bits: data, +-- stereo, 16-bit flags, an 8-bit Huffman tree per channel and byte, the first samples raw (16-bit byte-swapped, right +-- first), then wrapping deltas. Raw u8 / s16le too; floats as ffmpeg gives them (u8 (v - 128) / 128, s16 v / 32768). local Smacker = require("@rosetta/codecs/video/Legacy/Smacker") local readu8, readi16 = buffer.readu8, buffer.readi16 local Audio = {} --- decode(data, channels, bits, packed) -> frames, floats (1-based interleaved) | nil, message function Audio.decode(d: buffer, channels: number, bits: number, packed: boolean): (number?, { number } | string) local n = buffer.len(d) if not packed then @@ -43,7 +38,7 @@ function Audio.decode(d: buffer, channels: number, bits: number, packed: boolean local br = Smacker.bits(d, 4, n - 4) local bit, read, walk = Smacker.bit, Smacker.read, Smacker.walk if bit(br) == 0 then - return 0, {} -- no data + return 0, {} end local stereo = bit(br) local wide = bit(br) diff --git a/src/Rosetta/video/smk/init.luau b/src/Rosetta/video/smk/init.luau index ded8c40..e741837 100644 --- a/src/Rosetta/video/smk/init.luau +++ b/src/Rosetta/video/smk/init.luau @@ -1,16 +1,7 @@ --!strict --- video/smk: RAD Game Tools' Smacker video (SMK2 and SMK4). New in rosetta, written from the format description --- (MultimediaWiki "Smacker"). --- Read: the header (size, frame count, frame time: > 0 ms, < 0 units of 10 us; the ring-frame flag), up to 7 audio --- tracks (rate, packed / 16-bit / stereo flags), the frame sizes and flags, the four Huffman trees; per frame a palette --- update (skip / copy-from-old / new 6-bit entries), the audio chunks and the video data, into a Demuxer. open() --- returns a VideoDecoder: rgba8 frames from the Smacker video codec (codecs/video/Legacy/Smacker, through the --- codecs/video/Video registry: the frame's palette rides on each packet as packet.palette), and the first audio --- track as an audio Decoder built here (Smacker's packed DPCM audio has no audio format, so the format decodes it --- itself: video/smk/Audio over codecs/audio/Stream; raw u8 / s16le tracks too). The ring frame (the extra frame that --- leads back to the first) is not shown unless opts.ringFrame. Smk.demux(r) gives the Demuxer; Smk.openAudio(dmx, --- track) the Decoder of any of its audio tracks. --- Not supported: writing, Bink audio tracks (flags 0x08 / 0x04: reported as "binkaudio", no decoder). +-- video/smk: RAD Smacker video (SMK2, SMK4), from MultimediaWiki "Smacker": header, up to 7 audio tracks, Huffman +-- trees, per-frame palette updates; rgba8 through codecs/video/Legacy/Smacker, audio through video/smk/Audio; the ring +-- frame only with opts.ringFrame. Not supported: writing, Bink audio tracks (flags 0x08 / 0x04). -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -33,11 +24,11 @@ local Smk = { -- ------------------------------------------------------------------------------------------------ types export type OpenOptions = { - rgba: boolean?, -- (frames are rgba8 already) + rgba: boolean?, -- frames are rgba8 already maxPixels: number?, -- default 2^26 - audio: boolean?, -- false: do not open the audio track - ringFrame: boolean?, -- true: also show the ring frame at the end (as ffmpeg does) - openAudio: any?, -- the api's hook: used only for tracks this format cannot decode (Bink audio) + audio: boolean?, + ringFrame: boolean?, -- also show the ring frame (as ffmpeg) + openAudio: any?, -- the api's hook, only for Bink audio } -- ------------------------------------------------------------------------------------------------ constants @@ -59,7 +50,6 @@ function Smk.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- a frame's palette update over the previous palette (pal: 256 u32 R, G, B, A); false when malformed local function palette(b: buffer, p: number, stop: number, old: buffer): (buffer?) local pal = buffer.create(1024) buffer.copy(pal, 0, old, 0, 1024) @@ -96,7 +86,6 @@ local function palette(b: buffer, p: number, stop: number, old: buffer): (buffer return pal end --- demux(r, opts?) -> the Demuxer | nil, Err function Smk.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) local b, base, limit = r.buf, r.base, r.limit if limit - base < HEADER then @@ -247,7 +236,6 @@ function Smk.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) end -- ------------------------------------------------------------------------------------------------ open --- openAudio(dmx, track) -> an audio Decoder for one of the demuxer's audio tracks | nil, Err function Smk.openAudio(dmx: any, track: Types.Track): (Types.Decoder?, Err.Err?) local codec = track.codec if codec ~= "smackaudio" and codec ~= "pcm_u8" and codec ~= "pcm_s16le" then @@ -299,7 +287,6 @@ function Smk.openAudio(dmx: any, track: Types.Track): (Types.Decoder?, Err.Err?) }) end --- open(r, opts?) -> a VideoDecoder | nil, Err function Smk.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?) local dmx, err = Smk.demux(r, opts) if not dmx then diff --git a/src/Rosetta/video/y4m/init.luau b/src/Rosetta/video/y4m/init.luau index 2e97994..838a642 100644 --- a/src/Rosetta/video/y4m/init.luau +++ b/src/Rosetta/video/y4m/init.luau @@ -1,11 +1,7 @@ --!strict --- video/y4m: YUV4MPEG2 (the mjpegtools / ffmpeg raw video stream). New in rosetta. --- Read: the stream header (W H F I A C X tags) and every FRAME into a raw-video Demuxer; open() returns a VideoDecoder --- with yuv420p frames (C420 / C420jpeg / C420mpeg2 / C420paldv as they are; C422 / C444 chroma averaged down; Cmono --- with neutral chroma; 9..16-bit samples (C420p10, ...) scaled to 8 bits). Y4m.demux(r) gives the Demuxer. --- Write: yuv420p 8-bit frames ("C420jpeg", as ffmpeg writes for yuv420p) from any video or animated image; rgba8 --- frames are converted (BT.601 limited range); uneven frame times (a GIF's) become a constant rate with repeated frames. Not supported: interlaced field handling (the I tag is kept in meta), --- alpha (C444alpha drops it). +-- video/y4m: YUV4MPEG2 (mjpegtools / ffmpeg). Reads the W H F I A C X tags and FRAMEs as yuv420p (C422 / C444 +-- averaged, Cmono neutral chroma, high bit depths scaled to 8). Writes "C420jpeg" as ffmpeg does for yuv420p (BT.601 +-- limited range). Not supported: interlaced field handling (the I tag is kept in meta), alpha (C444alpha drops it). -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -27,13 +23,12 @@ local Y4m = { -- ------------------------------------------------------------------------------------------------ types export type OpenOptions = { - rgba: boolean?, -- nextFrame returns rgba8 (default false: yuv420p) + rgba: boolean?, -- default false: yuv420p maxPixels: number?, -- default 2^26 } export type EncodeOptions = { - frameRate: { number }?, -- { num, den } for the F tag, one frame per source frame (default: the constant rate of the - -- shortest frame, longer frames repeated) - maxFps: number?, -- the highest rate uneven frame times may need (default 100) + frameRate: { number }?, -- { num, den } of the F tag (default: the shortest frame's rate) + maxFps: number?, -- default 100 } -- ------------------------------------------------------------------------------------------------ constants @@ -77,7 +72,6 @@ local function frameSize(pf: string, bits: number, w: number, h: number): number return w * h * bps end --- demux(r, opts?) -> the raw-video Demuxer | nil, Err function Y4m.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) local buf, base, limit = r.buf, r.base, r.limit local nl = -1 @@ -164,7 +158,7 @@ function Y4m.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) end local data = e + 1 if data + size > limit then - break -- a truncated last frame is dropped + break end dmx:add(1, k, k, 1, true, data, size) k += 1 @@ -175,7 +169,6 @@ function Y4m.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) end -- ------------------------------------------------------------------------------------------------ encode --- encode(video, opts?) -> buffer | nil, Err function Y4m.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) local streams, err = Source.streams(value, { audio = false }, { video = { copy = nil, encode = "rawvideo" } }) if not streams then @@ -197,7 +190,6 @@ function Y4m.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts?) -> a VideoDecoder | nil, Err function Y4m.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?) local dmx, err = Y4m.demux(r, opts) if not dmx then