merge ws/video: containers mkv/avi/mp4/ts/ps/y4m (+writers), codecs Jpeg/Mpeg1/Vp8 inter/Video registry, AudioWrap, F.video.open
This commit is contained in:
commit
2eaed46eea
96 files changed
+13398
-517
No files matched your search
@@ -68,7 +68,7 @@ local list: { Entry } = {
|
||||
path = "image/jpeg",
|
||||
extensions = { "jpg", "jpeg", "jpe", "jfif" },
|
||||
mime = { "image/jpeg" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/Dct" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/Jpeg" },
|
||||
caps = { decode = true, encode = true, lossy = true, alpha = false, depths = { 8, 12 }, progressive = true, arithmetic = true },
|
||||
load = function()
|
||||
return require("@formats/image/jpeg")
|
||||
@@ -278,6 +278,78 @@ local list: { Entry } = {
|
||||
return require("@formats/audio/wav")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "avi",
|
||||
category = "video",
|
||||
path = "video/avi",
|
||||
extensions = { "avi" },
|
||||
mime = { "video/x-msvideo", "video/avi" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "containers/Avi", "containers/Demux", "codecs/Video", "codecs/Video/Source" },
|
||||
caps = { decode = true, encode = true, streaming = true, video = { "mjpeg", "mpeg1", "rawvideo" }, audio = true, odml = true },
|
||||
load = function()
|
||||
return require("@formats/video/avi")
|
||||
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/Deflate", "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 = "mp4",
|
||||
category = "video",
|
||||
path = "video/mp4",
|
||||
extensions = { "mp4", "m4v", "mov", "qt", "3gp", "3g2", "mj2" },
|
||||
mime = { "video/mp4", "video/quicktime", "video/3gpp" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "containers/IsoBmff", "containers/Demux", "codecs/Video", "codecs/Video/Source" },
|
||||
caps = { decode = true, encode = true, streaming = true, remux = true, video = { "mjpeg", "mpeg1", "h264" }, audio = true, fragments = true },
|
||||
load = function()
|
||||
return require("@formats/video/mp4")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "mpegps",
|
||||
category = "video",
|
||||
path = "video/mpegps",
|
||||
extensions = { "mpg", "mpeg", "vob", "m1v", "mpv", "dat" },
|
||||
mime = { "video/mpeg" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "containers/MpegPs", "containers/MpegEs", "containers/Demux", "codecs/Video" },
|
||||
caps = { decode = true, encode = false, streaming = true, video = { "mpeg1" }, audio = true },
|
||||
load = function()
|
||||
return require("@formats/video/mpegps")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "mpegts",
|
||||
category = "video",
|
||||
path = "video/mpegts",
|
||||
extensions = { "ts", "m2ts", "mts", "tsv" },
|
||||
mime = { "video/mp2t" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "containers/MpegTs", "containers/MpegEs", "containers/Demux", "codecs/Video" },
|
||||
caps = { decode = true, encode = false, streaming = true, video = { "mpeg1", "h264" }, audio = true },
|
||||
load = function()
|
||||
return require("@formats/video/mpegts")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "y4m",
|
||||
category = "video",
|
||||
path = "video/y4m",
|
||||
extensions = { "y4m" },
|
||||
mime = { "video/x-yuv4mpeg" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "containers/Demux", "codecs/Video", "codecs/Video/Source" },
|
||||
caps = { decode = true, encode = true, streaming = true, video = { "rawvideo" }, depths = { 8, 10, 12, 16 } },
|
||||
load = function()
|
||||
return require("@formats/video/y4m")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "3mf",
|
||||
category = "model",
|
||||
|
||||
+67
-15
@@ -163,38 +163,90 @@ 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)
|
||||
startTime: number, -- seconds: the first video / audio packet's presentation time (VideoFrame times count from it)
|
||||
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 from the start of the stream (the demuxer's startTime)
|
||||
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) -> (), -- the next frame is the first at or after the time (decoded from the keyframe before it)
|
||||
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)
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- image/jpeg/Arith: arithmetic-coded scans (ITU T.81 annex D / F.1.4, sequential and progressive) into quantised
|
||||
-- codecs/Jpeg/Arith: arithmetic-coded scans (ITU T.81 annex D / F.1.4, sequential and progressive) into quantised
|
||||
-- DCT coefficients (native; never throws). A Luau translation of libjpeg-turbo's jdarith.c (Guido Vollbeding's
|
||||
-- decoder, IJG licence: licenses/libjpeg-turbo-LICENSE.md) and the jaricom.c probability table.
|
||||
--
|
||||
@@ -1,7 +1,7 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- image/jpeg/Color: chroma upsampling and colour conversion to RGBA8, one output row at a time (native; never
|
||||
-- codecs/Jpeg/Color: chroma upsampling and colour conversion to RGBA8, one output row at a time (native; never
|
||||
-- throws). Absorbed from jpeg-luau 1.0 src/Jpeg/Color.luau (same author); a Luau translation of libjpeg-turbo's
|
||||
-- jdsample.c / jdcolor.c (IJG licence: licenses/libjpeg-turbo-LICENSE.md).
|
||||
--
|
||||
@@ -1,12 +1,15 @@
|
||||
--!strict
|
||||
-- image/jpeg/Decode: the JPEG marker parser and output stage (interpreted; it validates everything the native Scan /
|
||||
-- Arith / Dct / Color loops index). Absorbed from jpeg-luau 1.0 src/Jpeg/init.luau (same author) and extended:
|
||||
-- arithmetic-coded frames (SOF9 / SOF10, DAC), a reader range instead of a whole buffer, APP1 EXIF / APP2 ICC / COM
|
||||
-- / JFIF density collected for meta. The IDCT size choice for scaled decodes follows libjpeg-turbo's jdmaster.c.
|
||||
local Scan = require("@formats/image/jpeg/Scan")
|
||||
local Arith = require("@formats/image/jpeg/Arith")
|
||||
local Color = require("@formats/image/jpeg/Color")
|
||||
local Tables = require("@formats/image/jpeg/Tables")
|
||||
-- codecs/Jpeg/Decode: the JPEG marker parser and output stage (interpreted; it validates everything the native Scan /
|
||||
-- Arith / Dct / Color / Yuv loops index). Absorbed from jpeg-luau 1.0 src/Jpeg/init.luau (same author) and extended:
|
||||
-- arithmetic-coded frames (SOF9 / SOF10, DAC), a byte range instead of a whole buffer, APP1 EXIF / APP2 ICC / COM
|
||||
-- / JFIF density collected for meta, the AVI1 APP0 field polarity and the end of the image (Motion-JPEG), and a
|
||||
-- yuv420p output straight from the IDCT planes (outputYuv). The IDCT size choice for scaled decodes follows
|
||||
-- libjpeg-turbo's jdmaster.c. Moved from image/jpeg/Decode to codecs/Jpeg/Decode for the video formats.
|
||||
local Scan = require("@formats/codecs/Jpeg/Scan")
|
||||
local Arith = require("@formats/codecs/Jpeg/Arith")
|
||||
local Color = require("@formats/codecs/Jpeg/Color")
|
||||
local Tables = require("@formats/codecs/Jpeg/Tables")
|
||||
local Yuv = require("@formats/codecs/Jpeg/Yuv")
|
||||
local Dct = require("@formats/codecs/Dct")
|
||||
|
||||
local readu8 = buffer.readu8
|
||||
@@ -226,6 +229,8 @@ export type State = {
|
||||
comments: { string },
|
||||
truncated: boolean,
|
||||
scale: number,
|
||||
avi1: number?, -- the AVI1 APP0 field polarity (0 = progressive, 1 / 2 = interlaced: two fields back to back)
|
||||
endPos: number, -- the byte after the EOI marker (or the end of the data)
|
||||
}
|
||||
|
||||
-- parse(b, base, limit, opts, headerOnly) -> State | nil, code, message. Walks the markers in b[base, limit); with
|
||||
@@ -255,6 +260,8 @@ function Decode.parse(b: buffer, base: number, n: number, opts: any, headerOnly:
|
||||
comments = {},
|
||||
truncated = false,
|
||||
scale = scale,
|
||||
avi1 = nil,
|
||||
endPos = n,
|
||||
}
|
||||
local iccChunks: { buffer } = {}
|
||||
local ri = 0
|
||||
@@ -277,6 +284,7 @@ function Decode.parse(b: buffer, base: number, n: number, opts: any, headerOnly:
|
||||
local m = readu8(b, pos)
|
||||
pos += 1
|
||||
if m == 0xD9 then
|
||||
st.endPos = pos
|
||||
break -- EOI
|
||||
elseif m == 0 or m == 0x01 or m == 0xD8 or (m >= 0xD0 and m <= 0xD7) then
|
||||
continue -- standalone markers (or stray stuffing)
|
||||
@@ -303,6 +311,8 @@ function Decode.parse(b: buffer, base: number, n: number, opts: any, headerOnly:
|
||||
if e - p >= 12 and buffer.readstring(b, p, 5) == "JFIF\0" then
|
||||
st.jfif = true
|
||||
st.density = { unit = readu8(b, p + 7), x = be16(b, p + 8), y = be16(b, p + 10) }
|
||||
elseif e - p >= 5 and buffer.readstring(b, p, 4) == "AVI1" then
|
||||
st.avi1 = readu8(b, p + 4)
|
||||
end
|
||||
elseif m == 0xE1 then
|
||||
local t, o = exif(b, p, e)
|
||||
@@ -663,4 +673,90 @@ function Decode.output(st: State): (number?, any, any, string?)
|
||||
return outW, outH, pixels, space
|
||||
end
|
||||
|
||||
-- outputYuv(st) -> width, height, yuv420p pixels, sampling | nil when the frame has no direct yuv420p form (the
|
||||
-- caller falls back to output). The IDCT output planes as they are, cropped to the image, without colour conversion
|
||||
-- or upsampling: 8-bit YCbCr whose chroma is sampled at half the luma rate both ways ("420", 2x2 / 1x1); half
|
||||
-- horizontally ("422", 2x1 / 1x1 or ffmpeg's 2x2 / 1x2: each pair of chroma rows averaged, rounding up); at the luma
|
||||
-- rate ("444", 1x1 or ffmpeg's 1x2 everywhere: each 2 x 2 chroma block averaged, rounding to nearest); grey ("gray":
|
||||
-- chroma 128). Full scale only (opts.scale = 1).
|
||||
-- one IDCT plane at a time is live (each is cropped into the output before the next component): frame-sized planes
|
||||
-- (up to 4 MB) are kept between calls, so a stream of video frames does not allocate them per frame
|
||||
local scratch: buffer? = nil
|
||||
local function scratchPlane(n: number): buffer
|
||||
local sc = scratch
|
||||
if sc and buffer.len(sc) >= n then
|
||||
return sc
|
||||
end
|
||||
local b = buffer.create(n)
|
||||
if n <= 4 * 1024 * 1024 then
|
||||
scratch = b
|
||||
end
|
||||
return b
|
||||
end
|
||||
|
||||
function Decode.outputYuv(st: State): (number?, number?, buffer?, string?)
|
||||
local f: Frame = st.frame
|
||||
if st.scale ~= 1 or f.precision ~= 8 then
|
||||
return nil
|
||||
end
|
||||
local comps = f.comps
|
||||
local space = colorSpaceOf(f, st.adobe, st.jfif)
|
||||
local mode = nil
|
||||
if space == "gray" then
|
||||
mode = "gray"
|
||||
elseif space == "ycbcr" then
|
||||
-- the ratios of luma to chroma sampling (ffmpeg writes 4:2:2 as 2x2 / 1x2 and 4:4:4 as 1x2 everywhere)
|
||||
local l, cb, cr = comps[1], comps[2], comps[3]
|
||||
if l.h == f.hmax and l.v == f.vmax and cb.h == cr.h and cb.v == cr.v then
|
||||
local rh, rv = f.hmax // cb.h, f.vmax // cb.v
|
||||
if rh * cb.h ~= f.hmax or rv * cb.v ~= f.vmax then
|
||||
mode = nil
|
||||
elseif rh == 2 and rv == 2 then
|
||||
mode = "420"
|
||||
elseif rh == 2 and rv == 1 then
|
||||
mode = "422"
|
||||
elseif rh == 1 and rv == 1 then
|
||||
mode = "444"
|
||||
end
|
||||
end
|
||||
end
|
||||
if not mode then
|
||||
return nil
|
||||
end
|
||||
for _, c in comps do
|
||||
if c.coef and not c.quant then
|
||||
return nil -- output() reports the missing table
|
||||
end
|
||||
end
|
||||
local w, h = f.width, f.height
|
||||
local cw, ch = (w + 1) // 2, (h + 1) // 2
|
||||
local out = buffer.create(w * h + 2 * cw * ch)
|
||||
local zeroQ: buffer? = nil
|
||||
for i, c in comps do
|
||||
local stride, rows = c.bpl * 8, c.bpc * 8
|
||||
local plane = scratchPlane(stride * rows * 2)
|
||||
local coef = c.coef or buffer.create(c.bpl * c.bpc * 128)
|
||||
local q = c.quant
|
||||
if not q then
|
||||
zeroQ = zeroQ or buffer.create(128) -- the component never appeared in a scan: mid grey
|
||||
q = zeroQ
|
||||
end
|
||||
Dct.idctComponent(coef, q :: buffer, c.bpl, c.bpc, 8, plane, 2, 128, 255)
|
||||
if i == 1 then
|
||||
Yuv.crop(plane, stride, w, h, out, 0)
|
||||
elseif mode == "420" then
|
||||
Yuv.crop(plane, stride, cw, ch, out, w * h + (i - 2) * cw * ch)
|
||||
elseif mode == "422" then
|
||||
Yuv.rows(plane, stride, cw, h, out, w * h + (i - 2) * cw * ch)
|
||||
else
|
||||
Yuv.box(plane, stride, w, h, out, w * h + (i - 2) * cw * ch)
|
||||
end
|
||||
c.coef = nil
|
||||
end
|
||||
if mode == "gray" then
|
||||
buffer.fill(out, w * h, 128, 2 * cw * ch)
|
||||
end
|
||||
return w, h, out, mode
|
||||
end
|
||||
|
||||
return Decode
|
||||
@@ -1,15 +1,16 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- image/jpeg/Encode: the JPEG encoder (native; never throws). Baseline (SOF0) with the standard or optimised Huffman
|
||||
-- codecs/Jpeg/Encode: the JPEG encoder (native; never throws). Baseline (SOF0) with the standard or optimised Huffman
|
||||
-- tables and progressive (SOF2, libjpeg's jpeg_simple_progression script, optimised tables per scan); grey or YCbCr
|
||||
-- 4:4:4 / 4:2:2 / 4:2:0; restart intervals. It follows libjpeg-turbo's encoder step for step so that its output is
|
||||
-- byte-identical to cjpeg's for the same settings: jccolor.c (fixed-point RGB -> YCbCr), jcsample.c (box downsampling
|
||||
-- with alternating rounding bias, right-edge replication), jccoefct.c (dummy edge blocks), jfdctint.c + jcdctmgr.c
|
||||
-- (codecs/Dct), jchuff.c (sequential coding, jpeg_gen_optimal_table) and jcphuff.c (progressive coding: EOB runs,
|
||||
-- 4:4:4 / 4:2:2 / 4:2:0, or yuv420p planes coded as they are (4:2:0, no colour conversion: the Motion-JPEG
|
||||
-- encoders); restart intervals. Moved from image/jpeg/Encode to codecs/Jpeg/Encode. It follows libjpeg-turbo's
|
||||
-- encoder step for step so that its output is byte-identical to cjpeg's for the same settings: jccolor.c
|
||||
-- (fixed-point RGB -> YCbCr), jcsample.c (box downsampling with alternating rounding bias, right-edge replication),
|
||||
-- jccoefct.c (dummy edge blocks), jfdctint.c + jcdctmgr.c (codecs/Dct), jchuff.c (sequential coding, jpeg_gen_optimal_table) and jcphuff.c (progressive coding: EOB runs,
|
||||
-- correction-bit buffering). Luau translation of IJG code: licenses/libjpeg-turbo-LICENSE.md.
|
||||
local Dct = require("@formats/codecs/Dct")
|
||||
local Tables = require("@formats/image/jpeg/Tables")
|
||||
local Tables = require("@formats/codecs/Jpeg/Tables")
|
||||
|
||||
local readu8, writeu8, readi16, writei16, readu16, writeu16 = buffer.readu8, buffer.writeu8, buffer.readi16, buffer.writei16, buffer.readu16, buffer.writeu16
|
||||
local band, countlz = bit32.band, bit32.countlz
|
||||
@@ -574,8 +575,9 @@ export type Options = {
|
||||
density: { unit: number, x: number, y: number }?,
|
||||
}
|
||||
|
||||
-- run(pixels, w, h, bpp, opts) -> buffer. pixels: w * h * bpp bytes (bpp 4 rgba8 / 3 rgb8 / 1 gray8); the caller
|
||||
-- validated sizes (1..65535) and options.
|
||||
-- run(pixels, w, h, bpp, opts) -> buffer. pixels: w * h * bpp bytes (bpp 4 rgba8 / 3 rgb8 / 1 gray8), or bpp 0:
|
||||
-- yuv420p (w * h luma, then ceil(w / 2) * ceil(h / 2) Cb and Cr; opts.sampling must be "420" unless opts.gray). The
|
||||
-- caller validated sizes (1..65535), the buffer length and options.
|
||||
function Encode.run(px: buffer, w: number, h: number, bpp: number, o: Options): buffer
|
||||
OUT = buffer.create(math.max(1024, w * h // 2))
|
||||
CAP = buffer.len(OUT)
|
||||
@@ -584,7 +586,19 @@ function Encode.run(px: buffer, w: number, h: number, bpp: number, o: Options):
|
||||
GATHER = false
|
||||
EOBRUN, BE = 0, 0
|
||||
|
||||
local Y, Cb, Cr = planes(px, w, h, bpp, o.gray)
|
||||
local yuv = bpp == 0
|
||||
local Y, Cb, Cr
|
||||
if yuv then
|
||||
local n, cn = w * h, ((w + 1) // 2) * ((h + 1) // 2)
|
||||
Y = px
|
||||
if not o.gray then
|
||||
Cb, Cr = buffer.create(cn), buffer.create(cn)
|
||||
buffer.copy(Cb :: buffer, 0, px, n, cn)
|
||||
buffer.copy(Cr :: buffer, 0, px, n + cn, cn)
|
||||
end
|
||||
else
|
||||
Y, Cb, Cr = planes(px, w, h, bpp, o.gray)
|
||||
end
|
||||
local hs, vs = 1, 1
|
||||
if not o.gray then
|
||||
if o.sampling == "420" then
|
||||
@@ -615,7 +629,9 @@ function Encode.run(px: buffer, w: number, h: number, bpp: number, o: Options):
|
||||
local bw, bh = math.ceil(cw / 8), math.ceil(chh / 8)
|
||||
local bpl, bpc = mcusX * ch, mcusY * cv
|
||||
local plane, pw, ph = src, w, h
|
||||
if ch < hs or cv < vs then
|
||||
if yuv and i > 1 then
|
||||
pw, ph = (w + 1) // 2, (h + 1) // 2 -- already 4:2:0: fdctQuantize repeats the edges as jcsample.c does
|
||||
elseif ch < hs or cv < vs then
|
||||
pw, ph = bw * 8, chh
|
||||
plane = downsample(src, w, h, hs // ch, vs // cv, pw, ph)
|
||||
end
|
||||
@@ -1,7 +1,7 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- image/jpeg/Scan: Huffman-coded scan decoding into quantised DCT coefficients (native; never throws). Absorbed from
|
||||
-- codecs/Jpeg/Scan: Huffman-coded scan decoding into quantised DCT coefficients (native; never throws). Absorbed from
|
||||
-- jpeg-luau 1.0 src/Jpeg/Scan.luau (same author); unchanged but for this header.
|
||||
--
|
||||
-- `destuff` copies one scan's entropy-coded bytes into a clean buffer: it drops the stuffed 0x00 after each 0xFF,
|
||||
@@ -1,5 +1,5 @@
|
||||
--!strict
|
||||
-- image/jpeg/Tables: the standard tables of ITU T.81 annex K: the example Huffman tables (K.3, which every baseline
|
||||
-- codecs/Jpeg/Tables: the standard tables of ITU T.81 annex K: the example Huffman tables (K.3, which every baseline
|
||||
-- encoder without optimisation writes and Motion-JPEG frames leave out) and the luminance / chrominance quantisation
|
||||
-- tables (K.1) with libjpeg's quality scaling (jcparam.c jpeg_quality_scaling / jpeg_add_quant_table).
|
||||
local Tables = {}
|
||||
@@ -0,0 +1,76 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- codecs/Jpeg/Yuv: the yuv420p output of the JPEG decoder (native; never throws): the IDCT output planes (u16
|
||||
-- samples, block-padded) cropped into u8 yuv420p planes without colour conversion or upsampling, 4:2:2 / 4:4:4
|
||||
-- chroma reduced to 4:2:0 by averaging, and the interleaving of two fields (AVI1 interlaced Motion-JPEG).
|
||||
-- The callers (codecs/Jpeg/Decode, codecs/Jpeg) size every buffer; each loop reads and writes inside those sizes.
|
||||
local readu16, writeu8, readu32, writeu32 = buffer.readu16, buffer.writeu8, buffer.readu32, buffer.writeu32
|
||||
|
||||
local Yuv = {}
|
||||
|
||||
-- crop(src, stride, w, h, dst, doff): the top-left w x h samples of a u16 plane (stride samples per row) into u8
|
||||
-- samples at dst[doff], w per row
|
||||
function Yuv.crop(src: buffer, stride: number, w: number, h: number, dst: buffer, doff: number)
|
||||
local quads = w // 4
|
||||
local rest = w - quads * 4
|
||||
for y = 0, h - 1 do
|
||||
local s = y * stride * 2
|
||||
local d = doff + y * w
|
||||
-- four samples (two u32 reads of two u16 samples, each 0..255) per u32 write
|
||||
for _ = 1, quads do
|
||||
local a, b = readu32(src, s), readu32(src, s + 4)
|
||||
writeu32(dst, d, a % 65536 + (a // 65536) * 256 + (b % 65536) * 65536 + (b // 65536) * 16777216)
|
||||
s += 8
|
||||
d += 4
|
||||
end
|
||||
for k = 0, rest - 1 do
|
||||
writeu8(dst, d + k, readu16(src, s + k * 2))
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- rows(src, stride, w, h, dst, doff): a u16 plane of w x h samples (4:2:2 chroma) -> u8 w x ceil(h / 2), each output
|
||||
-- row the rounded mean of two source rows (the last row alone when h is odd)
|
||||
function Yuv.rows(src: buffer, stride: number, w: number, h: number, dst: buffer, doff: number)
|
||||
local oh = (h + 1) // 2
|
||||
for y = 0, oh - 1 do
|
||||
local a = 2 * y * stride * 2
|
||||
local b = if 2 * y + 1 < h then a + stride * 2 else a
|
||||
local d = doff + y * w
|
||||
for x = 0, w - 1 do
|
||||
writeu8(dst, d + x, (readu16(src, a + x * 2) + readu16(src, b + x * 2) + 1) // 2)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- box(src, stride, w, h, dst, doff): a u16 plane of w x h samples (4:4:4 chroma) -> u8 ceil(w / 2) x ceil(h / 2),
|
||||
-- each output sample the rounded mean of a 2 x 2 block (edges repeat the last row / column)
|
||||
function Yuv.box(src: buffer, stride: number, w: number, h: number, dst: buffer, doff: number)
|
||||
local ow, oh = (w + 1) // 2, (h + 1) // 2
|
||||
for y = 0, oh - 1 do
|
||||
local a = 2 * y * stride * 2
|
||||
local b = if 2 * y + 1 < h then a + stride * 2 else a
|
||||
local d = doff + y * ow
|
||||
for x = 0, ow - 1 do
|
||||
local x0 = 2 * x * 2
|
||||
local x1 = if 2 * x + 1 < w then x0 + 2 else x0
|
||||
writeu8(dst, d + x, (readu16(src, a + x0) + readu16(src, a + x1) + readu16(src, b + x0) + readu16(src, b + x1) + 2) // 4)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- weave(top, toff, bottom, boff, rowBytes, rows, dst, doff): interleave rows of two planes (field 1 on the even rows, field
|
||||
-- 2 on the odd rows) into rows output rows at dst[doff]; top holds ceil(rows / 2) rows, bottom floor(rows / 2)
|
||||
function Yuv.weave(top: buffer, toff: number, bottom: buffer, boff: number, rowBytes: number, rows: number, dst: buffer, doff: number)
|
||||
for y = 0, rows - 1 do
|
||||
local k = y // 2
|
||||
if y % 2 == 0 then
|
||||
buffer.copy(dst, doff + y * rowBytes, top, toff + k * rowBytes, rowBytes)
|
||||
else
|
||||
buffer.copy(dst, doff + y * rowBytes, bottom, boff + k * rowBytes, rowBytes)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
return Yuv
|
||||
@@ -0,0 +1,387 @@
|
||||
--!strict
|
||||
-- codecs/Jpeg: the JPEG codec (ITU T.81) on byte ranges: image/jpeg is a thin format over it, and the Motion-JPEG
|
||||
-- video tracks (AVI / Matroska / QuickTime) decode and encode their frames with it. The engine (Huffman and
|
||||
-- arithmetic scan decoding, IDCTs through codecs/Dct, libjpeg-turbo's upsampling and colour conversion, the encoder)
|
||||
-- was absorbed from jpeg-luau 1.0 (same author) into image/jpeg and moved down here; it is bit-exact with libjpeg-turbo's
|
||||
-- djpeg and byte-identical with cjpeg. IJG-derived parts: licenses/libjpeg-turbo-LICENSE.md.
|
||||
--
|
||||
-- local img, err = Jpeg.decode(buf, off?, len?, opts?) -- one JPEG -> rgba8 (or gray8 / yuv420p) Types.Image
|
||||
-- local img = Jpeg.decode(frame, 0, n, { yuv = true }) -- video: yuv420p straight from the IDCT planes
|
||||
-- local out, err = Jpeg.encode(img, opts?) -- rgba8 / rgb8 / gray8 / yuv420p Image -> buffer
|
||||
-- local info, err = Jpeg.info(buf, off?, len?) -- the headers up to the frame header
|
||||
--
|
||||
-- Decode: baseline, extended and progressive frames, Huffman or arithmetic coded (SOF0/1/2/9/10), 8 and 12-bit
|
||||
-- samples, 1, 3 or 4 components with any sampling factors 1..4, restart intervals (resynchronising after corrupt
|
||||
-- data), grey / YCbCr / RGB / CMYK / YCCK (Adobe APP14), scaled decodes (opts.scale = 2, 4, 8), EXIF orientation
|
||||
-- (meta.orientation, applied with opts.orient). Truncated or corrupt scans decode as far as they go
|
||||
-- (meta.truncated = true).
|
||||
-- Motion-JPEG: frames without DHT segments use the T.81 annex K tables; the AVI1 APP0 segment is read (its field
|
||||
-- polarity) and data after EOI is ignored. Two fields back to back (AVI1 interlaced: two JPEGs of half the frame
|
||||
-- height, polarity 1 or 2, or opts.fields = true) are decoded and woven into one frame, the first field on the even
|
||||
-- rows (top field first, as ffmpeg, which ignores the polarity value); a missing or different-sized second field
|
||||
-- leaves the first field alone (meta.source.fields = 1).
|
||||
-- opts.yuv: 8-bit YCbCr frames come out as yuv420p (full-range BT.601, meta.source.range = "full") without colour
|
||||
-- conversion or upsampling: 4:2:0 (2x2 luma) as the planes are; 4:2:2 (2x1 luma, the usual Motion-JPEG camera
|
||||
-- layout) with each pair of chroma rows averaged; 4:4:4 with 2 x 2 chroma averages; grey with chroma 128. Other
|
||||
-- layouts (RGB, CMYK, 4:1:1, 4:4:0, 12-bit) and scaled decodes fall back to rgba8 (check img.format).
|
||||
-- Encode: baseline (standard or optimised Huffman tables) and progressive (libjpeg's simple progression), grey or
|
||||
-- YCbCr 4:4:4 / 4:2:2 / 4:2:0, libjpeg quality tables, restart intervals, extra APPn / COM segments
|
||||
-- (opts.segments); yuv420p input is coded from its planes as they are (4:2:0, no colour conversion).
|
||||
-- Not supported: lossless (SOF3) and hierarchical frames, DNL, 2-component images, 12-bit or CMYK encoding.
|
||||
-- Never throws: bad data or arguments return nil, Err.
|
||||
local Err = require("@formats/core/Err")
|
||||
local Types = require("@formats/Types")
|
||||
local Decode = require("@formats/codecs/Jpeg/Decode")
|
||||
local Encode = require("@formats/codecs/Jpeg/Encode")
|
||||
local Yuv = require("@formats/codecs/Jpeg/Yuv")
|
||||
|
||||
local Jpeg = {}
|
||||
|
||||
export type DecodeOptions = {
|
||||
scale: number?, -- 1 (default), 2, 4 or 8: decode at ceil(size / scale) (8 reads the DC coefficients only)
|
||||
orient: boolean?, -- apply the EXIF orientation (default false: reported in meta.orientation only; rgba8 / gray8)
|
||||
native: boolean?, -- grey files decode to gray8 (default false: rgba8)
|
||||
yuv: boolean?, -- 8-bit YCbCr / grey frames decode to yuv420p (default false); see the header for the layouts
|
||||
fields: boolean?, -- two JPEGs back to back are two fields of one frame (default: when the AVI1 segment says so)
|
||||
maxPixels: number?, -- refuse larger images (default 2^26)
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
quality: number?, -- 1..100 (default 90), libjpeg's scaling of the T.81 annex K tables
|
||||
subsampling: ("420" | "422" | "444")?, -- chroma subsampling (default "420"; yuv420p input is always 4:2:0)
|
||||
progressive: boolean?, -- default false
|
||||
optimize: boolean?, -- optimised Huffman tables for baseline files (default false; progressive always optimises)
|
||||
gray: boolean?, -- a one-component file (default: true for gray8 images)
|
||||
restart: number?, -- restart interval in MCUs (default 0 = none)
|
||||
jfif: boolean?, -- write the JFIF APP0 header (default true)
|
||||
density: { unit: number, x: number, y: number }?, -- the JFIF density (default unit 0, 1 x 1)
|
||||
segments: { { marker: number, data: buffer } }?, -- APPn / COM segments written after the JFIF header
|
||||
}
|
||||
|
||||
export type Info = {
|
||||
width: number,
|
||||
height: number,
|
||||
components: number,
|
||||
progressive: boolean,
|
||||
arithmetic: boolean,
|
||||
precision: number,
|
||||
colorSpace: string,
|
||||
sampling: { { number } }, -- { h, v } per component
|
||||
orientation: number,
|
||||
adobe: number?,
|
||||
jfif: boolean,
|
||||
avi1: number?, -- the AVI1 field polarity, when the segment comes before the frame header
|
||||
}
|
||||
|
||||
local CODES = { corrupt = Err.CORRUPT, unsupported = Err.UNSUPPORTED, limit = Err.LIMIT, truncated = Err.TRUNCATED, arg = Err.ARG }
|
||||
|
||||
local function range(buf: buffer, off: number?, len: number?): (number, number)
|
||||
local n = buffer.len(buf)
|
||||
local o = math.clamp(math.floor(tonumber(off) or 0), 0, n)
|
||||
return o, math.clamp(math.floor(tonumber(len) or (n - o)), 0, n - o)
|
||||
end
|
||||
|
||||
-- the marker parser over [o, o + l): State | nil, Err
|
||||
local function parse(buf: buffer, o: number, l: number, opts: any, headerOnly: boolean): (Decode.State?, Err.Err?)
|
||||
local ok, st, code, msg = pcall(Decode.parse, buf, o, o + l, opts, headerOnly)
|
||||
if not ok then
|
||||
return nil, Err.new(Err.CORRUPT, "internal error: " .. tostring(st))
|
||||
end
|
||||
if not st then
|
||||
return nil, Err.new(CODES[code :: string] or Err.CORRUPT, msg or "decode failed", o)
|
||||
end
|
||||
return st, nil
|
||||
end
|
||||
|
||||
local function samplingOf(f: any): { { number } }
|
||||
local sampling = {}
|
||||
for _, c in f.comps do
|
||||
table.insert(sampling, { c.h, c.v })
|
||||
end
|
||||
return sampling
|
||||
end
|
||||
|
||||
-- info(buf, off?, len?) -> Info | nil, Err (reads the headers up to the frame header)
|
||||
function Jpeg.info(buf: buffer, off: number?, len: number?): (Info?, Err.Err?)
|
||||
if type(buf) ~= "buffer" then
|
||||
return nil, Err.new(Err.ARG, "expected a buffer")
|
||||
end
|
||||
local o, l = range(buf, off, len)
|
||||
local st, err = parse(buf, o, l, nil, true)
|
||||
if not st then
|
||||
return nil, err
|
||||
end
|
||||
local f = st.frame
|
||||
return {
|
||||
width = f.width,
|
||||
height = f.height,
|
||||
components = #f.comps,
|
||||
progressive = f.progressive,
|
||||
arithmetic = f.arithmetic,
|
||||
precision = f.precision,
|
||||
colorSpace = Decode.colorSpaceOf(f, st.adobe, st.jfif),
|
||||
sampling = samplingOf(f),
|
||||
orientation = st.orientation,
|
||||
adobe = st.adobe,
|
||||
jfif = st.jfif,
|
||||
avi1 = st.avi1,
|
||||
},
|
||||
nil
|
||||
end
|
||||
|
||||
-- the EXIF orientation applied to rgba8 pixels: buffer, width, height
|
||||
local function orient(px: buffer, w: number, h: number, o: number): (buffer, number, number)
|
||||
if o <= 1 or o > 8 then
|
||||
return px, w, h
|
||||
end
|
||||
local swap = o >= 5
|
||||
local ow, oh = if swap then h else w, if swap then w else h
|
||||
local out = buffer.create(ow * oh * 4)
|
||||
local readu32, writeu32 = buffer.readu32, buffer.writeu32
|
||||
for y = 0, oh - 1 do
|
||||
for x = 0, ow - 1 do
|
||||
local col, row
|
||||
if o == 2 then
|
||||
col, row = w - 1 - x, y
|
||||
elseif o == 3 then
|
||||
col, row = w - 1 - x, h - 1 - y
|
||||
elseif o == 4 then
|
||||
col, row = x, h - 1 - y
|
||||
elseif o == 5 then
|
||||
col, row = y, x
|
||||
elseif o == 6 then
|
||||
col, row = y, h - 1 - x
|
||||
elseif o == 7 then
|
||||
col, row = w - 1 - y, h - 1 - x
|
||||
else
|
||||
col, row = w - 1 - y, x
|
||||
end
|
||||
writeu32(out, (y * ow + x) * 4, readu32(px, (row * w + col) * 4))
|
||||
end
|
||||
end
|
||||
return out, ow, oh
|
||||
end
|
||||
|
||||
-- one JPEG at [o, o + l): Image, State | nil, Err
|
||||
local function decodeOne(buf: buffer, o: number, l: number, opts: DecodeOptions?): (Types.Image?, any)
|
||||
local st, err = parse(buf, o, l, opts, false)
|
||||
if not st then
|
||||
return nil, err
|
||||
end
|
||||
local s = st :: Decode.State
|
||||
local img = Types.Image.new(0, 0)
|
||||
local space, mode = nil, nil
|
||||
if opts and opts.yuv then
|
||||
local ok, w, h, px, m = pcall(Decode.outputYuv, s)
|
||||
if not ok then
|
||||
return nil, Err.new(Err.CORRUPT, "internal error: " .. tostring(w))
|
||||
end
|
||||
if w then
|
||||
img.width, img.height, img.pixels, img.format = w, h :: number, px :: buffer, "yuv420p"
|
||||
mode = m
|
||||
space = Decode.colorSpaceOf(s.frame, s.adobe, s.jfif)
|
||||
end
|
||||
end
|
||||
if not mode then
|
||||
local ok, w, h, px, sp = pcall(Decode.output, s)
|
||||
if not ok then
|
||||
return nil, Err.new(Err.CORRUPT, "internal error: " .. tostring(w))
|
||||
end
|
||||
if not w then
|
||||
return nil, Err.new(CODES[h :: string] or Err.CORRUPT, tostring(px), o)
|
||||
end
|
||||
space = sp
|
||||
if opts and opts.orient then
|
||||
px, w, h = orient(px, w, h, s.orientation)
|
||||
end
|
||||
img.width, img.height, img.pixels = w, h, px
|
||||
if opts and opts.native and space == "gray" then
|
||||
local g = buffer.create(w * h)
|
||||
for i = 0, w * h - 1 do
|
||||
buffer.writeu8(g, i, buffer.readu8(px, i * 4))
|
||||
end
|
||||
img.pixels, img.format = g, "gray8"
|
||||
end
|
||||
end
|
||||
local f = s.frame
|
||||
local meta = img.meta
|
||||
meta.orientation = s.orientation
|
||||
meta.oriented = (opts and opts.orient and not mode) or false
|
||||
meta.exif = s.exif
|
||||
meta.icc = s.icc
|
||||
if #s.comments > 0 then
|
||||
meta.text = { comment = table.concat(s.comments, "\n") }
|
||||
end
|
||||
if s.density and s.density.unit > 0 and s.density.x > 0 and s.density.y > 0 then
|
||||
local k = if s.density.unit == 2 then 2.54 else 1
|
||||
meta.dpi = { x = s.density.x * k, y = s.density.y * k }
|
||||
end
|
||||
meta.truncated = s.truncated
|
||||
meta.source = {
|
||||
format = "jpeg",
|
||||
bitDepth = f.precision,
|
||||
colorType = space,
|
||||
components = #f.comps,
|
||||
progressive = f.progressive,
|
||||
arithmetic = f.arithmetic,
|
||||
sampling = samplingOf(f),
|
||||
scale = s.scale,
|
||||
adobe = s.adobe,
|
||||
jfif = s.jfif,
|
||||
avi1 = s.avi1,
|
||||
yuv = mode, -- "420" | "422" | "444" | "gray": how the yuv420p planes were made (opts.yuv)
|
||||
range = if mode then "full" else nil,
|
||||
fields = 1,
|
||||
}
|
||||
return img, s
|
||||
end
|
||||
|
||||
-- the start of a second JPEG (FF D8 FF) at or after p, before e; -1 if none
|
||||
local function nextSoi(buf: buffer, p: number, e: number): number
|
||||
local readu8 = buffer.readu8
|
||||
while p + 3 <= e do
|
||||
if readu8(buf, p) == 0xFF and readu8(buf, p + 1) == 0xD8 and readu8(buf, p + 2) == 0xFF then
|
||||
return p
|
||||
end
|
||||
p += 1
|
||||
end
|
||||
return -1
|
||||
end
|
||||
|
||||
-- two fields (same size and format) -> one frame of twice the height, field a on the even rows
|
||||
local function weave(a: Types.Image, b: Types.Image): Types.Image
|
||||
local w, hf = a.width, a.height
|
||||
local h = hf * 2
|
||||
local out = Types.Image.new(w, h, a.format)
|
||||
local dst = out.pixels
|
||||
if a.format == "yuv420p" then
|
||||
local cw, chf = (w + 1) // 2, (hf + 1) // 2
|
||||
local ch = (h + 1) // 2 -- = hf
|
||||
Yuv.weave(a.pixels, 0, b.pixels, 0, w, h, dst, 0)
|
||||
for k = 0, 1 do
|
||||
Yuv.weave(a.pixels, w * hf + k * cw * chf, b.pixels, w * hf + k * cw * chf, cw, ch, dst, w * h + k * cw * ch)
|
||||
end
|
||||
else
|
||||
local bpp = Types.Image.bpp(a.format) or 4
|
||||
Yuv.weave(a.pixels, 0, b.pixels, 0, w * bpp, h, dst, 0)
|
||||
end
|
||||
out.meta = a.meta
|
||||
return out
|
||||
end
|
||||
|
||||
-- decode(buf, off?, len?, opts?) -> Image | nil, Err: one JPEG (or one interlaced Motion-JPEG frame) in [off, off + len)
|
||||
function Jpeg.decode(buf: buffer, off: number?, len: number?, opts: DecodeOptions?): (Types.Image?, Err.Err?)
|
||||
if type(buf) ~= "buffer" then
|
||||
return nil, Err.new(Err.ARG, "expected a buffer")
|
||||
end
|
||||
if opts ~= nil and type(opts) ~= "table" then
|
||||
return nil, Err.new(Err.ARG, "options must be a table")
|
||||
end
|
||||
local o, l = range(buf, off, len)
|
||||
local img, st = decodeOne(buf, o, l, opts)
|
||||
if not img then
|
||||
return nil, st
|
||||
end
|
||||
local s = st :: Decode.State
|
||||
local wantFields = if opts and opts.fields ~= nil then opts.fields else (s.avi1 == 1 or s.avi1 == 2)
|
||||
if wantFields and not (opts and opts.orient) then
|
||||
local e = o + l
|
||||
local p = nextSoi(buf, s.endPos, e)
|
||||
if p >= 0 then
|
||||
local o2 = table.clone(opts or {}) :: any
|
||||
if o2.maxPixels then
|
||||
o2.maxPixels = math.max(0, o2.maxPixels - img.width * img.height)
|
||||
end
|
||||
local b = decodeOne(buf, p, e - p, o2)
|
||||
if b and b.width == img.width and b.height == img.height and b.format == img.format then
|
||||
local truncated = img.meta.truncated or b.meta.truncated
|
||||
img = weave(img, b)
|
||||
img.meta.truncated = truncated
|
||||
local source: any = img.meta.source
|
||||
source.fields = 2
|
||||
end
|
||||
end
|
||||
end
|
||||
return img, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
local BPP = { rgba8 = 4, rgb8 = 3, gray8 = 1, yuv420p = 0 }
|
||||
|
||||
-- encode(img, opts?) -> buffer | nil, Err: an rgba8 / rgb8 / gray8 / yuv420p Image as a baseline or progressive JPEG
|
||||
function Jpeg.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
if type(img) ~= "table" or type(img.pixels) ~= "buffer" or type(img.width) ~= "number" or type(img.height) ~= "number" then
|
||||
return nil, Err.new(Err.ARG, "needs an Image")
|
||||
end
|
||||
local bpp = BPP[img.format]
|
||||
if not bpp then
|
||||
return nil, Err.new(Err.ARG, "needs an rgba8, rgb8, gray8 or yuv420p Image (got " .. tostring(img.format) .. ")")
|
||||
end
|
||||
local w, h = img.width, img.height
|
||||
local need = if bpp == 0 then w * h + 2 * ((w + 1) // 2) * ((h + 1) // 2) else w * h * bpp
|
||||
if w < 1 or h < 1 or w > 65535 or h > 65535 or w % 1 ~= 0 or h % 1 ~= 0 or buffer.len(img.pixels) < need then
|
||||
return nil, Err.new(Err.ARG, "bad image size or pixel buffer (1..65535 per side)")
|
||||
end
|
||||
if opts ~= nil and type(opts) ~= "table" then
|
||||
return nil, Err.new(Err.ARG, "options must be a table")
|
||||
end
|
||||
local o: any = opts or {}
|
||||
local quality = o.quality or 90
|
||||
if type(quality) ~= "number" or quality < 1 or quality > 100 then
|
||||
return nil, Err.new(Err.ARG, "quality must be 1..100")
|
||||
end
|
||||
local sub = o.subsampling or "420"
|
||||
if sub ~= "420" and sub ~= "422" and sub ~= "444" then
|
||||
return nil, Err.new(Err.ARG, "subsampling must be \"420\", \"422\" or \"444\"")
|
||||
end
|
||||
if bpp == 0 then
|
||||
sub = "420"
|
||||
end
|
||||
local restart = o.restart or 0
|
||||
if type(restart) ~= "number" or restart < 0 or restart > 65535 or restart % 1 ~= 0 then
|
||||
return nil, Err.new(Err.ARG, "restart must be 0..65535 MCUs")
|
||||
end
|
||||
local gray = o.gray
|
||||
if gray == nil then
|
||||
gray = img.format == "gray8"
|
||||
end
|
||||
local segments = {}
|
||||
if o.segments ~= nil then
|
||||
if type(o.segments) ~= "table" then
|
||||
return nil, Err.new(Err.ARG, "segments must be a list of { marker, data }")
|
||||
end
|
||||
for _, sg in o.segments do
|
||||
if type(sg) ~= "table" or type(sg.data) ~= "buffer" or buffer.len(sg.data) > 65533 or type(sg.marker) ~= "number" then
|
||||
return nil, Err.new(Err.ARG, "bad segment (marker 0xE0..0xEF / 0xFE, at most 65533 bytes)")
|
||||
end
|
||||
if not ((sg.marker >= 0xE0 and sg.marker <= 0xEF) or sg.marker == 0xFE) then
|
||||
return nil, Err.new(Err.ARG, "bad segment marker (0xE0..0xEF / 0xFE)")
|
||||
end
|
||||
table.insert(segments, sg)
|
||||
end
|
||||
end
|
||||
local density = o.density
|
||||
if density ~= nil then
|
||||
if type(density) ~= "table" or type(density.unit) ~= "number" or type(density.x) ~= "number" or type(density.y) ~= "number" then
|
||||
return nil, Err.new(Err.ARG, "bad density")
|
||||
end
|
||||
density = {
|
||||
unit = math.clamp(math.floor(density.unit), 0, 2),
|
||||
x = math.clamp(math.floor(density.x), 1, 65535),
|
||||
y = math.clamp(math.floor(density.y), 1, 65535),
|
||||
}
|
||||
end
|
||||
local out = Encode.run(img.pixels, w, h, bpp, {
|
||||
quality = quality,
|
||||
sampling = sub,
|
||||
progressive = o.progressive == true,
|
||||
optimize = o.optimize == true,
|
||||
gray = gray,
|
||||
restart = restart,
|
||||
segments = segments,
|
||||
jfif = o.jfif ~= false,
|
||||
density = density,
|
||||
})
|
||||
return out, nil
|
||||
end
|
||||
|
||||
return Jpeg
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,117 @@
|
||||
--!strict
|
||||
-- codecs/Mpeg1/Tables: the constant tables of jsmpeg's MPEG-1 video decoder (https://github.com/phoboslab/jsmpeg,
|
||||
-- Dominic Szablewski, MIT, licenses/jsmpeg-MIT.txt), generated by mpeg1-luau's tools/gen_tables.py (absorbed from
|
||||
-- mpeg1-luau e2e2898). Lists are 0-based like the JS arrays.
|
||||
local T = {}
|
||||
T.PICTURE_RATE = { [0] = 0.0,
|
||||
23.976, 24.0, 25.0, 29.97, 30.0, 50.0, 59.94, 60.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
|
||||
}
|
||||
T.ZIG_ZAG = { [0] = 0,
|
||||
1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27,
|
||||
20, 13, 6, 7, 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51, 58,
|
||||
59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63,
|
||||
}
|
||||
T.DEFAULT_INTRA_QUANT_MATRIX = { [0] = 8,
|
||||
16, 19, 22, 26, 27, 29, 34, 16, 16, 22, 24, 27, 29, 34, 37, 19, 22, 26, 27, 29, 34, 34, 38, 22,
|
||||
22, 26, 27, 29, 34, 37, 40, 22, 26, 27, 29, 32, 35, 40, 48, 26, 27, 29, 32, 35, 40, 48, 58, 26,
|
||||
27, 29, 34, 38, 46, 56, 69, 27, 29, 35, 38, 46, 56, 69, 83,
|
||||
}
|
||||
T.DEFAULT_NON_INTRA_QUANT_MATRIX = { [0] = 16,
|
||||
16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,
|
||||
16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,
|
||||
16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,
|
||||
}
|
||||
T.MACROBLOCK_ADDRESS_INCREMENT = { [0] = 3,
|
||||
6, 0, 9, 12, 0, 0, 0, 1, 15, 18, 0, 21, 24, 0, 27, 30, 0, 33, 36, 0, 0, 0, 3, 0,
|
||||
0, 2, 39, 42, 0, 45, 48, 0, 0, 0, 5, 0, 0, 4, 51, 54, 0, 57, 60, 0, 0, 0, 7, 0,
|
||||
0, 6, 63, 66, 0, 69, 72, 0, 75, 78, 0, 81, 84, 0, -1, 87, 0, -1, 90, 0, 93, 96, 0, 99,
|
||||
102, 0, 105, 108, 0, 111, 114, 0, 0, 0, 9, 0, 0, 8, 117, 120, 0, 123, 126, 0, 129, 132, 0, 135,
|
||||
138, 0, 0, 0, 15, 0, 0, 14, 0, 0, 13, 0, 0, 12, 0, 0, 11, 0, 0, 10, 141, -1, 0, -1,
|
||||
144, 0, 147, 150, 0, 153, 156, 0, 159, 162, 0, 165, 168, 0, 171, 174, 0, 177, 180, 0, 183, -1, 0, -1,
|
||||
186, 0, 189, 192, 0, 195, 198, 0, 201, 204, 0, 207, 210, 0, 213, 216, 0, 219, 222, 0, 0, 0, 21, 0,
|
||||
0, 20, 0, 0, 19, 0, 0, 18, 0, 0, 17, 0, 0, 16, 0, 0, 35, 0, 0, 34, 0, 0, 33, 0,
|
||||
0, 32, 0, 0, 31, 0, 0, 30, 0, 0, 29, 0, 0, 28, 0, 0, 27, 0, 0, 26, 0, 0, 25, 0,
|
||||
0, 24, 0, 0, 23, 0, 0, 22,
|
||||
}
|
||||
T.MACROBLOCK_TYPE_INTRA = { [0] = 3,
|
||||
6, 0, -1, 9, 0, 0, 0, 1, 0, 0, 17,
|
||||
}
|
||||
T.MACROBLOCK_TYPE_PREDICTIVE = { [0] = 3,
|
||||
6, 0, 9, 12, 0, 0, 0, 10, 15, 18, 0, 0, 0, 2, 21, 24, 0, 0, 0, 8, 27, 30, 0, 33,
|
||||
36, 0, -1, 39, 0, 0, 0, 18, 0, 0, 26, 0, 0, 1, 0, 0, 17,
|
||||
}
|
||||
T.MACROBLOCK_TYPE_B = { [0] = 3,
|
||||
6, 0, 9, 15, 0, 12, 18, 0, 24, 21, 0, 0, 0, 12, 27, 30, 0, 0, 0, 14, 39, 42, 0, 36,
|
||||
33, 0, 0, 0, 4, 0, 0, 6, 54, 48, 0, 45, 51, 0, 0, 0, 8, 0, 0, 10, -1, 57, 0, 0,
|
||||
0, 1, 60, 63, 0, 0, 0, 30, 0, 0, 17, 0, 0, 22, 0, 0, 26,
|
||||
}
|
||||
T.CODE_BLOCK_PATTERN = { [0] = 6,
|
||||
3, 0, 9, 18, 0, 12, 15, 0, 24, 33, 0, 36, 39, 0, 27, 21, 0, 30, 42, 0, 60, 57, 0, 54,
|
||||
48, 0, 69, 51, 0, 81, 75, 0, 63, 84, 0, 45, 66, 0, 72, 78, 0, 0, 0, 60, 105, 120, 0, 132,
|
||||
144, 0, 114, 108, 0, 126, 141, 0, 87, 93, 0, 117, 96, 0, 0, 0, 32, 135, 138, 0, 99, 123, 0, 129,
|
||||
102, 0, 0, 0, 4, 90, 111, 0, 0, 0, 8, 0, 0, 16, 0, 0, 44, 150, 168, 0, 0, 0, 28, 0,
|
||||
0, 52, 0, 0, 62, 183, 177, 0, 156, 180, 0, 0, 0, 1, 165, 162, 0, 0, 0, 61, 0, 0, 56, 171,
|
||||
174, 0, 0, 0, 2, 0, 0, 40, 153, 186, 0, 0, 0, 48, 192, 189, 0, 147, 159, 0, 0, 0, 20, 0,
|
||||
0, 12, 240, 249, 0, 0, 0, 63, 231, 225, 0, 195, 219, 0, 252, 198, 0, 0, 0, 24, 0, 0, 36, 0,
|
||||
0, 3, 207, 261, 0, 243, 237, 0, 204, 213, 0, 210, 234, 0, 201, 228, 0, 216, 222, 0, 258, 255, 0, 264,
|
||||
246, 0, -1, 282, 0, 285, 291, 0, 0, 0, 33, 0, 0, 9, 318, 330, 0, 306, 348, 0, 0, 0, 5, 0,
|
||||
0, 10, 279, 267, 0, 0, 0, 6, 0, 0, 18, 0, 0, 17, 0, 0, 34, 339, 357, 0, 309, 312, 0, 270,
|
||||
276, 0, 327, 321, 0, 351, 354, 0, 303, 297, 0, 294, 288, 0, 300, 273, 0, 342, 345, 0, 315, 324, 0, 336,
|
||||
333, 0, 363, 375, 0, 0, 0, 41, 0, 0, 14, 0, 0, 21, 372, 366, 0, 360, 369, 0, 0, 0, 11, 0,
|
||||
0, 19, 0, 0, 7, 0, 0, 35, 0, 0, 13, 0, 0, 50, 0, 0, 49, 0, 0, 58, 0, 0, 37, 0,
|
||||
0, 25, 0, 0, 45, 0, 0, 57, 0, 0, 26, 0, 0, 29, 0, 0, 38, 0, 0, 53, 0, 0, 23, 0,
|
||||
0, 43, 0, 0, 46, 0, 0, 42, 0, 0, 22, 0, 0, 54, 0, 0, 51, 0, 0, 15, 0, 0, 30, 0,
|
||||
0, 39, 0, 0, 47, 0, 0, 55, 0, 0, 27, 0, 0, 59, 0, 0, 31,
|
||||
}
|
||||
T.MOTION = { [0] = 3,
|
||||
6, 0, 12, 9, 0, 0, 0, 0, 18, 15, 0, 24, 21, 0, 0, 0, -1, 0, 0, 1, 27, 30, 0, 36,
|
||||
33, 0, 0, 0, 2, 0, 0, -2, 42, 45, 0, 48, 39, 0, 60, 54, 0, 0, 0, 3, 0, 0, -3, 51,
|
||||
57, 0, -1, 69, 0, 81, 75, 0, 78, 63, 0, 72, 66, 0, 96, 84, 0, 87, 93, 0, -1, 99, 0, 108,
|
||||
105, 0, 0, 0, -4, 90, 102, 0, 0, 0, 4, 0, 0, -7, 0, 0, 5, 111, 123, 0, 0, 0, -5, 0,
|
||||
0, 7, 114, 120, 0, 126, 117, 0, 0, 0, -6, 0, 0, 6, 153, 162, 0, 150, 147, 0, 135, 138, 0, 156,
|
||||
141, 0, 129, 159, 0, 132, 144, 0, 0, 0, 10, 0, 0, 9, 0, 0, 8, 0, 0, -8, 171, 198, 0, 0,
|
||||
0, -9, 180, 192, 0, 168, 183, 0, 165, 186, 0, 174, 189, 0, 0, 0, -10, 177, 195, 0, 0, 0, 12, 0,
|
||||
0, 16, 0, 0, 13, 0, 0, 14, 0, 0, 11, 0, 0, 15, 0, 0, -16, 0, 0, -12, 0, 0, -14, 0,
|
||||
0, -15, 0, 0, -11, 0, 0, -13,
|
||||
}
|
||||
T.DCT_DC_SIZE_LUMINANCE = { [0] = 6,
|
||||
3, 0, 18, 15, 0, 9, 12, 0, 0, 0, 1, 0, 0, 2, 27, 24, 0, 21, 30, 0, 0, 0, 0, 36,
|
||||
33, 0, 0, 0, 4, 0, 0, 3, 39, 42, 0, 0, 0, 5, 0, 0, 6, 48, 45, 0, 51, -1, 0, 0,
|
||||
0, 7, 0, 0, 8,
|
||||
}
|
||||
T.DCT_DC_SIZE_CHROMINANCE = { [0] = 6,
|
||||
3, 0, 12, 9, 0, 18, 15, 0, 24, 21, 0, 0, 0, 2, 0, 0, 1, 0, 0, 0, 30, 27, 0, 0,
|
||||
0, 3, 36, 33, 0, 0, 0, 4, 42, 39, 0, 0, 0, 5, 48, 45, 0, 0, 0, 6, 51, -1, 0, 0,
|
||||
0, 7, 0, 0, 8,
|
||||
}
|
||||
T.DCT_COEFF = { [0] = 3,
|
||||
6, 0, 12, 9, 0, 0, 0, 1, 21, 24, 0, 18, 15, 0, 39, 27, 0, 33, 30, 0, 42, 36, 0, 0,
|
||||
0, 257, 60, 66, 0, 54, 63, 0, 48, 57, 0, 0, 0, 513, 51, 45, 0, 0, 0, 2, 0, 0, 3, 81,
|
||||
75, 0, 87, 93, 0, 72, 78, 0, 96, 90, 0, 0, 0, 1025, 69, 84, 0, 0, 0, 769, 0, 0, 258, 0,
|
||||
0, 1793, 0, 0, 65535, 0, 0, 1537, 111, 108, 0, 0, 0, 1281, 105, 102, 0, 117, 114, 0, 99, 126, 0, 120,
|
||||
123, 0, 156, 150, 0, 162, 159, 0, 144, 147, 0, 129, 135, 0, 138, 132, 0, 0, 0, 2049, 0, 0, 4, 0,
|
||||
0, 514, 0, 0, 2305, 153, 141, 0, 165, 171, 0, 180, 168, 0, 177, 174, 0, 183, 186, 0, 0, 0, 2561, 0,
|
||||
0, 3329, 0, 0, 6, 0, 0, 259, 0, 0, 5, 0, 0, 770, 0, 0, 2817, 0, 0, 3073, 228, 225, 0, 201,
|
||||
210, 0, 219, 213, 0, 234, 222, 0, 216, 231, 0, 207, 192, 0, 204, 189, 0, 198, 195, 0, 243, 261, 0, 273,
|
||||
240, 0, 246, 237, 0, 249, 258, 0, 279, 276, 0, 252, 255, 0, 270, 282, 0, 264, 267, 0, 0, 0, 515, 0,
|
||||
0, 260, 0, 0, 7, 0, 0, 1026, 0, 0, 1282, 0, 0, 4097, 0, 0, 3841, 0, 0, 3585, 315, 321, 0, 333,
|
||||
342, 0, 312, 291, 0, 375, 357, 0, 288, 294, 0, -1, 369, 0, 285, 303, 0, 318, 363, 0, 297, 306, 0, 339,
|
||||
309, 0, 336, 348, 0, 330, 300, 0, 372, 345, 0, 351, 366, 0, 327, 354, 0, 360, 324, 0, 381, 408, 0, 417,
|
||||
420, 0, 390, 378, 0, 435, 438, 0, 384, 387, 0, 0, 0, 2050, 396, 402, 0, 465, 462, 0, 0, 0, 8, 411,
|
||||
399, 0, 429, 432, 0, 453, 414, 0, 426, 423, 0, 0, 0, 10, 0, 0, 9, 0, 0, 11, 0, 0, 5377, 0,
|
||||
0, 1538, 0, 0, 771, 0, 0, 5121, 0, 0, 1794, 0, 0, 4353, 0, 0, 4609, 0, 0, 4865, 444, 456, 0, 0,
|
||||
0, 1027, 459, 450, 0, 0, 0, 261, 393, 405, 0, 0, 0, 516, 447, 441, 0, 516, 519, 0, 486, 474, 0, 510,
|
||||
483, 0, 504, 498, 0, 471, 537, 0, 507, 501, 0, 522, 513, 0, 534, 531, 0, 468, 477, 0, 492, 495, 0, 549,
|
||||
546, 0, 525, 528, 0, 0, 0, 263, 0, 0, 2562, 0, 0, 2306, 0, 0, 5633, 0, 0, 5889, 0, 0, 6401, 0,
|
||||
0, 6145, 0, 0, 1283, 0, 0, 772, 0, 0, 13, 0, 0, 12, 0, 0, 14, 0, 0, 15, 0, 0, 517, 0,
|
||||
0, 6657, 0, 0, 262, 540, 543, 0, 480, 489, 0, 588, 597, 0, 0, 0, 27, 609, 555, 0, 606, 603, 0, 0,
|
||||
0, 19, 0, 0, 22, 591, 621, 0, 0, 0, 18, 573, 576, 0, 564, 570, 0, 0, 0, 20, 552, 582, 0, 0,
|
||||
0, 21, 558, 579, 0, 0, 0, 23, 612, 594, 0, 0, 0, 25, 0, 0, 24, 600, 615, 0, 0, 0, 31, 0,
|
||||
0, 30, 0, 0, 28, 0, 0, 29, 0, 0, 26, 0, 0, 17, 0, 0, 16, 567, 618, 0, 561, 585, 0, 654,
|
||||
633, 0, 0, 0, 37, 645, 648, 0, 0, 0, 36, 630, 636, 0, 0, 0, 34, 639, 627, 0, 663, 666, 0, 657,
|
||||
624, 0, 651, 642, 0, 669, 660, 0, 0, 0, 35, 0, 0, 267, 0, 0, 40, 0, 0, 268, 0, 0, 266, 0,
|
||||
0, 32, 0, 0, 264, 0, 0, 265, 0, 0, 38, 0, 0, 269, 0, 0, 270, 0, 0, 33, 0, 0, 39, 0,
|
||||
0, 7937, 0, 0, 6913, 0, 0, 7681, 0, 0, 4098, 0, 0, 7425, 0, 0, 7169, 0, 0, 271, 0, 0, 274, 0,
|
||||
0, 273, 0, 0, 272, 0, 0, 1539, 0, 0, 2818, 0, 0, 3586, 0, 0, 3330, 0, 0, 3074, 0, 0, 3842,
|
||||
}
|
||||
return T
|
||||
@@ -0,0 +1,116 @@
|
||||
--!strict
|
||||
-- codecs/Mpeg1/Vlc: lookup tables for the MPEG-1 variable-length codes, built at load time from jsmpeg's binary trees (Tables.luau).
|
||||
--
|
||||
-- A flat table is indexed by the next K bits of the stream (K = the longest code) and holds
|
||||
-- len * 65536 + (value + 32768) per entry; len = 0 marks an invalid code. The DCT coefficient tables are two-level
|
||||
-- (8 bits, then 8 more for the long codes) and hold len * 65536 + value, value = run * 256 + level, ESC = 0xFFFF,
|
||||
-- EOB = 0xFFFE, or SUB + subtable for a long-code prefix. DCT_NEXT is the table for every coefficient after the
|
||||
-- first one of a block, where "10" is end_of_block and "11" is run 0 / level 1 (jsmpeg reads this as "1" and one
|
||||
-- more bit); DCT_FIRST keeps "1" as run 0 / level 1. Absorbed from mpeg1-luau e2e2898 (same author), unchanged but
|
||||
-- for this header and the require.
|
||||
local T = require("@formats/codecs/Mpeg1/Tables")
|
||||
|
||||
local V = {}
|
||||
|
||||
type Leaf = { code: number, len: number, value: number }
|
||||
|
||||
local function leaves(tree: { [number]: number }): { Leaf }
|
||||
local out: { Leaf } = {}
|
||||
local function walk(state: number, code: number, len: number)
|
||||
if tree[state] == 0 and len > 0 then
|
||||
table.insert(out, { code = code, len = len, value = tree[state + 2] })
|
||||
return
|
||||
end
|
||||
for bit = 0, 1 do
|
||||
local nxt = tree[state + bit]
|
||||
if nxt ~= nil and nxt > 0 then
|
||||
walk(nxt, code * 2 + bit, len + 1)
|
||||
end
|
||||
end
|
||||
end
|
||||
walk(0, 0, 0)
|
||||
return out
|
||||
end
|
||||
|
||||
local function flat(tree: { [number]: number }): (buffer, number)
|
||||
local ls = leaves(tree)
|
||||
local k = 0
|
||||
for _, l in ls do
|
||||
k = math.max(k, l.len)
|
||||
end
|
||||
local lut = buffer.create(4 * 2 ^ k)
|
||||
for _, l in ls do
|
||||
local shift = k - l.len
|
||||
local first = l.code * 2 ^ shift
|
||||
for i = first, first + 2 ^ shift - 1 do
|
||||
buffer.writeu32(lut, i * 4, l.len * 65536 + l.value + 32768)
|
||||
end
|
||||
end
|
||||
return lut, k
|
||||
end
|
||||
|
||||
V.SUB = 0x1000000
|
||||
V.ESC = 0xFFFF
|
||||
V.EOB = 0xFFFE
|
||||
|
||||
-- two-level table: 256 first-level entries, then 256-entry subtables for prefixes of codes longer than 8 bits
|
||||
local function twoLevel(ls: { Leaf }): buffer
|
||||
local subs: { [number]: number } = {}
|
||||
local nsub = 0
|
||||
for _, l in ls do
|
||||
if l.len > 8 then
|
||||
local prefix = l.code // 2 ^ (l.len - 8)
|
||||
if subs[prefix] == nil then
|
||||
nsub += 1
|
||||
subs[prefix] = nsub
|
||||
end
|
||||
end
|
||||
end
|
||||
local lut = buffer.create(4 * 256 * (1 + nsub))
|
||||
for _, l in ls do
|
||||
if l.len <= 8 then
|
||||
local shift = 8 - l.len
|
||||
local first = l.code * 2 ^ shift
|
||||
for i = first, first + 2 ^ shift - 1 do
|
||||
buffer.writeu32(lut, i * 4, l.len * 65536 + l.value)
|
||||
end
|
||||
else
|
||||
local prefix = l.code // 2 ^ (l.len - 8)
|
||||
local s = subs[prefix]
|
||||
buffer.writeu32(lut, prefix * 4, V.SUB + s)
|
||||
local rest = l.code % 2 ^ (l.len - 8)
|
||||
local shift = 16 - l.len
|
||||
local first = rest * 2 ^ shift
|
||||
for i = first, first + 2 ^ shift - 1 do
|
||||
buffer.writeu32(lut, (s * 256 + i) * 4, l.len * 65536 + l.value)
|
||||
end
|
||||
end
|
||||
end
|
||||
return lut
|
||||
end
|
||||
|
||||
V.MBAI, V.MBAI_BITS = flat(T.MACROBLOCK_ADDRESS_INCREMENT) -- 34 = stuffing, 35 = escape
|
||||
V.MBTYPE_I, V.MBTYPE_I_BITS = flat(T.MACROBLOCK_TYPE_INTRA)
|
||||
V.MBTYPE_P, V.MBTYPE_P_BITS = flat(T.MACROBLOCK_TYPE_PREDICTIVE)
|
||||
V.MBTYPE_B, V.MBTYPE_B_BITS = flat(T.MACROBLOCK_TYPE_B)
|
||||
V.CBP, V.CBP_BITS = flat(T.CODE_BLOCK_PATTERN)
|
||||
V.MOTION, V.MOTION_BITS = flat(T.MOTION)
|
||||
V.DC_LUMA, V.DC_LUMA_BITS = flat(T.DCT_DC_SIZE_LUMINANCE)
|
||||
V.DC_CHROMA, V.DC_CHROMA_BITS = flat(T.DCT_DC_SIZE_CHROMINANCE)
|
||||
|
||||
do
|
||||
local ls = leaves(T.DCT_COEFF)
|
||||
V.DCT_FIRST = twoLevel(ls)
|
||||
local nextLs: { Leaf } = {}
|
||||
for _, l in ls do
|
||||
if l.len == 1 and l.code == 1 then
|
||||
table.insert(nextLs, { code = 2, len = 2, value = V.EOB }) -- "10"
|
||||
table.insert(nextLs, { code = 3, len = 2, value = 0x0001 }) -- "11"
|
||||
else
|
||||
table.insert(nextLs, l)
|
||||
end
|
||||
end
|
||||
V.DCT_NEXT = twoLevel(nextLs)
|
||||
end
|
||||
|
||||
return V
|
||||
@@ -0,0 +1,262 @@
|
||||
--!strict
|
||||
-- codecs/Mpeg1: an MPEG-1 video decoder (ISO/IEC 11172-2) for the MPEG-TS / MPEG-PS video formats. Absorbed from
|
||||
-- mpeg1-luau e2e2898 (same author; README, docs/api.md and docs/performance.md there), a port of jsmpeg's decoder
|
||||
-- (https://github.com/phoboslab/jsmpeg, Dominic Szablewski, MIT: licenses/jsmpeg-MIT.txt) extended with B-pictures,
|
||||
-- an islow integer IDCT, table-driven VLC decoding and BT.601 RGBA8 output; added here: frameImage.
|
||||
-- Supports: I, P and B pictures (D-pictures skipped), half / full-pel motion vectors with any f_code, custom
|
||||
-- quantiser matrices, sequence headers anywhere (size changes), any size up to 4095 x 4095 (maxPixels), display
|
||||
-- reordering. Accuracy: within ~0.75 MAE per RGBA channel of ffmpeg's decode (tests/codecs/mpeg1.luau).
|
||||
-- Not supported: MPEG-2 streams (no picture coding extension parsing), field pictures, D-picture decoding.
|
||||
--
|
||||
-- local dec = Mpeg1.new({ reorder = true, rgba = false })
|
||||
-- local frame = dec:decode(packetData, 0, len, pts) -- one picture (+ sequence / GOP headers) -> Frame?, tag = pts
|
||||
-- local img = Mpeg1.frameImage(frame) -- a fresh yuv420p Types.Image (rgba8 with frameImage(f, true))
|
||||
-- dec:write(bytes); local f = dec:decodeFrame() -- or an elementary stream in pieces
|
||||
-- while true do local f = dec:flush(); if not f then break end end -- at the end; dec:reset() after a seek
|
||||
-- -- frame = { width, height, pixels (RGBA8 or nil, decoder-owned), y / cb / cr / codedWidth, pictureType, ... }
|
||||
--
|
||||
-- Nothing here throws: bad arguments return nil / false, bad data is skipped (see Decoder.luau).
|
||||
local Types = require("@formats/Types")
|
||||
local D = require("@formats/codecs/Mpeg1/Decoder")
|
||||
|
||||
local Mpeg1 = {}
|
||||
|
||||
Mpeg1.PICTURE_I = 1
|
||||
Mpeg1.PICTURE_P = 2
|
||||
Mpeg1.PICTURE_B = 3
|
||||
|
||||
export type Frame = {
|
||||
width: number,
|
||||
height: number,
|
||||
pixels: buffer?, -- RGBA8, width * height * 4 bytes, row-major, alpha 255; nil with { rgba = false }
|
||||
pictureType: number, -- 1 I, 2 P, 3 B
|
||||
temporalReference: number, -- the picture's 10-bit display index within its GOP
|
||||
index: number, -- frames returned so far (1-based)
|
||||
tag: any, -- the tag passed to decode() with this picture's data (follows the picture through reordering)
|
||||
-- the decoded YCbCr 4:2:0 planes (decoder-owned, valid until the next decode): luma stride codedWidth,
|
||||
-- chroma stride codedWidth / 2
|
||||
y: buffer,
|
||||
cb: buffer,
|
||||
cr: buffer,
|
||||
codedWidth: number,
|
||||
}
|
||||
|
||||
export type Options = {
|
||||
reorder: boolean?, -- true: return frames in display order (B-frame streams; one frame of delay, flush() at the
|
||||
-- end). Default false: every picture is returned as soon as it is decoded (decode order, no delay), which is
|
||||
-- display order for streams without B-frames.
|
||||
rgba: boolean?, -- default true; false skips the RGBA conversion (use frame.y / cb / cr)
|
||||
maxPixels: number?, -- larger sequence headers are rejected (default 4096 * 2304)
|
||||
}
|
||||
|
||||
local Decoder = {}
|
||||
Decoder.__index = Decoder
|
||||
|
||||
export type Decoder = typeof(setmetatable(
|
||||
{} :: {
|
||||
_core: D.Core,
|
||||
_reorder: boolean,
|
||||
_rgba: boolean,
|
||||
_held: D.Store?,
|
||||
_pixels: buffer?,
|
||||
_count: number,
|
||||
width: number,
|
||||
height: number,
|
||||
frameRate: number,
|
||||
bitRate: number,
|
||||
stats: { pictures: number, errors: number, skipped: number },
|
||||
},
|
||||
Decoder
|
||||
))
|
||||
|
||||
function Mpeg1.new(opts: Options?): Decoder
|
||||
local o: Options = if type(opts) == "table" then opts else {}
|
||||
local core = D.new(o.maxPixels)
|
||||
return setmetatable({
|
||||
_core = core,
|
||||
_reorder = o.reorder == true,
|
||||
_rgba = o.rgba ~= false,
|
||||
_held = nil,
|
||||
_pixels = nil,
|
||||
_count = 0,
|
||||
width = 0,
|
||||
height = 0,
|
||||
frameRate = 0,
|
||||
bitRate = 0,
|
||||
stats = { pictures = 0, errors = 0, skipped = 0 },
|
||||
}, Decoder)
|
||||
end
|
||||
|
||||
local function emit(self: Decoder, s: D.Store): Frame
|
||||
local core = self._core
|
||||
local pixels: buffer? = nil
|
||||
if self._rgba then
|
||||
local need = s.w * s.h * 4
|
||||
local px = self._pixels
|
||||
if px == nil or buffer.len(px) ~= need then
|
||||
px = buffer.create(need)
|
||||
self._pixels = px
|
||||
end
|
||||
core.toRgba(s, px :: buffer)
|
||||
pixels = px
|
||||
end
|
||||
self._count += 1
|
||||
return {
|
||||
width = s.w,
|
||||
height = s.h,
|
||||
pixels = pixels,
|
||||
pictureType = s.ptype,
|
||||
temporalReference = s.tref,
|
||||
index = self._count,
|
||||
tag = s.tag,
|
||||
y = s.y,
|
||||
cb = s.cb,
|
||||
cr = s.cr,
|
||||
codedWidth = s.cw,
|
||||
}
|
||||
end
|
||||
|
||||
local function sync(self: Decoder)
|
||||
local st = self._core.state
|
||||
self.width = st.width
|
||||
self.height = st.height
|
||||
self.frameRate = st.frameRate
|
||||
self.bitRate = st.bitRate
|
||||
self.stats.pictures = st.pictures
|
||||
self.stats.errors = st.errors
|
||||
self.stats.skipped = st.skipped
|
||||
end
|
||||
|
||||
-- a decoded picture -> the frame to return now (nil while reordering holds it)
|
||||
local function handle(self: Decoder, s: D.Store): Frame?
|
||||
if not self._reorder or s.ptype == D.PICTURE_B then
|
||||
return emit(self, s)
|
||||
end
|
||||
local prev = self._held
|
||||
self._held = s
|
||||
if prev then
|
||||
return emit(self, prev)
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
local function run(self: Decoder, atEnd: boolean, tag: any): Frame?
|
||||
local core = self._core
|
||||
while true do
|
||||
local s, needData = core.nextPicture(atEnd, tag)
|
||||
sync(self)
|
||||
if s then
|
||||
local f = handle(self, s)
|
||||
if f then
|
||||
return f
|
||||
end
|
||||
elseif needData then
|
||||
return nil
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
local function append(self: Decoder, data: any, offset: number?, len: number?): boolean
|
||||
local src: buffer
|
||||
if type(data) == "string" then
|
||||
src = buffer.fromstring(data)
|
||||
elseif type(data) == "buffer" then
|
||||
src = data
|
||||
else
|
||||
return false
|
||||
end
|
||||
local total = buffer.len(src)
|
||||
local off = math.floor(tonumber(offset) or 0)
|
||||
if off < 0 or off > total then
|
||||
return false
|
||||
end
|
||||
local n = math.floor(tonumber(len) or (total - off))
|
||||
if n < 0 or off + n > total then
|
||||
return false
|
||||
end
|
||||
self._core.write(src, off, n)
|
||||
return true
|
||||
end
|
||||
|
||||
-- Appends elementary-stream bytes (buffer or string; offset / len select a part). False for a bad argument.
|
||||
function Decoder.write(self: Decoder, data: buffer | string, offset: number?, len: number?): boolean
|
||||
return append(self, data, offset, len)
|
||||
end
|
||||
|
||||
-- The next complete picture of the written stream as a frame, or nil when more data is needed (a picture is
|
||||
-- complete once the next picture / sequence / GOP start code has been written; flush() ends the last one).
|
||||
function Decoder.decodeFrame(self: Decoder): Frame?
|
||||
return run(self, false, nil)
|
||||
end
|
||||
|
||||
-- Decodes one access unit (a picture, optionally preceded by sequence / GOP headers: a TS video unit's data).
|
||||
-- The end of the data ends the picture. tag (any value, e.g. the unit's pts) comes back as frame.tag.
|
||||
function Decoder.decode(self: Decoder, data: buffer | string, offset: number?, len: number?, tag: any): Frame?
|
||||
if not append(self, data, offset, len) then
|
||||
return nil
|
||||
end
|
||||
return run(self, true, tag)
|
||||
end
|
||||
|
||||
-- At the end of the stream: decodes what is left of the written data, then returns the reference picture held
|
||||
-- for reordering. Call until it returns nil.
|
||||
function Decoder.flush(self: Decoder): Frame?
|
||||
local f = run(self, true, nil)
|
||||
if f then
|
||||
return f
|
||||
end
|
||||
local held = self._held
|
||||
if held then
|
||||
self._held = nil
|
||||
return emit(self, held)
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
-- Forgets buffered data and references (after a seek: the next picture decoded is the next I-picture).
|
||||
function Decoder.reset(self: Decoder)
|
||||
self._core.reset()
|
||||
self._held = nil
|
||||
end
|
||||
|
||||
-- frameImage(frame, rgba?) -> Types.Image: a copy of a decoded frame (the decoder reuses its planes), cropped to
|
||||
-- width x height: yuv420p from frame.y / cb / cr (BT.601 limited range, meta.source.range = "limited"), or rgba8
|
||||
-- (the decoder's BT.601 conversion) when rgba is true. nil for a value that is not a Frame.
|
||||
function Mpeg1.frameImage(frame: Frame, rgba: boolean?): Types.Image?
|
||||
if type(frame) ~= "table" or type(frame.y) ~= "buffer" or type(frame.cb) ~= "buffer" or type(frame.cr) ~= "buffer" then
|
||||
return nil
|
||||
end
|
||||
local w, h, cw = frame.width, frame.height, frame.codedWidth
|
||||
if type(w) ~= "number" or type(h) ~= "number" or type(cw) ~= "number" or w < 1 or h < 1 or cw < w then
|
||||
return nil
|
||||
end
|
||||
local chw, ow, oh = cw // 2, (w + 1) // 2, (h + 1) // 2
|
||||
if buffer.len(frame.y) < cw * h or buffer.len(frame.cb) < chw * oh or buffer.len(frame.cr) < chw * oh then
|
||||
return nil
|
||||
end
|
||||
local img
|
||||
if rgba then
|
||||
img = Types.Image.new(w, h)
|
||||
D.toRgba(frame.y, frame.cb, frame.cr, cw, w, h, img.pixels)
|
||||
else
|
||||
img = Types.Image.new(w, h, "yuv420p")
|
||||
local px = img.pixels
|
||||
for y = 0, h - 1 do
|
||||
buffer.copy(px, y * w, frame.y, y * cw, w)
|
||||
end
|
||||
local o = w * h
|
||||
for y = 0, oh - 1 do
|
||||
buffer.copy(px, o + y * ow, frame.cb, y * chw, ow)
|
||||
buffer.copy(px, o + ow * oh + y * ow, frame.cr, y * chw, ow)
|
||||
end
|
||||
end
|
||||
img.meta.source = {
|
||||
format = "mpeg1",
|
||||
pictureType = frame.pictureType,
|
||||
temporalReference = frame.temporalReference,
|
||||
range = if rgba then nil else "limited",
|
||||
}
|
||||
return img
|
||||
end
|
||||
|
||||
return Mpeg1
|
||||
@@ -0,0 +1,305 @@
|
||||
--!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
|
||||
|
||||
-- rational(fps) -> num, den: integer rates as n / 1, NTSC rates as n * 1000 / 1001, else to a millisecond
|
||||
function Source.rational(fps: number): (number, number)
|
||||
if fps ~= fps or fps <= 0 then
|
||||
return 25, 1
|
||||
end
|
||||
if math.abs(fps - math.floor(fps + 0.5)) < 1e-6 then
|
||||
return math.floor(fps + 0.5), 1
|
||||
end
|
||||
local ntsc = fps * 1001 / 1000
|
||||
if math.abs(ntsc - math.floor(ntsc + 0.5)) < 1e-4 then
|
||||
return math.floor(ntsc + 0.5) * 1000, 1001
|
||||
end
|
||||
return math.floor(fps * 1000 + 0.5), 1000
|
||||
end
|
||||
|
||||
-- constantRate(stream, maxFps?) -> num, den, { OutPacket }: a video stream at a constant frame rate for the
|
||||
-- containers that have one (AVI, Y4M): the rate of the shortest frame (at most maxFps, default 100), each packet
|
||||
-- repeated to fill its duration (a GIF's 100 / 50 / 200 ms frames become 2, 1 and 4 frames at 20 fps)
|
||||
function Source.constantRate(s: Stream, maxFps: number?): (number, number, { OutPacket })
|
||||
local fd = math.huge
|
||||
for _, p in s.packets do
|
||||
if p.duration and p.duration > 0 and p.duration < fd then
|
||||
fd = p.duration
|
||||
end
|
||||
end
|
||||
if fd == math.huge then
|
||||
fd = if s.frameRate and s.frameRate > 0 then 1 / s.frameRate else 0.04
|
||||
end
|
||||
fd = math.max(fd, 1 / (maxFps or 100))
|
||||
local num, den = Source.rational(1 / fd)
|
||||
local step = den / num
|
||||
local out: { OutPacket } = {}
|
||||
local slots = 0
|
||||
local t0 = if s.packets[1] then s.packets[1].pts else 0
|
||||
for _, p in s.packets do
|
||||
local stop = p.pts - t0 + (if p.duration and p.duration > 0 then p.duration else step)
|
||||
local n = math.max(1, math.floor(stop / step + 0.5) - slots)
|
||||
for _ = 1, n do
|
||||
table.insert(out, { pts = t0 + slots * step, duration = step, keyframe = p.keyframe, data = p.data })
|
||||
slots += 1
|
||||
end
|
||||
end
|
||||
return num, den, out
|
||||
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
|
||||
@@ -0,0 +1,577 @@
|
||||
--!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), yuv422p / yuv444p / yuva444p / gray (chroma averaged
|
||||
-- down to 4:2:0, alpha dropped), track.bitDepth 9..16 (little-endian 16-bit samples scaled to 8 bits), rgb24 / bgr24 /
|
||||
-- bgra / rgba (AVI DIBs: track.flip = bottom-up rows, track.stride = padded rows)
|
||||
local function rawPlanar(data: buffer, pf: string, bits: number, w: number, h: number): Types.Image
|
||||
local img = Types.Image.new(w, h, "yuv420p")
|
||||
local px = img.pixels
|
||||
local cw, ch = (w + 1) // 2, (h + 1) // 2
|
||||
local bps = if bits > 8 then 2 else 1
|
||||
local shift = 2 ^ (bits - 8)
|
||||
local function sample(o: number): number
|
||||
if bps == 1 then
|
||||
return buffer.readu8(data, o)
|
||||
end
|
||||
return math.min(255, buffer.readu16(data, o) // shift)
|
||||
end
|
||||
for i = 0, w * h - 1 do
|
||||
buffer.writeu8(px, i, sample(i * bps))
|
||||
end
|
||||
local scw, sch = w, h -- source chroma plane size
|
||||
if pf == "yuv420p" then
|
||||
scw, sch = cw, ch
|
||||
elseif pf == "yuv422p" then
|
||||
scw, sch = cw, h
|
||||
end
|
||||
local uo, vo = w * h * bps, (w * h + scw * sch) * bps
|
||||
for cy = 0, ch - 1 do
|
||||
for cx = 0, cw - 1 do
|
||||
local i = cy * cw + cx
|
||||
local u, v
|
||||
if pf == "gray" then
|
||||
u, v = 128, 128
|
||||
elseif pf == "yuv420p" then
|
||||
u, v = sample(uo + i * bps), sample(vo + i * bps)
|
||||
elseif pf == "yuv422p" then
|
||||
local y0, y1 = cy * 2, math.min(cy * 2 + 1, h - 1)
|
||||
u = (sample(uo + (y0 * scw + cx) * bps) + sample(uo + (y1 * scw + cx) * bps) + 1) // 2
|
||||
v = (sample(vo + (y0 * scw + cx) * bps) + sample(vo + (y1 * scw + cx) * bps) + 1) // 2
|
||||
else
|
||||
local x0, x1 = cx * 2, math.min(cx * 2 + 1, w - 1)
|
||||
local y0, y1 = cy * 2, math.min(cy * 2 + 1, h - 1)
|
||||
local a, b, c, d = (y0 * w + x0) * bps, (y0 * w + x1) * bps, (y1 * w + x0) * bps, (y1 * w + x1) * bps
|
||||
u = (sample(uo + a) + sample(uo + b) + sample(uo + c) + sample(uo + d) + 2) // 4
|
||||
v = (sample(vo + a) + sample(vo + b) + sample(vo + c) + sample(vo + d) + 2) // 4
|
||||
end
|
||||
buffer.writeu8(px, w * h + i, u)
|
||||
buffer.writeu8(px, w * h + cw * ch + i, v)
|
||||
end
|
||||
end
|
||||
return img
|
||||
end
|
||||
|
||||
local PLANAR_SIZE: { [string]: (w: number, h: number, cw: number, ch: number) -> number } = {
|
||||
yuv420p = function(w, h, cw, ch)
|
||||
return w * h + 2 * cw * ch
|
||||
end,
|
||||
yv12 = function(w, h, cw, ch)
|
||||
return w * h + 2 * cw * ch
|
||||
end,
|
||||
yuv422p = function(w, h, cw, _ch)
|
||||
return w * h + 2 * cw * h
|
||||
end,
|
||||
yuv444p = function(w, h)
|
||||
return w * h * 3
|
||||
end,
|
||||
yuva444p = function(w, h)
|
||||
return w * h * 4
|
||||
end,
|
||||
gray = function(w, h)
|
||||
return w * h
|
||||
end,
|
||||
}
|
||||
|
||||
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 bits = track.bitDepth or 8
|
||||
local cw, ch = (w + 1) // 2, (h + 1) // 2
|
||||
local flip = track.flip == true
|
||||
local planar = PLANAR_SIZE[pf]
|
||||
return Video.simpleDecoder(function(data: buffer): (Types.Image?, Err.Err?)
|
||||
local n = buffer.len(data)
|
||||
if planar then
|
||||
local need = planar(w, h, cw, ch) * (if bits > 8 then 2 else 1)
|
||||
if n < need then
|
||||
return nil, Err.new(Err.TRUNCATED, "raw frame: " .. n .. " of " .. need .. " bytes")
|
||||
end
|
||||
if pf == "yuv420p" and bits == 8 then
|
||||
local img = Types.Image.new(w, h, "yuv420p")
|
||||
buffer.copy(img.pixels, 0, data, 0, need)
|
||||
return img
|
||||
elseif pf == "yv12" then
|
||||
local img = Types.Image.new(w, h, "yuv420p")
|
||||
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)
|
||||
return img
|
||||
end
|
||||
return rawPlanar(data, pf, bits, w, h)
|
||||
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
|
||||
|
||||
-- Motion JPEG: every packet one JPEG (or two fields), yuv420p straight from the planes (full range) when the layout
|
||||
-- allows, else rgba8
|
||||
local function mjpegDecoder(_track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?)
|
||||
local Jpeg = require("@formats/codecs/Jpeg")
|
||||
local o = { yuv = true, maxPixels = opts and opts.maxPixels }
|
||||
return Video.simpleDecoder(function(data: buffer): (Types.Image?, Err.Err?)
|
||||
local img, err = Jpeg.decode(data, 0, buffer.len(data), o)
|
||||
if img and img.format == "yuv420p" then
|
||||
img.meta.yuv = { range = "full", matrix = "bt601" }
|
||||
end
|
||||
return img, err
|
||||
end)
|
||||
end
|
||||
|
||||
-- the MJPEG encoder (writers): JPEG is full-range, so limited-range yuv420p frames are remapped first
|
||||
local function mjpegEncode(img: Types.Image, opts: any?): (buffer?, Err.Err?)
|
||||
local Jpeg = require("@formats/codecs/Jpeg")
|
||||
local src = img
|
||||
if img.format == "yuv420p" then
|
||||
local range = Yuv.info(img)
|
||||
if range ~= "full" then
|
||||
src = Yuv.toFullRange(img)
|
||||
end
|
||||
end
|
||||
return Jpeg.encode(src, { quality = opts and opts.quality or 90 })
|
||||
end
|
||||
|
||||
-- MPEG-1 video: pictures in decode order, reordered for display (the packet's pts travels with its picture)
|
||||
local function mpeg1Decoder(_track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?)
|
||||
local Mpeg1 = require("@formats/codecs/Mpeg1")
|
||||
local dec = Mpeg1.new({ reorder = true, rgba = false, maxPixels = opts and opts.maxPixels })
|
||||
local queue: { any } = {}
|
||||
local function push(f: any)
|
||||
local img = Mpeg1.frameImage(f)
|
||||
if img then
|
||||
img.meta.yuv = { range = "limited", matrix = "bt601" }
|
||||
local tag = f.tag
|
||||
table.insert(queue, { img, if type(tag) == "table" then tag[1] else nil, f.pictureType == 1 })
|
||||
end
|
||||
end
|
||||
local self = {}
|
||||
function self.decode(_: any, packet: Types.Packet): Err.Err?
|
||||
local ok, f = pcall(dec.decode, dec, packet.data, 0, buffer.len(packet.data), { packet.pts })
|
||||
if not ok then
|
||||
return Err.new(Err.CORRUPT, "decoder threw: " .. tostring(f))
|
||||
end
|
||||
if f then
|
||||
push(f)
|
||||
end
|
||||
return nil
|
||||
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)
|
||||
for _ = 1, 4 do
|
||||
local f = dec:flush()
|
||||
if not f then
|
||||
break
|
||||
end
|
||||
push(f)
|
||||
end
|
||||
end
|
||||
function self.reset(_: any)
|
||||
dec:reset()
|
||||
table.clear(queue)
|
||||
end
|
||||
return self :: any, nil
|
||||
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" }, new = mjpegDecoder, encode = mjpegEncode },
|
||||
{ id = "mpeg1", name = "MPEG-1 video", fourcc = { "mpg1", "MPG1", "PIM1", "m1v " }, matroska = { "V_MPEG1" }, new = mpeg1Decoder },
|
||||
{ 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 start = demuxer.startTime or 0
|
||||
v.startTime = start
|
||||
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 - start
|
||||
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 + start)
|
||||
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
|
||||
+880
-246
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,274 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- codecs/Vp8/Predict: VP8 inter prediction (RFC 6386 section 18): the six-tap sub-pixel filters (version 0), the
|
||||
-- bilinear ones (versions 1-3; version 3 also rounds chroma vectors to full pixels), chroma vectors derived from the
|
||||
-- luma ones, split macroblocks, and the reference frame borders. After libvpx 1.17 vp8/common/reconinter.c and
|
||||
-- filter.c (BSD-3-Clause, licenses/libvpx-LICENSE.txt). Out-of-frame motion reads the reference as if its edge pixels
|
||||
-- extended forever, which is exactly what libvpx computes with its 32 pixel border plus its motion vector clamping (the
|
||||
-- clamps only kick in once every tap is in the border). The planes keep a BORDER pixel border filled by extend(); a
|
||||
-- block whose taps leave it is first copied with clamped coordinates. Never throws.
|
||||
local Tables = require("@formats/codecs/Vp8/Tables")
|
||||
|
||||
local readu8, writeu8, bcopy, bcreate, bfill = buffer.readu8, buffer.writeu8, buffer.copy, buffer.create, buffer.fill
|
||||
local readu32, writeu32 = buffer.readu32, buffer.writeu32
|
||||
local rshift, band = bit32.rshift, bit32.band
|
||||
local SIX, BIL = Tables.SIXTAP, Tables.BILINEAR
|
||||
|
||||
local Predict = {}
|
||||
|
||||
local BORDER = 32
|
||||
Predict.BORDER = BORDER
|
||||
|
||||
-- the work buffer stride (codecs/Vp8/Decode: BPS)
|
||||
local BPS = 32
|
||||
|
||||
local emu = bcreate(32 * 32) -- a block with its taps, edges replicated
|
||||
local tmp = bcreate(32 * 32) -- the first (horizontal) pass of a two-dimensional filter
|
||||
|
||||
-- the six-tap filter along rows: dst[i] = clamp((sum of src[i - 2 .. i + 3] * taps + 64) >> 7). Each output reads
|
||||
-- its six pixels (a sliding window of locals is no faster in Luau and stops LuaJIT's register allocator).
|
||||
local function sixH(src: buffer, so: number, ss: number, dst: buffer, d: number, ds: number, w: number, h: number, f: number)
|
||||
local k = f * 6
|
||||
local t0, t1, t2, t3, t4, t5 = SIX[k + 1], SIX[k + 2], SIX[k + 3], SIX[k + 4], SIX[k + 5], SIX[k + 6]
|
||||
for _ = 1, h do
|
||||
for i = so - 2, so + w - 3 do
|
||||
local v = readu8(src, i) * t0 + readu8(src, i + 1) * t1 + readu8(src, i + 2) * t2 + readu8(src, i + 3) * t3
|
||||
+ readu8(src, i + 4) * t4 + readu8(src, i + 5) * t5 + 64
|
||||
writeu8(dst, d + i - so + 2, if v < 0 then 0 elseif v >= 32768 then 255 else rshift(v, 7))
|
||||
end
|
||||
so += ss
|
||||
d += ds
|
||||
end
|
||||
end
|
||||
|
||||
-- the six-tap filter along columns
|
||||
local function sixV(src: buffer, so: number, ss: number, dst: buffer, d: number, ds: number, w: number, h: number, f: number)
|
||||
local k = f * 6
|
||||
local t0, t1, t2, t3, t4, t5 = SIX[k + 1], SIX[k + 2], SIX[k + 3], SIX[k + 4], SIX[k + 5], SIX[k + 6]
|
||||
local s1, s2, s3 = ss, 2 * ss, 3 * ss
|
||||
for _ = 1, h do
|
||||
local p = so - s2
|
||||
for i = 0, w - 1 do
|
||||
local q = p + i
|
||||
local v = readu8(src, q) * t0 + readu8(src, q + s1) * t1 + readu8(src, q + s2) * t2 + readu8(src, q + s3) * t3
|
||||
+ readu8(src, q + s2 + s2) * t4 + readu8(src, q + s2 + s3) * t5 + 64
|
||||
writeu8(dst, d + i, if v < 0 then 0 elseif v >= 32768 then 255 else rshift(v, 7))
|
||||
end
|
||||
so += ss
|
||||
d += ds
|
||||
end
|
||||
end
|
||||
|
||||
-- the bilinear filters: dst[i] = (src[i] * t0 + src[i + 1] * t1 + 64) >> 7
|
||||
local function bilH(src: buffer, so: number, ss: number, dst: buffer, d: number, ds: number, w: number, h: number, f: number)
|
||||
local t0, t1 = BIL[f * 2 + 1], BIL[f * 2 + 2]
|
||||
for _ = 1, h do
|
||||
for i = 0, w - 1 do
|
||||
writeu8(dst, d + i, rshift(readu8(src, so + i) * t0 + readu8(src, so + i + 1) * t1 + 64, 7))
|
||||
end
|
||||
so += ss
|
||||
d += ds
|
||||
end
|
||||
end
|
||||
|
||||
local function bilV(src: buffer, so: number, ss: number, dst: buffer, d: number, ds: number, w: number, h: number, f: number)
|
||||
local t0, t1 = BIL[f * 2 + 1], BIL[f * 2 + 2]
|
||||
for _ = 1, h do
|
||||
for i = 0, w - 1 do
|
||||
writeu8(dst, d + i, rshift(readu8(src, so + i) * t0 + readu8(src, so + ss + i) * t1 + 64, 7))
|
||||
end
|
||||
so += ss
|
||||
d += ds
|
||||
end
|
||||
end
|
||||
|
||||
-- block(src, stride, base, wmax, hmax, x, y, mvx, mvy, w, h, dst, d, bil): predicts the w x h block at plane pixel
|
||||
-- (x, y) moved by (mvx, mvy) eighth pixels into dst at d (stride BPS). base: the offset of plane pixel (0, 0); wmax,
|
||||
-- hmax: the last pixel column / row of the (macroblock aligned) plane.
|
||||
local function block(src: buffer, stride: number, base: number, wmax: number, hmax: number, x: number, y: number, mvx: number, mvy: number, w: number, h: number, dst: buffer, d: number, bil: boolean)
|
||||
local fx, fy = band(mvx, 7), band(mvy, 7)
|
||||
local px, py = x + (mvx - fx) // 8, y + (mvy - fy) // 8
|
||||
local sb, so, ss = src, 0, stride
|
||||
if px >= 2 - BORDER and py >= 2 - BORDER and px + w + 3 <= wmax + 1 + BORDER and py + h + 3 <= hmax + 1 + BORDER then
|
||||
so = base + py * stride + px
|
||||
else
|
||||
for r = 0, h + 4 do
|
||||
local sy = py - 2 + r
|
||||
if sy < 0 then
|
||||
sy = 0
|
||||
elseif sy > hmax then
|
||||
sy = hmax
|
||||
end
|
||||
local row = base + sy * stride
|
||||
local o = r * 32
|
||||
for c = 0, w + 4 do
|
||||
local sx = px - 2 + c
|
||||
if sx < 0 then
|
||||
sx = 0
|
||||
elseif sx > wmax then
|
||||
sx = wmax
|
||||
end
|
||||
writeu8(emu, o + c, readu8(src, row + sx))
|
||||
end
|
||||
end
|
||||
sb, so, ss = emu, 66, 32
|
||||
end
|
||||
if fx == 0 then
|
||||
if fy == 0 then
|
||||
for _ = 1, h do
|
||||
for i = 0, w - 4, 4 do
|
||||
writeu32(dst, d + i, readu32(sb, so + i))
|
||||
end
|
||||
so += ss
|
||||
d += BPS
|
||||
end
|
||||
elseif bil then
|
||||
bilV(sb, so, ss, dst, d, BPS, w, h, fy)
|
||||
else
|
||||
sixV(sb, so, ss, dst, d, BPS, w, h, fy)
|
||||
end
|
||||
elseif fy == 0 then
|
||||
if bil then
|
||||
bilH(sb, so, ss, dst, d, BPS, w, h, fx)
|
||||
else
|
||||
sixH(sb, so, ss, dst, d, BPS, w, h, fx)
|
||||
end
|
||||
elseif bil then
|
||||
bilH(sb, so, ss, tmp, 0, 32, w, h + 1, fx)
|
||||
bilV(tmp, 0, 32, dst, d, BPS, w, h, fy)
|
||||
else
|
||||
sixH(sb, so - 2 * ss, ss, tmp, 0, 32, w, h + 5, fx)
|
||||
sixV(tmp, 64, 32, dst, d, BPS, w, h, fy)
|
||||
end
|
||||
end
|
||||
|
||||
local function chroma16(v: number): number
|
||||
-- the chroma vector of a whole macroblock: half the luma one, rounded away from zero
|
||||
if v < 0 then
|
||||
return -((1 - v) // 2)
|
||||
end
|
||||
return (v + 1) // 2
|
||||
end
|
||||
|
||||
local function chroma4(s: number): number
|
||||
-- the chroma vector of a 2x2 group of luma blocks: the sum of their 4 vectors / 8, rounded half away from zero
|
||||
if s < 0 then
|
||||
return -((4 - s) // 8)
|
||||
end
|
||||
return (s + 4) // 8
|
||||
end
|
||||
|
||||
export type Planes = {
|
||||
Y: buffer,
|
||||
U: buffer,
|
||||
V: buffer,
|
||||
ys: number, -- luma stride
|
||||
uvs: number, -- chroma stride
|
||||
yb: number, -- offset of luma pixel (0, 0)
|
||||
uvb: number,
|
||||
mbw: number,
|
||||
mbh: number,
|
||||
}
|
||||
|
||||
-- mb(ref, mbx, mby, mvr, mvc, split, subR, subC, sb, dst, yo, uo, vo, bil, full): the prediction of one inter
|
||||
-- macroblock into the work buffer (luma at yo, chroma at uo / vo). Not split: one vector (mvr, mvc) in eighth pixels;
|
||||
-- split: the 16 block vectors subR / subC[sb + 1 .. sb + 16] (part < 3: the four 8x8 quarters share them).
|
||||
function Predict.mb(ref: Planes, mbx: number, mby: number, mvr: number, mvc: number, part: number, subR: { number }, subC: { number }, sb: number, dst: buffer, yo: number, uo: number, vo: number, bil: boolean, full: boolean)
|
||||
local Y, U, V, ys, uvs, yb, uvb = ref.Y, ref.U, ref.V, ref.ys, ref.uvs, ref.yb, ref.uvb
|
||||
local wl, hl = ref.mbw * 16 - 1, ref.mbh * 16 - 1
|
||||
local wc, hc = ref.mbw * 8 - 1, ref.mbh * 8 - 1
|
||||
local x, y = mbx * 16, mby * 16
|
||||
local cx, cy = mbx * 8, mby * 8
|
||||
if part < 0 then
|
||||
block(Y, ys, yb, wl, hl, x, y, mvc, mvr, 16, 16, dst, yo, bil)
|
||||
local cr, cc = chroma16(mvr), chroma16(mvc)
|
||||
if full then
|
||||
cr -= band(cr, 7)
|
||||
cc -= band(cc, 7)
|
||||
end
|
||||
block(U, uvs, uvb, wc, hc, cx, cy, cc, cr, 8, 8, dst, uo, bil)
|
||||
block(V, uvs, uvb, wc, hc, cx, cy, cc, cr, 8, 8, dst, vo, bil)
|
||||
return
|
||||
end
|
||||
if part < 3 then
|
||||
for q = 0, 3 do
|
||||
local bx, by = (q % 2) * 8, (q // 2) * 8
|
||||
local k = sb + by + bx // 4 + 1
|
||||
block(Y, ys, yb, wl, hl, x + bx, y + by, subC[k], subR[k], 8, 8, dst, yo + by * BPS + bx, bil)
|
||||
end
|
||||
else
|
||||
for b = 0, 15, 2 do
|
||||
local k = sb + b + 1
|
||||
local bx, by = (b % 4) * 4, (b // 4) * 4
|
||||
local r0, c0 = subR[k], subC[k]
|
||||
if r0 == subR[k + 1] and c0 == subC[k + 1] then
|
||||
block(Y, ys, yb, wl, hl, x + bx, y + by, c0, r0, 8, 4, dst, yo + by * BPS + bx, bil)
|
||||
else
|
||||
block(Y, ys, yb, wl, hl, x + bx, y + by, c0, r0, 4, 4, dst, yo + by * BPS + bx, bil)
|
||||
block(Y, ys, yb, wl, hl, x + bx + 4, y + by, subC[k + 1], subR[k + 1], 4, 4, dst, yo + by * BPS + bx + 4, bil)
|
||||
end
|
||||
end
|
||||
end
|
||||
for i = 0, 1 do
|
||||
local rr, rc = 0, 0
|
||||
for j = 0, 1 do
|
||||
local k = sb + i * 8 + j * 2 + 1
|
||||
local cr = chroma4(subR[k] + subR[k + 1] + subR[k + 4] + subR[k + 5])
|
||||
local cc = chroma4(subC[k] + subC[k + 1] + subC[k + 4] + subC[k + 5])
|
||||
if full then
|
||||
cr -= band(cr, 7)
|
||||
cc -= band(cc, 7)
|
||||
end
|
||||
if j == 0 then
|
||||
rr, rc = cr, cc
|
||||
elseif cr == rr and cc == rc then
|
||||
-- both 4x4 chroma blocks of the row share one vector: one 8x4 block
|
||||
block(U, uvs, uvb, wc, hc, cx, cy + i * 4, cc, cr, 8, 4, dst, uo + i * 4 * BPS, bil)
|
||||
block(V, uvs, uvb, wc, hc, cx, cy + i * 4, cc, cr, 8, 4, dst, vo + i * 4 * BPS, bil)
|
||||
else
|
||||
block(U, uvs, uvb, wc, hc, cx, cy + i * 4, rc, rr, 4, 4, dst, uo + i * 4 * BPS, bil)
|
||||
block(V, uvs, uvb, wc, hc, cx, cy + i * 4, rc, rr, 4, 4, dst, vo + i * 4 * BPS, bil)
|
||||
block(U, uvs, uvb, wc, hc, cx + 4, cy + i * 4, cc, cr, 4, 4, dst, uo + i * 4 * BPS + 4, bil)
|
||||
block(V, uvs, uvb, wc, hc, cx + 4, cy + i * 4, cc, cr, 4, 4, dst, vo + i * 4 * BPS + 4, bil)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- row(refs, mby, mbw, ref, part, miMvR, miMvC, miSubR, miSubC, mi0, pred, chunk, yo, uo, vo, bil, full): predicts the
|
||||
-- inter macroblocks of a row (ref[mbx + 1] > 0: refs[ref]) into pred, macroblock mbx at mbx * chunk + yo / uo / vo;
|
||||
-- mi0 + mbx + 1: the mode info index of macroblock mbx. A loop of its own (LuaJIT traces it apart from the decoder).
|
||||
function Predict.row(refs: { Planes }, mby: number, mbw: number, ref: { number }, part: { number }, miMvR: { number }, miMvC: { number }, miSubR: { number }, miSubC: { number }, mi0: number, pred: buffer, chunk: number, yo: number, uo: number, vo: number, bil: boolean, full: boolean)
|
||||
for mbx = 0, mbw - 1 do
|
||||
local rf = ref[mbx + 1]
|
||||
if rf > 0 then
|
||||
local mi = mi0 + mbx + 1
|
||||
local o = mbx * chunk
|
||||
Predict.mb(refs[rf], mbx, mby, miMvR[mi], miMvC[mi], part[mbx + 1], miSubR, miSubC, (mi - 1) * 16, pred, o + yo, o + uo, o + vo, bil, full)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- extend(P, stride, base, w, h): fills the BORDER pixels around a w x h plane with its edge pixels
|
||||
local function extend(P: buffer, stride: number, base: number, w: number, h: number)
|
||||
for r = 0, h - 1 do
|
||||
local o = base + r * stride
|
||||
bfill(P, o - BORDER, readu8(P, o), BORDER)
|
||||
bfill(P, o + w, readu8(P, o + w - 1), BORDER)
|
||||
end
|
||||
local top = base - BORDER
|
||||
local bottom = base + (h - 1) * stride - BORDER
|
||||
for r = 1, BORDER do
|
||||
bcopy(P, top - r * stride, P, top, stride)
|
||||
bcopy(P, bottom + r * stride, P, bottom, stride)
|
||||
end
|
||||
end
|
||||
|
||||
function Predict.extend(ref: Planes)
|
||||
extend(ref.Y, ref.ys, ref.yb, ref.mbw * 16, ref.mbh * 16)
|
||||
extend(ref.U, ref.uvs, ref.uvb, ref.mbw * 8, ref.mbh * 8)
|
||||
extend(ref.V, ref.uvs, ref.uvb, ref.mbw * 8, ref.mbh * 8)
|
||||
end
|
||||
|
||||
return Predict
|
||||
@@ -1,6 +1,9 @@
|
||||
--!strict
|
||||
-- codecs/Vp8/Tables: the constant VP8 tables of RFC 6386 (sections 13.5, 13.4, 11.5, 14.1), copied from libwebp 1.6
|
||||
-- src/dec/tree_dec.c and src/dec/quant_dec.c (BSD-3-Clause, licenses/libwebp-LICENSE.txt). Flat 1-based arrays.
|
||||
-- src/dec/tree_dec.c and src/dec/quant_dec.c (BSD-3-Clause, licenses/libwebp-LICENSE.txt); the inter frame tables
|
||||
-- (sections 16-18: mode / motion vector probabilities, mode contexts, split partitions, sub-pixel filters) from
|
||||
-- libvpx 1.17 vp8/common (entropymode.c, vp8_entropymodedata.h, entropymv.c, modecont.c, decodemv.c, filter.c;
|
||||
-- BSD-3-Clause, licenses/libvpx-LICENSE.txt). Flat 1-based arrays.
|
||||
local Tables = {}
|
||||
|
||||
-- default token probabilities [type 4][band 8][ctx 3][proba 11]: index ((t * 8 + b) * 3 + c) * 11 + p + 1
|
||||
@@ -177,4 +180,70 @@ Tables.CAT4 = { 176, 155, 140, 135 }
|
||||
Tables.CAT5 = { 180, 157, 141, 134, 130 }
|
||||
Tables.CAT6 = { 254, 254, 243, 230, 196, 177, 153, 140, 133, 130, 129 }
|
||||
|
||||
-- inter frames: default intra mode probabilities (16x16 / chroma, kept in the frame context) and the fixed 4x4 ones
|
||||
Tables.YMODE_PROB = { 112, 86, 140, 37 }
|
||||
Tables.UVMODE_PROB = { 162, 101, 204 }
|
||||
Tables.BMODE_PROB = { 120, 90, 79, 133, 87, 85, 80, 111, 151 }
|
||||
|
||||
-- motion vector probabilities, row then column (19 each): is short, sign, short tree (7), long bits (10)
|
||||
Tables.MV_DEFAULT = {
|
||||
162, 128, 225, 146, 172, 147, 214, 39, 156, 128, 129, 132, 75, 145, 178, 206, 239, 254, 254,
|
||||
164, 128, 204, 170, 119, 235, 140, 230, 228, 128, 130, 130, 74, 148, 180, 203, 236, 254, 254,
|
||||
}
|
||||
Tables.MV_UPDATE = {
|
||||
237, 246, 253, 253, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 250, 250, 252, 254, 254,
|
||||
231, 243, 245, 253, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 251, 251, 254, 254, 254,
|
||||
}
|
||||
|
||||
-- mode contexts [count 0..5][tree node 0..3]: index count * 4 + node + 1
|
||||
Tables.MODE_CONTEXTS = {
|
||||
7, 1, 1, 143,
|
||||
14, 18, 14, 107,
|
||||
135, 64, 57, 68,
|
||||
60, 56, 128, 65,
|
||||
159, 134, 128, 34,
|
||||
234, 188, 128, 28,
|
||||
}
|
||||
|
||||
-- sub-block motion vector reference probabilities [(above zero << 2) | (left zero << 1) | (left == above)][3]
|
||||
Tables.SUB_MV_REF_PROB = {
|
||||
147, 136, 18,
|
||||
223, 1, 34,
|
||||
106, 145, 1,
|
||||
208, 1, 1,
|
||||
179, 121, 1,
|
||||
223, 1, 34,
|
||||
179, 121, 1,
|
||||
208, 1, 1,
|
||||
}
|
||||
|
||||
-- split partitions (16x8, 8x16, 8x8, 4x4): the first block of each partition [s * 16 + j + 1], the blocks of each
|
||||
-- partition in order [s * 16 + j * count + i + 1], and the number of blocks per partition
|
||||
Tables.SPLIT_OFFSET = {
|
||||
0, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 2, 8, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
|
||||
}
|
||||
Tables.SPLIT_FILL = {
|
||||
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
|
||||
0, 1, 4, 5, 8, 9, 12, 13, 2, 3, 6, 7, 10, 11, 14, 15,
|
||||
0, 1, 4, 5, 2, 3, 6, 7, 8, 9, 12, 13, 10, 11, 14, 15,
|
||||
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
|
||||
}
|
||||
Tables.SPLIT_COUNT = { 8, 8, 4, 1 }
|
||||
|
||||
-- the six-tap sub-pixel filters [fraction 0..7][tap 0..5] and the bilinear ones [fraction][2] (versions 1-3)
|
||||
Tables.SIXTAP = {
|
||||
0, 0, 128, 0, 0, 0,
|
||||
0, -6, 123, 12, -1, 0,
|
||||
2, -11, 108, 36, -8, 1,
|
||||
0, -9, 93, 50, -6, 0,
|
||||
3, -16, 77, 77, -16, 3,
|
||||
0, -6, 50, 93, -9, 0,
|
||||
1, -8, 36, 108, -11, 2,
|
||||
0, -1, 12, 123, -6, 0,
|
||||
}
|
||||
Tables.BILINEAR = { 128, 0, 112, 16, 96, 32, 80, 48, 64, 64, 48, 80, 32, 96, 16, 112 }
|
||||
|
||||
return Tables
|
||||
@@ -1,16 +1,23 @@
|
||||
--!strict
|
||||
-- codecs/Vp8: the VP8 video codec (RFC 6386), decode only. A codec (layer 1): image/webp uses it for lossy frames, the
|
||||
-- WebM / Matroska and IVF video tracks can use it too. A port of libwebp 1.6 (BSD-3-Clause,
|
||||
-- WebM / Matroska and IVF video tracks use its decoder object. Key frames are a port of libwebp 1.6 (BSD-3-Clause,
|
||||
-- licenses/libwebp-LICENSE.txt), bit-exact with libwebp: the yuv420p planes equal `dwebp -yuv`, and toRgba equals
|
||||
-- `dwebp -pam` (fancy upsampling) or `dwebp -nofancy -pam`.
|
||||
-- Supports: key frames (intra 16x16 / 4x4 / chroma prediction, segments, both loop filters, token partitions,
|
||||
-- probability updates, skip). Not supported yet: inter frames (decodeFrame returns UNSUPPORTED; the decoder object
|
||||
-- keeps the cross-frame state so they can be added), the horizontal / vertical scale bits (ignored, as libwebp does).
|
||||
-- `dwebp -pam` (fancy upsampling) or `dwebp -nofancy -pam`. Inter frames follow libvpx 1.17 (BSD-3-Clause,
|
||||
-- licenses/libvpx-LICENSE.txt), bit-exact with libvpx / ffmpeg on the official test vectors and libvpx streams.
|
||||
-- Supports: key and inter frames of every version / profile (0: six-tap filters, normal loop filter; 1-2: bilinear;
|
||||
-- 3: bilinear with full pixel chroma; the loop filter type is the header's), last / golden / altref references with
|
||||
-- sign bias, hidden (altref) frames, token partitions, segments, loop filter deltas, probability context save /
|
||||
-- restore. Not supported: the horizontal / vertical scale bits (ignored, as libwebp and ffmpeg do), error
|
||||
-- concealment (a damaged frame returns an Err).
|
||||
-- Speed (one Zen 5 core): 640x480 inter frames ~190 fps under luau --codegen, ~220 fps under LuaJIT with the trace
|
||||
-- limits the host module sets (maxtrace=8000; with LuaJIT's default 1000 traces the decoder thrashes: ~70 fps).
|
||||
--
|
||||
-- local Vp8 = require("@formats/codecs/Vp8")
|
||||
-- local frame, err = Vp8.decodeFrame(buf, off, len) -- a yuv420p Types.Image (+ frame.meta.source.vp8 header)
|
||||
-- local frame, err = Vp8.decodeFrame(buf, off, len) -- one key frame: a yuv420p Types.Image
|
||||
-- local rgba = Vp8.toRgba(frame) -- rgba8 Image (libwebp's fancy upsampling)
|
||||
-- local dec = Vp8.newDecoder(); dec:decodeFrame(...) -- a stream of frames (WebM)
|
||||
-- local dec = Vp8.newDecoder() -- a stream (WebM, IVF): key and inter frames
|
||||
-- local img, err = dec:decodeFrame(buf, off, len) -- img.meta.source.show == false: a hidden frame
|
||||
-- dec:reset() -- after a seek: the next frame must be a key frame
|
||||
--
|
||||
-- Never throws: bad data returns nil, Err (core/Err codes TRUNCATED / CORRUPT / UNSUPPORTED / LIMIT / ARG).
|
||||
local Err = require("@formats/core/Err")
|
||||
@@ -67,7 +74,9 @@ function Vp8.newDecoder(): Decoder
|
||||
return setmetatable({ state = Decode.new() }, DecoderMeta)
|
||||
end
|
||||
|
||||
-- decoder:decodeFrame(buf, off?, len?, opts?) -> a yuv420p Image | nil, Err
|
||||
-- decoder:decodeFrame(buf, off?, len?, opts?) -> a yuv420p Image (a fresh buffer) | nil, Err. Key and inter frames;
|
||||
-- meta.source = { format = "vp8", keyFrame, show (false: a hidden frame, decoded as a reference but not displayed),
|
||||
-- profile, width, height }. An inter frame before the first key frame (or after reset) returns CORRUPT.
|
||||
function DecoderMeta.decodeFrame(self: Decoder, buf: buffer, off: number?, len: number?, opts: Options?): (Types.Image?, Err.Err?)
|
||||
if type(buf) ~= "buffer" then
|
||||
return nil, Err.new(Err.ARG, "decodeFrame: expected a buffer")
|
||||
@@ -79,14 +88,18 @@ function DecoderMeta.decodeFrame(self: Decoder, buf: buffer, off: number?, len:
|
||||
end
|
||||
local img = Types.Image.new(f.width, f.height, "yuv420p")
|
||||
local ny = f.width * f.height
|
||||
local nc = buffer.len(f.u)
|
||||
buffer.copy(img.pixels, 0, f.y, 0, ny)
|
||||
buffer.copy(img.pixels, ny, f.u, 0, nc)
|
||||
buffer.copy(img.pixels, ny + nc, f.v, 0, nc)
|
||||
img.meta.source = { format = "vp8", keyFrame = f.header.keyFrame, profile = f.header.profile }
|
||||
local nc = ((f.width + 1) // 2) * ((f.height + 1) // 2)
|
||||
Decode.cropTo(f, img.pixels, 0, img.pixels, ny, img.pixels, ny + nc)
|
||||
local h = f.header
|
||||
img.meta.source = { format = "vp8", keyFrame = h.keyFrame, show = h.show, profile = h.profile, width = f.width, height = f.height }
|
||||
return img, nil
|
||||
end
|
||||
|
||||
-- decoder:reset(): drops the reference frames (after a seek); the next frame must be a key frame
|
||||
function DecoderMeta.reset(self: Decoder)
|
||||
Decode.reset(self.state)
|
||||
end
|
||||
|
||||
-- decodeFrame(buf, off?, len?, opts?) -> a yuv420p Image | nil, Err (one key frame)
|
||||
function Vp8.decodeFrame(buf: buffer, off: number?, len: number?, opts: Options?): (Types.Image?, Err.Err?)
|
||||
return Vp8.newDecoder():decodeFrame(buf, off, len, opts)
|
||||
@@ -102,7 +115,10 @@ function Vp8.decodePlanes(buf: buffer, off: number?, len: number?, opts: Options
|
||||
if not f then
|
||||
return nil, fail(err, o)
|
||||
end
|
||||
return f.y, f.u, f.v, f.width, f.height
|
||||
local nc = ((f.width + 1) // 2) * ((f.height + 1) // 2)
|
||||
local y, u, v = buffer.create(f.width * f.height), buffer.create(nc), buffer.create(nc)
|
||||
Decode.cropTo(f, y, 0, u, 0, v, 0)
|
||||
return y, u, v, f.width, f.height
|
||||
end
|
||||
|
||||
-- planes(img) -> y, u, v offsets in img.pixels and the chroma width / height
|
||||
|
||||
@@ -0,0 +1,225 @@
|
||||
--!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 m = img.meta
|
||||
local y = m and m.yuv
|
||||
if type(y) == "table" then
|
||||
return y.range or "limited", y.matrix or "bt601"
|
||||
end
|
||||
local src = m and m.source
|
||||
if type(src) == "table" and src.range == "full" then
|
||||
return "full", "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
|
||||
|
||||
-- FULL_Y / FULL_C: limited -> full range sample maps
|
||||
local FULL_Y = bcreate(256)
|
||||
local FULL_C = bcreate(256)
|
||||
for v = 0, 255 do
|
||||
writeu8(FULL_Y, v, math.clamp(floor((v - 16) * 255 / 219 + 0.5), 0, 255))
|
||||
writeu8(FULL_C, v, math.clamp(floor((v - 128) * 255 / 224 + 128.5), 0, 255))
|
||||
end
|
||||
|
||||
-- toFullRange(img) -> a yuv420p Image in full range (a limited-range one remapped; a full-range one returned)
|
||||
function Yuv.toFullRange(img: Types.Image): Types.Image
|
||||
if img.format ~= "yuv420p" or info(img) == "full" then
|
||||
return img
|
||||
end
|
||||
local w, h = img.width, img.height
|
||||
local out = Types.Image.new(w, h, "yuv420p")
|
||||
local src, dst = img.pixels, out.pixels
|
||||
local ny = w * h
|
||||
local n = math.min(buffer.len(src), buffer.len(dst))
|
||||
for i = 0, math.min(ny, n) - 1 do
|
||||
writeu8(dst, i, readu8(FULL_Y, readu8(src, i)))
|
||||
end
|
||||
for i = ny, n - 1 do
|
||||
writeu8(dst, i, readu8(FULL_C, readu8(src, i)))
|
||||
end
|
||||
out.meta.yuv = { range = "full", matrix = select(2, info(img)) }
|
||||
out.meta.source = img.meta.source
|
||||
return out
|
||||
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
|
||||
@@ -0,0 +1,463 @@
|
||||
--!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
|
||||
|
||||
-- Vorbis packet sizes: the block sizes from the identification header and each mode's block flag from the end of the
|
||||
-- setup header (read backwards from its framing bit: mode entries are 41 bits whose window / transform types are 0,
|
||||
-- preceded by the 6-bit mode count), so the Ogg granules are exact: a packet yields (previous + current block) / 4
|
||||
-- samples (the first one as if its previous block had its own size, as ffmpeg times it).
|
||||
local function bit(b: buffer, k: number): number
|
||||
return bit32.extract(buffer.readu8(b, k // 8), k % 8, 1)
|
||||
end
|
||||
local function bits(b: buffer, k: number, n: number): number
|
||||
local v = 0
|
||||
for i = n - 1, 0, -1 do
|
||||
v = v * 2 + bit(b, k + i)
|
||||
end
|
||||
return v
|
||||
end
|
||||
|
||||
local function vorbisModes(id: buffer, setup: buffer): ({ number }?, { boolean }?)
|
||||
if buffer.len(id) < 30 or buffer.len(setup) < 8 then
|
||||
return nil
|
||||
end
|
||||
local bs = buffer.readu8(id, 28)
|
||||
local sizes = { 2 ^ (bs % 16), 2 ^ (bs // 16) }
|
||||
-- the framing bit: the highest set bit of the last non-zero byte
|
||||
local last = buffer.len(setup) - 1
|
||||
while last > 0 and buffer.readu8(setup, last) == 0 do
|
||||
last -= 1
|
||||
end
|
||||
local v = buffer.readu8(setup, last)
|
||||
local hb = 7
|
||||
while hb > 0 and bit32.extract(v, hb, 1) == 0 do
|
||||
hb -= 1
|
||||
end
|
||||
local f = last * 8 + hb
|
||||
local flags: { boolean } = {}
|
||||
local pos = f
|
||||
while #flags < 64 and pos - 41 >= 7 * 8 do
|
||||
local s0 = pos - 41
|
||||
if bits(setup, s0 + 1, 16) ~= 0 or bits(setup, s0 + 17, 16) ~= 0 then
|
||||
break
|
||||
end
|
||||
table.insert(flags, 1, bit(setup, s0) == 1)
|
||||
pos = s0
|
||||
end
|
||||
-- the largest count whose 6-bit field matches
|
||||
for n = #flags, 1, -1 do
|
||||
local start = f - 41 * n
|
||||
if start - 6 >= 0 and bits(setup, start - 6, 6) == n - 1 then
|
||||
local out = {}
|
||||
for i = #flags - n + 1, #flags do
|
||||
table.insert(out, flags[i])
|
||||
end
|
||||
return sizes, out
|
||||
end
|
||||
end
|
||||
return nil
|
||||
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
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ trim
|
||||
-- trim(decoder, frames) -> an audio Decoder that drops the first `frames` sample frames (a container's codec delay:
|
||||
-- Matroska CodecDelay for MP2 / MP3 / AAC, which ffmpeg drops too; Opus handles its pre-skip itself)
|
||||
function AudioWrap.trim(dec: any, skip: number): any
|
||||
if skip <= 0 then
|
||||
return dec
|
||||
end
|
||||
local rate = dec.sampleRate
|
||||
local w: any = setmetatable({}, { __index = dec })
|
||||
w.frames = math.max(0, (dec.frames or 0) - skip)
|
||||
w.duration = math.max(0, (dec.duration or 0) - skip / rate)
|
||||
local function drop()
|
||||
local left = skip
|
||||
while left > 0 do
|
||||
local _, n = dec:read(math.min(left, 4096))
|
||||
if not n or n <= 0 then
|
||||
break
|
||||
end
|
||||
left -= n
|
||||
end
|
||||
end
|
||||
local started = false
|
||||
function w.read(_: any, n: number, out: buffer?): (buffer, number)
|
||||
if not started then
|
||||
started = true
|
||||
drop()
|
||||
end
|
||||
return dec:read(n, out)
|
||||
end
|
||||
function w.seek(_: any, seconds: number)
|
||||
started = true
|
||||
if seconds <= 0 then
|
||||
dec:seek(0)
|
||||
drop()
|
||||
else
|
||||
dec:seek(seconds + skip / rate)
|
||||
end
|
||||
end
|
||||
function w.position(_: any): number
|
||||
return math.max(0, dec:position() - skip / rate)
|
||||
end
|
||||
return w
|
||||
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 string.sub(codec, 1, 6) == "adpcm_" 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 sizes, modes = vorbisModes(headers[1], headers[3])
|
||||
local granule, prev = 0, nil :: number?
|
||||
local rate = track.sampleRate or 44100
|
||||
local scale = track.timescale
|
||||
local out = ogg(headers, packets, function(p: Types.Packet): number
|
||||
if not sizes or not modes then
|
||||
return math.floor((p.pts + (p.duration or 0)) / scale * rate + 0.5) -- from the container's times
|
||||
end
|
||||
local d = p.data
|
||||
if buffer.len(d) == 0 or buffer.readu8(d, 0) % 2 ~= 0 then
|
||||
return granule
|
||||
end
|
||||
local mb = 0
|
||||
while 2 ^ mb < #modes do
|
||||
mb += 1
|
||||
end
|
||||
local m = if mb > 0 and buffer.len(d) * 8 > mb then bits(d, 1, mb) else 0
|
||||
local cur = sizes[if modes[m + 1] then 2 else 1]
|
||||
if prev then
|
||||
granule += (prev + cur) // 4
|
||||
end
|
||||
prev = cur
|
||||
return granule
|
||||
end)
|
||||
return out, "vorbis", nil
|
||||
end
|
||||
if codec == "aac" then
|
||||
if track.adts then
|
||||
return concat(packets), "aac", nil -- already ADTS (MPEG-TS)
|
||||
end
|
||||
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
|
||||
@@ -0,0 +1,523 @@
|
||||
--!strict
|
||||
-- containers/Avi: the AVI RIFF form (Microsoft AVI 1.0 + the OpenDML 1.02 extensions). New in formats-luau.
|
||||
-- Reading: hdrl (avih, strl: strh / strf / strn / indx), every RIFF piece (RIFF AVI + RIFF AVIX ...), and the chunk
|
||||
-- index of every stream: from the OpenDML super index (indx -> ix## standard / field indexes), else idx1 (offsets
|
||||
-- relative to the movi list or absolute, detected), else a linear scan of the movi lists (LIST rec included).
|
||||
-- Writing: AVI 1.0 (avih, strl, LIST movi, idx1) with an OpenDML odml / dmlh header, chunks interleaved as given.
|
||||
--
|
||||
-- local avi, err = Avi.read(buf, base, limit)
|
||||
-- avi.streams[i] = { type = "vids" | "auds" | ..., handler, scale, rate, start, length, sampleSize, strf
|
||||
-- (buffer), name, chunks = { { offset, size, key } } } -- offsets of the chunk data, absolute
|
||||
-- local w = Avi.writer({ streams = {...}, avih = {...} }); w:chunk(streamIndex, data, key); local file = w:finish()
|
||||
--
|
||||
-- Never throws: malformed data returns nil, Err (a damaged index falls back to scanning).
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
|
||||
local readu8, readu16, readu32, readstring = buffer.readu8, buffer.readu16, buffer.readu32, buffer.readstring
|
||||
|
||||
local Avi = {}
|
||||
|
||||
export type Chunk = { offset: number, size: number, key: boolean }
|
||||
export type Stream = {
|
||||
index: number, -- 0-based stream number (the "##" of the chunk ids)
|
||||
type: string, -- strh fccType: "vids", "auds", "txts", "mids"
|
||||
handler: string,
|
||||
flags: number,
|
||||
scale: number,
|
||||
rate: number,
|
||||
start: number,
|
||||
length: number,
|
||||
suggestedBufferSize: number,
|
||||
sampleSize: number,
|
||||
frame: { number }, -- rcFrame left, top, right, bottom
|
||||
strf: buffer, -- the format block (BITMAPINFOHEADER / WAVEFORMATEX ...)
|
||||
name: string?,
|
||||
chunks: { Chunk },
|
||||
}
|
||||
export type File = {
|
||||
avih: { microSecPerFrame: number, flags: number, totalFrames: number, streams: number, width: number, height: number },
|
||||
streams: { Stream },
|
||||
odml: { totalFrames: number }?,
|
||||
info: { [string]: string },
|
||||
index: string, -- "odml" | "idx1" | "scan"
|
||||
}
|
||||
|
||||
local function u32(b: buffer, o: number): number
|
||||
return readu32(b, o)
|
||||
end
|
||||
|
||||
-- chunk walker over [p, limit): calls fn(id, dataOffset, size, listType?) for each chunk (LIST bodies are not
|
||||
-- entered); returns where it stopped
|
||||
local function walk(b: buffer, p: number, limit: number, fn: (id: string, data: number, size: number, ltype: string?) -> boolean?): number
|
||||
while p + 8 <= limit do
|
||||
local id = readstring(b, p, 4)
|
||||
local size = u32(b, p + 4)
|
||||
local data = p + 8
|
||||
local ltype: string? = nil
|
||||
if (id == "LIST" or id == "RIFF") and data + 4 <= limit then
|
||||
ltype = readstring(b, data, 4)
|
||||
end
|
||||
if data + size > limit then
|
||||
size = limit - data
|
||||
end
|
||||
if fn(id, data, size, ltype) == false then
|
||||
return p
|
||||
end
|
||||
p = data + size + (size % 2)
|
||||
end
|
||||
return p
|
||||
end
|
||||
|
||||
local function streamNumber(id: string): number?
|
||||
local a, b = string.byte(id, 1, 2)
|
||||
if not a or not b then
|
||||
return nil
|
||||
end
|
||||
local function hex(c: number): number?
|
||||
if c >= 48 and c <= 57 then
|
||||
return c - 48
|
||||
elseif c >= 65 and c <= 70 then
|
||||
return c - 55
|
||||
elseif c >= 97 and c <= 102 then
|
||||
return c - 87
|
||||
end
|
||||
return nil
|
||||
end
|
||||
local h, l = hex(a), hex(b)
|
||||
if h and l then
|
||||
return h * 16 + l
|
||||
end
|
||||
return nil
|
||||
end
|
||||
Avi.streamNumber = streamNumber
|
||||
|
||||
local function parseStrl(b: buffer, data: number, size: number, index: number): Stream
|
||||
local s: Stream = {
|
||||
index = index,
|
||||
type = "",
|
||||
handler = "",
|
||||
flags = 0,
|
||||
scale = 1,
|
||||
rate = 1,
|
||||
start = 0,
|
||||
length = 0,
|
||||
suggestedBufferSize = 0,
|
||||
sampleSize = 0,
|
||||
frame = { 0, 0, 0, 0 },
|
||||
strf = buffer.create(0),
|
||||
chunks = {},
|
||||
}
|
||||
local indx: { number }? = nil
|
||||
walk(b, data + 4, data + size, function(id: string, d: number, n: number): boolean?
|
||||
if id == "strh" and n >= 48 then
|
||||
s.type = readstring(b, d, 4)
|
||||
s.handler = readstring(b, d + 4, 4)
|
||||
s.flags = u32(b, d + 8)
|
||||
s.scale = u32(b, d + 20)
|
||||
s.rate = u32(b, d + 24)
|
||||
s.start = u32(b, d + 28)
|
||||
s.length = u32(b, d + 32)
|
||||
s.suggestedBufferSize = u32(b, d + 36)
|
||||
s.sampleSize = u32(b, d + 44)
|
||||
if n >= 56 then
|
||||
s.frame = { buffer.readi16(b, d + 48), buffer.readi16(b, d + 50), buffer.readi16(b, d + 52), buffer.readi16(b, d + 54) }
|
||||
end
|
||||
elseif id == "strf" then
|
||||
local f = buffer.create(n)
|
||||
buffer.copy(f, 0, b, d, n)
|
||||
s.strf = f
|
||||
elseif id == "strn" then
|
||||
local str = readstring(b, d, n)
|
||||
s.name = string.match(str, "^[^%z]*")
|
||||
elseif id == "indx" and n >= 24 then
|
||||
indx = { d, n }
|
||||
end
|
||||
return nil
|
||||
end)
|
||||
;(s :: any)._indx = indx
|
||||
return s
|
||||
end
|
||||
|
||||
-- an OpenDML index chunk (indx super index or ix## standard index) at d with n bytes: appends chunks to s
|
||||
local function readIndex(b: buffer, d: number, n: number, s: Stream, limit: number, depth: number): boolean
|
||||
if n < 24 or depth > 2 then
|
||||
return false
|
||||
end
|
||||
local longsPerEntry = readu16(b, d)
|
||||
local subType = readu8(b, d + 2)
|
||||
local indexType = readu8(b, d + 3)
|
||||
local entries = u32(b, d + 4)
|
||||
if indexType == 0 then -- AVI_INDEX_OF_INDEXES: { qwOffset, dwSize, dwDuration }
|
||||
if longsPerEntry ~= 4 then
|
||||
return false
|
||||
end
|
||||
local p = d + 24
|
||||
for _ = 1, entries do
|
||||
if p + 16 > d + n then
|
||||
break
|
||||
end
|
||||
local off = u32(b, p) + u32(b, p + 4) * 4294967296
|
||||
local size = u32(b, p + 8)
|
||||
p += 16
|
||||
if off > 0 and off + 8 <= limit then
|
||||
local sz = math.min(u32(b, off + 4), limit - off - 8)
|
||||
readIndex(b, off + 8, if size > 0 then math.min(sz, size) else sz, s, limit, depth + 1)
|
||||
end
|
||||
end
|
||||
return #s.chunks > 0
|
||||
elseif indexType == 1 then -- AVI_INDEX_OF_CHUNKS: base offset, { dwOffset, dwSize } (or field index: 3 longs)
|
||||
if n < 24 then
|
||||
return false
|
||||
end
|
||||
local base = u32(b, d + 12) + u32(b, d + 16) * 4294967296
|
||||
local per = if subType == 1 then 12 else 8 -- AVI_INDEX_2FIELD
|
||||
local p = d + 24
|
||||
for _ = 1, entries do
|
||||
if p + per > d + n then
|
||||
break
|
||||
end
|
||||
local off = u32(b, p)
|
||||
local size = u32(b, p + 4)
|
||||
p += per
|
||||
local key = size < 0x80000000
|
||||
size %= 0x80000000
|
||||
local at = base + off
|
||||
if at >= 0 and at + size <= limit then
|
||||
table.insert(s.chunks, { offset = at, size = size, key = key })
|
||||
end
|
||||
end
|
||||
return true
|
||||
end
|
||||
return false
|
||||
end
|
||||
|
||||
-- read(buf, base, limit) -> File | nil, Err
|
||||
function Avi.read(b: buffer, base: number, limit: number): (File?, Err.Err?)
|
||||
if limit - base < 12 or readstring(b, base, 4) ~= "RIFF" or readstring(b, base + 8, 4) ~= "AVI " then
|
||||
return nil, Err.new(Err.CORRUPT, "not an AVI file", base)
|
||||
end
|
||||
local file: File = {
|
||||
avih = { microSecPerFrame = 0, flags = 0, totalFrames = 0, streams = 0, width = 0, height = 0 },
|
||||
streams = {},
|
||||
odml = nil,
|
||||
info = {},
|
||||
index = "scan",
|
||||
}
|
||||
local movis: { { number } } = {} -- { data offset of the 'movi' fourcc, end }
|
||||
local idx1: { number }? = nil
|
||||
local hdrl = false
|
||||
-- every RIFF piece (AVI, then AVIX for OpenDML files)
|
||||
walk(b, base, limit, function(id: string, d: number, n: number, ltype: string?): boolean?
|
||||
if id ~= "RIFF" then
|
||||
return nil
|
||||
end
|
||||
walk(b, d + 4, d + n, function(cid: string, cd: number, cn: number, cltype: string?): boolean?
|
||||
if cid == "LIST" and cltype == "hdrl" and not hdrl then
|
||||
hdrl = true
|
||||
local si = 0
|
||||
walk(b, cd + 4, cd + cn, function(hid: string, hd: number, hn: number, hltype: string?): boolean?
|
||||
if hid == "avih" and hn >= 40 then
|
||||
file.avih = {
|
||||
microSecPerFrame = u32(b, hd),
|
||||
flags = u32(b, hd + 12),
|
||||
totalFrames = u32(b, hd + 16),
|
||||
streams = u32(b, hd + 24),
|
||||
width = u32(b, hd + 32),
|
||||
height = u32(b, hd + 36),
|
||||
}
|
||||
elseif hid == "LIST" and hltype == "strl" then
|
||||
table.insert(file.streams, parseStrl(b, hd, hn, si))
|
||||
si += 1
|
||||
elseif hid == "LIST" and hltype == "odml" then
|
||||
walk(b, hd + 4, hd + hn, function(oid: string, od: number, on: number): boolean?
|
||||
if oid == "dmlh" and on >= 4 then
|
||||
file.odml = { totalFrames = u32(b, od) }
|
||||
end
|
||||
return nil
|
||||
end)
|
||||
end
|
||||
return nil
|
||||
end)
|
||||
elseif cid == "LIST" and cltype == "movi" then
|
||||
table.insert(movis, { cd, cd + cn })
|
||||
elseif cid == "LIST" and cltype == "INFO" then
|
||||
walk(b, cd + 4, cd + cn, function(iid: string, idd: number, inn: number): boolean?
|
||||
file.info[iid] = string.match(readstring(b, idd, inn), "^[^%z]*") or ""
|
||||
return nil
|
||||
end)
|
||||
elseif cid == "idx1" and not idx1 then
|
||||
idx1 = { cd, cn }
|
||||
end
|
||||
return nil
|
||||
end)
|
||||
return nil
|
||||
end)
|
||||
if not hdrl then
|
||||
return nil, Err.new(Err.CORRUPT, "no hdrl list")
|
||||
end
|
||||
if #file.streams == 0 then
|
||||
return nil, Err.new(Err.CORRUPT, "no streams")
|
||||
end
|
||||
-- 1. OpenDML indexes
|
||||
local odml = true
|
||||
for _, s in file.streams do
|
||||
local ix = (s :: any)._indx
|
||||
if not ix or not readIndex(b, ix[1], ix[2], s, limit, 0) then
|
||||
odml = false
|
||||
end
|
||||
end
|
||||
if odml then
|
||||
file.index = "odml"
|
||||
else
|
||||
for _, s in file.streams do
|
||||
table.clear(s.chunks)
|
||||
end
|
||||
-- 2. idx1
|
||||
local ok = false
|
||||
if idx1 and movis[1] then
|
||||
local d, n = idx1[1], idx1[2]
|
||||
local count = n // 16
|
||||
local moviBase = movis[1][1] -- the 'movi' fourcc
|
||||
-- relative or absolute offsets: check the first entry that points at a chunk id
|
||||
local rel = true
|
||||
if count > 0 then
|
||||
local off = u32(b, d + 8)
|
||||
local ckid = readstring(b, d, 4)
|
||||
local relAt, absAt = moviBase + off, base + off
|
||||
if relAt + 4 <= limit and readstring(b, relAt, 4) == ckid then
|
||||
rel = true
|
||||
elseif absAt + 4 <= limit and readstring(b, absAt, 4) == ckid then
|
||||
rel = false
|
||||
end
|
||||
end
|
||||
for k = 0, count - 1 do
|
||||
local e = d + k * 16
|
||||
local ckid = readstring(b, e, 4)
|
||||
local flags = u32(b, e + 4)
|
||||
local off = u32(b, e + 8)
|
||||
local size = u32(b, e + 12)
|
||||
local sn = streamNumber(ckid)
|
||||
local s = sn and file.streams[sn + 1]
|
||||
if s and string.sub(ckid, 3, 4) ~= "pc" then
|
||||
local at = (if rel then moviBase else base) + off + 8
|
||||
if at + size <= limit then
|
||||
table.insert(s.chunks, { offset = at, size = size, key = bit32.band(flags, 0x10) ~= 0 })
|
||||
ok = true
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
if ok then
|
||||
file.index = "idx1"
|
||||
else
|
||||
for _, s in file.streams do
|
||||
table.clear(s.chunks)
|
||||
end
|
||||
-- 3. scan the movi lists
|
||||
local function scan(d0: number, e0: number)
|
||||
walk(b, d0, e0, function(id: string, d: number, n: number, ltype: string?): boolean?
|
||||
if id == "LIST" and ltype == "rec " then
|
||||
scan(d + 4, d + n)
|
||||
return nil
|
||||
end
|
||||
local sn = streamNumber(id)
|
||||
local s = sn and file.streams[sn + 1]
|
||||
if s and string.sub(id, 1, 2) ~= "ix" and string.sub(id, 3, 4) ~= "pc" then
|
||||
table.insert(s.chunks, { offset = d, size = n, key = true })
|
||||
end
|
||||
return nil
|
||||
end)
|
||||
end
|
||||
for _, m in movis do
|
||||
scan(m[1] + 4, m[2])
|
||||
end
|
||||
file.index = "scan"
|
||||
end
|
||||
end
|
||||
for _, s in file.streams do
|
||||
(s :: any)._indx = nil
|
||||
end
|
||||
return file, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ writing
|
||||
export type WStream = {
|
||||
type: string, -- "vids" | "auds"
|
||||
handler: string, -- fccHandler (4 chars)
|
||||
scale: number,
|
||||
rate: number,
|
||||
sampleSize: number, -- 0 = every chunk one sample (video, VBR audio)
|
||||
strf: buffer,
|
||||
name: string?,
|
||||
width: number?,
|
||||
height: number?,
|
||||
quality: number?,
|
||||
ckid: string?, -- the chunk id suffix: "dc" (video), "wb" (audio)
|
||||
}
|
||||
export type WOptions = {
|
||||
streams: { WStream },
|
||||
microSecPerFrame: number,
|
||||
width: number,
|
||||
height: number,
|
||||
software: string?,
|
||||
}
|
||||
|
||||
-- write(opts, chunks) -> buffer: chunks = { { stream (1-based), data: buffer, key: boolean } } in file order
|
||||
function Avi.write(opts: WOptions, chunks: { { any } }): buffer
|
||||
local ns = #opts.streams
|
||||
local lengths = table.create(ns, 0)
|
||||
local maxChunk = table.create(ns, 0)
|
||||
local bytes = table.create(ns, 0)
|
||||
local total = 0
|
||||
for _, c in chunks do
|
||||
local si, data = c[1], c[2]
|
||||
local n = buffer.len(data)
|
||||
local s = opts.streams[si]
|
||||
if s.sampleSize > 0 then
|
||||
lengths[si] += n // s.sampleSize
|
||||
else
|
||||
lengths[si] += 1
|
||||
end
|
||||
bytes[si] += n
|
||||
if n > maxChunk[si] then
|
||||
maxChunk[si] = n
|
||||
end
|
||||
total += n + 8 + (n % 2)
|
||||
end
|
||||
local frames = 0
|
||||
for si, s in opts.streams do
|
||||
if s.type == "vids" and frames == 0 then
|
||||
frames = lengths[si]
|
||||
end
|
||||
end
|
||||
local w = Bytes.writer(total + 4096 + #chunks * 16)
|
||||
w:string("RIFF")
|
||||
local riffSize = w:tell()
|
||||
w:u32le(0)
|
||||
w:string("AVI ")
|
||||
-- hdrl
|
||||
w:string("LIST")
|
||||
local hdrlSize = w:tell()
|
||||
w:u32le(0)
|
||||
w:string("hdrl")
|
||||
w:string("avih")
|
||||
w:u32le(56)
|
||||
local duration = if opts.microSecPerFrame > 0 then frames * opts.microSecPerFrame / 1e6 else 1
|
||||
local maxBytes = 0
|
||||
for si = 1, ns do
|
||||
maxBytes += bytes[si]
|
||||
end
|
||||
w:u32le(math.floor(opts.microSecPerFrame + 0.5))
|
||||
w:u32le(if duration > 0 then math.floor(maxBytes / duration) else 0)
|
||||
w:u32le(0) -- padding granularity
|
||||
w:u32le(0x10 + 0x100) -- AVIF_HASINDEX | AVIF_ISINTERLEAVED
|
||||
w:u32le(frames)
|
||||
w:u32le(0) -- initial frames
|
||||
w:u32le(ns)
|
||||
local suggested = 0
|
||||
for si = 1, ns do
|
||||
suggested = math.max(suggested, maxChunk[si] + 8)
|
||||
end
|
||||
w:u32le(suggested)
|
||||
w:u32le(opts.width)
|
||||
w:u32le(opts.height)
|
||||
for _ = 1, 4 do
|
||||
w:u32le(0)
|
||||
end
|
||||
for si, s in opts.streams do
|
||||
w:string("LIST")
|
||||
local strlSize = w:tell()
|
||||
w:u32le(0)
|
||||
w:string("strl")
|
||||
w:string("strh")
|
||||
w:u32le(56)
|
||||
w:string(s.type)
|
||||
w:string(s.handler)
|
||||
w:u32le(0) -- flags
|
||||
w:u16le(0) -- priority
|
||||
w:u16le(0) -- language
|
||||
w:u32le(0) -- initial frames
|
||||
w:u32le(s.scale)
|
||||
w:u32le(s.rate)
|
||||
w:u32le(0) -- start
|
||||
w:u32le(lengths[si])
|
||||
w:u32le(maxChunk[si])
|
||||
w:u32le(if s.quality then s.quality else 0xFFFFFFFF)
|
||||
w:u32le(s.sampleSize)
|
||||
w:u16le(0)
|
||||
w:u16le(0)
|
||||
w:u16le(s.width or 0)
|
||||
w:u16le(s.height or 0)
|
||||
w:string("strf")
|
||||
w:u32le(buffer.len(s.strf))
|
||||
w:bytes(s.strf)
|
||||
if buffer.len(s.strf) % 2 == 1 then
|
||||
w:u8(0)
|
||||
end
|
||||
if s.name then
|
||||
local nm = s.name .. "\0"
|
||||
w:string("strn")
|
||||
w:u32le(#nm)
|
||||
w:string(nm)
|
||||
if #nm % 2 == 1 then
|
||||
w:u8(0)
|
||||
end
|
||||
end
|
||||
w:setU32le(strlSize, w:tell() - strlSize - 4)
|
||||
end
|
||||
-- OpenDML extended header (total frames)
|
||||
w:string("LIST")
|
||||
w:u32le(16)
|
||||
w:string("odml")
|
||||
w:string("dmlh")
|
||||
w:u32le(4)
|
||||
w:u32le(frames)
|
||||
w:setU32le(hdrlSize, w:tell() - hdrlSize - 4)
|
||||
-- INFO
|
||||
local sw = (opts.software or "formats-luau") .. "\0"
|
||||
if #sw % 2 == 1 then
|
||||
sw ..= "\0"
|
||||
end
|
||||
w:string("LIST")
|
||||
w:u32le(4 + 8 + #sw)
|
||||
w:string("INFO")
|
||||
w:string("ISFT")
|
||||
w:u32le(#sw)
|
||||
w:string(sw)
|
||||
-- movi
|
||||
w:string("LIST")
|
||||
local moviSize = w:tell()
|
||||
w:u32le(0)
|
||||
local moviBase = w:tell()
|
||||
w:string("movi")
|
||||
local index = table.create(#chunks)
|
||||
for _, c in chunks do
|
||||
local si, data, key = c[1], c[2], c[3]
|
||||
local s = opts.streams[si]
|
||||
local id = string.format("%02d", si - 1) .. (s.ckid or (if s.type == "vids" then "dc" else "wb"))
|
||||
local at = w:tell()
|
||||
local n = buffer.len(data)
|
||||
w:string(id)
|
||||
w:u32le(n)
|
||||
w:bytes(data)
|
||||
if n % 2 == 1 then
|
||||
w:u8(0)
|
||||
end
|
||||
table.insert(index, { id, if key then 0x10 else 0, at - moviBase, n })
|
||||
end
|
||||
w:setU32le(moviSize, w:tell() - moviSize - 4)
|
||||
-- idx1
|
||||
w:string("idx1")
|
||||
w:u32le(#index * 16)
|
||||
for _, e in index do
|
||||
w:string(e[1])
|
||||
w:u32le(e[2])
|
||||
w:u32le(e[3])
|
||||
w:u32le(e[4])
|
||||
end
|
||||
w:setU32le(riffSize, w:tell() - 8)
|
||||
return w:finish()
|
||||
end
|
||||
|
||||
return Avi
|
||||
@@ -0,0 +1,296 @@
|
||||
--!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,
|
||||
startTime: 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,
|
||||
startTime = 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
|
||||
local start = math.huge
|
||||
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]
|
||||
if t.kind == "video" or t.kind == "audio" then
|
||||
start = math.min(start, self.pts[first] / scale)
|
||||
end
|
||||
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
|
||||
-- the presentation time of the first video / audio packet (MPEG-TS streams start at ~1.4 s): VideoDecoders count
|
||||
-- frame times from it
|
||||
self.startTime = if start ~= math.huge and start > 0 then start else 0
|
||||
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
|
||||
@@ -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
|
||||
@@ -92,7 +92,7 @@ local function esds(w: Bytes.Writer, t: MuxTrack)
|
||||
c:u24be(0)
|
||||
c:u32be(t.bitrate or 0)
|
||||
c:u32be(t.bitrate or 0)
|
||||
if t.config then
|
||||
if t.config and buffer.len(t.config) > 0 then -- (MJPEG / MP3 have no decoder-specific info)
|
||||
descriptor(c, 5, function(s)
|
||||
s:bytes(t.config :: buffer)
|
||||
end)
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
--!strict
|
||||
-- containers/MpegEs: helpers over MPEG video elementary streams for the MPEG-TS / PS demuxers. New in formats-luau.
|
||||
-- Start-code scanning, MPEG-1 / MPEG-2 video access units (a picture with the sequence / GOP headers before it,
|
||||
-- picture type and temporal reference, the sequence's frame rate and size, MPEG-2 detection by its sequence
|
||||
-- extension) and H.264 Annex B keyframes (an IDR slice, or a recovery-point SEI). Interpreted; never throws.
|
||||
local readu8 = buffer.readu8
|
||||
|
||||
local MpegEs = {}
|
||||
|
||||
-- next start code (00 00 01 xx) at or after p, before limit: position of the 00 00 01 | nil
|
||||
function MpegEs.findStart(b: buffer, p: number, limit: number): number?
|
||||
local i = p
|
||||
while i + 3 <= limit do
|
||||
local c = readu8(b, i + 2)
|
||||
if c > 1 then
|
||||
i += 3
|
||||
elseif c == 1 then
|
||||
if readu8(b, i) == 0 and readu8(b, i + 1) == 0 then
|
||||
return i
|
||||
end
|
||||
i += 3
|
||||
else -- c == 0: the start code may begin at i + 1 or i + 2
|
||||
i += 1
|
||||
end
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
local FRAME_RATES = { 24000 / 1001, 24, 25, 30000 / 1001, 30, 50, 60000 / 1001, 60 }
|
||||
|
||||
export type Picture = {
|
||||
offset: number, -- start of the access unit (its first header's start code)
|
||||
size: number,
|
||||
type: number, -- 1 I, 2 P, 3 B, 4 D (0 unknown)
|
||||
temporal: number, -- temporal_reference
|
||||
gop: boolean, -- a GOP header precedes the picture
|
||||
sequence: boolean, -- a sequence header precedes the picture
|
||||
}
|
||||
export type Info = { width: number, height: number, frameRate: number, mpeg2: boolean }
|
||||
|
||||
-- info(b, off, limit) -> the first sequence header's facts | nil
|
||||
function MpegEs.info(b: buffer, off: number, limit: number): Info?
|
||||
local p = MpegEs.findStart(b, off, limit)
|
||||
local info: Info? = nil
|
||||
local count = 0
|
||||
while p and count < 64 do
|
||||
count += 1
|
||||
local code = if p + 3 < limit then readu8(b, p + 3) else -1
|
||||
if code == 0xB3 and p + 11 < limit and not info then
|
||||
local w = readu8(b, p + 4) * 16 + readu8(b, p + 5) // 16
|
||||
local h = (readu8(b, p + 5) % 16) * 256 + readu8(b, p + 6)
|
||||
local fr = readu8(b, p + 7) % 16
|
||||
info = { width = w, height = h, frameRate = FRAME_RATES[fr] or 0, mpeg2 = false }
|
||||
elseif code == 0xB5 and info then
|
||||
info.mpeg2 = true
|
||||
return info
|
||||
elseif code == 0x00 and info then
|
||||
return info
|
||||
end
|
||||
p = MpegEs.findStart(b, p + 4, limit)
|
||||
end
|
||||
return info
|
||||
end
|
||||
|
||||
-- pictureType(b, off, limit) -> the type (1 I, 2 P, 3 B) and temporal reference of the first picture header | 0
|
||||
function MpegEs.pictureType(b: buffer, off: number, limit: number): (number, number)
|
||||
local p = MpegEs.findStart(b, off, limit)
|
||||
local count = 0
|
||||
while p and count < 32 do
|
||||
count += 1
|
||||
if p + 5 < limit and readu8(b, p + 3) == 0x00 then
|
||||
local x = readu8(b, p + 4) * 256 + readu8(b, p + 5)
|
||||
return (x // 8) % 8, x // 64
|
||||
end
|
||||
p = MpegEs.findStart(b, p + 4, limit)
|
||||
end
|
||||
return 0, 0
|
||||
end
|
||||
|
||||
-- pictures(b, off, limit) -> access units of an MPEG-1 / 2 video elementary stream: each picture starts at its
|
||||
-- sequence / GOP header when one precedes it and runs to the next unit's start
|
||||
function MpegEs.pictures(b: buffer, off: number, limit: number): { Picture }
|
||||
local out: { Picture } = {}
|
||||
local unitStart: number? = nil
|
||||
local seq, gop = false, false
|
||||
local cur: Picture? = nil
|
||||
local p = MpegEs.findStart(b, off, limit)
|
||||
while p do
|
||||
local code = if p + 3 < limit then readu8(b, p + 3) else -1
|
||||
if code == 0xB3 or code == 0xB8 or code == 0x00 or code == 0xB7 then
|
||||
-- a sequence / GOP header or a picture after a picture closes it
|
||||
if cur and (code ~= 0xB7) then
|
||||
cur.size = p - cur.offset
|
||||
table.insert(out, cur)
|
||||
cur = nil
|
||||
end
|
||||
if code == 0xB3 then
|
||||
unitStart = unitStart or p
|
||||
seq = true
|
||||
elseif code == 0xB8 then
|
||||
unitStart = unitStart or p
|
||||
gop = true
|
||||
elseif code == 0x00 then
|
||||
local t, tr = 0, 0
|
||||
if p + 5 < limit then
|
||||
local x = readu8(b, p + 4) * 256 + readu8(b, p + 5)
|
||||
t, tr = (x // 8) % 8, x // 64
|
||||
end
|
||||
cur = { offset = unitStart or p, size = 0, type = t, temporal = tr, gop = gop, sequence = seq }
|
||||
unitStart, seq, gop = nil, false, false
|
||||
elseif code == 0xB7 and cur then
|
||||
cur.size = p + 4 - cur.offset
|
||||
table.insert(out, cur)
|
||||
cur = nil
|
||||
end
|
||||
end
|
||||
p = MpegEs.findStart(b, p + 4, limit)
|
||||
end
|
||||
if cur then
|
||||
cur.size = limit - cur.offset
|
||||
table.insert(out, cur)
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
-- h264Key(b, off, limit) -> an Annex B access unit holds an IDR slice (NAL type 5)
|
||||
function MpegEs.h264Key(b: buffer, off: number, limit: number): boolean
|
||||
local p = MpegEs.findStart(b, off, limit)
|
||||
local count = 0
|
||||
while p and count < 64 do
|
||||
count += 1
|
||||
if p + 3 < limit then
|
||||
local t = readu8(b, p + 3) % 32
|
||||
if t == 5 then
|
||||
return true
|
||||
elseif t == 1 then
|
||||
return false
|
||||
end
|
||||
end
|
||||
p = MpegEs.findStart(b, p + 3, limit)
|
||||
end
|
||||
return false
|
||||
end
|
||||
|
||||
return MpegEs
|
||||
@@ -0,0 +1,224 @@
|
||||
--!strict
|
||||
-- containers/MpegPs: the MPEG program stream (ISO/IEC 11172-1 system streams and ISO/IEC 13818-1 program streams:
|
||||
-- .mpg / .mpeg / .vob). New in formats-luau. Pack headers (MPEG-1 and MPEG-2 layouts), system headers, the program
|
||||
-- stream map (stream types), padding, and PES packets of the video (0xE0..0xEF), audio (0xC0..0xDF) and private
|
||||
-- stream 1 (0xBD: AC-3 / DTS / LPCM / subpicture sub-streams) ids with their PTS / DTS (both PES header layouts,
|
||||
-- 33-bit timestamps unwrapped). Data between packs that is not a start code is skipped (resync).
|
||||
--
|
||||
-- local ps, err = MpegPs.read(buf, base, limit)
|
||||
-- ps.streams[id] = { id, kind, codec, streamType, pes = { { pts?, dts?, offset, size } } } (id: stream_id, or
|
||||
-- 0xBD00 + sub-stream id for private stream 1); ps.order = the ids in order of appearance
|
||||
--
|
||||
-- Never throws: malformed packets are skipped and counted in ps.errors.
|
||||
local Err = require("@formats/core/Err")
|
||||
local MpegEs = require("@formats/containers/MpegEs")
|
||||
|
||||
local readu8 = buffer.readu8
|
||||
|
||||
local MpegPs = {}
|
||||
|
||||
export type Pes = { pts: number?, dts: number?, offset: number, size: number }
|
||||
export type Stream = { id: number, kind: string, codec: string, streamType: number?, pes: { Pes } }
|
||||
export type File = { streams: { [number]: Stream }, order: { number }, mpeg2: boolean, errors: number }
|
||||
|
||||
local WRAP = 8589934592 -- 2^33
|
||||
|
||||
-- PSM stream_type -> kind, codec
|
||||
local TYPES: { [number]: { string } } = {
|
||||
[0x01] = { "video", "mpeg1" },
|
||||
[0x02] = { "video", "mpeg2" },
|
||||
[0x03] = { "audio", "mp2" },
|
||||
[0x04] = { "audio", "mp2" },
|
||||
[0x0F] = { "audio", "aac" },
|
||||
[0x10] = { "video", "mpeg4" },
|
||||
[0x1B] = { "video", "h264" },
|
||||
[0x24] = { "video", "hevc" },
|
||||
[0x81] = { "audio", "ac3" },
|
||||
}
|
||||
|
||||
local function ts(b: buffer, p: number): number
|
||||
local a = readu8(b, p)
|
||||
local v = (a // 2) % 8
|
||||
v = v * 32768 + (readu8(b, p + 1) * 256 + readu8(b, p + 2)) // 2
|
||||
v = v * 32768 + (readu8(b, p + 3) * 256 + readu8(b, p + 4)) // 2
|
||||
return v
|
||||
end
|
||||
|
||||
-- read(buf, base, limit) -> File | nil, Err
|
||||
function MpegPs.read(b: buffer, base: number, limit: number): (File?, Err.Err?)
|
||||
local file: File = { streams = {}, order = {}, mpeg2 = false, errors = 0 }
|
||||
local types: { [number]: number } = {}
|
||||
local last: { [number]: number } = {}
|
||||
local wrap: { [number]: number } = {}
|
||||
local packs = 0
|
||||
local p = MpegEs.findStart(b, base, limit)
|
||||
local function unwrap(id: number, v: number): number
|
||||
local off = wrap[id] or 0
|
||||
local prev = last[id]
|
||||
local t = v + off
|
||||
if prev and t < prev - WRAP / 2 then
|
||||
off += WRAP
|
||||
wrap[id] = off
|
||||
t = v + off
|
||||
end
|
||||
last[id] = t
|
||||
return t
|
||||
end
|
||||
while p do
|
||||
if p + 4 > limit then
|
||||
break
|
||||
end
|
||||
local code = readu8(b, p + 3)
|
||||
local nextP = p + 4
|
||||
if code == 0xBA then
|
||||
packs += 1
|
||||
if p + 5 > limit then
|
||||
break
|
||||
end
|
||||
local m = readu8(b, p + 4)
|
||||
if m // 64 == 1 then -- MPEG-2 pack: 14 bytes + stuffing
|
||||
file.mpeg2 = true
|
||||
if p + 14 > limit then
|
||||
break
|
||||
end
|
||||
nextP = p + 14 + readu8(b, p + 13) % 8
|
||||
else
|
||||
nextP = p + 12
|
||||
end
|
||||
elseif code == 0xB9 then
|
||||
nextP = p + 4
|
||||
elseif code >= 0xBB then
|
||||
if p + 6 > limit then
|
||||
break
|
||||
end
|
||||
local len = readu8(b, p + 4) * 256 + readu8(b, p + 5)
|
||||
local stop = p + 6 + len
|
||||
if stop > limit then
|
||||
stop = limit
|
||||
end
|
||||
nextP = stop
|
||||
if code == 0xBC and len >= 10 then -- program stream map
|
||||
local infoLen = readu8(b, p + 8) * 256 + readu8(b, p + 9)
|
||||
local q = p + 10 + infoLen
|
||||
if q + 2 <= stop then
|
||||
local mapLen = readu8(b, q) * 256 + readu8(b, q + 1)
|
||||
q += 2
|
||||
local e = math.min(stop, q + mapLen)
|
||||
while q + 4 <= e do
|
||||
local st, sid = readu8(b, q), readu8(b, q + 1)
|
||||
local il = readu8(b, q + 2) * 256 + readu8(b, q + 3)
|
||||
types[sid] = st
|
||||
q += 4 + il
|
||||
end
|
||||
end
|
||||
elseif code == 0xBD or (code >= 0xC0 and code <= 0xEF) then
|
||||
-- a PES packet
|
||||
local q = p + 6
|
||||
local pts, dts: number? = nil, nil
|
||||
local ok = true
|
||||
if q < stop and readu8(b, q) // 64 == 2 then -- MPEG-2 PES header
|
||||
if q + 3 > stop then
|
||||
ok = false
|
||||
else
|
||||
local flags = readu8(b, q + 1)
|
||||
local hlen = readu8(b, q + 2)
|
||||
local h = q + 3
|
||||
if flags >= 0x80 and h + 5 <= stop then
|
||||
pts = ts(b, h)
|
||||
if flags // 64 == 3 and h + 10 <= stop then
|
||||
dts = ts(b, h + 5)
|
||||
end
|
||||
end
|
||||
q = h + hlen
|
||||
end
|
||||
else -- MPEG-1 packet header
|
||||
local n = 0
|
||||
while q < stop and readu8(b, q) == 0xFF and n < 16 do
|
||||
q += 1
|
||||
n += 1
|
||||
end
|
||||
if q < stop and readu8(b, q) // 64 == 1 then
|
||||
q += 2
|
||||
end
|
||||
if q < stop then
|
||||
local c = readu8(b, q) // 16
|
||||
if c == 2 and q + 5 <= stop then
|
||||
pts = ts(b, q)
|
||||
q += 5
|
||||
elseif c == 3 and q + 10 <= stop then
|
||||
pts = ts(b, q)
|
||||
dts = ts(b, q + 5)
|
||||
q += 10
|
||||
elseif readu8(b, q) == 0x0F then
|
||||
q += 1
|
||||
else
|
||||
ok = false
|
||||
end
|
||||
end
|
||||
end
|
||||
if ok and q <= stop then
|
||||
local id = code
|
||||
local kind, codec = "other", "unknown"
|
||||
if code == 0xBD then
|
||||
if q >= stop then
|
||||
ok = false
|
||||
else
|
||||
local sub = readu8(b, q)
|
||||
id = 0xBD00 + sub
|
||||
if sub >= 0x80 and sub <= 0x87 then
|
||||
kind, codec = "audio", "ac3"
|
||||
q += 4
|
||||
elseif sub >= 0x88 and sub <= 0x8F then
|
||||
kind, codec = "audio", "dts"
|
||||
q += 4
|
||||
elseif sub >= 0xA0 and sub <= 0xA7 then
|
||||
kind, codec = "audio", "pcm_dvd"
|
||||
q += 7
|
||||
elseif sub >= 0x20 and sub <= 0x3F then
|
||||
kind, codec = "subtitle", "dvdsub"
|
||||
q += 1
|
||||
else
|
||||
q += 1
|
||||
end
|
||||
end
|
||||
elseif code >= 0xE0 then
|
||||
kind, codec = "video", "mpeg1"
|
||||
else
|
||||
kind, codec = "audio", "mp2"
|
||||
end
|
||||
local st = types[code]
|
||||
if st and TYPES[st] then
|
||||
kind, codec = TYPES[st][1], TYPES[st][2]
|
||||
end
|
||||
if ok and q <= stop then
|
||||
local s = file.streams[id]
|
||||
if not s then
|
||||
s = { id = id, kind = kind, codec = codec, streamType = st, pes = {} }
|
||||
file.streams[id] = s
|
||||
table.insert(file.order, id)
|
||||
end
|
||||
table.insert(s.pes, {
|
||||
pts = if pts then unwrap(id, pts) else nil,
|
||||
dts = if dts then unwrap(id + 0x10000, dts) else nil,
|
||||
offset = q,
|
||||
size = stop - q,
|
||||
})
|
||||
end
|
||||
end
|
||||
if not ok then
|
||||
file.errors += 1
|
||||
end
|
||||
end
|
||||
else
|
||||
-- a start code that is not a system one (stray ES data between packets): resync
|
||||
file.errors += 1
|
||||
end
|
||||
p = MpegEs.findStart(b, nextP, limit)
|
||||
end
|
||||
if packs == 0 and #file.order == 0 then
|
||||
return nil, Err.new(Err.CORRUPT, "no MPEG pack or PES packet", base)
|
||||
end
|
||||
return file, nil
|
||||
end
|
||||
|
||||
return MpegPs
|
||||
@@ -0,0 +1,831 @@
|
||||
--!strict
|
||||
--!native
|
||||
-- containers/MpegTs: an MPEG transport stream demuxer (ISO/IEC 13818-1). Absorbed from mpegts-luau 6e16197 (same
|
||||
-- author; no third-party code). Changed: this header, and the unit queue keeps an explicit tail (pull() used #q on a
|
||||
-- table with holes at its front, which LuaJIT's border rule makes lose units). 188-byte packets with resync, PAT / PMT sections
|
||||
-- (assembled across packets, CRC-checked), adaptation fields (PCR, discontinuity, random access), continuity
|
||||
-- counter checks (gaps are flagged on the unit, duplicates dropped), PES reassembly with 33-bit PTS / DTS.
|
||||
--
|
||||
-- local units = MpegTs.demux(buf) -- whole segment: { video = {...}, audio = {...}, streams, ... }
|
||||
-- local d = MpegTs.new(); d:push(chunk); local u = d:pull() ... d:flush() -- streamed
|
||||
--
|
||||
-- Native code must never throw (an error unwinding through native code crashes Roblox Studio), so every read is
|
||||
-- bounds-checked by construction and bad input is skipped and counted in `stats`, never raised.
|
||||
|
||||
local MpegTs = {}
|
||||
|
||||
export type Stream = {
|
||||
pid: number,
|
||||
streamType: number, -- PMT stream_type (0 when the stream was found without a PMT)
|
||||
kind: string, -- "video" | "audio" | "other"
|
||||
codec: string, -- "mpeg1video" | "mpeg2video" | "mpegaudio" | "aac" | "h264" | "hevc" | "ac3" | "unknown" ...
|
||||
program: number, -- program_number (0 without a PMT)
|
||||
language: string?, -- ISO 639 language descriptor, when present
|
||||
}
|
||||
|
||||
export type Unit = {
|
||||
pid: number,
|
||||
kind: string,
|
||||
codec: string,
|
||||
streamType: number,
|
||||
streamId: number, -- PES stream_id (0xE0.. video, 0xC0.. audio)
|
||||
pts: number?, -- seconds (33-bit 90 kHz clock, unwrapped per PID)
|
||||
dts: number?, -- seconds; equals pts when the PES carries no DTS
|
||||
pts90: number?, -- the same in 90 kHz ticks
|
||||
dts90: number?,
|
||||
data: buffer, -- the PES payload (one access unit for video as muxed by ffmpeg; one or more frames for audio)
|
||||
ccError: boolean, -- a continuity counter gap (lost packets) happened inside this unit
|
||||
randomAccess: boolean, -- the first packet's adaptation field had random_access_indicator set
|
||||
discontinuity: boolean, -- the first packet's adaptation field had discontinuity_indicator set
|
||||
}
|
||||
|
||||
export type Stats = {
|
||||
packets: number,
|
||||
syncLosses: number, -- resyncs (bytes skipped to find 0x47 again)
|
||||
skippedBytes: number,
|
||||
teiErrors: number, -- transport_error_indicator packets (dropped)
|
||||
ccErrors: number, -- continuity counter gaps
|
||||
duplicates: number, -- duplicate packets (same CC), dropped
|
||||
crcErrors: number, -- PSI sections with a bad CRC (ignored)
|
||||
pesErrors: number, -- PES units without a valid header (dropped)
|
||||
scrambled: number, -- scrambled packets (dropped)
|
||||
pcr: number?, -- last PCR seen, seconds
|
||||
}
|
||||
|
||||
export type Demuxed = {
|
||||
video: { Unit }, -- units of the selected video PID (first video stream of the PMT), in stream order
|
||||
audio: { Unit }, -- units of the selected audio PID
|
||||
streams: { Stream }, -- every elementary stream, PMT order
|
||||
units: { Unit }, -- every unit of every PID, in completion order
|
||||
videoPid: number?,
|
||||
audioPid: number?,
|
||||
stats: Stats,
|
||||
}
|
||||
|
||||
type PesState = {
|
||||
buf: buffer,
|
||||
len: number,
|
||||
active: boolean,
|
||||
expected: number, -- total PES bytes when PES_packet_length is set, else 0 (ends at the next unit start)
|
||||
hdrChecked: boolean,
|
||||
ccError: boolean,
|
||||
randomAccess: boolean,
|
||||
discontinuity: boolean,
|
||||
lastPts: number, -- for 33-bit wrap unwrapping
|
||||
wrapOffset: number,
|
||||
}
|
||||
|
||||
type SectionState = { buf: buffer, len: number, active: boolean }
|
||||
|
||||
local TS_SIZE = 188
|
||||
local SYNC = 0x47
|
||||
local MAX_SECTION = 4096 + 188
|
||||
local WRAP = 8589934592 -- 2^33
|
||||
|
||||
local readu8 = buffer.readu8
|
||||
local band = bit32.band
|
||||
local bor = bit32.bor
|
||||
local lshift = bit32.lshift
|
||||
local rshift = bit32.rshift
|
||||
|
||||
local CODECS: { [number]: { string } } = {
|
||||
[0x01] = { "video", "mpeg1video" },
|
||||
[0x02] = { "video", "mpeg2video" },
|
||||
[0x03] = { "audio", "mpegaudio" },
|
||||
[0x04] = { "audio", "mpegaudio" },
|
||||
[0x0F] = { "audio", "aac" },
|
||||
[0x10] = { "video", "mpeg4" },
|
||||
[0x11] = { "audio", "aac_latm" },
|
||||
[0x1B] = { "video", "h264" },
|
||||
[0x24] = { "video", "hevc" },
|
||||
[0x81] = { "audio", "ac3" },
|
||||
[0x87] = { "audio", "eac3" },
|
||||
}
|
||||
|
||||
-- CRC-32/MPEG-2 (poly 0x04C11DB7, init 0xFFFFFFFF, MSB first, no final xor): a section including its CRC sums to 0
|
||||
local CRC = buffer.create(256 * 4)
|
||||
for i = 0, 255 do
|
||||
local c = lshift(i, 24)
|
||||
for _ = 1, 8 do
|
||||
if band(c, 0x80000000) ~= 0 then
|
||||
c = bit32.bxor(lshift(c, 1), 0x04C11DB7)
|
||||
else
|
||||
c = lshift(c, 1)
|
||||
end
|
||||
end
|
||||
buffer.writeu32(CRC, i * 4, c)
|
||||
end
|
||||
|
||||
local function crc32(b: buffer, off: number, n: number): number
|
||||
local c = 0xFFFFFFFF
|
||||
for i = off, off + n - 1 do
|
||||
c = bit32.bxor(lshift(c, 8), buffer.readu32(CRC, band(bit32.bxor(rshift(c, 24), readu8(b, i)), 255) * 4))
|
||||
end
|
||||
return c
|
||||
end
|
||||
MpegTs.crc32 = crc32
|
||||
|
||||
local function u16(b: buffer, p: number): number
|
||||
return readu8(b, p) * 256 + readu8(b, p + 1)
|
||||
end
|
||||
|
||||
-- 33-bit timestamp from the 5-byte PES encoding at p
|
||||
local function readTs(b: buffer, p: number): number
|
||||
local b0 = readu8(b, p)
|
||||
local hi = band(rshift(b0, 1), 7) * 1073741824 -- bits 32..30
|
||||
local mid = bor(lshift(readu8(b, p + 1), 7), rshift(readu8(b, p + 2), 1)) -- bits 29..15
|
||||
local lo = bor(lshift(readu8(b, p + 3), 7), rshift(readu8(b, p + 4), 1)) -- bits 14..0
|
||||
return hi + mid * 32768 + lo
|
||||
end
|
||||
|
||||
local Demuxer = {}
|
||||
Demuxer.__index = Demuxer
|
||||
|
||||
export type Demuxer = typeof(setmetatable(
|
||||
{} :: {
|
||||
_pend: buffer,
|
||||
_pendLen: number,
|
||||
_pmtPids: { [number]: number },
|
||||
_streams: { [number]: Stream },
|
||||
_pes: { [number]: PesState },
|
||||
_sections: { [number]: SectionState },
|
||||
_cc: { [number]: number },
|
||||
_queue: { Unit },
|
||||
_qhead: number,
|
||||
_qtail: number,
|
||||
streams: { Stream },
|
||||
stats: Stats,
|
||||
},
|
||||
Demuxer
|
||||
))
|
||||
|
||||
function MpegTs.new(): Demuxer
|
||||
local self = setmetatable({
|
||||
_pend = buffer.create(64 * 1024),
|
||||
_pendLen = 0,
|
||||
_pmtPids = {},
|
||||
_streams = {},
|
||||
_pes = {},
|
||||
_sections = {},
|
||||
_cc = {},
|
||||
_queue = {},
|
||||
_qhead = 1,
|
||||
_qtail = 0,
|
||||
streams = {},
|
||||
stats = {
|
||||
packets = 0,
|
||||
syncLosses = 0,
|
||||
skippedBytes = 0,
|
||||
teiErrors = 0,
|
||||
ccErrors = 0,
|
||||
duplicates = 0,
|
||||
crcErrors = 0,
|
||||
pesErrors = 0,
|
||||
scrambled = 0,
|
||||
pcr = nil,
|
||||
} :: Stats,
|
||||
}, Demuxer)
|
||||
return self
|
||||
end
|
||||
|
||||
-- PSI ---------------------------------------------------------------------------------------------------------
|
||||
|
||||
local function addStream(self: Demuxer, pid: number, streamType: number, program: number, language: string?)
|
||||
local info = CODECS[streamType]
|
||||
local s = self._streams[pid]
|
||||
if s == nil then
|
||||
s = {
|
||||
pid = pid,
|
||||
streamType = streamType,
|
||||
kind = if info then info[1] else "other",
|
||||
codec = if info then info[2] else "unknown",
|
||||
program = program,
|
||||
language = language,
|
||||
}
|
||||
self._streams[pid] = s
|
||||
table.insert(self.streams, s)
|
||||
else
|
||||
s.streamType = streamType
|
||||
s.kind = if info then info[1] else "other"
|
||||
s.codec = if info then info[2] else "unknown"
|
||||
s.program = program
|
||||
s.language = language
|
||||
end
|
||||
end
|
||||
|
||||
local function parseSection(self: Demuxer, pid: number, b: buffer, n: number)
|
||||
-- n >= 3 bytes: table_id, section_length (n = 3 + section_length)
|
||||
if n < 12 then
|
||||
return
|
||||
end
|
||||
if band(readu8(b, 1), 0x80) == 0 then
|
||||
return -- no section_syntax_indicator: not a PAT / PMT
|
||||
end
|
||||
if crc32(b, 0, n) ~= 0 then
|
||||
self.stats.crcErrors += 1
|
||||
return
|
||||
end
|
||||
if band(readu8(b, 5), 1) == 0 then
|
||||
return -- current_next_indicator = 0: a future table
|
||||
end
|
||||
local tid = readu8(b, 0)
|
||||
local stop = n - 4
|
||||
if tid == 0x00 and pid == 0 then
|
||||
local p = 8
|
||||
while p + 4 <= stop do
|
||||
local prog = u16(b, p)
|
||||
local pmt = band(u16(b, p + 2), 0x1FFF)
|
||||
if prog ~= 0 then
|
||||
self._pmtPids[pmt] = prog
|
||||
end
|
||||
p += 4
|
||||
end
|
||||
elseif tid == 0x02 and self._pmtPids[pid] ~= nil then
|
||||
local program = u16(b, 3)
|
||||
local p = 12 + band(u16(b, 10), 0x0FFF)
|
||||
while p + 5 <= stop do
|
||||
local st = readu8(b, p)
|
||||
local epid = band(u16(b, p + 1), 0x1FFF)
|
||||
local esl = band(u16(b, p + 3), 0x0FFF)
|
||||
local d = p + 5
|
||||
local dend = math.min(d + esl, stop)
|
||||
local language: string? = nil
|
||||
while d + 2 <= dend do
|
||||
local tag, len = readu8(b, d), readu8(b, d + 1)
|
||||
if tag == 0x0A and len >= 3 and d + 5 <= dend then
|
||||
language = buffer.readstring(b, d + 2, 3)
|
||||
end
|
||||
d += 2 + len
|
||||
end
|
||||
addStream(self, epid, st, program, language)
|
||||
p += 5 + esl
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
local function sectionBytes(self: Demuxer, pid: number, s: SectionState, src: buffer, from: number, to: number)
|
||||
local n = to - from
|
||||
if n <= 0 then
|
||||
return
|
||||
end
|
||||
if s.len + n > MAX_SECTION then
|
||||
s.active = false
|
||||
s.len = 0
|
||||
return
|
||||
end
|
||||
buffer.copy(s.buf, s.len, src, from, n)
|
||||
s.len += n
|
||||
-- every complete section in the buffer
|
||||
while s.active and s.len >= 3 do
|
||||
if readu8(s.buf, 0) == 0xFF then
|
||||
s.active = false -- stuffing: no more sections until the next unit start
|
||||
s.len = 0
|
||||
return
|
||||
end
|
||||
local need = 3 + band(u16(s.buf, 1), 0x0FFF)
|
||||
if s.len < need then
|
||||
return
|
||||
end
|
||||
parseSection(self, pid, s.buf, need)
|
||||
local rest = s.len - need
|
||||
if rest > 0 then
|
||||
buffer.copy(s.buf, 0, s.buf, need, rest)
|
||||
end
|
||||
s.len = rest
|
||||
end
|
||||
end
|
||||
|
||||
local function sectionPayload(self: Demuxer, pid: number, pusi: boolean, b: buffer, pos: number, stop: number)
|
||||
local s = self._sections[pid]
|
||||
if s == nil then
|
||||
s = { buf = buffer.create(MAX_SECTION), len = 0, active = false }
|
||||
self._sections[pid] = s
|
||||
end
|
||||
if pusi then
|
||||
if pos >= stop then
|
||||
return
|
||||
end
|
||||
local ptr = readu8(b, pos)
|
||||
pos += 1
|
||||
local tail = math.min(pos + ptr, stop)
|
||||
if s.active then
|
||||
sectionBytes(self, pid, s, b, pos, tail) -- the end of the previous section
|
||||
end
|
||||
s.active = true
|
||||
s.len = 0
|
||||
pos = tail
|
||||
elseif not s.active then
|
||||
return
|
||||
end
|
||||
sectionBytes(self, pid, s, b, pos, stop)
|
||||
end
|
||||
|
||||
-- PES ---------------------------------------------------------------------------------------------------------
|
||||
|
||||
local function completePes(self: Demuxer, pid: number, st: PesState)
|
||||
st.active = false
|
||||
local b, len = st.buf, st.len
|
||||
if len < 6 or readu8(b, 0) ~= 0 or readu8(b, 1) ~= 0 or readu8(b, 2) ~= 1 then
|
||||
self.stats.pesErrors += 1
|
||||
return
|
||||
end
|
||||
local sid = readu8(b, 3)
|
||||
local stop = if st.expected > 0 then math.min(st.expected, len) else len
|
||||
local start = 6
|
||||
local pts: number?, dts: number? = nil, nil
|
||||
if not (sid == 0xBC or sid == 0xBE or sid == 0xBF or sid == 0xF0 or sid == 0xF1 or sid == 0xF2 or sid == 0xF8 or sid == 0xFF) then
|
||||
if stop < 9 then
|
||||
self.stats.pesErrors += 1
|
||||
return
|
||||
end
|
||||
if band(readu8(b, 6), 0xC0) == 0x80 then
|
||||
-- MPEG-2 PES header
|
||||
local flags = readu8(b, 7)
|
||||
local hl = readu8(b, 8)
|
||||
start = 9 + hl
|
||||
if band(flags, 0x80) ~= 0 and hl >= 5 and 14 <= stop then
|
||||
pts = readTs(b, 9)
|
||||
if band(flags, 0x40) ~= 0 and hl >= 10 and 19 <= stop then
|
||||
dts = readTs(b, 14)
|
||||
end
|
||||
end
|
||||
else
|
||||
-- MPEG-1 (ISO 11172-1) packet header: stuffing, STD buffer, PTS / DTS
|
||||
local p = 6
|
||||
local k = 0
|
||||
while p < stop and readu8(b, p) == 0xFF and k < 16 do
|
||||
p += 1
|
||||
k += 1
|
||||
end
|
||||
if p < stop and band(readu8(b, p), 0xC0) == 0x40 then
|
||||
p += 2
|
||||
end
|
||||
if p < stop then
|
||||
local c = band(readu8(b, p), 0xF0)
|
||||
if c == 0x20 and p + 5 <= stop then
|
||||
pts = readTs(b, p)
|
||||
p += 5
|
||||
elseif c == 0x30 and p + 10 <= stop then
|
||||
pts = readTs(b, p)
|
||||
dts = readTs(b, p + 5)
|
||||
p += 10
|
||||
else
|
||||
p += 1
|
||||
end
|
||||
end
|
||||
start = p
|
||||
end
|
||||
end
|
||||
if start > stop then
|
||||
self.stats.pesErrors += 1
|
||||
return
|
||||
end
|
||||
-- unwrap the 33-bit clock (per PID)
|
||||
if pts ~= nil then
|
||||
pts += st.wrapOffset
|
||||
if st.lastPts >= 0 then
|
||||
if pts < st.lastPts - WRAP / 2 then
|
||||
st.wrapOffset += WRAP
|
||||
pts += WRAP
|
||||
elseif pts > st.lastPts + WRAP / 2 and st.wrapOffset >= WRAP then
|
||||
st.wrapOffset -= WRAP
|
||||
pts -= WRAP
|
||||
end
|
||||
end
|
||||
st.lastPts = pts
|
||||
if dts ~= nil then
|
||||
dts += st.wrapOffset
|
||||
if dts > pts + WRAP / 2 then
|
||||
dts -= WRAP
|
||||
elseif dts < pts - WRAP / 2 then
|
||||
dts += WRAP
|
||||
end
|
||||
else
|
||||
dts = pts
|
||||
end
|
||||
end
|
||||
local n = stop - start
|
||||
local data = buffer.create(n)
|
||||
if n > 0 then
|
||||
buffer.copy(data, 0, b, start, n)
|
||||
end
|
||||
local s = self._streams[pid]
|
||||
local kind, codec, streamType
|
||||
if s then
|
||||
kind, codec, streamType = s.kind, s.codec, s.streamType
|
||||
elseif sid >= 0xE0 and sid <= 0xEF then
|
||||
kind, codec, streamType = "video", "unknown", 0
|
||||
elseif sid >= 0xC0 and sid <= 0xDF then
|
||||
kind, codec, streamType = "audio", "mpegaudio", 0
|
||||
else
|
||||
kind, codec, streamType = "other", "unknown", 0
|
||||
end
|
||||
local unit: Unit = {
|
||||
pid = pid,
|
||||
kind = kind,
|
||||
codec = codec,
|
||||
streamType = streamType,
|
||||
streamId = sid,
|
||||
pts = if pts then pts / 90000 else nil,
|
||||
dts = if dts then dts / 90000 else nil,
|
||||
pts90 = pts,
|
||||
dts90 = dts,
|
||||
data = data,
|
||||
ccError = st.ccError,
|
||||
randomAccess = st.randomAccess,
|
||||
discontinuity = st.discontinuity,
|
||||
}
|
||||
local tail = self._qtail + 1
|
||||
self._qtail = tail
|
||||
self._queue[tail] = unit
|
||||
end
|
||||
|
||||
local function pesPayload(
|
||||
self: Demuxer,
|
||||
pid: number,
|
||||
pusi: boolean,
|
||||
b: buffer,
|
||||
pos: number,
|
||||
stop: number,
|
||||
ccError: boolean,
|
||||
randomAccess: boolean,
|
||||
discontinuity: boolean
|
||||
)
|
||||
local st = self._pes[pid]
|
||||
-- a unit starts with a PES start code; anything else on a PID outside the PMT (SDT, EIT ...) is ignored
|
||||
local startCode = pusi
|
||||
and stop - pos >= 3
|
||||
and readu8(b, pos) == 0
|
||||
and readu8(b, pos + 1) == 0
|
||||
and readu8(b, pos + 2) == 1
|
||||
if st == nil then
|
||||
if not startCode then
|
||||
return
|
||||
end
|
||||
st = {
|
||||
buf = buffer.create(16 * 1024),
|
||||
len = 0,
|
||||
active = false,
|
||||
expected = 0,
|
||||
hdrChecked = false,
|
||||
ccError = false,
|
||||
randomAccess = false,
|
||||
discontinuity = false,
|
||||
lastPts = -1,
|
||||
wrapOffset = 0,
|
||||
}
|
||||
self._pes[pid] = st
|
||||
end
|
||||
if ccError and st.active then
|
||||
st.ccError = true -- packets of the unit in progress were lost
|
||||
end
|
||||
if pusi then
|
||||
if st.active then
|
||||
completePes(self, pid, st)
|
||||
end
|
||||
if not startCode then
|
||||
if self._streams[pid] ~= nil then
|
||||
self.stats.pesErrors += 1
|
||||
end
|
||||
return
|
||||
end
|
||||
st.active = true
|
||||
st.len = 0
|
||||
st.expected = 0
|
||||
st.hdrChecked = false
|
||||
st.ccError = false
|
||||
st.randomAccess = randomAccess
|
||||
st.discontinuity = discontinuity
|
||||
elseif not st.active then
|
||||
return
|
||||
end
|
||||
local n = stop - pos
|
||||
if n <= 0 then
|
||||
return
|
||||
end
|
||||
if st.len + n > buffer.len(st.buf) then
|
||||
local cap = buffer.len(st.buf) * 2
|
||||
while cap < st.len + n do
|
||||
cap *= 2
|
||||
end
|
||||
if cap > 64 * 1024 * 1024 then
|
||||
st.active = false -- runaway unit (no unit start for 64 MB): drop it
|
||||
st.len = 0
|
||||
self.stats.pesErrors += 1
|
||||
return
|
||||
end
|
||||
local nb = buffer.create(cap)
|
||||
buffer.copy(nb, 0, st.buf, 0, st.len)
|
||||
st.buf = nb
|
||||
end
|
||||
buffer.copy(st.buf, st.len, b, pos, n)
|
||||
st.len += n
|
||||
if not st.hdrChecked and st.len >= 6 then
|
||||
st.hdrChecked = true
|
||||
local plen = u16(st.buf, 4)
|
||||
if plen > 0 then
|
||||
st.expected = 6 + plen
|
||||
end
|
||||
end
|
||||
if st.expected > 0 and st.len >= st.expected then
|
||||
completePes(self, pid, st)
|
||||
end
|
||||
end
|
||||
|
||||
-- packets -----------------------------------------------------------------------------------------------------
|
||||
|
||||
local function packet(self: Demuxer, b: buffer, pk: number)
|
||||
local stats = self.stats
|
||||
stats.packets += 1
|
||||
local b1 = readu8(b, pk + 1)
|
||||
if band(b1, 0x80) ~= 0 then
|
||||
stats.teiErrors += 1
|
||||
return
|
||||
end
|
||||
local pusi = band(b1, 0x40) ~= 0
|
||||
local pid = band(b1, 0x1F) * 256 + readu8(b, pk + 2)
|
||||
if pid == 0x1FFF then
|
||||
return
|
||||
end
|
||||
local b3 = readu8(b, pk + 3)
|
||||
if band(b3, 0xC0) ~= 0 then
|
||||
stats.scrambled += 1
|
||||
return
|
||||
end
|
||||
local afc = band(rshift(b3, 4), 3)
|
||||
local cc = band(b3, 15)
|
||||
if afc == 0 then
|
||||
return
|
||||
end
|
||||
local pos = pk + 4
|
||||
local stop = pk + TS_SIZE
|
||||
local discontinuity, randomAccess = false, false
|
||||
if afc >= 2 then
|
||||
local afl = readu8(b, pos)
|
||||
pos += 1
|
||||
if afl > 183 then
|
||||
return
|
||||
end
|
||||
if afl > 0 then
|
||||
local flags = readu8(b, pos)
|
||||
discontinuity = band(flags, 0x80) ~= 0
|
||||
randomAccess = band(flags, 0x40) ~= 0
|
||||
if band(flags, 0x10) ~= 0 and afl >= 7 then
|
||||
local base = readu8(b, pos + 1) * 33554432
|
||||
+ readu8(b, pos + 2) * 131072
|
||||
+ readu8(b, pos + 3) * 512
|
||||
+ readu8(b, pos + 4) * 2
|
||||
+ rshift(readu8(b, pos + 5), 7)
|
||||
local ext = band(readu8(b, pos + 5), 1) * 256 + readu8(b, pos + 6)
|
||||
stats.pcr = base / 90000 + ext / 27000000
|
||||
end
|
||||
end
|
||||
pos += afl
|
||||
if afc == 2 then
|
||||
if discontinuity then
|
||||
self._cc[pid] = nil
|
||||
end
|
||||
return -- adaptation field only: the counter does not advance
|
||||
end
|
||||
end
|
||||
-- continuity counter
|
||||
local ccError = false
|
||||
local last = self._cc[pid]
|
||||
if last ~= nil and not discontinuity then
|
||||
if cc == last then
|
||||
stats.duplicates += 1
|
||||
return
|
||||
elseif cc ~= band(last + 1, 15) then
|
||||
ccError = true
|
||||
stats.ccErrors += 1
|
||||
end
|
||||
end
|
||||
self._cc[pid] = cc
|
||||
if pid == 0 or self._pmtPids[pid] ~= nil then
|
||||
sectionPayload(self, pid, pusi, b, pos, stop)
|
||||
elseif pid >= 0x10 then
|
||||
pesPayload(self, pid, pusi, b, pos, stop, ccError, randomAccess, discontinuity)
|
||||
end
|
||||
end
|
||||
|
||||
-- Appends bytes (a buffer, or a string) and demuxes every whole packet in them. Completed units queue up for
|
||||
-- pull(). Returns false for a bad argument.
|
||||
function Demuxer.push(self: Demuxer, data: buffer | string, offset: number?, len: number?): boolean
|
||||
local src: buffer
|
||||
if type(data) == "string" then
|
||||
src = buffer.fromstring(data)
|
||||
elseif type(data) == "buffer" then
|
||||
src = data
|
||||
else
|
||||
return false
|
||||
end
|
||||
local off = math.max(0, math.floor(offset or 0))
|
||||
local total = buffer.len(src)
|
||||
if off > total then
|
||||
return false
|
||||
end
|
||||
local n = math.min(math.floor(len or (total - off)), total - off)
|
||||
if n < 0 then
|
||||
return false
|
||||
end
|
||||
-- append to the pending bytes
|
||||
local need = self._pendLen + n
|
||||
if need > buffer.len(self._pend) then
|
||||
local cap = buffer.len(self._pend)
|
||||
while cap < need do
|
||||
cap *= 2
|
||||
end
|
||||
local nb = buffer.create(cap)
|
||||
buffer.copy(nb, 0, self._pend, 0, self._pendLen)
|
||||
self._pend = nb
|
||||
end
|
||||
if n > 0 then
|
||||
buffer.copy(self._pend, self._pendLen, src, off, n)
|
||||
end
|
||||
self._pendLen = need
|
||||
local b, avail = self._pend, self._pendLen
|
||||
local p = 0
|
||||
while p + TS_SIZE <= avail do
|
||||
if readu8(b, p) ~= SYNC then
|
||||
-- resync: the next 0x47 that is followed by another one 188 bytes later (or by the end of the data)
|
||||
self.stats.syncLosses += 1
|
||||
local q = p + 1
|
||||
local found = -1
|
||||
local waitAt = -1
|
||||
while q < avail do
|
||||
if readu8(b, q) == SYNC then
|
||||
if q + TS_SIZE < avail then
|
||||
if readu8(b, q + TS_SIZE) == SYNC then
|
||||
found = q
|
||||
break
|
||||
end
|
||||
elseif q + TS_SIZE == avail then
|
||||
found = q
|
||||
break
|
||||
else
|
||||
waitAt = q -- not enough bytes to confirm: wait for more
|
||||
break
|
||||
end
|
||||
end
|
||||
q += 1
|
||||
end
|
||||
if found >= 0 then
|
||||
self.stats.skippedBytes += found - p
|
||||
p = found
|
||||
elseif waitAt >= 0 then
|
||||
self.stats.skippedBytes += waitAt - p
|
||||
p = waitAt
|
||||
break
|
||||
else
|
||||
self.stats.skippedBytes += avail - p
|
||||
p = avail
|
||||
break
|
||||
end
|
||||
else
|
||||
packet(self, b, p)
|
||||
p += TS_SIZE
|
||||
end
|
||||
end
|
||||
local rest = avail - p
|
||||
if rest > 0 and p > 0 then
|
||||
buffer.copy(b, 0, b, p, rest)
|
||||
end
|
||||
self._pendLen = rest
|
||||
return true
|
||||
end
|
||||
|
||||
-- The next completed unit (any PID), or nil.
|
||||
function Demuxer.pull(self: Demuxer): Unit?
|
||||
local q = self._queue
|
||||
local h = self._qhead
|
||||
local u = q[h]
|
||||
if u == nil then
|
||||
return nil
|
||||
end
|
||||
q[h] = nil :: any
|
||||
h += 1
|
||||
if h > self._qtail then
|
||||
table.clear(q)
|
||||
h = 1
|
||||
self._qtail = 0
|
||||
end
|
||||
self._qhead = h
|
||||
return u
|
||||
end
|
||||
|
||||
-- Ends every unit in progress (call at the end of the data: a video PES with no length only ends at the next
|
||||
-- unit start). Units still queue up for pull().
|
||||
function Demuxer.flush(self: Demuxer)
|
||||
local pids = {}
|
||||
for pid, st in self._pes do
|
||||
if st.active then
|
||||
table.insert(pids, pid)
|
||||
end
|
||||
end
|
||||
table.sort(pids)
|
||||
for _, pid in pids do
|
||||
completePes(self, pid, self._pes[pid])
|
||||
end
|
||||
self._pendLen = 0
|
||||
end
|
||||
|
||||
-- Forgets buffered bytes, units in progress and continuity state, but keeps the PAT / PMT (for a seek).
|
||||
function Demuxer.reset(self: Demuxer)
|
||||
self._pendLen = 0
|
||||
for _, st in self._pes do
|
||||
st.active = false
|
||||
st.len = 0
|
||||
st.lastPts = -1
|
||||
st.wrapOffset = 0
|
||||
end
|
||||
for _, s in self._sections do
|
||||
s.active = false
|
||||
s.len = 0
|
||||
end
|
||||
table.clear(self._cc)
|
||||
table.clear(self._queue)
|
||||
self._qhead = 1
|
||||
self._qtail = 0
|
||||
end
|
||||
|
||||
-- Streams by kind: the first video / audio PID in PMT order (or in unit order without a PMT).
|
||||
function Demuxer.streamFor(self: Demuxer, kind: string): Stream?
|
||||
for _, s in self.streams do
|
||||
if s.kind == kind then
|
||||
return s
|
||||
end
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
export type DemuxOptions = { videoPid: number?, audioPid: number? }
|
||||
|
||||
-- Demuxes a whole buffer (one segment). Video and audio are the units of one PID each: opts.videoPid /
|
||||
-- opts.audioPid, else the first video / audio stream of the PMT, else the first PID whose units look like video /
|
||||
-- audio (PES stream_id). Never throws; a bad argument gives empty lists.
|
||||
function MpegTs.demux(data: buffer | string, opts: DemuxOptions?): Demuxed
|
||||
local d = MpegTs.new()
|
||||
d:push(data)
|
||||
d:flush()
|
||||
local units = {}
|
||||
while true do
|
||||
local u = d:pull()
|
||||
if u == nil then
|
||||
break
|
||||
end
|
||||
table.insert(units, u)
|
||||
end
|
||||
local videoPid = opts and opts.videoPid
|
||||
local audioPid = opts and opts.audioPid
|
||||
if videoPid == nil then
|
||||
local s = d:streamFor("video")
|
||||
videoPid = if s then s.pid else nil
|
||||
end
|
||||
if audioPid == nil then
|
||||
local s = d:streamFor("audio")
|
||||
audioPid = if s then s.pid else nil
|
||||
end
|
||||
for _, u in units do
|
||||
if videoPid == nil and u.kind == "video" then
|
||||
videoPid = u.pid
|
||||
end
|
||||
if audioPid == nil and u.kind == "audio" then
|
||||
audioPid = u.pid
|
||||
end
|
||||
end
|
||||
local video, audio = {}, {}
|
||||
for _, u in units do
|
||||
if u.pid == videoPid then
|
||||
table.insert(video, u)
|
||||
elseif u.pid == audioPid then
|
||||
table.insert(audio, u)
|
||||
end
|
||||
end
|
||||
return {
|
||||
video = video,
|
||||
audio = audio,
|
||||
streams = d.streams,
|
||||
units = units,
|
||||
videoPid = videoPid,
|
||||
audioPid = audioPid,
|
||||
stats = d.stats,
|
||||
}
|
||||
end
|
||||
|
||||
-- Concatenates the data of a list of units (e.g. a segment's audio access units, for Mp3.open).
|
||||
function MpegTs.concat(units: { Unit }): buffer
|
||||
local n = 0
|
||||
for _, u in units do
|
||||
n += buffer.len(u.data)
|
||||
end
|
||||
local out = buffer.create(n)
|
||||
local p = 0
|
||||
for _, u in units do
|
||||
local l = buffer.len(u.data)
|
||||
buffer.copy(out, p, u.data, 0, l)
|
||||
p += l
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
return MpegTs
|
||||
@@ -1,7 +1,10 @@
|
||||
--!strict
|
||||
-- image/jpeg: JPEG / JFIF / EXIF (ITU T.81). Absorbed from jpeg-luau 1.0 (same author: the Huffman decoder, IDCTs,
|
||||
-- upsampling and colour conversion, bit-exact with libjpeg-turbo's djpeg) and extended with arithmetic coding, meta
|
||||
-- (EXIF, ICC, comments, density) and an encoder. IJG-derived parts: licenses/libjpeg-turbo-LICENSE.md.
|
||||
-- image/jpeg: JPEG / JFIF / EXIF (ITU T.81), a thin format over codecs/Jpeg (the engine, shared with the Motion-JPEG
|
||||
-- video tracks; absorbed from jpeg-luau 1.0, same author, bit-exact with libjpeg-turbo's djpeg and byte-identical
|
||||
-- with cjpeg; IJG-derived parts: licenses/libjpeg-turbo-LICENSE.md). This module is the contract, the sniff, the
|
||||
-- options and the meta segments: meta.exif (APP1), meta.icc (APP2 chunks), meta.text.comment (COM) and meta.dpi
|
||||
-- (JFIF density) are written from the Image on encode and read back on decode. Encode also takes yuv420p Images
|
||||
-- (coded 4:2:0 from the planes as they are).
|
||||
-- Decode: baseline, extended and progressive frames, Huffman or arithmetic coded (SOF0/1/2/9/10), 8 and 12-bit
|
||||
-- samples, 1, 3 or 4 components with any sampling factors 1..4, restart intervals (resynchronising after corrupt
|
||||
-- data), grey / YCbCr / RGB / CMYK / YCCK (Adobe APP14), scaled decodes (opts.scale = 2, 4, 8 through libjpeg's
|
||||
@@ -17,8 +20,7 @@
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Types = require("@formats/Types")
|
||||
local Decode = require("@formats/image/jpeg/Decode")
|
||||
local Encode = require("@formats/image/jpeg/Encode")
|
||||
local Codec = require("@formats/codecs/Jpeg")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Jpeg = {
|
||||
@@ -26,7 +28,7 @@ local Jpeg = {
|
||||
category = "image",
|
||||
extensions = { "jpg", "jpeg", "jpe", "jfif" },
|
||||
mime = { "image/jpeg" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/Dct" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/Jpeg" },
|
||||
caps = { decode = true, encode = true, lossy = true, alpha = false, depths = { 8, 12 }, progressive = true, arithmetic = true },
|
||||
}
|
||||
|
||||
@@ -48,22 +50,7 @@ export type EncodeOptions = {
|
||||
meta: boolean?, -- write meta.exif (APP1), meta.icc (APP2) and meta.text.comment (COM) (default true)
|
||||
}
|
||||
|
||||
export type Info = {
|
||||
width: number,
|
||||
height: number,
|
||||
components: number,
|
||||
progressive: boolean,
|
||||
arithmetic: boolean,
|
||||
precision: number,
|
||||
colorSpace: string,
|
||||
sampling: { { number } }, -- { h, v } per component
|
||||
orientation: number,
|
||||
adobe: number?,
|
||||
jfif: boolean,
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
local CODES = { corrupt = Err.CORRUPT, unsupported = Err.UNSUPPORTED, limit = Err.LIMIT, truncated = Err.TRUNCATED, arg = Err.ARG }
|
||||
export type Info = Codec.Info
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Jpeg.sniff(r: Bytes.Reader): number
|
||||
@@ -72,214 +59,91 @@ function Jpeg.sniff(r: Bytes.Reader): number
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
local function parse(r: Bytes.Reader, opts: any, headerOnly: boolean): (Decode.State?, Err.Err?)
|
||||
local ok, st, code, msg = pcall(Decode.parse, r.buf, r.base, r.limit, opts, headerOnly)
|
||||
if not ok then
|
||||
return nil, Err.new(Err.CORRUPT, "internal error: " .. tostring(st))
|
||||
end
|
||||
if not st then
|
||||
return nil, Err.new(CODES[code :: string] or Err.CORRUPT, msg or "decode failed")
|
||||
end
|
||||
return st, nil
|
||||
end
|
||||
|
||||
-- info(r) -> Info | nil, Err (reads the headers up to the frame header)
|
||||
function Jpeg.info(r: Bytes.Reader): (Info?, Err.Err?)
|
||||
local st, err = parse(r, nil, true)
|
||||
if not st then
|
||||
return nil, err
|
||||
end
|
||||
local f = st.frame
|
||||
local sampling = {}
|
||||
for _, c in f.comps do
|
||||
table.insert(sampling, { c.h, c.v })
|
||||
end
|
||||
return {
|
||||
width = f.width,
|
||||
height = f.height,
|
||||
components = #f.comps,
|
||||
progressive = f.progressive,
|
||||
arithmetic = f.arithmetic,
|
||||
precision = f.precision,
|
||||
colorSpace = Decode.colorSpaceOf(f, st.adobe, st.jfif),
|
||||
sampling = sampling,
|
||||
orientation = st.orientation,
|
||||
adobe = st.adobe,
|
||||
jfif = st.jfif,
|
||||
},
|
||||
nil
|
||||
end
|
||||
|
||||
-- the EXIF orientation applied to rgba8 pixels: buffer, width, height
|
||||
local function orient(px: buffer, w: number, h: number, o: number): (buffer, number, number)
|
||||
if o <= 1 or o > 8 then
|
||||
return px, w, h
|
||||
end
|
||||
local swap = o >= 5
|
||||
local ow, oh = if swap then h else w, if swap then w else h
|
||||
local out = buffer.create(ow * oh * 4)
|
||||
local readu32, writeu32 = buffer.readu32, buffer.writeu32
|
||||
for y = 0, oh - 1 do
|
||||
for x = 0, ow - 1 do
|
||||
local col, row
|
||||
if o == 2 then
|
||||
col, row = w - 1 - x, y
|
||||
elseif o == 3 then
|
||||
col, row = w - 1 - x, h - 1 - y
|
||||
elseif o == 4 then
|
||||
col, row = x, h - 1 - y
|
||||
elseif o == 5 then
|
||||
col, row = y, x
|
||||
elseif o == 6 then
|
||||
col, row = y, h - 1 - x
|
||||
elseif o == 7 then
|
||||
col, row = w - 1 - y, h - 1 - x
|
||||
else
|
||||
col, row = w - 1 - y, x
|
||||
end
|
||||
writeu32(out, (y * ow + x) * 4, readu32(px, (row * w + col) * 4))
|
||||
end
|
||||
end
|
||||
return out, ow, oh
|
||||
return Codec.info(r.buf, r.base, r.limit - r.base)
|
||||
end
|
||||
|
||||
function Jpeg.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
|
||||
local st, err = parse(r, opts, false)
|
||||
if not st then
|
||||
return nil, err
|
||||
if opts ~= nil and type(opts) ~= "table" then
|
||||
return nil, Err.new(Err.ARG, "options must be a table")
|
||||
end
|
||||
local ok, w, h, px, space = pcall(Decode.output, st :: Decode.State)
|
||||
if not ok then
|
||||
return nil, Err.new(Err.CORRUPT, "internal error: " .. tostring(w))
|
||||
end
|
||||
if not w then
|
||||
return nil, Err.new(CODES[h :: string] or Err.CORRUPT, tostring(px))
|
||||
end
|
||||
local orientation = st.orientation
|
||||
if opts and opts.orient then
|
||||
px, w, h = orient(px, w, h, orientation)
|
||||
end
|
||||
local img = Types.Image.new(1, 1)
|
||||
img.width, img.height, img.pixels = w, h, px
|
||||
if opts and opts.native and space == "gray" then
|
||||
local g = buffer.create(w * h)
|
||||
for i = 0, w * h - 1 do
|
||||
buffer.writeu8(g, i, buffer.readu8(px, i * 4))
|
||||
end
|
||||
img.pixels, img.format = g, "gray8"
|
||||
end
|
||||
local f = st.frame
|
||||
local sampling = {}
|
||||
for _, c in f.comps do
|
||||
table.insert(sampling, { c.h, c.v })
|
||||
end
|
||||
img.meta.orientation = orientation
|
||||
img.meta.oriented = (opts and opts.orient) or false
|
||||
img.meta.exif = st.exif
|
||||
img.meta.icc = st.icc
|
||||
if #st.comments > 0 then
|
||||
img.meta.text = { comment = table.concat(st.comments, "\n") }
|
||||
end
|
||||
if st.density and st.density.unit > 0 and st.density.x > 0 and st.density.y > 0 then
|
||||
local k = if st.density.unit == 2 then 2.54 else 1
|
||||
img.meta.dpi = { x = st.density.x * k, y = st.density.y * k }
|
||||
end
|
||||
img.meta.truncated = st.truncated
|
||||
img.meta.source = {
|
||||
format = "jpeg",
|
||||
bitDepth = f.precision,
|
||||
colorType = space,
|
||||
components = #f.comps,
|
||||
progressive = f.progressive,
|
||||
arithmetic = f.arithmetic,
|
||||
sampling = sampling,
|
||||
scale = st.scale,
|
||||
adobe = st.adobe,
|
||||
jfif = st.jfif,
|
||||
}
|
||||
return img, nil
|
||||
local o = opts or {} :: DecodeOptions
|
||||
-- one image: no yuv output, no field weaving (two JPEGs back to back are an image and a preview, as in MPF)
|
||||
return Codec.decode(r.buf, r.base, r.limit - r.base, {
|
||||
scale = o.scale,
|
||||
orient = o.orient,
|
||||
native = o.native,
|
||||
maxPixels = o.maxPixels,
|
||||
fields = false,
|
||||
})
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
local BPP = { rgba8 = 4, rgb8 = 3, gray8 = 1 }
|
||||
|
||||
function Jpeg.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
if type(img) ~= "table" or type(img.pixels) ~= "buffer" or type(img.width) ~= "number" or type(img.height) ~= "number" then
|
||||
return nil, Err.new(Err.ARG, "needs an Image")
|
||||
end
|
||||
local bpp = BPP[img.format]
|
||||
if not bpp then
|
||||
return nil, Err.new(Err.ARG, "needs an rgba8, rgb8 or gray8 Image (got " .. tostring(img.format) .. ")")
|
||||
end
|
||||
local w, h = img.width, img.height
|
||||
if w < 1 or h < 1 or w > 65535 or h > 65535 or w % 1 ~= 0 or h % 1 ~= 0 or buffer.len(img.pixels) < w * h * bpp then
|
||||
return nil, Err.new(Err.ARG, "bad image size or pixel buffer (1..65535 per side)")
|
||||
end
|
||||
local o: any = opts or {}
|
||||
local quality = o.quality or 90
|
||||
if type(quality) ~= "number" or quality < 1 or quality > 100 then
|
||||
return nil, Err.new(Err.ARG, "quality must be 1..100")
|
||||
end
|
||||
local sub = o.subsampling or "420"
|
||||
if sub ~= "420" and sub ~= "422" and sub ~= "444" then
|
||||
return nil, Err.new(Err.ARG, "subsampling must be \"420\", \"422\" or \"444\"")
|
||||
end
|
||||
local restart = o.restart or 0
|
||||
if type(restart) ~= "number" or restart < 0 or restart > 65535 or restart % 1 ~= 0 then
|
||||
return nil, Err.new(Err.ARG, "restart must be 0..65535 MCUs")
|
||||
end
|
||||
local gray = o.gray
|
||||
if gray == nil then
|
||||
gray = img.format == "gray8"
|
||||
end
|
||||
-- the APP1 / APP2 / COM segments and the JFIF density from img.meta
|
||||
local function metaSegments(meta: any): ({ { marker: number, data: buffer } }, { unit: number, x: number, y: number }?)
|
||||
local segments = {}
|
||||
local meta = img.meta or {}
|
||||
if o.meta ~= false then
|
||||
if type(meta.exif) == "buffer" and buffer.len(meta.exif) <= 65527 then
|
||||
local d = buffer.create(buffer.len(meta.exif) + 6)
|
||||
buffer.writestring(d, 0, "Exif\0\0")
|
||||
buffer.copy(d, 6, meta.exif)
|
||||
table.insert(segments, { marker = 0xE1, data = d })
|
||||
end
|
||||
if type(meta.icc) == "buffer" then
|
||||
local icc = meta.icc :: buffer
|
||||
local n = buffer.len(icc)
|
||||
local chunk = 65519
|
||||
local count = math.max(1, math.ceil(n / chunk))
|
||||
if count <= 255 then
|
||||
for i = 1, count do
|
||||
local a = (i - 1) * chunk
|
||||
local l = math.min(chunk, n - a)
|
||||
local d = buffer.create(l + 14)
|
||||
buffer.writestring(d, 0, "ICC_PROFILE\0")
|
||||
buffer.writeu8(d, 12, i)
|
||||
buffer.writeu8(d, 13, count)
|
||||
buffer.copy(d, 14, icc, a, l)
|
||||
table.insert(segments, { marker = 0xE2, data = d })
|
||||
end
|
||||
if type(meta.exif) == "buffer" and buffer.len(meta.exif) <= 65527 then
|
||||
local d = buffer.create(buffer.len(meta.exif) + 6)
|
||||
buffer.writestring(d, 0, "Exif\0\0")
|
||||
buffer.copy(d, 6, meta.exif)
|
||||
table.insert(segments, { marker = 0xE1, data = d })
|
||||
end
|
||||
if type(meta.icc) == "buffer" then
|
||||
local icc = meta.icc :: buffer
|
||||
local n = buffer.len(icc)
|
||||
local chunk = 65519
|
||||
local count = math.max(1, math.ceil(n / chunk))
|
||||
if count <= 255 then
|
||||
for i = 1, count do
|
||||
local a = (i - 1) * chunk
|
||||
local l = math.min(chunk, n - a)
|
||||
local d = buffer.create(l + 14)
|
||||
buffer.writestring(d, 0, "ICC_PROFILE\0")
|
||||
buffer.writeu8(d, 12, i)
|
||||
buffer.writeu8(d, 13, count)
|
||||
buffer.copy(d, 14, icc, a, l)
|
||||
table.insert(segments, { marker = 0xE2, data = d })
|
||||
end
|
||||
end
|
||||
local text = meta.text
|
||||
if type(text) == "table" and type(text.comment) == "string" and #text.comment <= 65533 then
|
||||
table.insert(segments, { marker = 0xFE, data = buffer.fromstring(text.comment) })
|
||||
end
|
||||
end
|
||||
local text = meta.text
|
||||
if type(text) == "table" and type(text.comment) == "string" and #text.comment <= 65533 then
|
||||
table.insert(segments, { marker = 0xFE, data = buffer.fromstring(text.comment) })
|
||||
end
|
||||
local density = nil
|
||||
if type(meta.dpi) == "table" and type(meta.dpi.x) == "number" and type(meta.dpi.y) == "number" then
|
||||
density = { unit = 1, x = math.clamp(math.floor(meta.dpi.x + 0.5), 1, 65535), y = math.clamp(math.floor(meta.dpi.y + 0.5), 1, 65535) }
|
||||
end
|
||||
local out = Encode.run(img.pixels, w, h, bpp, {
|
||||
quality = quality,
|
||||
sampling = sub,
|
||||
progressive = o.progressive == true,
|
||||
optimize = o.optimize == true,
|
||||
gray = gray,
|
||||
restart = restart,
|
||||
segments = segments,
|
||||
jfif = o.jfif ~= false,
|
||||
return segments, density
|
||||
end
|
||||
|
||||
function Jpeg.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
if type(img) ~= "table" then
|
||||
return nil, Err.new(Err.ARG, "needs an Image")
|
||||
end
|
||||
if opts ~= nil and type(opts) ~= "table" then
|
||||
return nil, Err.new(Err.ARG, "options must be a table")
|
||||
end
|
||||
local o: any = opts or {}
|
||||
local segments, density = {}, nil
|
||||
if o.meta ~= false then
|
||||
segments, density = metaSegments(img.meta or {})
|
||||
elseif type(img.meta) == "table" then
|
||||
local _
|
||||
_, density = metaSegments({ dpi = img.meta.dpi })
|
||||
end
|
||||
return Codec.encode(img, {
|
||||
quality = o.quality,
|
||||
subsampling = o.subsampling,
|
||||
progressive = o.progressive,
|
||||
optimize = o.optimize,
|
||||
gray = o.gray,
|
||||
restart = o.restart,
|
||||
jfif = o.jfif,
|
||||
density = density,
|
||||
segments = segments,
|
||||
})
|
||||
return out, nil
|
||||
end
|
||||
|
||||
return Jpeg
|
||||
+95
-3
@@ -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,6 +259,7 @@ 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.
|
||||
<<<<<<< HEAD
|
||||
-- They also see the injected plug-ins as opts.plugins (F.plugins: the B-rep kernel for cad/step) unless given their own.
|
||||
local function withHooks(o: Options): Options
|
||||
if o.decodeImage ~= nil and o.encodeImage ~= nil and o.plugins ~= nil then
|
||||
@@ -263,6 +268,33 @@ local function withHooks(o: Options): Options
|
||||
local c = table.clone(o)
|
||||
if c.plugins == nil then
|
||||
c.plugins = F.plugins
|
||||
=======
|
||||
--
|
||||
-- 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
|
||||
local dec, oerr = F.open(buf, { format = fmt, category = "audio" })
|
||||
-- Matroska CodecDelay: ffmpeg drops it for MPEG audio / AAC; Opus has its own pre-skip and Vorbis's delay is
|
||||
-- already the decoder's own (its first packet returns nothing)
|
||||
if dec and fmt ~= "opus" and fmt ~= "vorbis" and type(track.codecDelay) == "number" and track.codecDelay > 0 then
|
||||
dec = AudioWrap.trim(dec, math.floor(track.codecDelay * dec.sampleRate + 0.5))
|
||||
end
|
||||
return dec, oerr
|
||||
end
|
||||
|
||||
local function withHooks(o: Options): Options
|
||||
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
|
||||
>>>>>>> ws/video
|
||||
end
|
||||
if c.decodeImage == nil then
|
||||
c.decodeImage = function(b: buffer): (any, Err.Err?)
|
||||
@@ -309,12 +341,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
|
||||
@@ -337,6 +369,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
|
||||
@@ -344,10 +379,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 == "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
|
||||
@@ -373,6 +418,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
|
||||
@@ -427,6 +475,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
|
||||
@@ -543,6 +598,7 @@ for category in Types.CATEGORIES do
|
||||
end
|
||||
F.data.null = Types.null
|
||||
|
||||
<<<<<<< HEAD
|
||||
-- F.cad.toBodies(cad, opts?) -> bodies, result | nil, Err; F.cad.fromBodies(bodies, opts?) -> Cad | nil, Err;
|
||||
-- F.cad.tessellate(cad | bodies, opts?) -> Scene | nil, Err: cad/step's B-rep calls with the injected kernel
|
||||
-- (F.plugins.brep, unless opts.brep / opts.plugins is given). Without a plug-in they return Err.UNSUPPORTED.
|
||||
@@ -567,6 +623,42 @@ for _, fn in { "toBodies", "fromBodies", "tessellate" } do
|
||||
return a, b
|
||||
end
|
||||
end
|
||||
=======
|
||||
-- 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.fromFrames(images, delays?, opts?) -> a VideoDecoder over a list of same-size images (an image sequence:
|
||||
-- F.save(F.video.fromFrames(list, 1 / 25), "out.avi")); delays in seconds (a number = every frame, default 0.1)
|
||||
F.video.fromFrames = function(images: any, delays: any?, opts: Options?): (any, Err.Err?)
|
||||
return Video.fromFrames(images, delays, opts)
|
||||
end
|
||||
-- F.video.codecs: the video codec registry (codecs/Video: register / entry / fromFourcc / fromMatroska / decoder)
|
||||
F.video.codecs = Video
|
||||
>>>>>>> ws/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
|
||||
|
||||
@@ -0,0 +1,299 @@
|
||||
--!strict
|
||||
-- video/avi: AVI (Microsoft RIFF AVI 1.0, OpenDML 1.02). New in formats-luau, 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 registry by FourCC (MJPEG, MPEG-1,
|
||||
-- uncompressed BI_RGB 24 / 32-bit bottom-up or top-down, I420 / YV12; H.264 and others when a decoder is
|
||||
-- registered), audio through the api's opts.openAudio hook (PCM, A-law / mu-law, IMA / MS ADPCM with its WAVEFORMATEX,
|
||||
-- MP3 / MP2, AAC). Dropped frames (empty video chunks) keep their time slot. Avi.demux(r) gives the Demuxer.
|
||||
-- Write: MJPEG video (copied from an MJPEG source, else every frame encoded; variable frame delays such as a GIF's
|
||||
-- become a constant rate with repeated frames) plus PCM s16 audio, AVI 1.0 with idx1 and an odml / dmlh header.
|
||||
-- Not supported: writing files over 1 GB (no AVIX pieces), palette changes (##pc chunks are skipped), text streams.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Types = require("@formats/Types")
|
||||
local Avi = require("@formats/containers/Avi")
|
||||
local Demux = require("@formats/containers/Demux")
|
||||
local Video = require("@formats/codecs/Video")
|
||||
local Source = require("@formats/codecs/Video/Source")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local AviFormat = {
|
||||
name = "avi",
|
||||
category = "video",
|
||||
extensions = { "avi" },
|
||||
mime = { "video/x-msvideo", "video/avi" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "containers/Avi", "containers/Demux", "codecs/Video", "codecs/Video/Source" },
|
||||
caps = { decode = true, encode = true, streaming = true, video = { "mjpeg", "mpeg1", "rawvideo" }, audio = true, odml = true },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type OpenOptions = {
|
||||
rgba: boolean?, -- nextFrame returns rgba8 (default false: the codec's native yuv420p; BI_RGB gives rgba8)
|
||||
track: number?, -- the video track (stream index + 1) to decode
|
||||
audio: boolean?, -- false: do not open the audio track
|
||||
maxPixels: number?,
|
||||
openAudio: any?, -- set by the api
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
quality: number?, -- MJPEG quality 1..100 (default 90)
|
||||
reencode: boolean?, -- encode the frames even when the source is MJPEG
|
||||
audio: boolean?, -- false: no audio (default: PCM s16 from the source's audio, when it has one)
|
||||
video: boolean?,
|
||||
maxFps: number?, -- the highest frame rate variable delays may need (default 100)
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
-- WAVEFORMATEX wFormatTag -> codec id
|
||||
local AUDIO_TAGS: { [number]: string } = {
|
||||
[0x0001] = "pcm",
|
||||
[0x0002] = "adpcm_ms",
|
||||
[0x0003] = "pcm_f",
|
||||
[0x0006] = "pcm_alaw",
|
||||
[0x0007] = "pcm_mulaw",
|
||||
[0x0011] = "adpcm_ima_wav",
|
||||
[0x0050] = "mp2",
|
||||
[0x0055] = "mp3",
|
||||
[0x00FF] = "aac",
|
||||
[0x1610] = "aac",
|
||||
[0x706D] = "aac",
|
||||
[0x2000] = "ac3",
|
||||
[0x2001] = "dts",
|
||||
[0xF1AC] = "flac",
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function AviFormat.sniff(r: Bytes.Reader): number
|
||||
if r:peek(4) == "RIFF" and r:peek(4, 8) == "AVI " then
|
||||
return 1
|
||||
end
|
||||
return 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
local function videoTrack(s: Avi.Stream, id: number): Types.Track
|
||||
local f = s.strf
|
||||
local t: any = {
|
||||
id = id,
|
||||
kind = "video",
|
||||
codec = "",
|
||||
codecTag = s.handler,
|
||||
timescale = if s.scale > 0 then s.rate / s.scale else 25,
|
||||
frameRate = if s.scale > 0 then s.rate / s.scale else 0,
|
||||
default = true,
|
||||
name = s.name,
|
||||
frames = s.length,
|
||||
}
|
||||
if buffer.len(f) >= 40 then
|
||||
local w = buffer.readi32(f, 4)
|
||||
local h = buffer.readi32(f, 8)
|
||||
local bits = buffer.readu16(f, 14)
|
||||
local comp = buffer.readstring(f, 16, 4)
|
||||
t.width = math.abs(w)
|
||||
t.height = math.abs(h)
|
||||
t.codecTag = comp
|
||||
t.bitsPerPixel = bits
|
||||
if comp == "\0\0\0\0" or comp == "DIB " or comp == "RGB " then
|
||||
t.codec = "rawvideo"
|
||||
t.pixelFormat = if bits == 32 then "bgra" else "bgr24"
|
||||
t.flip = h > 0
|
||||
t.stride = ((math.abs(w) * bits + 31) // 32) * 4
|
||||
if bits ~= 24 and bits ~= 32 then
|
||||
t.codec = "rawvideo_" .. bits
|
||||
end
|
||||
else
|
||||
t.codec = Video.fromFourcc(comp) or Video.fromFourcc(s.handler) or string.lower((string.gsub(comp, "%z", "")))
|
||||
if comp == "YV12" then
|
||||
t.pixelFormat = "yv12"
|
||||
elseif t.codec == "rawvideo" then
|
||||
t.pixelFormat = "yuv420p"
|
||||
end
|
||||
end
|
||||
local size = buffer.readu32(f, 0)
|
||||
if size > 40 and buffer.len(f) > 40 then
|
||||
local c = buffer.create(buffer.len(f) - 40)
|
||||
buffer.copy(c, 0, f, 40)
|
||||
t.config = c
|
||||
end
|
||||
else
|
||||
t.codec = Video.fromFourcc(s.handler) or string.lower(s.handler)
|
||||
local fr = s.frame
|
||||
t.width, t.height = fr[3] - fr[1], fr[4] - fr[2]
|
||||
end
|
||||
return t
|
||||
end
|
||||
|
||||
local function audioTrack(s: Avi.Stream, id: number): Types.Track
|
||||
local f = s.strf
|
||||
local t: any = {
|
||||
id = id,
|
||||
kind = "audio",
|
||||
codec = "unknown",
|
||||
codecTag = s.handler,
|
||||
timescale = if s.scale > 0 then s.rate / s.scale else 1,
|
||||
default = true,
|
||||
name = s.name,
|
||||
waveFormat = f,
|
||||
}
|
||||
if buffer.len(f) >= 16 then
|
||||
local tag = buffer.readu16(f, 0)
|
||||
t.channels = buffer.readu16(f, 2)
|
||||
t.sampleRate = buffer.readu32(f, 4)
|
||||
t.blockAlign = buffer.readu16(f, 12)
|
||||
local bits = buffer.readu16(f, 14)
|
||||
t.bitsPerSample = bits
|
||||
if tag == 0xFFFE and buffer.len(f) >= 26 then
|
||||
tag = buffer.readu16(f, 24) -- WAVE_FORMAT_EXTENSIBLE: the sub-format GUID's tag
|
||||
end
|
||||
t.formatTag = tag
|
||||
local c = AUDIO_TAGS[tag] or string.format("wav_0x%04x", tag)
|
||||
if c == "pcm" then
|
||||
c = if bits == 8 then "pcm_u8" else "pcm_s" .. bits .. "le"
|
||||
elseif c == "pcm_f" then
|
||||
c = "pcm_f" .. bits .. "le"
|
||||
end
|
||||
t.codec = c
|
||||
if buffer.len(f) >= 18 then
|
||||
local cb = buffer.readu16(f, 16)
|
||||
if cb > 0 and 18 + cb <= buffer.len(f) and c ~= "mp3" then
|
||||
local cfg = buffer.create(cb)
|
||||
buffer.copy(cfg, 0, f, 18, cb)
|
||||
t.config = cfg
|
||||
end
|
||||
end
|
||||
end
|
||||
return t
|
||||
end
|
||||
|
||||
-- demux(r, opts?) -> the Demuxer | nil, Err
|
||||
function AviFormat.demux(r: Bytes.Reader, _opts: OpenOptions?): (any, Err.Err?)
|
||||
local ok, file, err = pcall(Avi.read, r.buf, r.base, r.limit)
|
||||
if not ok then
|
||||
return nil, Err.new(Err.CORRUPT, "internal error: " .. tostring(file))
|
||||
end
|
||||
if not file then
|
||||
return nil, err
|
||||
end
|
||||
local tracks: { Types.Track } = {}
|
||||
local streams: { { any } } = {}
|
||||
for i, s in file.streams do
|
||||
local t: Types.Track? = nil
|
||||
if s.type == "vids" then
|
||||
t = videoTrack(s, i)
|
||||
elseif s.type == "auds" then
|
||||
t = audioTrack(s, i)
|
||||
elseif s.type == "txts" then
|
||||
t = { id = i, kind = "subtitle", codec = "text", timescale = if s.scale > 0 then s.rate / s.scale else 1 }
|
||||
end
|
||||
if t then
|
||||
table.insert(tracks, t)
|
||||
table.insert(streams, { s, t })
|
||||
end
|
||||
end
|
||||
local meta = { info = file.info, index = file.index, odml = file.odml ~= nil }
|
||||
local dmx = Demux.new("avi", tracks, r.buf, meta)
|
||||
-- packets in file order across streams: merge by offset
|
||||
local items: { { number } } = {}
|
||||
for k, st in streams do
|
||||
local s: Avi.Stream, t: any = st[1], st[2]
|
||||
local tick = s.start
|
||||
for _, c in s.chunks do
|
||||
local dur = if s.sampleSize > 0 then c.size / s.sampleSize else 1
|
||||
if t.kind == "audio" and s.sampleSize == 0 and (t.blockAlign or 0) > 0 and t.codec:sub(1, 3) == "pcm" then
|
||||
dur = c.size / t.blockAlign
|
||||
end
|
||||
if c.size > 0 then
|
||||
table.insert(items, { c.offset, k, tick, dur, if c.key then 1 else 0, c.size })
|
||||
tick += dur
|
||||
elseif t.kind == "video" then
|
||||
tick += 1 -- an empty video chunk: a dropped frame keeps its slot (empty audio chunks are padding)
|
||||
end
|
||||
end
|
||||
end
|
||||
table.sort(items, function(a: { number }, b: { number }): boolean
|
||||
return a[1] < b[1]
|
||||
end)
|
||||
for _, it in items do
|
||||
local t: any = streams[it[2]][2]
|
||||
dmx:add(t.id, it[3], nil, it[4], it[5] == 1 or t.kind ~= "video" or t.codec == "mjpeg" or t.codec == "rawvideo", it[1], it[6])
|
||||
end
|
||||
dmx:finish()
|
||||
return dmx, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
-- encode(video, opts?) -> buffer | nil, Err
|
||||
function AviFormat.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
local o: any = table.clone(opts or {})
|
||||
o.quality = o.quality or 90
|
||||
local streams, err = Source.streams(value, o, {
|
||||
video = { copy = { mjpeg = true }, encode = "mjpeg" },
|
||||
audio = { copy = { pcm_s16le = true, pcm_u8 = true }, pcm = true },
|
||||
})
|
||||
if not streams then
|
||||
return nil, err
|
||||
end
|
||||
local wstreams: { Avi.WStream } = {}
|
||||
local width, height, usPerFrame = 0, 0, 0
|
||||
local frameDur = 0
|
||||
for _, s in streams do
|
||||
if s.kind == "video" then
|
||||
-- a constant frame rate: the shortest frame duration (variable delays repeat frames)
|
||||
local num, den, packets = Source.constantRate(s, o.maxFps)
|
||||
s.packets = packets
|
||||
frameDur = den / num
|
||||
width, height = s.width or 0, s.height or 0
|
||||
usPerFrame = 1e6 * frameDur
|
||||
local bih = Bytes.writer(40)
|
||||
bih:u32le(40)
|
||||
bih:u32le(width)
|
||||
bih:u32le(height)
|
||||
bih:u16le(1)
|
||||
bih:u16le(24)
|
||||
bih:string("MJPG")
|
||||
bih:u32le(width * height * 3)
|
||||
bih:u32le(0)
|
||||
bih:u32le(0)
|
||||
bih:u32le(0)
|
||||
bih:u32le(0)
|
||||
table.insert(wstreams, { type = "vids", handler = "MJPG", scale = den, rate = num, sampleSize = 0, strf = bih:finish(), width = width, height = height, ckid = "dc" })
|
||||
else
|
||||
local ch = s.channels or 1
|
||||
local bits = if s.codec == "pcm_u8" then 8 else 16
|
||||
local align = ch * bits // 8
|
||||
local rate = math.floor((s.sampleRate or 44100) + 0.5)
|
||||
local wf = Bytes.writer(18)
|
||||
wf:u16le(1)
|
||||
wf:u16le(ch)
|
||||
wf:u32le(rate)
|
||||
wf:u32le(rate * align)
|
||||
wf:u16le(align)
|
||||
wf:u16le(bits)
|
||||
wf:u16le(0)
|
||||
table.insert(wstreams, { type = "auds", handler = "\0\0\0\0", scale = align, rate = rate * align, sampleSize = align, strf = wf:finish(), ckid = "wb" })
|
||||
end
|
||||
end
|
||||
-- chunks in time order (the video packets already repeated to the constant rate)
|
||||
local chunks: { { any } } = {}
|
||||
for _, item in Source.interleave(streams) do
|
||||
table.insert(chunks, { item[1], item[2].data, true })
|
||||
end
|
||||
local ok, buf = pcall(Avi.write, { streams = wstreams, microSecPerFrame = usPerFrame, width = width, height = height }, chunks)
|
||||
if not ok then
|
||||
return nil, Err.new(Err.ARG, "internal error: " .. tostring(buf))
|
||||
end
|
||||
return buf, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ open
|
||||
-- open(r, opts?) -> a VideoDecoder | nil, Err
|
||||
function AviFormat.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?)
|
||||
local dmx, err = AviFormat.demux(r, opts)
|
||||
if not dmx then
|
||||
return nil, err
|
||||
end
|
||||
return Video.open(dmx, opts)
|
||||
end
|
||||
|
||||
return AviFormat
|
||||
@@ -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
|
||||
@@ -0,0 +1,681 @@
|
||||
--!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 Deflate = require("@formats/codecs/Deflate")
|
||||
|
||||
local Parse = {}
|
||||
|
||||
-- element IDs
|
||||
local ID = {
|
||||
EBML = 0x1A45DFA3,
|
||||
DocType = 0x4282,
|
||||
Segment = 0x18538067,
|
||||
SeekHead = 0x114D9B74,
|
||||
Info = 0x1549A966,
|
||||
TimecodeScale = 0x2AD7B1,
|
||||
Duration = 0x4489,
|
||||
Title = 0x7BA9,
|
||||
MuxingApp = 0x4D80,
|
||||
WritingApp = 0x5741,
|
||||
DateUTC = 0x4461,
|
||||
Tracks = 0x1654AE6B,
|
||||
TrackEntry = 0xAE,
|
||||
TrackNumber = 0xD7,
|
||||
TrackUID = 0x73C5,
|
||||
TrackType = 0x83,
|
||||
FlagEnabled = 0xB9,
|
||||
FlagDefault = 0x88,
|
||||
FlagForced = 0x55AA,
|
||||
FlagLacing = 0x9C,
|
||||
DefaultDuration = 0x23E383,
|
||||
Name = 0x536E,
|
||||
Language = 0x22B59C,
|
||||
LanguageBCP47 = 0x22B59D,
|
||||
CodecID = 0x86,
|
||||
CodecPrivate = 0x63A2,
|
||||
CodecDelay = 0x56AA,
|
||||
SeekPreRoll = 0x56BB,
|
||||
Video = 0xE0,
|
||||
PixelWidth = 0xB0,
|
||||
PixelHeight = 0xBA,
|
||||
DisplayWidth = 0x54B0,
|
||||
DisplayHeight = 0x54BA,
|
||||
ColourSpace = 0x2EB524,
|
||||
Audio = 0xE1,
|
||||
SamplingFrequency = 0xB5,
|
||||
OutputSamplingFrequency = 0x78B5,
|
||||
Channels = 0x9F,
|
||||
BitDepth = 0x6264,
|
||||
ContentEncodings = 0x6D80,
|
||||
ContentEncoding = 0x6240,
|
||||
ContentEncodingType = 0x5033,
|
||||
ContentEncodingScope = 0x5032,
|
||||
ContentCompression = 0x5034,
|
||||
ContentCompAlgo = 0x4254,
|
||||
ContentCompSettings = 0x4255,
|
||||
ContentEncryption = 0x5035,
|
||||
Cluster = 0x1F43B675,
|
||||
Timecode = 0xE7,
|
||||
SimpleBlock = 0xA3,
|
||||
BlockGroup = 0xA0,
|
||||
Block = 0xA1,
|
||||
BlockDuration = 0x9B,
|
||||
ReferenceBlock = 0xFB,
|
||||
DiscardPadding = 0x75A2,
|
||||
Cues = 0x1C53BB6B,
|
||||
CuePoint = 0xBB,
|
||||
CueTime = 0xB3,
|
||||
CueTrackPositions = 0xB7,
|
||||
CueTrack = 0xF7,
|
||||
CueClusterPosition = 0xF1,
|
||||
CueRelativePosition = 0xF0,
|
||||
Tags = 0x1254C367,
|
||||
Tag = 0x7373,
|
||||
SimpleTag = 0x67C8,
|
||||
TagName = 0x45A3,
|
||||
TagString = 0x4487,
|
||||
Targets = 0x63C0,
|
||||
Chapters = 0x1043A770,
|
||||
Attachments = 0x1941A469,
|
||||
Void = 0xEC,
|
||||
Crc32 = 0xBF,
|
||||
}
|
||||
Parse.ID = ID
|
||||
|
||||
-- the top-level children of a Segment (an unknown-size Cluster ends where one of these starts)
|
||||
local TOP: { [number]: boolean } = {
|
||||
[ID.SeekHead] = true,
|
||||
[ID.Info] = true,
|
||||
[ID.Tracks] = true,
|
||||
[ID.Cluster] = true,
|
||||
[ID.Cues] = true,
|
||||
[ID.Tags] = true,
|
||||
[ID.Chapters] = true,
|
||||
[ID.Attachments] = true,
|
||||
[ID.Segment] = true,
|
||||
[ID.EBML] = true,
|
||||
}
|
||||
|
||||
-- Matroska audio / subtitle CodecIDs -> our codec ids (video ids come from the codecs/Video 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) and zlib (algo 0) are supported; bzip / lzo compression and encryption
|
||||
-- are not
|
||||
local function parseEncodings(buf: buffer, off: number, len: number, t: any): string?
|
||||
for id, o, n in Ebml.children(buf, off, off + len) do
|
||||
if id == ID.ContentEncoding then
|
||||
local etype = 0
|
||||
local scope = 1
|
||||
for id2, o2, n2 in Ebml.children(buf, o, o + n) do
|
||||
if id2 == ID.ContentEncodingScope then
|
||||
scope = Ebml.uint(buf, o2, n2)
|
||||
elseif id2 == ID.ContentEncodingType then
|
||||
etype = Ebml.uint(buf, o2, n2)
|
||||
elseif id2 == ID.ContentCompression then
|
||||
local algo, settings = 0, nil
|
||||
for id3, o3, n3 in Ebml.children(buf, o2, o2 + n2) do
|
||||
if id3 == ID.ContentCompAlgo then
|
||||
algo = Ebml.uint(buf, o3, n3)
|
||||
elseif id3 == ID.ContentCompSettings then
|
||||
settings = Ebml.binary(buf, o3, n3)
|
||||
end
|
||||
end
|
||||
if algo == 3 then
|
||||
t.strip = settings
|
||||
elseif algo == 0 then
|
||||
t.zlib = scope -- 1: frames, 2: CodecPrivate
|
||||
else
|
||||
return "content compression algorithm " .. algo
|
||||
end
|
||||
elseif id2 == ID.ContentEncryption then
|
||||
return "encrypted track"
|
||||
end
|
||||
end
|
||||
if etype ~= 0 then
|
||||
return "encrypted track"
|
||||
end
|
||||
end
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
local function parseTracks(buf: buffer, off: number, len: number, scaleNs: number): ({ TrackInfo }, { [number]: string })
|
||||
local tracks: { TrackInfo } = {}
|
||||
local problems: { [number]: string } = {}
|
||||
for id, o, n in Ebml.children(buf, off, off + len) do
|
||||
if id == ID.TrackEntry then
|
||||
local t: any = { id = 0, kind = "data", codec = "", timescale = 1e9 / scaleNs, default = true, lacing = true, language = "eng" }
|
||||
local ttype, codecId = 0, ""
|
||||
local problem: string? = nil
|
||||
for id2, o2, n2 in Ebml.children(buf, o, o + n) do
|
||||
if id2 == ID.TrackNumber then
|
||||
t.id = Ebml.uint(buf, o2, n2)
|
||||
elseif id2 == ID.TrackUID then
|
||||
t.uid = Ebml.uint(buf, o2, n2)
|
||||
elseif id2 == ID.TrackType then
|
||||
ttype = Ebml.uint(buf, o2, n2)
|
||||
elseif id2 == ID.FlagDefault then
|
||||
t.default = Ebml.uint(buf, o2, n2) ~= 0
|
||||
elseif id2 == ID.FlagEnabled then
|
||||
t.enabled = Ebml.uint(buf, o2, n2) ~= 0
|
||||
elseif id2 == ID.FlagLacing then
|
||||
t.lacing = Ebml.uint(buf, o2, n2) ~= 0
|
||||
elseif id2 == ID.DefaultDuration then
|
||||
t.defaultDurationNs = Ebml.uint(buf, o2, n2)
|
||||
elseif id2 == ID.Name then
|
||||
t.name = Ebml.string(buf, o2, n2)
|
||||
elseif id2 == ID.Language then
|
||||
t.language = Ebml.string(buf, o2, n2)
|
||||
elseif id2 == ID.CodecID then
|
||||
codecId = Ebml.string(buf, o2, n2)
|
||||
elseif id2 == ID.CodecPrivate then
|
||||
t.config = Ebml.binary(buf, o2, n2)
|
||||
elseif id2 == ID.CodecDelay then
|
||||
t.codecDelay = Ebml.uint(buf, o2, n2) / 1e9
|
||||
elseif id2 == ID.SeekPreRoll then
|
||||
t.seekPreRoll = Ebml.uint(buf, o2, n2) / 1e9
|
||||
elseif id2 == ID.Video then
|
||||
parseVideo(buf, o2, n2, t)
|
||||
elseif id2 == ID.Audio then
|
||||
parseAudio(buf, o2, n2, t)
|
||||
elseif id2 == ID.ContentEncodings then
|
||||
problem = parseEncodings(buf, o2, n2, t)
|
||||
end
|
||||
end
|
||||
if t.zlib and bit32.band(t.zlib, 2) ~= 0 and t.config then
|
||||
local c = Deflate.zlib(t.config)
|
||||
if c then
|
||||
t.config = c
|
||||
else
|
||||
problem = "bad zlib-compressed CodecPrivate"
|
||||
end
|
||||
end
|
||||
t.kind = if ttype == 1 then "video" elseif ttype == 2 then "audio" elseif ttype == 17 then "subtitle" else "data"
|
||||
t.codecTag = codecId
|
||||
t.codec = codecFor(codecId, t.kind, t.bitsPerSample)
|
||||
if t.kind == "audio" then
|
||||
t.sampleRate = t.sampleRate or 8000
|
||||
t.channels = t.channels or 1
|
||||
end
|
||||
if t.defaultDurationNs and t.defaultDurationNs > 0 and t.kind == "video" then
|
||||
t.frameRate = 1e9 / t.defaultDurationNs
|
||||
end
|
||||
if t.id > 0 then
|
||||
table.insert(tracks, t)
|
||||
if problem then
|
||||
problems[t.id] = problem
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
return tracks, problems
|
||||
end
|
||||
|
||||
local function parseInfo(buf: buffer, off: number, len: number, meta: { [string]: any }): (number, number?)
|
||||
local scale, duration = 1000000, nil
|
||||
for id, o, n in Ebml.children(buf, off, off + len) do
|
||||
if id == ID.TimecodeScale then
|
||||
scale = Ebml.uint(buf, o, n)
|
||||
elseif id == ID.Duration then
|
||||
duration = Ebml.float(buf, o, n)
|
||||
elseif id == ID.Title then
|
||||
meta.title = Ebml.string(buf, o, n)
|
||||
elseif id == ID.MuxingApp then
|
||||
meta.muxingApp = Ebml.string(buf, o, n)
|
||||
elseif id == ID.WritingApp then
|
||||
meta.writingApp = Ebml.string(buf, o, n)
|
||||
end
|
||||
end
|
||||
if scale <= 0 then
|
||||
scale = 1000000
|
||||
end
|
||||
return scale, duration
|
||||
end
|
||||
|
||||
local function parseCues(buf: buffer, off: number, len: number, segData: number): { { time: number, track: number, position: number } }
|
||||
local cues = {}
|
||||
for id, o, n in Ebml.children(buf, off, off + len) do
|
||||
if id == ID.CuePoint then
|
||||
local time = 0
|
||||
local positions = {}
|
||||
for id2, o2, n2 in Ebml.children(buf, o, o + n) do
|
||||
if id2 == ID.CueTime then
|
||||
time = Ebml.uint(buf, o2, n2)
|
||||
elseif id2 == ID.CueTrackPositions then
|
||||
local tr, pos = 0, 0
|
||||
for id3, o3, n3 in Ebml.children(buf, o2, o2 + n2) do
|
||||
if id3 == ID.CueTrack then
|
||||
tr = Ebml.uint(buf, o3, n3)
|
||||
elseif id3 == ID.CueClusterPosition then
|
||||
pos = Ebml.uint(buf, o3, n3)
|
||||
end
|
||||
end
|
||||
table.insert(positions, { tr, pos })
|
||||
end
|
||||
end
|
||||
for _, p in positions do
|
||||
table.insert(cues, { time = time, track = p[1], position = segData + p[2] })
|
||||
end
|
||||
end
|
||||
end
|
||||
return cues
|
||||
end
|
||||
|
||||
local function parseTags(buf: buffer, off: number, len: number, meta: { [string]: any })
|
||||
local tags = meta.tags or {}
|
||||
meta.tags = tags
|
||||
for id, o, n in Ebml.children(buf, off, off + len) do
|
||||
if id == ID.Tag then
|
||||
for id2, o2, n2 in Ebml.children(buf, o, o + n) do
|
||||
if id2 == ID.SimpleTag then
|
||||
local name, value = nil, nil
|
||||
for id3, o3, n3 in Ebml.children(buf, o2, o2 + n2) do
|
||||
if id3 == ID.TagName then
|
||||
name = Ebml.string(buf, o3, n3)
|
||||
elseif id3 == ID.TagString then
|
||||
value = Ebml.string(buf, o3, n3)
|
||||
end
|
||||
end
|
||||
if name and value and tags[string.lower(name)] == nil then
|
||||
tags[string.lower(name)] = value
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
type Ctx = {
|
||||
buf: buffer,
|
||||
dmx: any,
|
||||
byNum: { [number]: TrackInfo },
|
||||
scaleNs: number,
|
||||
err: string?,
|
||||
maxPackets: number,
|
||||
}
|
||||
|
||||
-- one Block / SimpleBlock payload at [off, off + len): track, relative timecode, flags, lacing
|
||||
local function block(ctx: Ctx, off: number, len: number, clusterTime: number, simple: boolean, keyHint: boolean?, durTicks: number?, discardNs: number?)
|
||||
local buf = ctx.buf
|
||||
local limit = off + len
|
||||
local tn, tl = Ebml.vint(buf, off, limit)
|
||||
if not tn or not tl or tn < 0 or off + tl + 3 > limit then
|
||||
return
|
||||
end
|
||||
local p = off + tl
|
||||
local rel = buffer.readu8(buf, p) * 256 + buffer.readu8(buf, p + 1)
|
||||
if rel >= 32768 then
|
||||
rel -= 65536
|
||||
end
|
||||
local flags = buffer.readu8(buf, p + 2)
|
||||
p += 3
|
||||
local t = ctx.byNum[tn]
|
||||
if not t then
|
||||
return
|
||||
end
|
||||
local key = if simple then bit32.band(flags, 0x80) ~= 0 else (keyHint ~= false)
|
||||
if t.kind == "audio" or t.kind == "subtitle" then
|
||||
key = true
|
||||
end
|
||||
local pts = clusterTime + rel
|
||||
local lacing = bit32.band(bit32.rshift(flags, 1), 3)
|
||||
local sizes: { number } = {}
|
||||
if lacing == 0 then
|
||||
sizes[1] = limit - p
|
||||
else
|
||||
if p >= limit then
|
||||
return
|
||||
end
|
||||
local count = buffer.readu8(buf, p) + 1
|
||||
p += 1
|
||||
if lacing == 1 then -- Xiph
|
||||
local total = 0
|
||||
for k = 1, count - 1 do
|
||||
local s = 0
|
||||
while true do
|
||||
if p >= limit then
|
||||
return
|
||||
end
|
||||
local b = buffer.readu8(buf, p)
|
||||
p += 1
|
||||
s += b
|
||||
if b ~= 255 then
|
||||
break
|
||||
end
|
||||
end
|
||||
sizes[k] = s
|
||||
total += s
|
||||
end
|
||||
sizes[count] = limit - p - total
|
||||
elseif lacing == 3 then -- EBML
|
||||
local s, l = Ebml.vint(buf, p, limit)
|
||||
if not s or not l or s < 0 then
|
||||
return
|
||||
end
|
||||
p += l
|
||||
sizes[1] = s
|
||||
local total = s
|
||||
for k = 2, count - 1 do
|
||||
local d, dl = Ebml.svint(buf, p, limit)
|
||||
if not d or not dl then
|
||||
return
|
||||
end
|
||||
p += dl
|
||||
s += d
|
||||
if s < 0 then
|
||||
return
|
||||
end
|
||||
sizes[k] = s
|
||||
total += s
|
||||
end
|
||||
sizes[count] = limit - p - total
|
||||
else -- fixed
|
||||
local each = (limit - p) // count
|
||||
for k = 1, count do
|
||||
sizes[k] = each
|
||||
end
|
||||
end
|
||||
if sizes[count] < 0 then
|
||||
return
|
||||
end
|
||||
end
|
||||
-- frames after the first of a lace: the track's default duration
|
||||
local stepTicks = 0
|
||||
if t.defaultDurationNs and t.defaultDurationNs > 0 then
|
||||
stepTicks = t.defaultDurationNs / ctx.scaleNs
|
||||
elseif durTicks and #sizes > 0 then
|
||||
stepTicks = durTicks / #sizes
|
||||
end
|
||||
local dmx = ctx.dmx
|
||||
for k, s in sizes do
|
||||
if p + s > limit then
|
||||
return
|
||||
end
|
||||
if dmx.n >= ctx.maxPackets then
|
||||
ctx.err = "too many packets"
|
||||
return
|
||||
end
|
||||
local d = if #sizes == 1 then durTicks else (if stepTicks > 0 then stepTicks else nil)
|
||||
local kf = key and (k == 1 or t.kind ~= "video")
|
||||
local strip = t.strip
|
||||
local z = (t :: any).zlib
|
||||
if z and bit32.band(z, 1) ~= 0 then
|
||||
local out = Deflate.zlib(buf, p, s)
|
||||
if out then
|
||||
dmx:addData(tn, pts + (k - 1) * stepTicks, nil, d, kf, out)
|
||||
end
|
||||
elseif strip then
|
||||
local nb = buffer.create(buffer.len(strip) + s)
|
||||
buffer.copy(nb, 0, strip)
|
||||
buffer.copy(nb, buffer.len(strip), buf, p, s)
|
||||
dmx:addData(tn, pts + (k - 1) * stepTicks, nil, d, kf, nb)
|
||||
else
|
||||
dmx:add(tn, pts + (k - 1) * stepTicks, nil, d, kf, p, s)
|
||||
end
|
||||
if discardNs and k == #sizes then
|
||||
dmx:setExtra("discardPadding", discardNs / 1e9)
|
||||
end
|
||||
p += s
|
||||
end
|
||||
end
|
||||
|
||||
-- a Cluster's children from off to limit (an unknown-size cluster: until a top-level ID); returns where it ended
|
||||
local function cluster(ctx: Ctx, off: number, limit: number, unknown: boolean): number
|
||||
local buf = ctx.buf
|
||||
local pos = off
|
||||
local time = 0
|
||||
while pos < limit and not ctx.err do
|
||||
local id, size, data = Ebml.header(buf, pos, limit)
|
||||
if not id or not size or not data then
|
||||
return limit
|
||||
end
|
||||
if unknown and TOP[id] then
|
||||
return pos
|
||||
end
|
||||
if size < 0 then
|
||||
size = limit - data -- an unknown-size child: to the end
|
||||
end
|
||||
if data + size > limit then
|
||||
size = limit - data
|
||||
end
|
||||
if id == ID.Timecode then
|
||||
time = Ebml.uint(buf, data, size)
|
||||
elseif id == ID.SimpleBlock then
|
||||
block(ctx, data, size, time, true)
|
||||
elseif id == ID.BlockGroup then
|
||||
local bo, bl = -1, 0
|
||||
local ref, dur, discard = false, nil, nil
|
||||
for id2, o2, n2 in Ebml.children(buf, data, data + size) do
|
||||
if id2 == ID.Block then
|
||||
bo, bl = o2, n2
|
||||
elseif id2 == ID.ReferenceBlock then
|
||||
ref = true
|
||||
elseif id2 == ID.BlockDuration then
|
||||
dur = Ebml.uint(buf, o2, n2)
|
||||
elseif id2 == ID.DiscardPadding then
|
||||
discard = Ebml.int(buf, o2, n2)
|
||||
end
|
||||
end
|
||||
if bo >= 0 then
|
||||
block(ctx, bo, bl, time, false, not ref, dur, discard)
|
||||
end
|
||||
end
|
||||
pos = data + size
|
||||
end
|
||||
return pos
|
||||
end
|
||||
|
||||
export type Options = { maxPackets: number? }
|
||||
|
||||
-- parse(buf, base, limit, opts) -> a Demux | nil, Err
|
||||
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
|
||||
@@ -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 and zlib 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: 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/Deflate", "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
|
||||
@@ -0,0 +1,324 @@
|
||||
--!strict
|
||||
-- video/mp4: MP4 / M4V / QuickTime MOV / 3GP (ISO/IEC 14496-12 / 14496-14, the QuickTime file format), on
|
||||
-- containers/IsoBmff (ws-m4a's box parser, sample tables, fragments and muxer). New in formats-luau.
|
||||
-- Read: every track's samples into a Demuxer (pts = dts + composition offset, moved by the edit list: the first
|
||||
-- edit's media time is subtracted (B-frame delay, AAC priming), an initial empty edit added; sync samples as
|
||||
-- keyframes; fragmented files too) and open() returns a VideoDecoder: video through the codecs/Video registry (MJPEG
|
||||
-- 'jpeg' / 'mjpa' / mp4v 0x6C, MPEG-1, raw; H.264 'avc1' with its avcC when a decoder is registered), audio through
|
||||
-- the api's opts.openAudio hook (AAC, ALAC (audio/m4a), MP3, Opus (dOps -> OpusHead), FLAC, PCM 'sowt' / 'twos' /
|
||||
-- 'lpcm' / 'ipcm').
|
||||
-- Write: MP4 (or MOV with opts.format = "mov" / a .mov destination): H.264 / HEVC / AV1 / MJPEG / MPEG-4 video copied
|
||||
-- from an ISO / Matroska source (their configurations are the same boxes), else MJPEG encoded from the frames (mp4v
|
||||
-- object type 0x6C in MP4, 'jpeg' in MOV); AAC / ALAC / Opus / FLAC / MP3 audio copied, else PCM s16 ('sowt', MOV
|
||||
-- only; MP4 drops other audio unless opts.audio = true, which fails).
|
||||
-- Edit lists are written for a B-frame delay and an audio codec delay (AAC priming). Not supported: fragmented
|
||||
-- writing, timed text tracks, encrypted tracks.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Types = require("@formats/Types")
|
||||
local IsoBmff = require("@formats/containers/IsoBmff")
|
||||
local Demux = require("@formats/containers/Demux")
|
||||
local Video = require("@formats/codecs/Video")
|
||||
local Source = require("@formats/codecs/Video/Source")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Mp4 = {
|
||||
name = "mp4",
|
||||
category = "video",
|
||||
extensions = { "mp4", "m4v", "mov", "qt", "3gp", "3g2", "mj2" },
|
||||
mime = { "video/mp4", "video/quicktime", "video/3gpp" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "containers/IsoBmff", "containers/Demux", "codecs/Video", "codecs/Video/Source" },
|
||||
caps = { decode = true, encode = true, streaming = true, remux = true, video = { "mjpeg", "mpeg1", "h264" }, audio = true, fragments = true },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type OpenOptions = {
|
||||
rgba: boolean?,
|
||||
track: number?, -- the video track id (default: the first video track)
|
||||
audio: boolean?,
|
||||
maxPixels: number?,
|
||||
maxSamples: number?,
|
||||
openAudio: any?, -- set by the api
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
format: string?, -- "mov" writes QuickTime (brand 'qt '); else MP4 (brand 'isom')
|
||||
quality: number?, -- MJPEG quality when frames are encoded (default 90)
|
||||
reencode: boolean?, -- encode the frames to MJPEG even when the video could be copied
|
||||
video: boolean?,
|
||||
audio: boolean?, -- false: no audio; true: fail when the audio cannot be written
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
local IMAGE_BRANDS = { avif = true, avis = true, heic = true, heix = true, mif1 = true, msf1 = true, ["crx "] = true }
|
||||
local AUDIO_BRANDS = { ["M4A "] = true, ["M4B "] = true, ["M4P "] = true }
|
||||
-- copied video codecs -> sample entry (MP4 / MOV)
|
||||
local VIDEO_ENTRY: { [string]: string } = { h264 = "avc1", hevc = "hvc1", av1 = "av01", vp9 = "vp09" }
|
||||
local AUDIO_ENTRY: { [string]: string } = { aac = "mp4a", alac = "alac", opus = "Opus", flac = "fLaC", mp3 = "mp4a" }
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Mp4.sniff(r: Bytes.Reader): number
|
||||
local brand = IsoBmff.sniff(r)
|
||||
if brand == nil or IMAGE_BRANDS[brand] then
|
||||
return 0
|
||||
end
|
||||
if AUDIO_BRANDS[brand] then
|
||||
return 0.2
|
||||
end
|
||||
if brand == "M4V " then
|
||||
return 0.9
|
||||
end
|
||||
return if brand == "" then 0.6 else 0.8
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
-- OpusHead (RFC 7845, little-endian) from an ISO dOps box payload (big-endian)
|
||||
local function opusHead(d: buffer): buffer?
|
||||
if buffer.len(d) < 11 then
|
||||
return nil
|
||||
end
|
||||
local w = Bytes.writer(19 + buffer.len(d))
|
||||
w:string("OpusHead")
|
||||
w:u8(1)
|
||||
local ch = buffer.readu8(d, 1)
|
||||
w:u8(ch)
|
||||
w:u16le(buffer.readu8(d, 2) * 256 + buffer.readu8(d, 3))
|
||||
w:u32le(((buffer.readu8(d, 4) * 256 + buffer.readu8(d, 5)) * 256 + buffer.readu8(d, 6)) * 256 + buffer.readu8(d, 7))
|
||||
w:u16le(buffer.readu8(d, 8) * 256 + buffer.readu8(d, 9))
|
||||
local family = buffer.readu8(d, 10)
|
||||
w:u8(family)
|
||||
if family ~= 0 and buffer.len(d) >= 13 + ch then
|
||||
w:bytes(d, 11, 2 + ch) -- stream count, coupled count, mapping
|
||||
end
|
||||
return w:finish()
|
||||
end
|
||||
|
||||
local function pcmCodec(t: any): string
|
||||
local p = t.pcm
|
||||
local bits = if p then p.bits else (t.bitsPerSample or 16)
|
||||
if p and p.float then
|
||||
return "pcm_f" .. bits .. (if p.little then "le" else "be")
|
||||
end
|
||||
if bits == 8 then
|
||||
return if t.entry == "raw " then "pcm_u8" else "pcm_s8"
|
||||
end
|
||||
return "pcm_s" .. bits .. (if p == nil or p.little then "le" else "be")
|
||||
end
|
||||
|
||||
-- demux(r, opts?) -> the Demuxer | nil, Err
|
||||
function Mp4.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?)
|
||||
local ok, movie, err = pcall(IsoBmff.parse, r, opts and opts.maxSamples and { maxSamples = opts.maxSamples } or nil)
|
||||
if not ok then
|
||||
return nil, Err.new(Err.CORRUPT, "internal error: " .. tostring(movie))
|
||||
end
|
||||
if not movie then
|
||||
return nil, err
|
||||
end
|
||||
local tracks: { Types.Track } = {}
|
||||
local src = {}
|
||||
for _, it in movie.tracks do
|
||||
local t: any = {
|
||||
id = it.id,
|
||||
kind = it.kind,
|
||||
codec = it.codec,
|
||||
codecTag = it.entry,
|
||||
timescale = it.timescale,
|
||||
duration = it.duration,
|
||||
language = it.language,
|
||||
width = it.width,
|
||||
height = it.height,
|
||||
sampleRate = it.sampleRate,
|
||||
channels = it.channels,
|
||||
bitsPerSample = it.bitsPerSample,
|
||||
config = it.config,
|
||||
default = true,
|
||||
}
|
||||
if it.kind == "video" then
|
||||
if not Video.entry(t.codec) then
|
||||
t.codec = Video.fromFourcc(it.entry) or t.codec
|
||||
end
|
||||
if it.sampleCount > 0 and it.duration > 0 then
|
||||
t.frameRate = it.sampleCount / it.duration
|
||||
end
|
||||
elseif it.kind == "audio" then
|
||||
if it.codec == "pcm" then
|
||||
t.codec = pcmCodec(it)
|
||||
elseif it.codec == "ulaw" then
|
||||
t.codec = "pcm_mulaw"
|
||||
elseif it.codec == "alaw" then
|
||||
t.codec = "pcm_alaw"
|
||||
elseif it.codec == "opus" and it.config then
|
||||
t.config = opusHead(it.config)
|
||||
end
|
||||
if it.skip and it.skip > 0 then
|
||||
t.codecDelay = it.skip / it.timescale -- AAC priming: dropped like ffmpeg
|
||||
end
|
||||
end
|
||||
table.insert(tracks, t)
|
||||
table.insert(src, it)
|
||||
end
|
||||
local dmx = Demux.new(if movie.brand == "qt " then "mov" else "mp4", tracks, r.buf, { brand = movie.brand })
|
||||
-- samples in file order across tracks
|
||||
local items: { { number } } = {}
|
||||
for k, it in src do
|
||||
-- the edit list moves presentation times: minus the first edit's media time (video: the B-frame delay; audio
|
||||
-- keeps it as its codec delay), plus an initial empty edit (converted to media ticks)
|
||||
local shift = 0
|
||||
if it.kind == "video" then
|
||||
shift = -(it.skip or 0)
|
||||
end
|
||||
if it.delay and it.delay > 0 and movie.timescale and movie.timescale > 0 then
|
||||
shift += it.delay / movie.timescale * it.timescale
|
||||
end
|
||||
for i = 1, it.sampleCount do
|
||||
table.insert(items, { it.offsets[i], k, i, shift })
|
||||
end
|
||||
end
|
||||
table.sort(items, function(a: { number }, b: { number }): boolean
|
||||
return a[1] < b[1]
|
||||
end)
|
||||
for _, e in items do
|
||||
local it = src[e[2]]
|
||||
local i = e[3]
|
||||
local dts = it.dts[i]
|
||||
local pts = dts + (if it.cts then it.cts[i] or 0 else 0) + e[4]
|
||||
dmx:add(it.id, pts, dts + e[4], it.durations[i], it.sync == nil or it.sync[i] == true, it.offsets[i], it.sizes[i])
|
||||
end
|
||||
dmx:finish()
|
||||
return dmx, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
-- OpusHead -> dOps payload
|
||||
local function dOps(head: buffer?): buffer?
|
||||
if not head or buffer.len(head) < 19 then
|
||||
return nil
|
||||
end
|
||||
local w = Bytes.writer(16)
|
||||
w:u8(0)
|
||||
local ch = buffer.readu8(head, 9)
|
||||
w:u8(ch)
|
||||
w:u16be(buffer.readu16(head, 10))
|
||||
w:u32be(buffer.readu32(head, 12))
|
||||
w:u16be(buffer.readu16(head, 16))
|
||||
local family = buffer.readu8(head, 18)
|
||||
w:u8(family)
|
||||
if family ~= 0 and buffer.len(head) >= 21 + ch then
|
||||
w:bytes(head, 19, 2 + ch)
|
||||
end
|
||||
return w:finish()
|
||||
end
|
||||
|
||||
-- encode(video, opts?) -> buffer | nil, Err
|
||||
function Mp4.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
local o: any = table.clone(opts or {})
|
||||
o.quality = o.quality or 90
|
||||
local mov = type(o.format) == "string" and (string.lower(o.format) == "mov" or string.lower(o.format) == "qt")
|
||||
local vcopy: { [string]: boolean } = { mjpeg = true }
|
||||
for id in VIDEO_ENTRY do
|
||||
vcopy[id] = true
|
||||
end
|
||||
local acopy: { [string]: boolean } = {}
|
||||
for id in AUDIO_ENTRY do
|
||||
acopy[id] = true
|
||||
end
|
||||
acopy.pcm_s16le = mov
|
||||
local streams, err = Source.streams(value, o, {
|
||||
video = { copy = vcopy, encode = "mjpeg" },
|
||||
audio = { copy = acopy, pcm = mov },
|
||||
})
|
||||
if not streams then
|
||||
return nil, err
|
||||
end
|
||||
local mtracks = {}
|
||||
for _, s in streams do
|
||||
local scale = if s.kind == "audio" then math.floor((s.sampleRate or 48000) + 0.5) else 90000
|
||||
if s.kind == "video" and s.track and s.track.timescale and s.copied and s.track.timescale == math.floor(s.track.timescale) then
|
||||
scale = s.track.timescale
|
||||
end
|
||||
local samples, durations, cts, sync = {}, {}, {}, {}
|
||||
local anyCts = false
|
||||
local firstDts = nil :: number?
|
||||
for i, p in s.packets do
|
||||
samples[i] = p.data
|
||||
local dts = p.dts or p.pts
|
||||
firstDts = firstDts or dts
|
||||
local nextP = s.packets[i + 1]
|
||||
local d = if nextP then (nextP.dts or nextP.pts) - dts else p.duration
|
||||
durations[i] = math.max(0, math.floor(d * scale + 0.5))
|
||||
local c = math.floor((p.pts - dts) * scale + 0.5)
|
||||
cts[i] = c
|
||||
if c ~= 0 then
|
||||
anyCts = true
|
||||
end
|
||||
if p.keyframe then
|
||||
sync[i] = true
|
||||
end
|
||||
end
|
||||
-- an edit list keeps the source's start: video decode times before 0 (B-frame delay), audio codec delay
|
||||
local skip = 0
|
||||
if firstDts and firstDts < 0 then
|
||||
skip = math.floor(-firstDts * scale + 0.5)
|
||||
end
|
||||
if s.kind == "audio" and s.track and s.track.codecDelay and s.copied then
|
||||
skip = math.floor(s.track.codecDelay * scale + 0.5)
|
||||
end
|
||||
local t: any = {
|
||||
kind = s.kind,
|
||||
timescale = scale,
|
||||
skip = if skip > 0 then skip else nil,
|
||||
samples = samples,
|
||||
durations = durations,
|
||||
cts = if anyCts then cts else nil,
|
||||
sync = sync,
|
||||
width = s.width,
|
||||
height = s.height,
|
||||
sampleRate = s.sampleRate and math.floor(s.sampleRate + 0.5),
|
||||
channels = s.channels,
|
||||
}
|
||||
if s.kind == "video" then
|
||||
if s.codec == "mjpeg" then
|
||||
t.entry = if mov then "jpeg" else "mp4v"
|
||||
if not mov then
|
||||
t.objectType = 0x6C
|
||||
t.configBox = "esds"
|
||||
t.config = buffer.create(0)
|
||||
end
|
||||
else
|
||||
t.entry = VIDEO_ENTRY[s.codec]
|
||||
t.config = s.config
|
||||
end
|
||||
else
|
||||
if s.codec == "pcm_s16le" then
|
||||
t.entry = "sowt"
|
||||
t.bitsPerSample = 16
|
||||
else
|
||||
t.entry = AUDIO_ENTRY[s.codec]
|
||||
t.config = if s.codec == "opus" then dOps(s.config) else s.config
|
||||
if s.codec == "mp3" then
|
||||
t.objectType = 0x6B
|
||||
t.configBox = "esds"
|
||||
t.config = buffer.create(0)
|
||||
end
|
||||
end
|
||||
end
|
||||
if not t.entry then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "no sample entry for " .. s.kind .. " codec " .. s.codec)
|
||||
end
|
||||
table.insert(mtracks, t)
|
||||
end
|
||||
return IsoBmff.mux({ brand = if mov then "qt " else "isom", compatible = if mov then { "qt " } else { "isom", "iso2", "mp41" }, tracks = mtracks })
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ open
|
||||
-- open(r, opts?) -> a VideoDecoder | nil, Err
|
||||
function Mp4.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?)
|
||||
local dmx, err = Mp4.demux(r, opts)
|
||||
if not dmx then
|
||||
return nil, err
|
||||
end
|
||||
return Video.open(dmx, opts)
|
||||
end
|
||||
|
||||
return Mp4
|
||||
@@ -0,0 +1,192 @@
|
||||
--!strict
|
||||
-- video/mpegps: MPEG program streams (ISO/IEC 11172-1 system streams and 13818-1 program streams: .mpg / .mpeg /
|
||||
-- .vob / VCD .dat). New in formats-luau, 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); 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
|
||||
-- video through the codecs/Video registry (MPEG-2 detected and reported), audio through the api's opts.openAudio hook.
|
||||
-- Timescale 90 kHz. Not supported: writing, H.264 in PS (packets are whole PES payloads), DVD navigation packets.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Types = require("@formats/Types")
|
||||
local MpegPs = require("@formats/containers/MpegPs")
|
||||
local MpegEs = require("@formats/containers/MpegEs")
|
||||
local Demux = require("@formats/containers/Demux")
|
||||
local Video = require("@formats/codecs/Video")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Ps = {
|
||||
name = "mpegps",
|
||||
category = "video",
|
||||
extensions = { "mpg", "mpeg", "vob", "m1v", "mpv", "dat" },
|
||||
mime = { "video/mpeg" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "containers/MpegPs", "containers/MpegEs", "containers/Demux", "codecs/Video" },
|
||||
caps = { decode = true, encode = false, streaming = true, video = { "mpeg1" }, audio = true },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type OpenOptions = {
|
||||
rgba: boolean?,
|
||||
track: number?, -- the video stream id to decode (0xE0.. ; default: the first video stream)
|
||||
audio: boolean?,
|
||||
maxPixels: number?,
|
||||
openAudio: any?, -- set by the api
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Ps.sniff(r: Bytes.Reader): number
|
||||
if r:peek(4) == "\0\0\1\186" then
|
||||
return 0.9
|
||||
end
|
||||
if r:peek(4) == "\0\0\1\179" then
|
||||
return 0.5 -- an MPEG-1 / 2 video elementary stream (sequence header)
|
||||
end
|
||||
return 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
-- the pictures of a video stream as packets: join the PES payloads, cut at pictures, place the timestamps
|
||||
local function videoPackets(dmx: any, buf: buffer, s: MpegPs.Stream, t: any)
|
||||
local total = 0
|
||||
for _, p in s.pes do
|
||||
total += p.size
|
||||
end
|
||||
local es = buffer.create(total)
|
||||
local starts: { number } = {}
|
||||
local o = 0
|
||||
for i, p in s.pes do
|
||||
starts[i] = o
|
||||
buffer.copy(es, o, buf, p.offset, p.size)
|
||||
o += p.size
|
||||
end
|
||||
local info = MpegEs.info(es, 0, total)
|
||||
if info then
|
||||
t.width, t.height, t.frameRate = info.width, info.height, info.frameRate
|
||||
if info.mpeg2 then
|
||||
t.codec = "mpeg2"
|
||||
end
|
||||
end
|
||||
local pics = MpegEs.pictures(es, 0, total)
|
||||
local fd = if t.frameRate and t.frameRate > 0 then 90000 / t.frameRate else 3600
|
||||
-- the PTS of the PES each picture starts in (only the first picture starting in a PES takes it)
|
||||
local k = 1
|
||||
local used: { [number]: boolean } = {}
|
||||
local ptsOf: { [number]: number } = {}
|
||||
for i, pic in pics do
|
||||
while k < #s.pes and starts[k + 1] <= pic.offset do
|
||||
k += 1
|
||||
end
|
||||
-- a PES whose payload starts inside this picture's headers also labels it
|
||||
local pes = s.pes[k]
|
||||
if pes and pes.pts and not used[k] then
|
||||
used[k] = true
|
||||
ptsOf[i] = pes.pts
|
||||
end
|
||||
end
|
||||
-- fill the rest from the temporal references of each GOP (an elementary stream without any PTS: from 0)
|
||||
local anchorPts, anchorTr = nil :: number?, 0
|
||||
local lastPts = nil :: number?
|
||||
local timed = next(ptsOf) ~= nil
|
||||
local count = 0
|
||||
for i, pic in pics do
|
||||
if pic.gop then
|
||||
anchorPts = nil
|
||||
if not timed then
|
||||
anchorPts, anchorTr = count * fd, 0
|
||||
end
|
||||
end
|
||||
if not timed and anchorPts == nil then
|
||||
anchorPts, anchorTr = count * fd, pic.temporal
|
||||
end
|
||||
count += 1
|
||||
local pts = ptsOf[i]
|
||||
if pts then
|
||||
anchorPts, anchorTr = pts, pic.temporal
|
||||
elseif anchorPts then
|
||||
pts = anchorPts + (pic.temporal - anchorTr) * fd
|
||||
elseif lastPts then
|
||||
pts = lastPts + fd
|
||||
end
|
||||
if pts then
|
||||
lastPts = pts
|
||||
local d = buffer.create(pic.size)
|
||||
buffer.copy(d, 0, es, pic.offset, pic.size)
|
||||
dmx:addData(t.id, pts, nil, fd, pic.type == 1, d)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- demux(r, opts?) -> the Demuxer | nil, Err
|
||||
function Ps.demux(r: Bytes.Reader, _opts: OpenOptions?): (any, Err.Err?)
|
||||
if r:peek(4) == "\0\0\1\179" then
|
||||
-- an MPEG-1 / 2 video elementary stream (.m1v): one video stream, no timestamps
|
||||
local t: any = { id = 0xE0, kind = "video", codec = "mpeg1", codecTag = "es", timescale = 90000, streamId = 0xE0 }
|
||||
local dmx = Demux.new("mpegps", { t }, r.buf, { elementary = true })
|
||||
videoPackets(dmx, r.buf, { id = 0xE0, kind = "video", codec = "mpeg1", pes = { { offset = r.base, size = r.limit - r.base } } }, t)
|
||||
dmx:finish()
|
||||
return dmx, nil
|
||||
end
|
||||
local ok, file, err = pcall(MpegPs.read, r.buf, r.base, r.limit)
|
||||
if not ok then
|
||||
return nil, Err.new(Err.CORRUPT, "internal error: " .. tostring(file))
|
||||
end
|
||||
if not file then
|
||||
return nil, err
|
||||
end
|
||||
local tracks: { Types.Track } = {}
|
||||
for _, id in file.order do
|
||||
local s = file.streams[id]
|
||||
table.insert(tracks, {
|
||||
id = id,
|
||||
kind = s.kind :: any,
|
||||
codec = s.codec,
|
||||
codecTag = string.format("0x%02x", id % 256),
|
||||
timescale = 90000,
|
||||
streamId = id,
|
||||
})
|
||||
end
|
||||
local dmx = Demux.new("mpegps", tracks, r.buf, { mpeg2 = file.mpeg2, errors = file.errors })
|
||||
for i, id in file.order do
|
||||
local s = file.streams[id]
|
||||
local t: any = tracks[i]
|
||||
if t.kind == "video" and (t.codec == "mpeg1" or t.codec == "mpeg2") then
|
||||
videoPackets(dmx, r.buf, s, t)
|
||||
else
|
||||
local last = nil :: number?
|
||||
for _, p in s.pes do
|
||||
local pts = p.pts or last
|
||||
if pts and p.size > 0 then
|
||||
last = pts
|
||||
dmx:add(id, pts, p.dts, nil, true, p.offset, p.size)
|
||||
end
|
||||
end
|
||||
if t.codec == "mp2" and #s.pes > 0 then
|
||||
local p = s.pes[1]
|
||||
local b = r.buf
|
||||
for i2 = p.offset, math.min(p.offset + p.size, r.limit) - 2 do
|
||||
if buffer.readu8(b, i2) == 0xFF and buffer.readu8(b, i2 + 1) >= 0xE0 then
|
||||
local layer = (buffer.readu8(b, i2 + 1) // 2) % 4
|
||||
t.codec = if layer == 1 then "mp3" elseif layer == 3 then "mp1" else "mp2"
|
||||
break
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
dmx:finish() -- (read() without a track gives the video packets first, then the audio ones)
|
||||
return dmx, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ open
|
||||
-- open(r, opts?) -> a VideoDecoder | nil, Err
|
||||
function Ps.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?)
|
||||
local dmx, err = Ps.demux(r, opts)
|
||||
if not dmx then
|
||||
return nil, err
|
||||
end
|
||||
return Video.open(dmx, opts)
|
||||
end
|
||||
|
||||
return Ps
|
||||
@@ -0,0 +1,245 @@
|
||||
--!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 video through the codecs/Video
|
||||
-- registry (stream type 0x02 checked for an MPEG-2 sequence extension), H.264 when registered, audio (MP1 / MP2 /
|
||||
-- MP3, AAC in ADTS) through the api's opts.openAudio hook. Keyframes: MPEG-1 / 2 I-pictures, H.264 IDR access units.
|
||||
-- M2TS (192-byte packets with a 4-byte timestamp prefix) is read too. Not supported: writing, scrambled streams,
|
||||
-- PES without PTS for video before the first one (dropped).
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Types = require("@formats/Types")
|
||||
local MpegTs = require("@formats/containers/MpegTs")
|
||||
local MpegEs = require("@formats/containers/MpegEs")
|
||||
local Demux = require("@formats/containers/Demux")
|
||||
local Video = require("@formats/codecs/Video")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Ts = {
|
||||
name = "mpegts",
|
||||
category = "video",
|
||||
extensions = { "ts", "m2ts", "mts", "tsv" },
|
||||
mime = { "video/mp2t" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "containers/MpegTs", "containers/MpegEs", "containers/Demux", "codecs/Video" },
|
||||
caps = { decode = true, encode = false, streaming = true, video = { "mpeg1", "h264" }, audio = true },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type OpenOptions = {
|
||||
rgba: boolean?,
|
||||
track: number?, -- the video PID to decode (default: the first video stream of the PMT)
|
||||
audio: boolean?,
|
||||
maxPixels: number?,
|
||||
openAudio: any?, -- set by the api
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
local CODEC: { [string]: string } = {
|
||||
mpeg1video = "mpeg1",
|
||||
mpeg2video = "mpeg2",
|
||||
mpegaudio = "mp2",
|
||||
aac = "aac",
|
||||
aac_latm = "aac_latm",
|
||||
h264 = "h264",
|
||||
hevc = "hevc",
|
||||
mpeg4 = "mpeg4",
|
||||
ac3 = "ac3",
|
||||
eac3 = "eac3",
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
-- packetSize(r) -> 188 | 192 (M2TS) | 0, and the offset of the first sync byte: three sync bytes a packet apart
|
||||
-- (fewer in a short file) within the first 2 KB
|
||||
local function packetSize(r: Bytes.Reader): (number, number)
|
||||
local n = r:remaining()
|
||||
for start = 0, math.min(n, 2048) - 1 do
|
||||
if r:peekU8(start) == 0x47 then
|
||||
for _, size in { 188, 192 } do
|
||||
local hits, need = 0, math.min(3, (n - start - 1) // size + 1)
|
||||
for k = 0, 2 do
|
||||
local at = start + k * size
|
||||
if at < n and r:peekU8(at) == 0x47 then
|
||||
hits += 1
|
||||
end
|
||||
end
|
||||
if hits >= need and (need >= 2 or start == 0) then
|
||||
if size == 192 and start >= 4 then
|
||||
return 192, start - 4
|
||||
elseif size == 188 then
|
||||
return 188, start
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
return 0, 0
|
||||
end
|
||||
|
||||
function Ts.sniff(r: Bytes.Reader): number
|
||||
local s, off = packetSize(r)
|
||||
if s == 0 then
|
||||
return 0
|
||||
end
|
||||
if off > 0 then
|
||||
return 0.6
|
||||
end
|
||||
return if r:remaining() >= 3 * s then 0.9 else 0.5
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
-- the 188-byte packets of an M2TS file (192-byte packets: drop the 4-byte timestamps)
|
||||
local function strip192(b: buffer, base: number, limit: number): buffer
|
||||
local n = (limit - base) // 192
|
||||
local out = buffer.create(n * 188)
|
||||
for i = 0, n - 1 do
|
||||
buffer.copy(out, i * 188, b, base + i * 192 + 4, 188)
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
local function mpegAudioCodec(u: any): string
|
||||
local d: buffer = u.data
|
||||
for i = 0, math.min(buffer.len(d), 4096) - 2 do
|
||||
if buffer.readu8(d, i) == 0xFF and buffer.readu8(d, i + 1) >= 0xE0 then
|
||||
local layer = (buffer.readu8(d, i + 1) // 2) % 4
|
||||
return if layer == 1 then "mp3" elseif layer == 3 then "mp1" else "mp2"
|
||||
end
|
||||
end
|
||||
return "mp2"
|
||||
end
|
||||
|
||||
-- demux(r, opts?) -> the Demuxer | nil, Err
|
||||
function Ts.demux(r: Bytes.Reader, _opts: OpenOptions?): (any, Err.Err?)
|
||||
local size, off = packetSize(r)
|
||||
if size == 0 then
|
||||
return nil, Err.new(Err.CORRUPT, "no transport stream sync", r.base)
|
||||
end
|
||||
local d = MpegTs.new()
|
||||
if size == 192 then
|
||||
local b = strip192(r.buf, r.base + off, r.limit)
|
||||
d:push(b, 0, buffer.len(b))
|
||||
else
|
||||
d:push(r.buf, r.base + off, r.limit - r.base - off)
|
||||
end
|
||||
d:flush()
|
||||
local units = {}
|
||||
while true do
|
||||
local u = d:pull()
|
||||
if u == nil then
|
||||
break
|
||||
end
|
||||
table.insert(units, u)
|
||||
end
|
||||
if #units == 0 then
|
||||
return nil, Err.new(Err.CORRUPT, "no PES units")
|
||||
end
|
||||
-- tracks: the PMT's streams, then PIDs found without one
|
||||
local tracks: { Types.Track } = {}
|
||||
local byPid: { [number]: any } = {}
|
||||
local function track(pid: number, kind: string, codec: string, st: number, lang: string?): any
|
||||
local t = byPid[pid]
|
||||
if t then
|
||||
return t
|
||||
end
|
||||
t = {
|
||||
id = pid,
|
||||
kind = if kind == "other" then "data" else kind,
|
||||
codec = CODEC[codec] or codec,
|
||||
codecTag = string.format("0x%02x", st),
|
||||
timescale = 90000,
|
||||
language = lang,
|
||||
streamType = st,
|
||||
}
|
||||
byPid[pid] = t
|
||||
table.insert(tracks, t)
|
||||
return t
|
||||
end
|
||||
for _, s in d.streams do
|
||||
track(s.pid, s.kind, s.codec, s.streamType, s.language)
|
||||
end
|
||||
for _, u in units do
|
||||
track(u.pid, u.kind, u.codec, u.streamType, nil)
|
||||
end
|
||||
-- codec details from the first unit
|
||||
local seen: { [number]: boolean } = {}
|
||||
for _, u in units do
|
||||
local t = byPid[u.pid]
|
||||
if not seen[u.pid] then
|
||||
seen[u.pid] = true
|
||||
if t.codec == "unknown" or t.kind == "data" then
|
||||
-- a private / unknown stream type: go by the PES stream id and the payload
|
||||
local sid = u.streamId or 0
|
||||
if sid >= 0xE0 and sid <= 0xEF then
|
||||
t.kind = "video"
|
||||
local info = MpegEs.info(u.data, 0, buffer.len(u.data))
|
||||
t.codec = if info then (if info.mpeg2 then "mpeg2" else "mpeg1") elseif MpegEs.findStart(u.data, 0, math.min(buffer.len(u.data), 8)) then "h264" else "unknown"
|
||||
elseif sid >= 0xC0 and sid <= 0xDF then
|
||||
t.kind, t.codec = "audio", "mp2"
|
||||
end
|
||||
end
|
||||
if t.codec == "mpeg1" or t.codec == "mpeg2" then
|
||||
local info = MpegEs.info(u.data, 0, buffer.len(u.data))
|
||||
if info then
|
||||
t.codec = if info.mpeg2 then "mpeg2" else "mpeg1"
|
||||
t.width, t.height, t.frameRate = info.width, info.height, info.frameRate
|
||||
end
|
||||
elseif t.codec == "mp2" then
|
||||
t.codec = mpegAudioCodec(u)
|
||||
elseif t.codec == "aac" then
|
||||
t.adts = true
|
||||
local b: buffer = u.data
|
||||
if buffer.len(b) >= 4 and buffer.readu8(b, 0) == 0xFF then
|
||||
local rates = { 96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350 }
|
||||
t.sampleRate = rates[(buffer.readu8(b, 2) // 4) % 16 + 1]
|
||||
t.channels = (buffer.readu8(b, 2) % 2) * 4 + buffer.readu8(b, 3) // 64
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
local dmx = Demux.new("mpegts", tracks, r.buf, { stats = d.stats })
|
||||
local lastPts: { [number]: number } = {}
|
||||
for _, u in units do
|
||||
local t = byPid[u.pid]
|
||||
local pts = u.pts90 or u.dts90
|
||||
if pts == nil then
|
||||
local prev = lastPts[u.pid]
|
||||
if prev and t.frameRate and t.frameRate > 0 then
|
||||
pts = prev + 90000 / t.frameRate
|
||||
else
|
||||
pts = prev
|
||||
end
|
||||
end
|
||||
if pts ~= nil then
|
||||
lastPts[u.pid] = pts
|
||||
local key = true
|
||||
local data: buffer = u.data
|
||||
if t.kind == "video" then
|
||||
if t.codec == "mpeg1" or t.codec == "mpeg2" then
|
||||
key = MpegEs.pictureType(data, 0, buffer.len(data)) == 1
|
||||
elseif t.codec == "h264" then
|
||||
key = u.randomAccess or MpegEs.h264Key(data, 0, buffer.len(data))
|
||||
else
|
||||
key = u.randomAccess
|
||||
end
|
||||
end
|
||||
dmx:addData(u.pid, pts, u.dts90 or pts, nil, key, data)
|
||||
end
|
||||
end
|
||||
dmx:finish()
|
||||
return dmx, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ open
|
||||
-- open(r, opts?) -> a VideoDecoder | nil, Err
|
||||
function Ts.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?)
|
||||
local dmx, err = Ts.demux(r, opts)
|
||||
if not dmx then
|
||||
return nil, err
|
||||
end
|
||||
return Video.open(dmx, opts)
|
||||
end
|
||||
|
||||
return Ts
|
||||
@@ -0,0 +1,209 @@
|
||||
--!strict
|
||||
-- video/y4m: YUV4MPEG2 (the mjpegtools / ffmpeg raw video stream). New in formats-luau.
|
||||
-- Read: the stream header (W H F I A C X tags) and every FRAME into a raw-video Demuxer; open() returns a VideoDecoder
|
||||
-- with yuv420p frames (C420 / C420jpeg / C420mpeg2 / C420paldv as they are; C422 / C444 chroma averaged down; Cmono
|
||||
-- with neutral chroma; 9..16-bit samples (C420p10, ...) scaled to 8 bits). Y4m.demux(r) gives the Demuxer.
|
||||
-- Write: yuv420p 8-bit frames ("C420jpeg", as ffmpeg writes for yuv420p) from any video or animated image; rgba8
|
||||
-- frames are converted (BT.601 limited range); uneven frame times (a GIF's) become a constant rate with repeated frames. Not supported: interlaced field handling (the I tag is kept in meta),
|
||||
-- alpha (C444alpha drops it).
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Types = require("@formats/Types")
|
||||
local Demux = require("@formats/containers/Demux")
|
||||
local Video = require("@formats/codecs/Video")
|
||||
local Source = require("@formats/codecs/Video/Source")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Y4m = {
|
||||
name = "y4m",
|
||||
category = "video",
|
||||
extensions = { "y4m" },
|
||||
mime = { "video/x-yuv4mpeg" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "containers/Demux", "codecs/Video", "codecs/Video/Source" },
|
||||
caps = { decode = true, encode = true, streaming = true, video = { "rawvideo" }, depths = { 8, 10, 12, 16 } },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type OpenOptions = {
|
||||
rgba: boolean?, -- nextFrame returns rgba8 (default false: yuv420p)
|
||||
maxPixels: number?, -- default 2^26
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
frameRate: { number }?, -- { num, den } for the F tag, one frame per source frame (default: the constant rate of the
|
||||
-- shortest frame, longer frames repeated)
|
||||
maxFps: number?, -- the highest rate uneven frame times may need (default 100)
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
local MAGIC = "YUV4MPEG2 "
|
||||
-- C tag -> pixel format, bits
|
||||
local COLOR: { [string]: { any } } = {
|
||||
["420jpeg"] = { "yuv420p", 8 },
|
||||
["420paldv"] = { "yuv420p", 8 },
|
||||
["420mpeg2"] = { "yuv420p", 8 },
|
||||
["420"] = { "yuv420p", 8 },
|
||||
["422"] = { "yuv422p", 8 },
|
||||
["444"] = { "yuv444p", 8 },
|
||||
["444alpha"] = { "yuva444p", 8 },
|
||||
mono = { "gray", 8 },
|
||||
}
|
||||
for _, b in { 9, 10, 12, 14, 16 } do
|
||||
COLOR["420p" .. b] = { "yuv420p", b }
|
||||
COLOR["422p" .. b] = { "yuv422p", b }
|
||||
COLOR["444p" .. b] = { "yuv444p", b }
|
||||
COLOR["mono" .. b] = { "gray", b }
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Y4m.sniff(r: Bytes.Reader): number
|
||||
return if r:peek(10) == MAGIC then 1 else 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
local function frameSize(pf: string, bits: number, w: number, h: number): number
|
||||
local bps = if bits > 8 then 2 else 1
|
||||
local cw, ch = (w + 1) // 2, (h + 1) // 2
|
||||
if pf == "yuv420p" then
|
||||
return (w * h + 2 * cw * ch) * bps
|
||||
elseif pf == "yuv422p" then
|
||||
return (w * h + 2 * cw * h) * bps
|
||||
elseif pf == "yuv444p" then
|
||||
return w * h * 3 * bps
|
||||
elseif pf == "yuva444p" then
|
||||
return w * h * 4 * bps
|
||||
end
|
||||
return w * h * bps
|
||||
end
|
||||
|
||||
-- demux(r, opts?) -> the raw-video Demuxer | nil, Err
|
||||
function Y4m.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?)
|
||||
local buf, base, limit = r.buf, r.base, r.limit
|
||||
local nl = -1
|
||||
for i = base, math.min(limit, base + 4096) - 1 do
|
||||
if buffer.readu8(buf, i) == 10 then
|
||||
nl = i
|
||||
break
|
||||
end
|
||||
end
|
||||
if limit - base < 10 or buffer.readstring(buf, base, 10) ~= MAGIC then
|
||||
return nil, Err.new(Err.CORRUPT, "not a YUV4MPEG2 stream", base)
|
||||
end
|
||||
if nl < 0 then
|
||||
return nil, Err.new(Err.TRUNCATED, "no end of the stream header", base)
|
||||
end
|
||||
local header = buffer.readstring(buf, base + 10, nl - base - 10)
|
||||
local w, h, fn, fd = 0, 0, 25, 1
|
||||
local ctag, itag, atag = "420jpeg", "p", "0:0"
|
||||
local extra = {}
|
||||
for tok in string.gmatch(header, "%S+") do
|
||||
local k, v = string.sub(tok, 1, 1), string.sub(tok, 2)
|
||||
if k == "W" then
|
||||
w = tonumber(v) or 0
|
||||
elseif k == "H" then
|
||||
h = tonumber(v) or 0
|
||||
elseif k == "F" then
|
||||
local a, b = string.match(v, "^(%d+):(%d+)$")
|
||||
if a and b and tonumber(a) > 0 and tonumber(b) > 0 then
|
||||
fn, fd = tonumber(a) :: number, tonumber(b) :: number
|
||||
end
|
||||
elseif k == "C" then
|
||||
ctag = v
|
||||
elseif k == "I" then
|
||||
itag = v
|
||||
elseif k == "A" then
|
||||
atag = v
|
||||
elseif k == "X" then
|
||||
table.insert(extra, v)
|
||||
end
|
||||
end
|
||||
local color = COLOR[ctag]
|
||||
if not color then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "colour space C" .. ctag)
|
||||
end
|
||||
if w <= 0 or h <= 0 or w > 65535 or h > 65535 then
|
||||
return nil, Err.new(Err.CORRUPT, "bad frame size " .. w .. "x" .. h)
|
||||
end
|
||||
local maxPixels = opts and opts.maxPixels or 2 ^ 26
|
||||
if w * h > maxPixels then
|
||||
return nil, Err.new(Err.LIMIT, "frame of " .. w .. "x" .. h .. " pixels")
|
||||
end
|
||||
local pf, bits = color[1], color[2]
|
||||
local size = frameSize(pf, bits, w, h)
|
||||
local track: Types.Track = {
|
||||
id = 1,
|
||||
kind = "video",
|
||||
codec = "rawvideo",
|
||||
codecTag = "C" .. ctag,
|
||||
timescale = fn / fd,
|
||||
width = w,
|
||||
height = h,
|
||||
frameRate = fn / fd,
|
||||
pixelFormat = pf,
|
||||
bitDepth = bits,
|
||||
default = true,
|
||||
}
|
||||
local meta = { interlace = itag, aspect = atag, extra = extra, colorTag = ctag }
|
||||
local dmx = Demux.new("y4m", { track }, buf, meta)
|
||||
local pos = nl + 1
|
||||
local k = 0
|
||||
while pos + 5 <= limit do
|
||||
if buffer.readstring(buf, pos, 5) ~= "FRAME" then
|
||||
return nil, Err.new(Err.CORRUPT, "expected FRAME", pos)
|
||||
end
|
||||
local e = -1
|
||||
for i = pos + 5, math.min(limit, pos + 4096) - 1 do
|
||||
if buffer.readu8(buf, i) == 10 then
|
||||
e = i
|
||||
break
|
||||
end
|
||||
end
|
||||
if e < 0 then
|
||||
break
|
||||
end
|
||||
local data = e + 1
|
||||
if data + size > limit then
|
||||
break -- a truncated last frame is dropped
|
||||
end
|
||||
dmx:add(1, k, k, 1, true, data, size)
|
||||
k += 1
|
||||
pos = data + size
|
||||
end
|
||||
dmx:finish()
|
||||
return dmx, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
-- encode(video, opts?) -> buffer | nil, Err
|
||||
function Y4m.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
local streams, err = Source.streams(value, { audio = false }, { video = { copy = nil, encode = "rawvideo" } })
|
||||
if not streams then
|
||||
return nil, err
|
||||
end
|
||||
local s = streams[1]
|
||||
local fn, fd, packets = Source.constantRate(s, opts and opts.maxFps)
|
||||
if opts and type(opts.frameRate) == "table" then
|
||||
fn, fd, packets = opts.frameRate[1], opts.frameRate[2], s.packets
|
||||
end
|
||||
s.packets = packets
|
||||
local w = Bytes.writer(64 + #s.packets * (buffer.len(s.packets[1].data) + 6))
|
||||
w:string(string.format("YUV4MPEG2 W%d H%d F%d:%d Ip A1:1 C420jpeg XYSCSS=420JPEG\n", s.width or 0, s.height or 0, fn, fd))
|
||||
for _, p in s.packets do
|
||||
w:string("FRAME\n")
|
||||
w:bytes(p.data)
|
||||
end
|
||||
return w:finish(), nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ open
|
||||
-- open(r, opts?) -> a VideoDecoder | nil, Err
|
||||
function Y4m.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?)
|
||||
local dmx, err = Y4m.demux(r, opts)
|
||||
if not dmx then
|
||||
return nil, err
|
||||
end
|
||||
return Video.open(dmx, opts)
|
||||
end
|
||||
|
||||
return Y4m
|
||||
Reference in new issue
Block a user