--!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 and zlib compression, unknown-size clusters, Cues and Tags in meta) and returns a VideoDecoder: video -- through the codecs/video/Video registry (VP8 with inter frames, MJPEG, MPEG-1, raw; H.264 when registered), audio -- through the api's opts.openAudio hook (Opus, Vorbis, FLAC, MP3, PCM, AAC, ... reach the audio formats), text -- subtitle tracks as cues (Mkv.subtitles). Mkv.demux(r) gives the Demuxer alone. -- Write: WebM (opts.format = "webm" or a .webm destination: VP8 / VP9 / AV1 video and Opus / Vorbis audio, copied -- from the source since VP8 is decode-only) and Matroska (any registered video codec copied, else MJPEG encoded from -- the frames; audio copied, else PCM s16), with SeekHead, Cues and Duration. -- Not supported: bzip2 / lzo content compression and encryption (the track's packets are left as stored, -- track.unsupported says why), chapters / attachments (skipped), writing subtitles. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") local Video = require("@formats/codecs/video/Video") local Source = require("@formats/codecs/video/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/compress/Deflate", "codecs/video/Video", "codecs/video/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 -- variant(r) -> "webm" for a WebM file (DocType webm), else nil: the name F.detect reports (never throws) function Mkv.variant(r: Bytes.Reader): string? local ok, docType = pcall(Parse.docType, r.buf, r.pos, r.limit) if ok and docType == "webm" then return "webm" end return nil end -- ------------------------------------------------------------------------------------------------ encode -- encode(video, opts?) -> buffer | nil, Err: a VideoDecoder (F.load / F.video.open of any video or animated image) -- or a Demuxer function Mkv.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) local o: any = opts or {} local webm = o.webm == true or (type(o.format) == "string" and string.lower(o.format) == "webm") local want: Source.Want if webm then want = { video = { copy = WEBM_VIDEO }, audio = { copy = WEBM_AUDIO } } else local copy: { [string]: boolean } = {} for id, e in Video.codecs do if e.matroska then copy[id] = true end end want = { video = { copy = copy, encode = "mjpeg" }, audio = { copy = { ["*"] = true }, pcm = true } } end local so = table.clone(o) so.quality = so.quality or 90 local streams, err = Source.streams(value, so, want) if not streams then return nil, err end if not webm then -- audio codecs Matroska cannot name: PCM instead for i, s in streams do if s.kind == "audio" and not Mux.codecId("audio", s.codec) then local alt, aerr = Source.streams(value, { video = false, reencodeAudio = true }, { audio = { pcm = true } }) if alt and alt[1] then streams[i] = alt[1] else return nil, aerr end end end end local ok, buf, merr = pcall(Mux.mux, streams, { webm = webm, title = o.title, clusterSeconds = o.clusterSeconds }) if not ok then return nil, Err.new(Err.ARG, "internal error: " .. tostring(buf)) end return buf, merr end -- ------------------------------------------------------------------------------------------------ open -- demux(r, opts?) -> the Demuxer (containers/Demux: tracks, packets, read, seek, count / get) | nil, Err function Mkv.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) local ok, dmx, err = pcall(Parse.parse, r.buf, r.base, r.limit, opts) if not ok then return nil, Err.new(Err.CORRUPT, "internal error: " .. tostring(dmx)) end return dmx, err end -- open(r, opts?) -> a VideoDecoder (kind "video": nextFrame / seek / audio / demuxer) | nil, Err function Mkv.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?) local dmx, err = Mkv.demux(r, opts) if not dmx then return nil, err end return Video.open(dmx, opts :: Video.OpenOptions?) end -- ------------------------------------------------------------------------------------------------ extras -- subtitles(demuxer, trackId?) -> Types.Subtitles from a text subtitle track (S_TEXT/UTF8, WebVTT, ASS text) | nil function Mkv.subtitles(dmx: any, trackId: number?): Types.Subtitles? local track = nil for _, t in dmx.tracks do if t.kind == "subtitle" and (trackId == nil or t.id == trackId) then track = t break end end if not track then return nil end local subs = Types.Subtitles.new() subs.meta.codec = track.codec subs.meta.language = track.language for k = 1, dmx:count(track.id) do local p = dmx:get(track.id, k) if p then local start = p.pts / track.timescale local stop = start + (p.duration or 0) / track.timescale table.insert(subs.cues, { start = start, stop = stop, text = buffer.tostring(p.data) } :: Types.Cue) end end return subs end return Mkv