merge ws/video2-flv
This commit is contained in:
commit
a02ece071b
18 files changed
+3088
-1
No files matched your search
@@ -554,6 +554,18 @@ local list: { Entry } = {
|
||||
return require("@formats/video/fli")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "flv",
|
||||
category = "video",
|
||||
path = "video/flv",
|
||||
extensions = { "flv" },
|
||||
mime = { "video/x-flv", "video/flv" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "containers/Demux", "codecs/video/Video", "codecs/video/Video/Source", "codecs/video/H263", "codecs/video/H264", "codecs/audio/Aac" },
|
||||
caps = { decode = true, encode = true, streaming = true, remux = true, video = { "flv1", "h264" }, audio = true, metadata = true },
|
||||
load = function()
|
||||
return require("@formats/video/flv")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "h264",
|
||||
category = "video",
|
||||
|
||||
@@ -17,6 +17,7 @@
|
||||
-- Dsp.idct(blk, dst, off, stride, add) -- blk: 64 i32 (256 bytes, row-major), left holding garbage: clear it
|
||||
-- Dsp.fill(dst, off, stride, v, add) -- an 8x8 block of constant v (a DC-only block: v = (dc + 4) >> 3)
|
||||
-- Dsp.mc(src, sStride, sOff, dst, dStride, dOff, w, h, hx, hy, avg) -- half-pel prediction of a w x h block
|
||||
-- Dsp.mcNoRound(src, sStride, sOff, dst, dStride, dOff, w, h, hx, hy) -- the same, averages rounded down (H.263+)
|
||||
-- Dsp.edge(src, stride, base, x, y, w, h, pw, ph, out) -- a block with edge samples repeated (EDGE_STRIDE)
|
||||
local Dsp = {}
|
||||
|
||||
@@ -692,6 +693,34 @@ function Dsp.mc(src: buffer, sStride: number, sOff: number, dst: buffer, dStride
|
||||
end
|
||||
end
|
||||
|
||||
-- Dsp.mc with the half-sample averages rounded down, (a + b) >> 1 and (a + b + c + d + 1) >> 2 (H.263 rounding type 1:
|
||||
-- RTYPE of an H.263+ picture header, MPEG-4 rounding_control). No averaging into dst.
|
||||
function Dsp.mcNoRound(src: buffer, sStride: number, sOff: number, dst: buffer, dStride: number, dOff: number, w: number, h: number, hx: number, hy: number)
|
||||
if hx == 0 and hy == 0 then
|
||||
Dsp.mc(src, sStride, sOff, dst, dStride, dOff, w, h, 0, 0, false)
|
||||
return
|
||||
end
|
||||
local dx = if hx == 0 then sStride else 1 -- the second sample of a two-tap average
|
||||
for _ = 1, h do
|
||||
for i = 0, w - 4, 4 do
|
||||
local p
|
||||
if hx == 0 or hy == 0 then
|
||||
local a, b = readu32(src, sOff + i), readu32(src, sOff + i + dx)
|
||||
p = band(a, b) + rshift(band(bxor(a, b), 0xFEFEFEFE), 1)
|
||||
else
|
||||
local a, b = readu32(src, sOff + i), readu32(src, sOff + i + 1)
|
||||
local c, d = readu32(src, sOff + i + sStride), readu32(src, sOff + i + sStride + 1)
|
||||
local l = band(a, 0x03030303) + band(b, 0x03030303) + band(c, 0x03030303) + band(d, 0x03030303) + 0x01010101
|
||||
local hi = rshift(band(a, 0xFCFCFCFC), 2) + rshift(band(b, 0xFCFCFCFC), 2) + rshift(band(c, 0xFCFCFCFC), 2) + rshift(band(d, 0xFCFCFCFC), 2)
|
||||
p = hi + band(rshift(l, 2), 0x0F0F0F0F)
|
||||
end
|
||||
writeu32(dst, dOff + i, p)
|
||||
end
|
||||
sOff += sStride
|
||||
dOff += dStride
|
||||
end
|
||||
end
|
||||
|
||||
-- Edge emulation: the (w + 1) x (h + 1) samples at (x, y) of a pw x ph plane (row r at base + r * stride) copied to
|
||||
-- out (rows EDGE_STRIDE apart), coordinates clamped into the plane, so a vector pointing outside the picture
|
||||
-- predicts from repeated edge samples (w + 1 <= EDGE_STRIDE, h + 1 <= 33; out holds EDGE_SIZE bytes).
|
||||
|
||||
@@ -0,0 +1,894 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- codecs/video/H263/Decoder: the H.263 / Sorenson Spark decoding core (native, never throws). Written from ITU-T
|
||||
-- H.263 (01/2005) and Adobe's Video File Format Specification v10 (the H.263VIDEOPACKET of Sorenson Spark).
|
||||
--
|
||||
-- H.263: picture headers with PTYPE (sub-QCIF .. 16CIF) and PLUSPTYPE (H.263+: standard and custom picture formats,
|
||||
-- custom pixel aspect ratios and picture clock frequencies, the rounding type RTYPE), I and P pictures, GOB headers
|
||||
-- (with or without stuffing), MCBPC / CBPY / MVD / TCOEF VLCs, DQUANT, the H.263 dequantiser, half-sample motion
|
||||
-- compensation with the H.263 chroma vector rounding, unrestricted motion vectors (Annex D in both header forms, the
|
||||
-- PLUSPTYPE form with its reversible MVD codes and unlimited range), slice structure (Annex K, without rectangular
|
||||
-- slices) and the extended escape of Annex T. Sorenson Spark
|
||||
-- (FLV1): its picture header (sizes, disposable inter pictures, which never become the reference), its 7 / 11-bit
|
||||
-- escape codes (version 1), unrestricted vectors. Not supported (the picture is refused with an "unsupported:" message):
|
||||
-- syntax-based arithmetic coding, advanced prediction (Annex F: four vectors and OBMC), PB / B / EI / EP pictures,
|
||||
-- advanced intra coding, the deblocking filter, rectangular slices, reference picture selection / resampling, reduced
|
||||
-- resolution update, independent segments, the alternative inter VLC, modified quantisation (other than the escape).
|
||||
--
|
||||
-- The IDCT and motion compensation are codecs/video/Dsp, the dequantiser is the H.263 one (|REC| = QUANT * (2 |LEVEL|
|
||||
-- + 1), minus 1 for an even QUANT, as ffmpeg without the -2048..2047 saturation), and vectors pointing outside the reference read
|
||||
-- repeated edge samples of the macroblock-aligned picture, so valid streams decode exactly as `ffmpeg -idct int`
|
||||
-- (tests/codecs/h263.luau). Corrupt data ends the picture: the rest is copied from the reference (state.errors).
|
||||
--
|
||||
-- local core = D.new(flv, maxPixels)
|
||||
-- local hdr, msg = D.header(buf, off, len, flv, core.state.opp) -- the picture header (no decoding)
|
||||
-- local store, msg = core.decode(buf, off, len) -- one picture -> the Store decoded into (decoder-owned)
|
||||
-- core.reset() -- forget the reference (after a seek)
|
||||
local Tb = require("@formats/codecs/video/H263/Tables")
|
||||
local Dsp = require("@formats/codecs/video/Dsp")
|
||||
|
||||
local readu8 = buffer.readu8
|
||||
local readu32 = buffer.readu32
|
||||
local readi32 = buffer.readi32
|
||||
local writei32 = buffer.writei32
|
||||
local bfill = buffer.fill
|
||||
local band = bit32.band
|
||||
local bor = bit32.bor
|
||||
local lshift = bit32.lshift
|
||||
local rshift = bit32.rshift
|
||||
local bswap = bit32.byteswap
|
||||
local idct = Dsp.idct
|
||||
local fillBlock = Dsp.fill
|
||||
local mc = Dsp.mc
|
||||
local mcNoRound = Dsp.mcNoRound
|
||||
local edge = Dsp.edge
|
||||
|
||||
local MCBPC_I = Tb.MCBPC_I
|
||||
local MCBPC_P = Tb.MCBPC_P
|
||||
local CBPY = Tb.CBPY
|
||||
local MVD = Tb.MVD
|
||||
local TCOEF = Tb.TCOEF
|
||||
local ZIGZAG = Tb.ZIGZAG
|
||||
local DQUANT = Tb.DQUANT
|
||||
local STUFFING = Tb.STUFFING
|
||||
local ESCAPE = Tb.ESCAPE
|
||||
|
||||
local PAD = 4096 -- zero bytes after the data: a macroblock reads at most ~2.5 KB, the end check runs per macroblock
|
||||
|
||||
local D = {}
|
||||
|
||||
D.PICTURE_I = 1
|
||||
D.PICTURE_P = 2
|
||||
|
||||
-- the PLUSPTYPE options that persist while UFEP = 0
|
||||
export type Opp = {
|
||||
format: number,
|
||||
customPcf: boolean,
|
||||
umv: boolean,
|
||||
ss: boolean, -- slice structured (Annex K)
|
||||
options: string?, -- the unsupported options set, or nil
|
||||
width: number,
|
||||
height: number,
|
||||
}
|
||||
|
||||
export type Header = {
|
||||
flv: boolean,
|
||||
version: number, -- Sorenson Spark: 0 (H.263 escapes) or 1 (7 / 11-bit escapes)
|
||||
tr: number, -- temporal reference
|
||||
width: number,
|
||||
height: number,
|
||||
ptype: number, -- 1 I, 2 P
|
||||
disposable: boolean, -- Sorenson: a P picture nothing predicts from
|
||||
quant: number,
|
||||
umv: boolean, -- unrestricted vectors, baseline form (long vectors)
|
||||
umvPlus: boolean, -- unrestricted vectors, PLUSPTYPE form
|
||||
rounding: number, -- RTYPE (0: half-sample averages round up)
|
||||
plus: boolean, -- PLUSPTYPE
|
||||
ss: boolean, -- slice structured (Annex K)
|
||||
cpm: boolean,
|
||||
deblock: boolean, -- Sorenson's deblocking hint (not applied, as ffmpeg)
|
||||
aspect: number?, -- PLUSPTYPE pixel aspect ratio code (15: aspectNum / aspectDen)
|
||||
aspectNum: number?,
|
||||
aspectDen: number?,
|
||||
opp: Opp?, -- the PLUSPTYPE options in force
|
||||
bitPos: number, -- absolute bit position of the first macroblock
|
||||
}
|
||||
|
||||
export type Store = {
|
||||
y: buffer,
|
||||
cb: buffer,
|
||||
cr: buffer,
|
||||
ls: number, -- luma stride (16 * macroblock columns); chroma stride ls / 2
|
||||
w: number,
|
||||
h: number,
|
||||
ptype: number,
|
||||
tr: number,
|
||||
disposable: boolean,
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ header
|
||||
-- the length of a slice's MBA field for a picture of n macroblocks (table K.2)
|
||||
function D.mbaBits(n: number): number
|
||||
return if n <= 48 then 6 elseif n <= 99 then 7 elseif n <= 396 then 9 elseif n <= 1584 then 11 elseif n <= 6336 then 13 else 14
|
||||
end
|
||||
|
||||
-- n (<= 24) bits at bit position p of buf, zeros past endByte
|
||||
local function bitsAt(buf: buffer, endByte: number, p: number, n: number): number
|
||||
local v = 0
|
||||
for k = p, p + n - 1 do
|
||||
local byte = rshift(k, 3)
|
||||
local b = if byte < endByte then readu8(buf, byte) else 0
|
||||
v = v * 2 + band(rshift(b, 7 - band(k, 7)), 1)
|
||||
end
|
||||
return v
|
||||
end
|
||||
|
||||
-- the byte offset of the first picture start code in buf[off, off + len) (H.263: 22 bits 0..01 00000; Sorenson:
|
||||
-- 17 bits 0..01 and version 0 / 1), or -1
|
||||
local function findStart(buf: buffer, off: number, len: number, flv: boolean): number
|
||||
local mask = if flv then 0xF8 else 0xFC
|
||||
for i = off, off + len - 3 do
|
||||
if readu8(buf, i) == 0 and readu8(buf, i + 1) == 0 and band(readu8(buf, i + 2), mask) == 0x80 then
|
||||
return i
|
||||
end
|
||||
end
|
||||
return -1
|
||||
end
|
||||
|
||||
-- header(buf, off, len, flv, opp?) -> Header | nil, message: the picture header of the first picture in
|
||||
-- buf[off, off + len); opp: the PLUSPTYPE options of the previous picture (pictures with UFEP = 0 keep them)
|
||||
function D.header(buf: buffer, off: number, len: number, flv: boolean, opp: Opp?): (Header?, string?)
|
||||
if off < 0 or len < 0 or off + len > buffer.len(buf) then
|
||||
return nil, "bad range"
|
||||
end
|
||||
local s = findStart(buf, off, len, flv)
|
||||
if s < 0 then
|
||||
return nil, "no picture start code"
|
||||
end
|
||||
local e = off + len
|
||||
local p = s * 8
|
||||
local function bits(n: number): number
|
||||
local v = bitsAt(buf, e, p, n)
|
||||
p += n
|
||||
return v
|
||||
end
|
||||
local h: Header = {
|
||||
flv = flv,
|
||||
version = 0,
|
||||
tr = 0,
|
||||
width = 0,
|
||||
height = 0,
|
||||
ptype = 1,
|
||||
disposable = false,
|
||||
quant = 1,
|
||||
umv = false,
|
||||
umvPlus = false,
|
||||
rounding = 0,
|
||||
plus = false,
|
||||
ss = false,
|
||||
cpm = false,
|
||||
deblock = false,
|
||||
bitPos = 0,
|
||||
}
|
||||
if flv then
|
||||
bits(17)
|
||||
h.version = bits(5)
|
||||
h.tr = bits(8)
|
||||
local size = bits(3)
|
||||
if size == 0 then
|
||||
h.width, h.height = bits(8), bits(8)
|
||||
elseif size == 1 then
|
||||
h.width, h.height = bits(16), bits(16)
|
||||
elseif size <= 6 then
|
||||
local d = Tb.FLV_SIZES[size]
|
||||
h.width, h.height = d[1], d[2]
|
||||
else
|
||||
return nil, "reserved picture size"
|
||||
end
|
||||
local t = bits(2)
|
||||
if t == 3 then
|
||||
return nil, "reserved picture type"
|
||||
end
|
||||
h.ptype = if t == 0 then 1 else 2
|
||||
h.disposable = t == 2
|
||||
h.deblock = bits(1) == 1
|
||||
h.quant = bits(5)
|
||||
else
|
||||
bits(22)
|
||||
h.tr = bits(8)
|
||||
if bits(1) ~= 1 or bits(1) ~= 0 then
|
||||
return nil, "bad PTYPE"
|
||||
end
|
||||
bits(3) -- split screen, document camera, freeze picture release
|
||||
local format = bits(3)
|
||||
if format >= 1 and format <= 5 then
|
||||
local d = Tb.FORMATS[format]
|
||||
h.width, h.height = d[1], d[2]
|
||||
h.ptype = bits(1) + 1
|
||||
h.umv = bits(1) == 1
|
||||
local sac, ap, pb = bits(1), bits(1), bits(1)
|
||||
if sac == 1 then
|
||||
return nil, "unsupported: syntax-based arithmetic coding"
|
||||
elseif ap == 1 then
|
||||
return nil, "unsupported: advanced prediction mode"
|
||||
elseif pb == 1 then
|
||||
return nil, "unsupported: PB-frames"
|
||||
end
|
||||
h.quant = bits(5)
|
||||
h.cpm = bits(1) == 1
|
||||
if h.cpm then
|
||||
bits(2)
|
||||
end
|
||||
elseif format == 7 then
|
||||
h.plus = true
|
||||
local ufep = bits(3)
|
||||
local o: Opp
|
||||
if ufep == 1 then
|
||||
local f = bits(3)
|
||||
local pcf, umv = bits(1) == 1, bits(1) == 1
|
||||
local names: { string } = { "syntax-based arithmetic coding", "advanced prediction", "advanced intra coding",
|
||||
"deblocking filter", "slice structure", "reference picture selection", "independent segment decoding",
|
||||
"alternative inter VLC", "modified quantisation" }
|
||||
local unsup: string? = nil
|
||||
local ss = false
|
||||
for i = 1, 9 do
|
||||
if bits(1) == 1 then
|
||||
if i == 5 then
|
||||
ss = true
|
||||
elseif not unsup then
|
||||
unsup = names[i]
|
||||
end
|
||||
end
|
||||
end
|
||||
bits(4) -- 1 000
|
||||
o = { format = f, customPcf = pcf, umv = umv, ss = ss, options = unsup, width = 0, height = 0 }
|
||||
elseif ufep == 0 and opp then
|
||||
o = opp
|
||||
else
|
||||
return nil, if ufep == 0 then "PLUSPTYPE without the options (UFEP 0 first)" else "bad UFEP"
|
||||
end
|
||||
local t = bits(3)
|
||||
if t ~= 0 and t ~= 1 then
|
||||
return nil, "unsupported: " .. ({ "", "improved PB-frames", "B-pictures", "EI-pictures", "EP-pictures", "reserved", "reserved" })[t] .. " picture type"
|
||||
end
|
||||
h.ptype = t + 1
|
||||
local rpr, rru = bits(1), bits(1)
|
||||
h.rounding = bits(1)
|
||||
bits(3) -- 0 0 1
|
||||
if rpr == 1 then
|
||||
return nil, "unsupported: reference picture resampling"
|
||||
elseif rru == 1 then
|
||||
return nil, "unsupported: reduced-resolution update"
|
||||
end
|
||||
local unsupported = o.options
|
||||
if unsupported ~= nil then
|
||||
return nil, "unsupported: " .. unsupported
|
||||
end
|
||||
h.cpm = bits(1) == 1
|
||||
if h.cpm then
|
||||
bits(2)
|
||||
end
|
||||
if ufep == 1 then
|
||||
if o.format == 6 then
|
||||
local par = bits(4)
|
||||
o.width = (bits(9) + 1) * 4
|
||||
bits(1)
|
||||
o.height = bits(9) * 4
|
||||
h.aspect = par
|
||||
if par == 15 then
|
||||
h.aspectNum, h.aspectDen = bits(8), bits(8)
|
||||
end
|
||||
elseif o.format >= 1 and o.format <= 5 then
|
||||
local d = Tb.FORMATS[o.format]
|
||||
o.width, o.height = d[1], d[2]
|
||||
else
|
||||
return nil, "bad source format " .. o.format
|
||||
end
|
||||
if o.customPcf then
|
||||
bits(8) -- clock conversion code, clock divisor
|
||||
end
|
||||
end
|
||||
if o.customPcf then
|
||||
bits(2) -- ETR
|
||||
end
|
||||
if ufep == 1 and o.umv then
|
||||
if bits(1) == 0 then
|
||||
bits(1)
|
||||
end
|
||||
end
|
||||
if ufep == 1 and o.ss then
|
||||
if bits(1) == 1 then
|
||||
return nil, "unsupported: rectangular slices"
|
||||
end
|
||||
bits(1) -- arbitrary slice ordering (slices carry their address)
|
||||
end
|
||||
h.width, h.height = o.width, o.height
|
||||
h.umvPlus = o.umv
|
||||
h.ss = o.ss
|
||||
h.opp = o
|
||||
else
|
||||
return nil, "bad source format " .. format
|
||||
end
|
||||
h.quant = if h.plus then bits(5) else h.quant
|
||||
end
|
||||
-- PEI / PSPARE
|
||||
local guard = 0
|
||||
while bits(1) == 1 do
|
||||
bits(8)
|
||||
guard += 1
|
||||
if guard > 256 then
|
||||
return nil, "PSPARE without end"
|
||||
end
|
||||
end
|
||||
if h.quant == 0 then
|
||||
return nil, "QUANT 0"
|
||||
end
|
||||
if h.width < 1 or h.height < 1 then
|
||||
return nil, "empty picture size"
|
||||
end
|
||||
if h.ss then
|
||||
-- the first slice's SEPB1, MBA and SEPB2
|
||||
bits(1)
|
||||
bits(D.mbaBits((h.width + 15) // 16 * ((h.height + 15) // 16)))
|
||||
bits(1)
|
||||
end
|
||||
if p > e * 8 then
|
||||
return nil, "truncated picture header"
|
||||
end
|
||||
h.bitPos = p
|
||||
return h, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decoder
|
||||
export type Core = {
|
||||
decode: (buf: buffer, off: number, len: number) -> (Store?, string?),
|
||||
reset: () -> (),
|
||||
state: {
|
||||
width: number,
|
||||
height: number,
|
||||
pictures: number,
|
||||
errors: number,
|
||||
header: Header?,
|
||||
opp: Opp?,
|
||||
maxPixels: number,
|
||||
},
|
||||
}
|
||||
|
||||
function D.new(flv: boolean, maxPixels: number?): Core
|
||||
local state = {
|
||||
width = 0,
|
||||
height = 0,
|
||||
pictures = 0,
|
||||
errors = 0,
|
||||
header = nil :: Header?,
|
||||
opp = nil :: Opp?,
|
||||
maxPixels = maxPixels or 4096 * 2304,
|
||||
}
|
||||
-- bitstream
|
||||
local data = buffer.create(64 * 1024 + PAD)
|
||||
local endBits = 0
|
||||
local pos = 0
|
||||
local err = false
|
||||
-- picture
|
||||
local W, H = 0, 0
|
||||
local mbW, mbH = 0, 0
|
||||
local ls, cs, lh, chh = 0, 0, 0, 0 -- luma / chroma strides, plane heights
|
||||
local stores: { Store } = {}
|
||||
local ref: Store? = nil
|
||||
local curY, curCb, curCr = data, data, data
|
||||
local refY, refCb, refCr = data, data, data
|
||||
local quant = 1
|
||||
local escFlv = false -- Sorenson version 1 escapes
|
||||
local longMv = false
|
||||
local umvPlus = false
|
||||
local mcf = mc
|
||||
local mvX, mvY = {} :: { number }, {} :: { number } -- the current row's vectors (half samples)
|
||||
local upX, upY = {} :: { number }, {} :: { number } -- the row above
|
||||
local blk = buffer.create(256)
|
||||
local EDGE = buffer.create(Dsp.EDGE_SIZE)
|
||||
|
||||
local function read(n: number): number
|
||||
local bp = rshift(pos, 3)
|
||||
local w = bswap(readu32(data, bp))
|
||||
local s = band(pos, 7)
|
||||
if s ~= 0 then
|
||||
w = bor(lshift(w, s), rshift(readu8(data, bp + 4), 8 - s))
|
||||
end
|
||||
pos += n
|
||||
return rshift(w, 32 - n)
|
||||
end
|
||||
|
||||
local function peek32(): number
|
||||
local bp = rshift(pos, 3)
|
||||
local w = bswap(readu32(data, bp))
|
||||
local s = band(pos, 7)
|
||||
if s ~= 0 then
|
||||
w = bor(lshift(w, s), rshift(readu8(data, bp + 4), 8 - s))
|
||||
end
|
||||
return w
|
||||
end
|
||||
|
||||
local function vlc(lut: buffer, k: number): number
|
||||
local e = readu32(lut, rshift(peek32(), 32 - k) * 4)
|
||||
local l = rshift(e, 16)
|
||||
if l == 0 then
|
||||
err = true
|
||||
return 0
|
||||
end
|
||||
pos += l
|
||||
return band(e, 0xFFFF)
|
||||
end
|
||||
|
||||
local function alloc(w: number, h: number)
|
||||
W, H = w, h
|
||||
mbW, mbH = (w + 15) // 16, (h + 15) // 16
|
||||
ls, cs, lh, chh = mbW * 16, mbW * 8, mbH * 16, mbH * 8
|
||||
stores = {}
|
||||
for i = 1, 2 do
|
||||
local y = buffer.create(ls * lh)
|
||||
local cb = buffer.create(cs * chh)
|
||||
local cr = buffer.create(cs * chh)
|
||||
bfill(cb, 0, 128)
|
||||
bfill(cr, 0, 128)
|
||||
stores[i] = { y = y, cb = cb, cr = cr, ls = ls, w = w, h = h, ptype = 0, tr = 0, disposable = false }
|
||||
end
|
||||
mvX, mvY, upX, upY = table.create(mbW, 0), table.create(mbW, 0), table.create(mbW, 0), table.create(mbW, 0)
|
||||
ref = nil
|
||||
state.width, state.height = w, h
|
||||
end
|
||||
|
||||
-- one 8x8 block: intra (INTRADC, then the coded coefficients from position 1) put into dst, or an inter block's
|
||||
-- coefficients added to the prediction already in dst
|
||||
local function block(intra: boolean, coded: boolean, dst: buffer, off: number, stride: number): boolean
|
||||
local i = 0
|
||||
local dcOnly = true
|
||||
if intra then
|
||||
local v = read(8)
|
||||
if v == 255 then
|
||||
v = 128
|
||||
end
|
||||
writei32(blk, 0, v * 8)
|
||||
i = 1
|
||||
end
|
||||
if coded then
|
||||
local q2 = quant * 2
|
||||
local qadd = if quant % 2 == 1 then quant else quant - 1
|
||||
while true do
|
||||
local bp = rshift(pos, 3)
|
||||
local w = bswap(readu32(data, bp))
|
||||
local s = band(pos, 7)
|
||||
if s ~= 0 then
|
||||
w = bor(lshift(w, s), rshift(readu8(data, bp + 4), 8 - s))
|
||||
end
|
||||
local e = readu32(TCOEF, rshift(w, 20) * 4)
|
||||
local l = rshift(e, 16)
|
||||
if l == 0 then
|
||||
err = true
|
||||
return false
|
||||
end
|
||||
local v = band(e, 0xFFFF)
|
||||
local last, run, level
|
||||
if v == ESCAPE then
|
||||
-- the escape and the 25 (H.263) / 22 or 26 (Sorenson v1) bits after it, all inside w's next bits
|
||||
if escFlv then
|
||||
local is11 = band(rshift(w, 24), 1)
|
||||
last = band(rshift(w, 23), 1)
|
||||
run = band(rshift(w, 17), 63)
|
||||
if is11 == 1 then
|
||||
level = band(rshift(w, 6), 2047)
|
||||
if level >= 1024 then
|
||||
level -= 2048
|
||||
end
|
||||
pos += 7 + 1 + 7 + 11
|
||||
else
|
||||
level = band(rshift(w, 10), 127)
|
||||
if level >= 64 then
|
||||
level -= 128
|
||||
end
|
||||
pos += 7 + 1 + 7 + 7
|
||||
end
|
||||
else
|
||||
last = band(rshift(w, 24), 1)
|
||||
run = band(rshift(w, 18), 63)
|
||||
level = band(rshift(w, 10), 255)
|
||||
pos += 7 + 1 + 6 + 8
|
||||
if level == 128 then
|
||||
-- the extended escape (Annex T): 5 low bits, then 6 signed high bits
|
||||
local x = read(11)
|
||||
level = band(x, 31) + (rshift(x, 5) - (if x >= 1024 then 64 else 0)) * 32
|
||||
elseif level > 128 then
|
||||
level -= 256
|
||||
end
|
||||
end
|
||||
if level == 0 then
|
||||
err = true
|
||||
return false
|
||||
end
|
||||
else
|
||||
last = rshift(v, 10)
|
||||
run = band(rshift(v, 4), 63)
|
||||
level = band(v, 15)
|
||||
if band(w, lshift(1, 31 - l)) ~= 0 then
|
||||
level = -level
|
||||
end
|
||||
pos += l + 1
|
||||
end
|
||||
i += run
|
||||
if i > 63 then
|
||||
err = true
|
||||
return false
|
||||
end
|
||||
local rec = if level > 0 then level * q2 + qadd else level * q2 - qadd
|
||||
-- not the -2048..2047 saturation of H.263 6.2.1: ffmpeg does not saturate, and encoders write values
|
||||
-- slightly past it (2055 = 68 * 30 + 15). +-2400 bounds the IDCT output to Dsp's clamp table.
|
||||
if rec > 2400 then
|
||||
rec = 2400
|
||||
elseif rec < -2400 then
|
||||
rec = -2400
|
||||
end
|
||||
local z = readu8(ZIGZAG, i)
|
||||
if z ~= 0 then
|
||||
dcOnly = false
|
||||
end
|
||||
writei32(blk, z * 4, rec)
|
||||
i += 1
|
||||
if last ~= 0 then
|
||||
break
|
||||
end
|
||||
end
|
||||
elseif not intra then
|
||||
return true
|
||||
end
|
||||
if dcOnly then
|
||||
local dc = readi32(blk, 0)
|
||||
writei32(blk, 0, 0)
|
||||
fillBlock(dst, off, stride, (dc + 4) // 8, not intra)
|
||||
else
|
||||
idct(blk, dst, off, stride, not intra)
|
||||
bfill(blk, 0, 0, 256)
|
||||
end
|
||||
return true
|
||||
end
|
||||
|
||||
-- one motion vector component from its prediction (half samples)
|
||||
local function motion(pred: number): number
|
||||
if umvPlus then
|
||||
-- reversible codes (Annex D.2): "1" = 0, else 0 x0 (1 x)* 0, the last x the sign
|
||||
if read(1) == 1 then
|
||||
return pred
|
||||
end
|
||||
local code = 2 + read(1)
|
||||
local guard = 0
|
||||
while read(1) == 1 do
|
||||
code = code * 2 + read(1)
|
||||
guard += 1
|
||||
if guard > 14 then
|
||||
err = true
|
||||
return pred
|
||||
end
|
||||
end
|
||||
local mag = code // 2
|
||||
return if code % 2 == 1 then pred - mag else pred + mag
|
||||
end
|
||||
local d = vlc(MVD, 12)
|
||||
if d == 0 then
|
||||
return pred
|
||||
end
|
||||
if read(1) == 1 then
|
||||
d = -d
|
||||
end
|
||||
local v = pred + d
|
||||
if longMv then
|
||||
-- Annex D (baseline header): vectors up to +-31.5; the other value of a code pair only past +-16
|
||||
if pred < -31 and v < -63 then
|
||||
v += 64
|
||||
elseif pred > 32 and v > 63 then
|
||||
v -= 64
|
||||
end
|
||||
return v
|
||||
end
|
||||
return (v + 32) % 64 - 32 -- the code pair's value in -16 .. 15.5
|
||||
end
|
||||
|
||||
-- the prediction of macroblock (col, row) from the reference, vector (mx, my) in half samples
|
||||
local function predict(col: number, row: number, mx: number, my: number)
|
||||
local hx, hy = mx % 2, my % 2
|
||||
local sx, sy = col * 16 + (mx - hx) // 2, row * 16 + (my - hy) // 2
|
||||
local dOff = row * 16 * ls + col * 16
|
||||
if sx < 0 or sy < 0 or sx + 16 + hx > ls or sy + 16 + hy > lh then
|
||||
edge(refY, ls, 0, sx, sy, 16, 16, ls, lh, EDGE)
|
||||
mcf(EDGE, 32, 0, curY, ls, dOff, 16, 16, hx, hy, false)
|
||||
else
|
||||
mcf(refY, ls, sy * ls + sx, curY, ls, dOff, 16, 16, hx, hy, false)
|
||||
end
|
||||
-- chroma: the luma position halved, half-sample flags from the quarter positions rounded to halves
|
||||
local cx, cy = sx // 2, sy // 2
|
||||
local chx = if hx == 1 or (mx // 2) % 2 == 1 then 1 else 0
|
||||
local chy = if hy == 1 or (my // 2) % 2 == 1 then 1 else 0
|
||||
local cOff = row * 8 * cs + col * 8
|
||||
if cx < 0 or cy < 0 or cx + 8 + chx > cs or cy + 8 + chy > chh then
|
||||
edge(refCb, cs, 0, cx, cy, 8, 8, cs, chh, EDGE)
|
||||
mcf(EDGE, 32, 0, curCb, cs, cOff, 8, 8, chx, chy, false)
|
||||
edge(refCr, cs, 0, cx, cy, 8, 8, cs, chh, EDGE)
|
||||
mcf(EDGE, 32, 0, curCr, cs, cOff, 8, 8, chx, chy, false)
|
||||
else
|
||||
local so = cy * cs + cx
|
||||
mcf(refCb, cs, so, curCb, cs, cOff, 8, 8, chx, chy, false)
|
||||
mcf(refCr, cs, so, curCr, cs, cOff, 8, 8, chx, chy, false)
|
||||
end
|
||||
end
|
||||
|
||||
-- a macroblock copied from the reference (not coded, or concealed); mid-grey without one
|
||||
local function copyMb(col: number, row: number)
|
||||
local yo, co = row * 16 * ls + col * 16, row * 8 * cs + col * 8
|
||||
if ref then
|
||||
mc(refY, ls, yo, curY, ls, yo, 16, 16, 0, 0, false)
|
||||
mc(refCb, cs, co, curCb, cs, co, 8, 8, 0, 0, false)
|
||||
mc(refCr, cs, co, curCr, cs, co, 8, 8, 0, 0, false)
|
||||
else
|
||||
fillBlock(curY, yo, ls, 128, false)
|
||||
fillBlock(curY, yo + 8, ls, 128, false)
|
||||
fillBlock(curY, yo + 8 * ls, ls, 128, false)
|
||||
fillBlock(curY, yo + 8 * ls + 8, ls, 128, false)
|
||||
fillBlock(curCb, co, cs, 128, false)
|
||||
fillBlock(curCr, co, cs, 128, false)
|
||||
end
|
||||
end
|
||||
|
||||
-- macroblock (col, row) of a picture (P: an inter picture; top: within the first macroblock columns' worth of
|
||||
-- the picture / a GOB or slice with a header, whose vector predictions do not look up; first: the first
|
||||
-- macroblock of a slice, whose left neighbour is outside). false on bad data.
|
||||
local function macroblock(col: number, row: number, P: boolean, top: boolean, first: boolean): boolean
|
||||
if pos > endBits then
|
||||
return false
|
||||
end
|
||||
if P and read(1) == 1 then
|
||||
copyMb(col, row)
|
||||
mvX[col + 1], mvY[col + 1] = 0, 0
|
||||
return true
|
||||
end
|
||||
local lut = if P then MCBPC_P else MCBPC_I
|
||||
local m = vlc(lut, 9)
|
||||
while m == STUFFING and not err do
|
||||
if P and read(1) == 1 then -- stuffing is followed by a new COD in P-pictures
|
||||
copyMb(col, row)
|
||||
mvX[col + 1], mvY[col + 1] = 0, 0
|
||||
return pos <= endBits
|
||||
end
|
||||
if pos > endBits then
|
||||
return false
|
||||
end
|
||||
m = vlc(lut, 9)
|
||||
end
|
||||
if err then
|
||||
return false
|
||||
end
|
||||
local mtype, cbpc = m // 4, m % 4
|
||||
if mtype == 2 then
|
||||
err = true -- INTER4V needs advanced prediction (Annex F), which the header refused
|
||||
return false
|
||||
end
|
||||
local intra = mtype >= 3
|
||||
local cbpy = vlc(CBPY, 6)
|
||||
if err then
|
||||
return false
|
||||
end
|
||||
if mtype == 1 or mtype == 4 then
|
||||
quant = math.clamp(quant + DQUANT[read(2)], 1, 31)
|
||||
end
|
||||
local yo, co = row * 16 * ls + col * 16, row * 8 * cs + col * 8
|
||||
if intra then
|
||||
mvX[col + 1], mvY[col + 1] = 0, 0
|
||||
if not block(true, cbpy >= 8, curY, yo, ls) or not block(true, cbpy % 8 >= 4, curY, yo + 8, ls)
|
||||
or not block(true, cbpy % 4 >= 2, curY, yo + 8 * ls, ls) or not block(true, cbpy % 2 == 1, curY, yo + 8 * ls + 8, ls)
|
||||
or not block(true, cbpc >= 2, curCb, co, cs) or not block(true, cbpc % 2 == 1, curCr, co, cs) then
|
||||
return false
|
||||
end
|
||||
return pos <= endBits
|
||||
end
|
||||
cbpy = 15 - cbpy
|
||||
-- the vector prediction: the median of left, above and above right (outside or past the right edge: 0; the
|
||||
-- first row of a picture / GOB: the left vector)
|
||||
local ax = if col > 0 and not first then mvX[col] else 0
|
||||
local ay = if col > 0 and not first then mvY[col] else 0
|
||||
local px, py = ax, ay
|
||||
if not top then
|
||||
local bx, by = upX[col + 1], upY[col + 1]
|
||||
local cx = if col + 1 < mbW then upX[col + 2] else 0
|
||||
local cy = if col + 1 < mbW then upY[col + 2] else 0
|
||||
px = math.max(math.min(ax, bx), math.min(math.max(ax, bx), cx))
|
||||
py = math.max(math.min(ay, by), math.min(math.max(ay, by), cy))
|
||||
end
|
||||
local mx = motion(px)
|
||||
local my = motion(py)
|
||||
if umvPlus and mx - px == 1 and my - py == 1 then
|
||||
pos += 1 -- start code emulation prevention bit
|
||||
end
|
||||
if err then
|
||||
return false
|
||||
end
|
||||
mvX[col + 1], mvY[col + 1] = mx, my
|
||||
predict(col, row, mx, my)
|
||||
if not block(false, cbpy >= 8, curY, yo, ls) or not block(false, cbpy % 8 >= 4, curY, yo + 8, ls)
|
||||
or not block(false, cbpy % 4 >= 2, curY, yo + 8 * ls, ls) or not block(false, cbpy % 2 == 1, curY, yo + 8 * ls + 8, ls)
|
||||
or not block(false, cbpc >= 2, curCb, co, cs) or not block(false, cbpc % 2 == 1, curCr, co, cs) then
|
||||
return false
|
||||
end
|
||||
return pos <= endBits
|
||||
end
|
||||
|
||||
-- a GBSC / SSC (17 bits 0..01) next, after zero stuffing to a byte boundary or not: consumed, true
|
||||
local function startCode(): boolean
|
||||
local w = peek32()
|
||||
if rshift(w, 15) ~= 1 then
|
||||
local s = (8 - pos % 8) % 8
|
||||
if s == 0 or rshift(w, 32 - s) ~= 0 or rshift(lshift(w, s), 15) ~= 1 then
|
||||
return false
|
||||
end
|
||||
pos += s
|
||||
end
|
||||
pos += 17
|
||||
return true
|
||||
end
|
||||
|
||||
-- an optional GOB header at a GOB boundary: its GN and GQUANT, or nil
|
||||
local function gobHeader(cpm: boolean): (number?, number?)
|
||||
if not startCode() then
|
||||
return nil, nil
|
||||
end
|
||||
local gn = read(5)
|
||||
if cpm then
|
||||
read(2)
|
||||
end
|
||||
read(2) -- GFID
|
||||
return gn, read(5)
|
||||
end
|
||||
|
||||
-- an optional slice header (Annex K, no rectangular slices): its MBA and SQUANT, or nil
|
||||
local function sliceHeader(cpm: boolean, mbaBits: number, sepb2: boolean): (number?, number?)
|
||||
if not startCode() then
|
||||
return nil, nil
|
||||
end
|
||||
read(1) -- SEPB1
|
||||
if cpm then
|
||||
read(2)
|
||||
end
|
||||
local mba = read(mbaBits)
|
||||
if sepb2 then
|
||||
read(1)
|
||||
end
|
||||
local q = read(5)
|
||||
read(3) -- SEPB3, GFID
|
||||
return mba, q
|
||||
end
|
||||
|
||||
local function picture(hdr: Header): (Store?, string?)
|
||||
if hdr.width ~= W or hdr.height ~= H then
|
||||
if hdr.width * hdr.height > state.maxPixels then
|
||||
return nil, "limit: picture size " .. hdr.width .. "x" .. hdr.height
|
||||
end
|
||||
alloc(hdr.width, hdr.height)
|
||||
end
|
||||
local P = hdr.ptype == 2
|
||||
local r = ref
|
||||
if P and not r then
|
||||
return nil, "a P picture without a reference picture"
|
||||
end
|
||||
local cur = if stores[1] == r then stores[2] else stores[1]
|
||||
curY, curCb, curCr = cur.y, cur.cb, cur.cr
|
||||
if r then
|
||||
refY, refCb, refCr = r.y, r.cb, r.cr
|
||||
end
|
||||
quant = hdr.quant
|
||||
escFlv = hdr.flv and hdr.version == 1
|
||||
longMv = hdr.umv
|
||||
umvPlus = hdr.umvPlus
|
||||
mcf = if hdr.rounding == 1 then mcNoRound :: any else mc
|
||||
pos = hdr.bitPos
|
||||
err = false
|
||||
local gobRows = if hdr.flv then 0 elseif H <= 400 then 1 elseif H <= 800 then 2 else 4
|
||||
local ss = hdr.ss
|
||||
local total = mbW * mbH
|
||||
local mbaBits = D.mbaBits(total)
|
||||
local resync = 0 -- the first macroblock of the current GOB with a header / slice
|
||||
local k = 0
|
||||
local failAt = -1
|
||||
mvX, upX = upX, mvX
|
||||
mvY, upY = upY, mvY
|
||||
while k < total do
|
||||
local col, row = k % mbW, k // mbW
|
||||
if k > 0 and (ss or (gobRows > 0 and col == 0 and row % gobRows == 0)) then
|
||||
local at, q
|
||||
if ss then
|
||||
at, q = sliceHeader(hdr.cpm, mbaBits, total > 1584)
|
||||
else
|
||||
local gn, gq = gobHeader(hdr.cpm)
|
||||
if gn then
|
||||
at, q = if gn == 0 then -1 else gn * gobRows * mbW, gq
|
||||
end
|
||||
end
|
||||
if at and q then
|
||||
if at < k or at >= total or q == 0 then
|
||||
failAt = k
|
||||
break
|
||||
end
|
||||
while k < at do -- macroblocks missing in between: copied
|
||||
copyMb(k % mbW, k // mbW)
|
||||
mvX[k % mbW + 1], mvY[k % mbW + 1] = 0, 0
|
||||
k += 1
|
||||
if k % mbW == 0 then
|
||||
mvX, upX = upX, mvX
|
||||
mvY, upY = upY, mvY
|
||||
end
|
||||
end
|
||||
col, row = k % mbW, k // mbW
|
||||
resync, quant = k, q
|
||||
end
|
||||
end
|
||||
-- above is outside for the slice's first mbW macroblocks (ffmpeg's first_slice_line: also the start of the
|
||||
-- next row for a slice starting mid-row)
|
||||
if not macroblock(col, row, P, k < resync + mbW, k == resync) then
|
||||
failAt = k
|
||||
break
|
||||
end
|
||||
k += 1
|
||||
if k % mbW == 0 then
|
||||
mvX, upX = upX, mvX
|
||||
mvY, upY = upY, mvY
|
||||
end
|
||||
end
|
||||
local msg: string? = nil
|
||||
if failAt >= 0 then
|
||||
state.errors += 1
|
||||
msg = "bad macroblock data at macroblock " .. failAt
|
||||
for k = failAt, mbW * mbH - 1 do
|
||||
copyMb(k % mbW, k // mbW)
|
||||
end
|
||||
end
|
||||
cur.ptype = hdr.ptype
|
||||
cur.tr = hdr.tr
|
||||
cur.disposable = hdr.disposable
|
||||
if not hdr.disposable then
|
||||
ref = cur
|
||||
end
|
||||
state.pictures += 1
|
||||
return cur, msg
|
||||
end
|
||||
|
||||
local core = {} :: Core
|
||||
core.state = state
|
||||
|
||||
function core.decode(buf: buffer, off: number, len: number): (Store?, string?)
|
||||
local hdr, herr = D.header(buf, off, len, flv, state.opp)
|
||||
if not hdr then
|
||||
state.errors += 1
|
||||
return nil, herr
|
||||
end
|
||||
state.header = hdr
|
||||
if hdr.opp then
|
||||
state.opp = hdr.opp
|
||||
end
|
||||
-- the data from the header on, with zero padding
|
||||
local need = len + PAD
|
||||
if buffer.len(data) < need then
|
||||
data = buffer.create(need)
|
||||
else
|
||||
bfill(data, len, 0, PAD)
|
||||
end
|
||||
buffer.copy(data, 0, buf, off, len)
|
||||
endBits = len * 8
|
||||
hdr.bitPos -= off * 8
|
||||
local s, msg = picture(hdr)
|
||||
hdr.bitPos += off * 8
|
||||
return s, msg
|
||||
end
|
||||
|
||||
function core.reset()
|
||||
ref = nil
|
||||
end
|
||||
|
||||
return core
|
||||
end
|
||||
|
||||
return D
|
||||
@@ -0,0 +1,206 @@
|
||||
--!strict
|
||||
-- codecs/video/H263/Tables: the H.263 variable-length codes (ITU-T H.263 (01/2005): table 7 MCBPC for I-pictures,
|
||||
-- table 8 MCBPC for P-pictures, table 12 DQUANT, table 13 CBPY, table 14 MVD, table 16 TCOEF, the zigzag scan of
|
||||
-- figure 14), written from the specification as bit strings and turned into flat lookup tables at load time.
|
||||
--
|
||||
-- A flat table is indexed by the next K bits of the stream and holds len * 65536 + value (len 0: not a code).
|
||||
-- MCBPC_I / MCBPC_P (K = 9): value = macroblock type * 4 + CBPC (types 0 INTER, 1 INTER+Q, 2 INTER4V, 3 INTRA,
|
||||
-- 4 INTRA+Q), STUFFING for the stuffing code
|
||||
-- CBPY (K = 6): the intra CBPY (Y1 the most significant bit; inter macroblocks use 15 - value)
|
||||
-- MVD (K = 12): the magnitude 0..32 in half samples (a sign bit follows every code but "1", which is 0)
|
||||
-- TCOEF (K = 12): last * 1024 + run * 16 + level (a sign bit follows), ESCAPE for the escape code
|
||||
local T = {}
|
||||
|
||||
T.STUFFING = 255
|
||||
T.ESCAPE = 0xFFFF
|
||||
|
||||
-- builds a K-bit flat table from { bits, value } pairs
|
||||
local function flat(codes: { { any } }, k: number): buffer
|
||||
local lut = buffer.create(4 * 2 ^ k)
|
||||
for _, c in codes do
|
||||
local bits: string = c[1]
|
||||
local len = #bits
|
||||
local code = tonumber(bits, 2) :: number
|
||||
local shift = k - len
|
||||
local first = code * 2 ^ shift
|
||||
for i = first, first + 2 ^ shift - 1 do
|
||||
buffer.writeu32(lut, i * 4, len * 65536 + c[2])
|
||||
end
|
||||
end
|
||||
return lut
|
||||
end
|
||||
|
||||
-- table 7: MCBPC for I-pictures (type 3 INTRA, 4 INTRA+Q; CBPC = Cb Cr)
|
||||
T.MCBPC_I = flat({
|
||||
{ "1", 3 * 4 + 0 },
|
||||
{ "001", 3 * 4 + 1 },
|
||||
{ "010", 3 * 4 + 2 },
|
||||
{ "011", 3 * 4 + 3 },
|
||||
{ "0001", 4 * 4 + 0 },
|
||||
{ "000001", 4 * 4 + 1 },
|
||||
{ "000010", 4 * 4 + 2 },
|
||||
{ "000011", 4 * 4 + 3 },
|
||||
{ "000000001", T.STUFFING },
|
||||
}, 9)
|
||||
|
||||
-- table 8: MCBPC for P-pictures
|
||||
T.MCBPC_P = flat({
|
||||
{ "1", 0 * 4 + 0 },
|
||||
{ "0011", 0 * 4 + 1 },
|
||||
{ "0010", 0 * 4 + 2 },
|
||||
{ "000101", 0 * 4 + 3 },
|
||||
{ "011", 1 * 4 + 0 },
|
||||
{ "0000111", 1 * 4 + 1 },
|
||||
{ "0000110", 1 * 4 + 2 },
|
||||
{ "000000101", 1 * 4 + 3 },
|
||||
{ "010", 2 * 4 + 0 },
|
||||
{ "0000101", 2 * 4 + 1 },
|
||||
{ "0000100", 2 * 4 + 2 },
|
||||
{ "00000101", 2 * 4 + 3 },
|
||||
{ "00011", 3 * 4 + 0 },
|
||||
{ "00000100", 3 * 4 + 1 },
|
||||
{ "00000011", 3 * 4 + 2 },
|
||||
{ "0000011", 3 * 4 + 3 },
|
||||
{ "000100", 4 * 4 + 0 },
|
||||
{ "000000100", 4 * 4 + 1 },
|
||||
{ "000000011", 4 * 4 + 2 },
|
||||
{ "000000010", 4 * 4 + 3 },
|
||||
{ "000000001", T.STUFFING },
|
||||
}, 9)
|
||||
|
||||
-- table 13: CBPY (intra values 0..15)
|
||||
do
|
||||
local codes = { "0011", "00101", "00100", "1001", "00011", "0111", "000010", "1011", "00010", "000011", "0101",
|
||||
"1010", "0100", "1000", "0110", "11" }
|
||||
local list = {}
|
||||
for i, c in codes do
|
||||
list[i] = { c, i - 1 }
|
||||
end
|
||||
T.CBPY = flat(list, 6)
|
||||
end
|
||||
|
||||
-- table 14: MVD magnitudes 0, 0.5, 1, ... 16 (in half samples 0..32); the sign bit is not part of these
|
||||
do
|
||||
local codes = { "1", "01", "001", "0001", "000011", "0000101", "0000100", "0000011", "000001011", "000001010",
|
||||
"000001001", "0000010001", "0000010000", "0000001111", "0000001110", "0000001101", "0000001100", "0000001011",
|
||||
"0000001010", "0000001001", "0000001000", "0000000111", "0000000110", "0000000101", "0000000100", "00000000111",
|
||||
"00000000110", "00000000101", "00000000100", "00000000011", "00000000010", "000000000011", "000000000010" }
|
||||
local list = {}
|
||||
for i, c in codes do
|
||||
list[i] = { c, i - 1 }
|
||||
end
|
||||
T.MVD = flat(list, 12)
|
||||
end
|
||||
|
||||
-- table 16: TCOEF, per LAST and RUN the codes of levels 1, 2, ... (without the sign bit)
|
||||
local TCOEF_LAST0: { [number]: { string } } = {
|
||||
[0] = { "10", "1111", "010101", "0010111", "00011111", "000100101", "000100100", "0000100001", "0000100000",
|
||||
"00000000111", "00000000110", "00000100000" },
|
||||
[1] = { "110", "010100", "00011110", "0000001111", "00000100001", "000001010000" },
|
||||
[2] = { "1110", "00011101", "0000001110", "000001010001" },
|
||||
[3] = { "01101", "000100011", "0000001101" },
|
||||
[4] = { "01100", "000100010", "000001010010" },
|
||||
[5] = { "01011", "0000001100", "000001010011" },
|
||||
[6] = { "010011", "0000001011", "000001010100" },
|
||||
[7] = { "010010", "0000001010" },
|
||||
[8] = { "010001", "0000001001" },
|
||||
[9] = { "010000", "0000001000" },
|
||||
[10] = { "0010110", "000001010101" },
|
||||
[11] = { "0010101" },
|
||||
[12] = { "0010100" },
|
||||
[13] = { "00011100" },
|
||||
[14] = { "00011011" },
|
||||
[15] = { "000100001" },
|
||||
[16] = { "000100000" },
|
||||
[17] = { "000011111" },
|
||||
[18] = { "000011110" },
|
||||
[19] = { "000011101" },
|
||||
[20] = { "000011100" },
|
||||
[21] = { "000011011" },
|
||||
[22] = { "000011010" },
|
||||
[23] = { "00000100010" },
|
||||
[24] = { "00000100011" },
|
||||
[25] = { "000001010110" },
|
||||
[26] = { "000001010111" },
|
||||
}
|
||||
local TCOEF_LAST1: { [number]: { string } } = {
|
||||
[0] = { "0111", "000011001", "00000000101" },
|
||||
[1] = { "001111", "00000000100" },
|
||||
[2] = { "001110" },
|
||||
[3] = { "001101" },
|
||||
[4] = { "001100" },
|
||||
[5] = { "0010011" },
|
||||
[6] = { "0010010" },
|
||||
[7] = { "0010001" },
|
||||
[8] = { "0010000" },
|
||||
[9] = { "00011010" },
|
||||
[10] = { "00011001" },
|
||||
[11] = { "00011000" },
|
||||
[12] = { "00010111" },
|
||||
[13] = { "00010110" },
|
||||
[14] = { "00010101" },
|
||||
[15] = { "00010100" },
|
||||
[16] = { "00010011" },
|
||||
[17] = { "000011000" },
|
||||
[18] = { "000010111" },
|
||||
[19] = { "000010110" },
|
||||
[20] = { "000010101" },
|
||||
[21] = { "000010100" },
|
||||
[22] = { "000010011" },
|
||||
[23] = { "000010010" },
|
||||
[24] = { "000010001" },
|
||||
[25] = { "0000000111" },
|
||||
[26] = { "0000000110" },
|
||||
[27] = { "0000000101" },
|
||||
[28] = { "0000000100" },
|
||||
[29] = { "00000100100" },
|
||||
[30] = { "00000100101" },
|
||||
[31] = { "00000100110" },
|
||||
[32] = { "00000100111" },
|
||||
[33] = { "000001011000" },
|
||||
[34] = { "000001011001" },
|
||||
[35] = { "000001011010" },
|
||||
[36] = { "000001011011" },
|
||||
[37] = { "000001011100" },
|
||||
[38] = { "000001011101" },
|
||||
[39] = { "000001011110" },
|
||||
[40] = { "000001011111" },
|
||||
}
|
||||
do
|
||||
local list = { { "0000011", T.ESCAPE } }
|
||||
for last = 0, 1 do
|
||||
local byRun = if last == 0 then TCOEF_LAST0 else TCOEF_LAST1
|
||||
for run = 0, 40 do
|
||||
local levels = byRun[run]
|
||||
if levels then
|
||||
for level, c in levels do
|
||||
table.insert(list, { c, last * 1024 + run * 16 + level })
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
T.TCOEF = flat(list, 12)
|
||||
T.TCOEF_COUNT = #list - 1
|
||||
end
|
||||
|
||||
-- figure 14: the zigzag scan (scan index -> natural position)
|
||||
T.ZIGZAG = buffer.create(64)
|
||||
do
|
||||
local zz = { 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 }
|
||||
for i, v in zz do
|
||||
buffer.writeu8(T.ZIGZAG, i - 1, v)
|
||||
end
|
||||
end
|
||||
|
||||
-- table 12: DQUANT (2 bits) -> the change of QUANT
|
||||
T.DQUANT = { [0] = -1, -2, 1, 2 }
|
||||
|
||||
-- source formats 1..5 (sub-QCIF, QCIF, CIF, 4CIF, 16CIF): width, height
|
||||
T.FORMATS = { { 128, 96 }, { 176, 144 }, { 352, 288 }, { 704, 576 }, { 1408, 1152 } }
|
||||
|
||||
-- Sorenson Spark picture sizes 2..6
|
||||
T.FLV_SIZES = { [2] = { 352, 288 }, [3] = { 176, 144 }, [4] = { 128, 96 }, [5] = { 320, 240 }, [6] = { 160, 120 } }
|
||||
|
||||
return T
|
||||
@@ -0,0 +1,176 @@
|
||||
--!strict
|
||||
-- codecs/video/H263: an H.263 / H.263+ and Sorenson Spark (FLV1) video decoder, bit-exact with ffmpeg -idct int.
|
||||
-- ITU-T H.263 baseline and the H.263+ picture header. Written from ITU-T H.263 (01/2005) and Adobe's Video File Format Specification v10; the decoding core is
|
||||
-- H263/Decoder.luau (native), the IDCT and motion compensation codecs/video/Dsp, so the output planes equal
|
||||
-- `ffmpeg -idct int` (tests/codecs/h263.luau). Supports sub-QCIF .. 16CIF and H.263+ custom sizes, I and P pictures,
|
||||
-- GOB headers, the rounding type, unrestricted motion vectors (Annex D), Sorenson's escape codes and disposable inter
|
||||
-- pictures. Not supported (UNSUPPORTED): arithmetic coding, advanced prediction / four vectors, PB / B / EI / EP
|
||||
-- pictures and the other H.263+ coding options (advanced intra coding, deblocking filter, slices, ...).
|
||||
--
|
||||
-- local dec = H263.new({ flv = false }) -- flv = true: Sorenson Spark (FLV1)
|
||||
-- local frame, err = dec:decode(packetData, off?, len?) -- one picture -> Frame (planes decoder-owned)
|
||||
-- local img = H263.frameImage(frame) -- a fresh yuv420p Types.Image (limited range, BT.601)
|
||||
-- local img, err = dec:image(packetData) -- both at once
|
||||
-- local info = H263.header(data, off?, len?, flv?) -- the picture header: width, height, ptype, ...
|
||||
-- dec:reset() -- after a seek: wait for the next I picture
|
||||
--
|
||||
-- Nothing here throws: bad arguments and bad data come back as nil, Err.
|
||||
local Err = require("@formats/core/Err")
|
||||
local Types = require("@formats/Types")
|
||||
local D = require("@formats/codecs/video/H263/Decoder")
|
||||
|
||||
local H263 = {}
|
||||
|
||||
H263.PICTURE_I = 1
|
||||
H263.PICTURE_P = 2
|
||||
|
||||
export type Header = D.Header
|
||||
|
||||
export type Frame = {
|
||||
width: number,
|
||||
height: number,
|
||||
-- decoder-owned planes, valid until the next decode: luma stride `stride`, chroma stride stride / 2
|
||||
y: buffer,
|
||||
cb: buffer,
|
||||
cr: buffer,
|
||||
stride: number,
|
||||
pictureType: number, -- 1 I, 2 P
|
||||
keyframe: boolean,
|
||||
disposable: boolean, -- a Sorenson disposable inter picture (not used as a reference)
|
||||
temporalReference: number,
|
||||
index: number, -- pictures returned so far
|
||||
flv: boolean,
|
||||
}
|
||||
|
||||
export type Options = {
|
||||
flv: boolean?, -- Sorenson Spark (FLV1) bitstreams (default false: H.263)
|
||||
maxPixels: number?, -- larger pictures are refused (LIMIT; default 4096 * 2304)
|
||||
}
|
||||
|
||||
local Decoder = {}
|
||||
Decoder.__index = Decoder
|
||||
|
||||
export type Decoder = typeof(setmetatable({} :: { _core: D.Core, _flv: boolean, _count: number, stats: { pictures: number, errors: number } }, Decoder))
|
||||
|
||||
function H263.new(opts: Options?): Decoder
|
||||
local o: Options = if type(opts) == "table" then opts else {}
|
||||
local flv = o.flv == true
|
||||
local maxPixels = if type(o.maxPixels) == "number" and o.maxPixels > 0 then o.maxPixels else nil
|
||||
return setmetatable({ _core = D.new(flv, maxPixels), _flv = flv, _count = 0, stats = { pictures = 0, errors = 0 } }, Decoder)
|
||||
end
|
||||
|
||||
local function span(data: any, off: number?, len: number?): (buffer?, number, number)
|
||||
local b: buffer
|
||||
if type(data) == "string" then
|
||||
b = buffer.fromstring(data)
|
||||
elseif type(data) == "buffer" then
|
||||
b = data
|
||||
else
|
||||
return nil, 0, 0
|
||||
end
|
||||
local total = buffer.len(b)
|
||||
local o = math.floor(tonumber(off) or 0)
|
||||
if o < 0 or o > total then
|
||||
return nil, 0, 0
|
||||
end
|
||||
local n = math.floor(tonumber(len) or (total - o))
|
||||
if n < 0 or o + n > total then
|
||||
return nil, 0, 0
|
||||
end
|
||||
return b, o, n
|
||||
end
|
||||
|
||||
-- Decodes one picture (a container packet or one picture of an elementary stream). A picture with damaged
|
||||
-- macroblock data still comes back (the damaged part copied from the reference; stats.errors counts them).
|
||||
function Decoder.decode(self: Decoder, data: buffer | string, off: number?, len: number?): (Frame?, Err.Err?)
|
||||
local b, o, n = span(data, off, len)
|
||||
if not b then
|
||||
return nil, Err.new(Err.ARG, "decode: expected a buffer or string and a valid range")
|
||||
end
|
||||
local core = self._core
|
||||
local s, msg = core.decode(b, o, n)
|
||||
self.stats.pictures = core.state.pictures
|
||||
self.stats.errors = core.state.errors
|
||||
if not s then
|
||||
return nil, Err.from(msg or "bad picture")
|
||||
end
|
||||
self._count += 1
|
||||
return {
|
||||
width = s.w,
|
||||
height = s.h,
|
||||
y = s.y,
|
||||
cb = s.cb,
|
||||
cr = s.cr,
|
||||
stride = s.ls,
|
||||
pictureType = s.ptype,
|
||||
keyframe = s.ptype == 1,
|
||||
disposable = s.disposable,
|
||||
temporalReference = s.tr,
|
||||
index = self._count,
|
||||
flv = self._flv,
|
||||
}, nil
|
||||
end
|
||||
|
||||
-- decode + frameImage
|
||||
function Decoder.image(self: Decoder, data: buffer | string, off: number?, len: number?): (Types.Image?, Err.Err?)
|
||||
local f, err = self:decode(data, off, len)
|
||||
if not f then
|
||||
return nil, err
|
||||
end
|
||||
return H263.frameImage(f), nil
|
||||
end
|
||||
|
||||
-- Forgets the reference picture (after a seek: P pictures fail until the next I picture).
|
||||
function Decoder.reset(self: Decoder)
|
||||
self._core.reset()
|
||||
end
|
||||
|
||||
-- frameImage(frame) -> a fresh yuv420p Types.Image of the frame, cropped to width x height (chroma ceil(w / 2) x
|
||||
-- ceil(h / 2)), meta.yuv = limited range BT.601; nil for a value that is not a Frame
|
||||
function H263.frameImage(frame: Frame): 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, ls = frame.width, frame.height, frame.stride
|
||||
if type(w) ~= "number" or type(h) ~= "number" or type(ls) ~= "number" or w < 1 or h < 1 or ls < w then
|
||||
return nil
|
||||
end
|
||||
local cw, ch, cs = (w + 1) // 2, (h + 1) // 2, ls // 2
|
||||
if buffer.len(frame.y) < ls * h or buffer.len(frame.cb) < cs * ch or buffer.len(frame.cr) < cs * ch then
|
||||
return nil
|
||||
end
|
||||
local 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 * ls, w)
|
||||
end
|
||||
local o = w * h
|
||||
for y = 0, ch - 1 do
|
||||
buffer.copy(px, o + y * cw, frame.cb, y * cs, cw)
|
||||
buffer.copy(px, o + cw * ch + y * cw, frame.cr, y * cs, cw)
|
||||
end
|
||||
img.meta.yuv = { range = "limited", matrix = "bt601" }
|
||||
img.meta.source = {
|
||||
format = if frame.flv then "flv1" else "h263",
|
||||
pictureType = frame.pictureType,
|
||||
temporalReference = frame.temporalReference,
|
||||
disposable = frame.disposable,
|
||||
}
|
||||
return img
|
||||
end
|
||||
|
||||
-- header(data, off?, len?, flv?) -> Header (width, height, ptype 1 I / 2 P, quant, tr, plus, umv, ...) | nil, Err:
|
||||
-- the first picture header in the data, without decoding (containers use it for the track size)
|
||||
function H263.header(data: buffer | string, off: number?, len: number?, flv: boolean?): (Header?, Err.Err?)
|
||||
local b, o, n = span(data, off, len)
|
||||
if not b then
|
||||
return nil, Err.new(Err.ARG, "header: expected a buffer or string and a valid range")
|
||||
end
|
||||
local h, msg = D.header(b, o, n, flv == true, nil)
|
||||
if not h then
|
||||
return nil, Err.from(msg or "bad picture header")
|
||||
end
|
||||
return h, nil
|
||||
end
|
||||
|
||||
return H263
|
||||
@@ -253,6 +253,17 @@ local function h264Decoder(track: Types.Track, opts: any?): (Types.VideoCodecDec
|
||||
return H264.newVideoDecoder(track, opts)
|
||||
end
|
||||
|
||||
-- H.263 / Sorenson Spark (codecs/video/H263): one picture per packet, no reordering
|
||||
local function h263Decoder(track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?)
|
||||
local H263 = require("@formats/codecs/video/H263")
|
||||
local dec = H263.new({ flv = track.codec == "flv1", maxPixels = opts and opts.maxPixels })
|
||||
return Video.simpleDecoder(function(data: buffer): (Types.Image?, Err.Err?)
|
||||
return dec:image(data)
|
||||
end, function()
|
||||
dec:reset()
|
||||
end), nil
|
||||
end
|
||||
|
||||
-- Theora (codecs/video/Theora): track.config = the three headers, Xiph-laced (Matroska's CodecPrivate; video/ogv
|
||||
-- builds the same); one picture per packet, empty packets repeat the previous one
|
||||
local function theoraDecoder(track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?)
|
||||
@@ -281,6 +292,12 @@ local BUILTIN: { Entry } = {
|
||||
{ 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" }, new = theoraDecoder },
|
||||
{ id = "h263", name = "H.263", fourcc = { "H263", "h263", "s263", "U263" }, new = h263Decoder },
|
||||
{ id = "flv1", name = "Sorenson Spark (FLV1)", fourcc = { "FLV1" }, new = h263Decoder },
|
||||
{ id = "vp6f", name = "On2 VP6 (Flash)", fourcc = { "VP6F", "FLV4" } },
|
||||
{ id = "vp6a", name = "On2 VP6 with alpha (Flash)", fourcc = { "VP6A" } },
|
||||
{ id = "flashsv", name = "Flash Screen Video", fourcc = { "FSV1" } },
|
||||
{ id = "flashsv2", name = "Flash Screen Video 2" },
|
||||
{ id = "png", name = "PNG", fourcc = { "png ", "MPNG" }, matroska = { "V_PNG" } },
|
||||
-- legacy inter-frame codecs (codecs/video/Legacy; rgba8 pictures, palettes from track.palette)
|
||||
{ id = "cinepak", name = "Cinepak", fourcc = { "cvid" }, new = legacyDecoder("cinepak") },
|
||||
|
||||
@@ -0,0 +1,166 @@
|
||||
--!strict
|
||||
-- video/flv/Amf: AMF0 values (Adobe's Action Message Format 0, as FLV script data tags use it). Written from the AMF0
|
||||
-- specification and the FLV specification v10. Read: number, boolean, string, object, null, undefined, reference
|
||||
-- (the referenced object), ECMA array, strict array, date (milliseconds), long string; anything else stops the
|
||||
-- value. Write: numbers, booleans, strings, strict arrays and ECMA arrays (ordered key / value lists). Never throws.
|
||||
--
|
||||
-- local name, value = Amf.script(reader) -- a script tag body: "onMetaData", { duration = 12.3, ... }
|
||||
-- Amf.writeValue(w, v); Amf.writeEcma(w, { { "duration", 12.3 }, ... })
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
|
||||
local Amf = {}
|
||||
|
||||
-- null / undefined inside arrays (dropped from objects)
|
||||
Amf.NULL = table.freeze({})
|
||||
|
||||
local MAX_DEPTH = 32
|
||||
|
||||
local function str(r: Bytes.Reader, long: boolean): string
|
||||
local n = if long then r:u32be() else r:u16be()
|
||||
return r:string(n)
|
||||
end
|
||||
|
||||
local readValue: (r: Bytes.Reader, depth: number, refs: { any }) -> any
|
||||
|
||||
-- object properties up to the end marker (00 00 09) or the end of the data
|
||||
local function props(r: Bytes.Reader, depth: number, refs: { any }, into: { [string]: any }): boolean
|
||||
while not r.err and r:remaining() >= 3 do
|
||||
local key = str(r, false)
|
||||
if key == "" and r:peekU8() == 9 then
|
||||
r:skip(1)
|
||||
return true
|
||||
end
|
||||
local v = readValue(r, depth + 1, refs)
|
||||
if r.err or v == nil then
|
||||
return false
|
||||
end
|
||||
if v ~= Amf.NULL then
|
||||
into[key] = v
|
||||
end
|
||||
end
|
||||
return false
|
||||
end
|
||||
|
||||
readValue = function(r: Bytes.Reader, depth: number, refs: { any }): any
|
||||
if depth > MAX_DEPTH or r:remaining() < 1 then
|
||||
return nil
|
||||
end
|
||||
local t = r:u8()
|
||||
if t == 0 then
|
||||
return r:f64be()
|
||||
elseif t == 1 then
|
||||
return r:u8() ~= 0
|
||||
elseif t == 2 then
|
||||
return str(r, false)
|
||||
elseif t == 12 then
|
||||
return str(r, true)
|
||||
elseif t == 3 or t == 8 then
|
||||
if t == 8 then
|
||||
r:u32be() -- the count (approximate in practice: the end marker ends it)
|
||||
end
|
||||
local o: { [string]: any } = {}
|
||||
table.insert(refs, o)
|
||||
props(r, depth, refs, o)
|
||||
return o
|
||||
elseif t == 10 then
|
||||
local n = r:u32be()
|
||||
local a: { any } = {}
|
||||
table.insert(refs, a)
|
||||
for i = 1, n do
|
||||
if r.err or r:remaining() < 1 then
|
||||
break
|
||||
end
|
||||
local v = readValue(r, depth + 1, refs)
|
||||
if v == nil then
|
||||
break
|
||||
end
|
||||
a[i] = v
|
||||
end
|
||||
return a
|
||||
elseif t == 5 or t == 6 then
|
||||
return Amf.NULL
|
||||
elseif t == 7 then
|
||||
local i = r:u16be()
|
||||
return refs[i + 1] or Amf.NULL
|
||||
elseif t == 11 then
|
||||
local ms = r:f64be()
|
||||
r:i16be()
|
||||
return ms
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
-- value(reader) -> the next AMF0 value | nil (unknown type, truncated, nested too deep)
|
||||
function Amf.value(r: Bytes.Reader): any
|
||||
local ok, v = pcall(readValue, r, 0, {})
|
||||
return if ok and not r.err then v else nil
|
||||
end
|
||||
|
||||
-- script(reader) -> name, value: a script data tag body (an AMF0 string, then its value) | nil
|
||||
function Amf.script(r: Bytes.Reader): (string?, any)
|
||||
local name = Amf.value(r)
|
||||
if type(name) ~= "string" then
|
||||
return nil, nil
|
||||
end
|
||||
return name, Amf.value(r)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ write
|
||||
local function writeString(w: Bytes.Writer, s: string)
|
||||
if #s > 65535 then
|
||||
w:u8(12)
|
||||
w:u32be(#s)
|
||||
else
|
||||
w:u8(2)
|
||||
w:u16be(#s)
|
||||
end
|
||||
w:string(s)
|
||||
end
|
||||
|
||||
-- writeValue(w, v): a number, boolean, string, array (strict array) or Amf.NULL; other values are written as null
|
||||
function Amf.writeValue(w: Bytes.Writer, v: any)
|
||||
local t = type(v)
|
||||
if t == "number" then
|
||||
w:u8(0)
|
||||
w:f64be(v)
|
||||
elseif t == "boolean" then
|
||||
w:u8(1)
|
||||
w:u8(if v then 1 else 0)
|
||||
elseif t == "string" then
|
||||
writeString(w, v)
|
||||
elseif t == "table" and v ~= Amf.NULL and #v > 0 then
|
||||
w:u8(10)
|
||||
w:u32be(#v)
|
||||
for _, x in v do
|
||||
Amf.writeValue(w, x)
|
||||
end
|
||||
else
|
||||
w:u8(5)
|
||||
end
|
||||
end
|
||||
|
||||
-- writeEcma(w, list): an ECMA array of { key, value } pairs (values: as writeValue; a list nested as
|
||||
-- { key, { pairs = { ... } } } becomes an object)
|
||||
function Amf.writeEcma(w: Bytes.Writer, list: { { any } }, object: boolean?)
|
||||
if object then
|
||||
w:u8(3)
|
||||
else
|
||||
w:u8(8)
|
||||
w:u32be(#list)
|
||||
end
|
||||
for _, kv in list do
|
||||
local k: string = kv[1]
|
||||
w:u16be(#k)
|
||||
w:string(k)
|
||||
local v = kv[2]
|
||||
if type(v) == "table" and v.pairs then
|
||||
Amf.writeEcma(w, v.pairs, true)
|
||||
else
|
||||
Amf.writeValue(w, v)
|
||||
end
|
||||
end
|
||||
w:u16be(0)
|
||||
w:u8(9)
|
||||
end
|
||||
|
||||
return Amf
|
||||
@@ -0,0 +1,288 @@
|
||||
--!strict
|
||||
-- video/flv/Mux: the FLV writer (Adobe's Video File Format Specification v10): the header, an onMetaData script tag
|
||||
-- (duration, width, height, data rates, frame rate, codec ids, audio format, encoder, file size), the H.264
|
||||
-- AVCDecoderConfigurationRecord / AAC AudioSpecificConfig sequence headers, the packets of codecs/video/Video/Source
|
||||
-- streams as tags interleaved by decode time (milliseconds, shifted so none is negative; H.264 composition times),
|
||||
-- and H.264's end-of-sequence tag. AAC from ADTS sources (MPEG-TS) is split into raw frames with a configuration made
|
||||
-- from the first ADTS header. Interpreted; never throws (returns nil, Err).
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Amf = require("@formats/video/flv/Amf")
|
||||
|
||||
local Mux = {}
|
||||
|
||||
-- the codecs FLV holds (copied from the source)
|
||||
local VIDEO_COPY: { [string]: boolean } = { h264 = true, flv1 = true, vp6f = true, vp6a = true, flashsv = true, flashsv2 = true }
|
||||
local AUDIO_COPY: { [string]: boolean } = { aac = true, mp3 = true, pcm_s16le = true, pcm_u8 = true, pcm_alaw = true, pcm_mulaw = true, adpcm_swf = true, nellymoser = true, speex = true }
|
||||
Mux.VIDEO_COPY = VIDEO_COPY
|
||||
Mux.AUDIO_COPY = AUDIO_COPY
|
||||
|
||||
local VIDEO_IDS: { [string]: number } = { flv1 = 2, flashsv = 3, vp6f = 4, vp6a = 5, flashsv2 = 6, h264 = 7 }
|
||||
local AUDIO_FORMATS: { [string]: number } = { pcm_s16le = 3, pcm_u8 = 3, adpcm_swf = 1, mp3 = 2, nellymoser = 6, pcm_alaw = 7, pcm_mulaw = 8, aac = 10, speex = 11 }
|
||||
local RATE_CODES: { [number]: number } = { [5512] = 0, [5513] = 0, [11025] = 1, [22050] = 2, [44100] = 3 }
|
||||
local AAC_RATES = { 96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350 }
|
||||
|
||||
local function isAdts(s: any): boolean
|
||||
if s.track and s.track.adts then
|
||||
return true
|
||||
end
|
||||
local p = s.packets[1]
|
||||
return s.config == nil and p ~= nil and buffer.len(p.data) >= 7 and buffer.readu8(p.data, 0) == 0xFF and buffer.readu8(p.data, 1) >= 0xF0
|
||||
end
|
||||
|
||||
-- audioProblem(stream) -> why FLV cannot hold this audio stream | nil
|
||||
function Mux.audioProblem(s: any): string?
|
||||
local fmt = AUDIO_FORMATS[s.codec]
|
||||
if not fmt then
|
||||
return "FLV has no audio codec " .. tostring(s.codec)
|
||||
end
|
||||
if (s.channels or 1) > 2 then
|
||||
return "FLV audio has at most 2 channels"
|
||||
end
|
||||
local rate = math.floor((s.sampleRate or 0) + 0.5)
|
||||
if s.codec == "aac" then
|
||||
if not s.config and not isAdts(s) then
|
||||
return "AAC without its AudioSpecificConfig"
|
||||
end
|
||||
elseif (s.codec == "pcm_alaw" or s.codec == "pcm_mulaw") and rate ~= 8000 then
|
||||
return "FLV G.711 audio is 8000 Hz (not " .. rate .. ")"
|
||||
elseif s.codec ~= "mp3" and s.codec ~= "speex" and s.codec ~= "nellymoser" and s.codec ~= "pcm_alaw" and s.codec ~= "pcm_mulaw" and RATE_CODES[rate] == nil then
|
||||
return "FLV " .. s.codec .. " audio is 5512, 11025, 22050 or 44100 Hz (not " .. rate .. ")"
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
local function audioFlags(s: any): number
|
||||
local fmt = AUDIO_FORMATS[s.codec]
|
||||
local rate = math.floor((s.sampleRate or 44100) + 0.5)
|
||||
local rc = RATE_CODES[rate] or 3
|
||||
local size = if s.codec == "pcm_u8" then 0 else 1
|
||||
local stereo = if (s.channels or 1) > 1 then 1 else 0
|
||||
if s.codec == "aac" then
|
||||
rc, stereo = 3, 1
|
||||
elseif s.codec == "mp3" and rate == 8000 then
|
||||
fmt = 14
|
||||
elseif s.codec == "speex" then
|
||||
rc, stereo = 0, 0
|
||||
elseif s.codec == "pcm_alaw" or s.codec == "pcm_mulaw" then
|
||||
rc = 0
|
||||
elseif s.codec == "nellymoser" then
|
||||
if rate == 16000 then
|
||||
fmt = 4
|
||||
elseif rate == 8000 then
|
||||
fmt = 5
|
||||
end
|
||||
stereo = 0
|
||||
end
|
||||
return fmt * 16 + rc * 4 + size * 2 + stereo
|
||||
end
|
||||
|
||||
-- ADTS frames -> raw AAC frames (1024 samples each) and the AudioSpecificConfig of the first header
|
||||
local function fromAdts(s: any): ({ any }?, buffer?)
|
||||
local out = {}
|
||||
local cfg: buffer? = nil
|
||||
local rate = s.sampleRate or 44100
|
||||
for _, p in s.packets do
|
||||
local d: buffer = p.data
|
||||
local n = buffer.len(d)
|
||||
local o = 0
|
||||
local t = p.pts
|
||||
while o + 7 <= n do
|
||||
local b1, b2, b3 = buffer.readu8(d, o + 1), buffer.readu8(d, o + 2), buffer.readu8(d, o + 3)
|
||||
if buffer.readu8(d, o) ~= 0xFF or b1 < 0xF0 then
|
||||
return nil, nil
|
||||
end
|
||||
local len = (b3 % 4) * 2048 + buffer.readu8(d, o + 4) * 8 + buffer.readu8(d, o + 5) // 32
|
||||
local hl = if b1 % 2 == 1 then 7 else 9
|
||||
if len < hl or o + len > n then
|
||||
return nil, nil
|
||||
end
|
||||
if not cfg then
|
||||
local aot = b2 // 64 + 1
|
||||
local sfi = (b2 // 4) % 16
|
||||
local ch = (b2 % 2) * 4 + b3 // 64
|
||||
cfg = buffer.create(2)
|
||||
buffer.writeu8(cfg, 0, aot * 8 + sfi // 2)
|
||||
buffer.writeu8(cfg, 1, (sfi % 2) * 128 + ch * 8)
|
||||
rate = AAC_RATES[sfi + 1] or rate
|
||||
end
|
||||
local f = buffer.create(len - hl)
|
||||
buffer.copy(f, 0, d, o + hl, len - hl)
|
||||
table.insert(out, { pts = t, dts = t, duration = 1024 / rate, keyframe = true, data = f })
|
||||
t += 1024 / rate
|
||||
o += len
|
||||
end
|
||||
end
|
||||
return out, cfg
|
||||
end
|
||||
|
||||
local function f64At(b: buffer, at: number, v: number)
|
||||
local t = buffer.create(8)
|
||||
buffer.writef64(t, 0, v)
|
||||
for i = 0, 7 do
|
||||
buffer.writeu8(b, at + i, buffer.readu8(t, 7 - i))
|
||||
end
|
||||
end
|
||||
|
||||
-- mux(streams) -> buffer | nil, Err
|
||||
function Mux.mux(streams: { any }): (buffer?, Err.Err?)
|
||||
local video, audio = nil :: any, nil :: any
|
||||
for _, s in streams do
|
||||
if s.kind == "video" and not video then
|
||||
if not VIDEO_IDS[s.codec] then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "FLV has no video codec " .. tostring(s.codec))
|
||||
end
|
||||
if s.codec == "h264" and (s.config == nil or buffer.len(s.config) < 7 or buffer.readu8(s.config, 0) ~= 1) then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "H.264 without an avcC (an Annex B source) cannot be written to FLV")
|
||||
end
|
||||
video = s
|
||||
elseif s.kind == "audio" and not audio then
|
||||
audio = s
|
||||
end
|
||||
end
|
||||
if not video and not audio then
|
||||
return nil, Err.new(Err.ARG, "no video or audio stream")
|
||||
end
|
||||
local aConfig: buffer? = audio and audio.config
|
||||
local aPackets: { any } = audio and audio.packets or {}
|
||||
if audio and audio.codec == "aac" and isAdts(audio) then
|
||||
local pk, cfg = fromAdts(audio)
|
||||
if not pk or not cfg then
|
||||
return nil, Err.new(Err.CORRUPT, "bad ADTS AAC audio")
|
||||
end
|
||||
aPackets, aConfig = pk, cfg
|
||||
end
|
||||
local order: { { any } } = {} -- { kind, packet }
|
||||
do
|
||||
local vi, ai = 1, 1
|
||||
local vp: { any } = if video then video.packets else {}
|
||||
while vi <= #vp or ai <= #aPackets do
|
||||
local a, v = aPackets[ai], vp[vi]
|
||||
if v and (not a or (v.dts or v.pts) <= (a.dts or a.pts)) then
|
||||
table.insert(order, { "video", v })
|
||||
vi += 1
|
||||
else
|
||||
table.insert(order, { "audio", a })
|
||||
ai += 1
|
||||
end
|
||||
end
|
||||
end
|
||||
-- times: milliseconds, shifted so the earliest decode time is 0 when any is negative
|
||||
local shift = 0
|
||||
local duration = 0
|
||||
local vBytes, aBytes = 0, 0
|
||||
for _, e in order do
|
||||
local p = e[2]
|
||||
local t = p.dts or p.pts
|
||||
if t < -shift then
|
||||
shift = -t
|
||||
end
|
||||
duration = math.max(duration, p.pts + (p.duration or 0))
|
||||
if e[1] == "video" then
|
||||
vBytes += buffer.len(p.data)
|
||||
else
|
||||
aBytes += buffer.len(p.data)
|
||||
end
|
||||
end
|
||||
local function ms(t: number): number
|
||||
return math.floor((t + shift) * 1000 + 0.5)
|
||||
end
|
||||
|
||||
local w = Bytes.writer(65536 + vBytes + aBytes + #order * 20)
|
||||
w:string("FLV")
|
||||
w:u8(1)
|
||||
w:u8((if audio then 4 else 0) + (if video then 1 else 0))
|
||||
w:u32be(9)
|
||||
w:u32be(0)
|
||||
local function tag(kind: number, ts: number, head: { number }, data: buffer?)
|
||||
local n = #head + (if data then buffer.len(data) else 0)
|
||||
w:u8(kind)
|
||||
w:u24be(n)
|
||||
local t = ts % 0x100000000
|
||||
w:u24be(t % 0x1000000)
|
||||
w:u8(t // 0x1000000)
|
||||
w:u24be(0)
|
||||
for _, x in head do
|
||||
w:u8(x)
|
||||
end
|
||||
if data then
|
||||
w:bytes(data)
|
||||
end
|
||||
w:u32be(11 + n)
|
||||
end
|
||||
|
||||
-- onMetaData
|
||||
local props: { { any } } = { { "duration", duration } }
|
||||
if video then
|
||||
table.insert(props, { "width", video.width or 0 })
|
||||
table.insert(props, { "height", video.height or 0 })
|
||||
table.insert(props, { "videodatarate", if duration > 0 then vBytes * 8 / duration / 1000 else 0 })
|
||||
table.insert(props, { "framerate", video.frameRate or 0 })
|
||||
table.insert(props, { "videocodecid", VIDEO_IDS[video.codec] })
|
||||
end
|
||||
if audio then
|
||||
local flags = audioFlags(audio)
|
||||
table.insert(props, { "audiodatarate", if duration > 0 then aBytes * 8 / duration / 1000 else 0 })
|
||||
table.insert(props, { "audiosamplerate", math.floor((audio.sampleRate or 44100) + 0.5) })
|
||||
table.insert(props, { "audiosamplesize", if audio.codec == "pcm_u8" then 8 else 16 })
|
||||
table.insert(props, { "stereo", (audio.channels or 1) > 1 })
|
||||
table.insert(props, { "audiocodecid", flags // 16 })
|
||||
end
|
||||
table.insert(props, { "encoder", "formats-luau" })
|
||||
table.insert(props, { "filesize", 0 })
|
||||
local mw = Bytes.writer(512)
|
||||
Amf.writeValue(mw, "onMetaData")
|
||||
Amf.writeEcma(mw, props)
|
||||
local metaBody = mw:finish()
|
||||
local metaAt = w:tell() + 11
|
||||
tag(18, 0, {}, metaBody)
|
||||
local fileSizeAt = metaAt + buffer.len(metaBody) - 3 - 8 -- the last value (filesize) before the end marker
|
||||
|
||||
-- sequence headers
|
||||
local vid = if video then VIDEO_IDS[video.codec] else 0
|
||||
if video and video.codec == "h264" then
|
||||
tag(9, 0, { 0x10 + vid, 0, 0, 0, 0 }, video.config)
|
||||
end
|
||||
local aflags = if audio then audioFlags(audio) else 0
|
||||
if audio and audio.codec == "aac" then
|
||||
tag(8, 0, { aflags, 0 }, aConfig)
|
||||
end
|
||||
local vp6 = if video and (video.codec == "vp6f" or video.codec == "vp6a") then video.config else nil
|
||||
local vp6Byte = if vp6 and buffer.len(vp6) > 0 then buffer.readu8(vp6, 0) else 0
|
||||
if video and (video.codec == "vp6f" or video.codec == "vp6a") and not vp6 then
|
||||
local wd, ht = video.width or 0, video.height or 0
|
||||
vp6Byte = ((16 - wd % 16) % 16) * 16 + (16 - ht % 16) % 16
|
||||
end
|
||||
local lastVideo = 0
|
||||
for _, e in order do
|
||||
local p = e[2]
|
||||
local dts = ms(p.dts or p.pts)
|
||||
if e[1] == "video" then
|
||||
local ft = (if p.keyframe then 1 else 2) * 16 + vid
|
||||
if video.codec == "h264" then
|
||||
local cts = ms(p.pts) - dts
|
||||
if cts < 0 then
|
||||
cts += 0x1000000
|
||||
end
|
||||
tag(9, dts, { ft, 1, cts // 65536 % 256, cts // 256 % 256, cts % 256 }, p.data)
|
||||
elseif vp6 or video.codec == "vp6f" or video.codec == "vp6a" then
|
||||
tag(9, dts, { ft, vp6Byte }, p.data)
|
||||
else
|
||||
tag(9, dts, { ft }, p.data)
|
||||
end
|
||||
lastVideo = math.max(lastVideo, dts)
|
||||
elseif audio.codec == "aac" then
|
||||
tag(8, dts, { aflags, 1 }, p.data)
|
||||
else
|
||||
tag(8, dts, { aflags }, p.data)
|
||||
end
|
||||
end
|
||||
if video and video.codec == "h264" then
|
||||
tag(9, lastVideo, { 0x10 + vid, 2, 0, 0, 0 }, nil)
|
||||
end
|
||||
local out = w:finish()
|
||||
f64At(out, fileSizeAt, buffer.len(out))
|
||||
return out, nil
|
||||
end
|
||||
|
||||
return Mux
|
||||
@@ -0,0 +1,402 @@
|
||||
--!strict
|
||||
-- video/flv: Flash Video (FLV, Adobe's Video File Format Specification v10, and the Enhanced RTMP / FLV extension's
|
||||
-- FourCC video tags). New in formats-luau.
|
||||
-- Read: the header, the tag stream and onMetaData (AMF0: duration, width, height, framerate, codec ids, keyframes, ...
|
||||
-- into meta.metadata) into a Demuxer (times in milliseconds; keyframe flags from the video tags; seeking by
|
||||
-- keyframes) and open() returns a VideoDecoder: video through the codecs/video/Video registry (Sorenson Spark / FLV1
|
||||
-- and H.264 decode; VP6 / VP6 alpha, screen video 1 / 2 and enhanced FourCC codecs (HEVC, AV1, VP9) are known tracks
|
||||
-- whose decoding is UNSUPPORTED); H.264's AVCDecoderConfigurationRecord in track.config, composition time offsets
|
||||
-- in the pts. Audio through the api's opts.openAudio hook: MP3 (also 8 kHz), AAC (AudioSpecificConfig in track.config),
|
||||
-- linear PCM (platform-endian read as little-endian), A-law / mu-law; Flash ADPCM, Nellymoser and Speex are known
|
||||
-- tracks without an audio decoder (UNSUPPORTED). Flv.demux(r) gives the Demuxer.
|
||||
-- Write: H.264 / Sorenson Spark / VP6 / screen video copied from the source (FLV has no codec we encode), AAC / MP3 /
|
||||
-- PCM / A-law / mu-law / ADPCM / Nellymoser / Speex audio copied (AAC from ADTS sources re-framed), else PCM s16 at
|
||||
-- the FLV sample rates (5512 / 11025 / 22050 / 44100 Hz), with onMetaData (duration, sizes, frame rate, data
|
||||
-- rates, codec ids, file size).
|
||||
-- Not supported: encrypted tags (the track's packets are dropped, track.unsupported says so), multitrack and ModEx
|
||||
-- enhanced packets (skipped), writing H.264 from Annex B sources (no avcC).
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ 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/Video")
|
||||
local Source = require("@formats/codecs/video/Video/Source")
|
||||
local H263 = require("@formats/codecs/video/H263")
|
||||
local H264 = require("@formats/codecs/video/H264")
|
||||
local Aac = require("@formats/codecs/audio/Aac")
|
||||
local Amf = require("@formats/video/flv/Amf")
|
||||
local Mux = require("@formats/video/flv/Mux")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Flv = {
|
||||
name = "flv",
|
||||
category = "video",
|
||||
extensions = { "flv" },
|
||||
mime = { "video/x-flv", "video/flv" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "containers/Demux", "codecs/video/Video", "codecs/video/Video/Source", "codecs/video/H263", "codecs/video/H264", "codecs/audio/Aac" },
|
||||
caps = { decode = true, encode = true, streaming = true, remux = true, video = { "flv1", "h264" }, audio = true, metadata = true },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type OpenOptions = {
|
||||
rgba: boolean?, -- nextFrame returns rgba8 images (default false: yuv420p from the codec)
|
||||
track: number?, -- the video track id (1 video, 2 audio)
|
||||
audio: boolean?, -- false: do not open the audio track
|
||||
maxPackets: number?, -- refuse files with more tags (default 2^24)
|
||||
maxPixels: number?,
|
||||
openAudio: any?, -- set by the api: (demuxer, track) -> audio Decoder
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
video: boolean?, -- false: no video
|
||||
audio: boolean?, -- false: no audio; true: fail when the audio cannot be written (default: dropped)
|
||||
reencodeAudio: boolean?, -- PCM s16 even when the audio could be copied
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
Flv.VIDEO_ID = 1
|
||||
Flv.AUDIO_ID = 2
|
||||
|
||||
-- SoundFormat -> codec id
|
||||
local AUDIO_CODECS: { [number]: string } = {
|
||||
[0] = "pcm", -- platform-endian (little-endian in practice)
|
||||
[1] = "adpcm_swf",
|
||||
[2] = "mp3",
|
||||
[3] = "pcm",
|
||||
[4] = "nellymoser",
|
||||
[5] = "nellymoser",
|
||||
[6] = "nellymoser",
|
||||
[7] = "pcm_alaw",
|
||||
[8] = "pcm_mulaw",
|
||||
[10] = "aac",
|
||||
[11] = "speex",
|
||||
[14] = "mp3",
|
||||
[15] = "device_specific",
|
||||
}
|
||||
local AUDIO_RATES = { [0] = 5512, 11025, 22050, 44100 }
|
||||
-- the formats with a fixed rate (G.711: 8 kHz as ffmpeg reads them) / always mono
|
||||
local FIXED_RATE: { [number]: number } = { [4] = 16000, [5] = 8000, [7] = 8000, [8] = 8000, [11] = 16000, [14] = 8000 }
|
||||
local MONO: { [number]: boolean } = { [4] = true, [5] = true, [11] = true }
|
||||
|
||||
-- CodecID -> codec id
|
||||
local VIDEO_CODECS: { [number]: string } = {
|
||||
[2] = "flv1",
|
||||
[3] = "flashsv",
|
||||
[4] = "vp6f",
|
||||
[5] = "vp6a",
|
||||
[6] = "flashsv2",
|
||||
[7] = "h264",
|
||||
}
|
||||
|
||||
-- Enhanced FLV audio FourCCs
|
||||
local AUDIO_FOURCC: { [string]: string } = { Opus = "opus", fLaC = "flac", mp4a = "aac", [".mp3"] = "mp3", ["ac-3"] = "ac3", ["ec-3"] = "eac3" }
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Flv.sniff(r: Bytes.Reader): number
|
||||
if r:remaining() >= 9 and r:peek(3) == "FLV" then
|
||||
return if r:peekU8(3) == 1 then 1 else 0.6
|
||||
end
|
||||
return 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
local readu8 = buffer.readu8
|
||||
|
||||
local function u24(b: buffer, p: number): number
|
||||
return readu8(b, p) * 65536 + readu8(b, p + 1) * 256 + readu8(b, p + 2)
|
||||
end
|
||||
|
||||
local function s24(b: buffer, p: number): number
|
||||
local v = u24(b, p)
|
||||
return if v >= 0x800000 then v - 0x1000000 else v
|
||||
end
|
||||
|
||||
local function copy(b: buffer, p: number, n: number): buffer
|
||||
local c = buffer.create(n)
|
||||
buffer.copy(c, 0, b, p, n)
|
||||
return c
|
||||
end
|
||||
|
||||
-- the picture size of a codec's first keyframe (Sorenson, VP6, screen video) | nil
|
||||
local function frameSize(codec: string, b: buffer, p: number, n: number): (number?, number?)
|
||||
if codec == "flv1" then
|
||||
local h = H263.header(b, p, n, true)
|
||||
if h then
|
||||
return h.width, h.height
|
||||
end
|
||||
elseif (codec == "vp6f" or codec == "vp6a") and n >= 8 then
|
||||
-- VP6 key frame header: type / quant / marker, version / profile / interlace, [16-bit offset], MB rows, MB
|
||||
-- cols, display rows, display cols; the FLV adjustment byte (p - 1, before the frame) crops width / height
|
||||
local adj = readu8(b, p - 1)
|
||||
local q = p + (if codec == "vp6a" then 3 else 0)
|
||||
if q + 6 > p + n or readu8(b, q) >= 128 then
|
||||
return nil, nil
|
||||
end
|
||||
local b1 = readu8(b, q + 1)
|
||||
local o = q + 2
|
||||
if readu8(b, q) % 2 == 1 or (b1 // 2) % 4 == 0 then
|
||||
o += 2
|
||||
end
|
||||
if o + 4 > p + n then
|
||||
return nil, nil
|
||||
end
|
||||
local w = readu8(b, o + 3) * 16 - adj // 16
|
||||
local h = readu8(b, o + 2) * 16 - adj % 16
|
||||
if w > 0 and h > 0 then
|
||||
return w, h
|
||||
end
|
||||
elseif (codec == "flashsv" or codec == "flashsv2") and n >= 4 then
|
||||
return (readu8(b, p) % 16) * 256 + readu8(b, p + 1), (readu8(b, p + 2) % 16) * 256 + readu8(b, p + 3)
|
||||
end
|
||||
return nil, nil
|
||||
end
|
||||
|
||||
-- demux(r, opts?) -> the Demuxer (containers/Demux) | nil, Err
|
||||
function Flv.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?)
|
||||
local o: OpenOptions = opts or {}
|
||||
local b, base, limit = r.buf, r.base, r.limit
|
||||
if limit - base < 9 or buffer.readstring(b, base, 3) ~= "FLV" then
|
||||
return nil, Err.new(Err.CORRUPT, "not an FLV file (no FLV signature)", base)
|
||||
end
|
||||
local flags = readu8(b, base + 4)
|
||||
local dataOffset = buffer.readu32(b, base + 5)
|
||||
dataOffset = bit32.byteswap(dataOffset)
|
||||
if dataOffset < 9 or base + dataOffset > limit then
|
||||
return nil, Err.new(Err.CORRUPT, "bad header size " .. dataOffset, base + 5)
|
||||
end
|
||||
local meta: { [string]: any } = { version = readu8(b, base + 3), hasAudio = bit32.band(flags, 4) ~= 0, hasVideo = bit32.band(flags, 1) ~= 0 }
|
||||
local tracks: { Types.Track } = {}
|
||||
local dmx = Demux.new("flv", tracks, b, meta)
|
||||
local vt: any, at: any = nil, nil
|
||||
local keyOff, keyLen = -1, 0 -- the first video keyframe
|
||||
local maxPackets = o.maxPackets or 2 ^ 24
|
||||
local count = 0
|
||||
local p = base + dataOffset + 4 -- after PreviousTagSize0
|
||||
while p + 11 <= limit do
|
||||
local tagType = bit32.band(readu8(b, p), 0x1F)
|
||||
local filtered = bit32.band(readu8(b, p), 0x20) ~= 0
|
||||
local size = u24(b, p + 1)
|
||||
local ts = u24(b, p + 4) + readu8(b, p + 7) * 0x1000000
|
||||
if ts >= 0x80000000 then
|
||||
ts -= 0x100000000
|
||||
end
|
||||
local d = p + 11
|
||||
if d + size > limit then
|
||||
meta.truncated = true
|
||||
break
|
||||
end
|
||||
count += 1
|
||||
if count > maxPackets then
|
||||
return nil, Err.new(Err.LIMIT, "more than " .. maxPackets .. " tags")
|
||||
end
|
||||
if tagType == 8 and size >= 1 then
|
||||
local a = readu8(b, d)
|
||||
local fmt = a // 16
|
||||
if not at then
|
||||
at = { id = Flv.AUDIO_ID, kind = "audio", codec = "unknown", codecTag = "flv audio " .. fmt, timescale = 1000, default = true }
|
||||
table.insert(tracks, at)
|
||||
local bits = if (a // 2) % 2 == 1 then 16 else 8
|
||||
local codec = AUDIO_CODECS[fmt] or ("flv_audio_" .. fmt)
|
||||
if codec == "pcm" then
|
||||
codec = if bits == 16 then "pcm_s16le" else "pcm_u8"
|
||||
end
|
||||
at.codec = codec
|
||||
at.soundFormat = fmt
|
||||
at.sampleRate = FIXED_RATE[fmt] or AUDIO_RATES[(a // 4) % 4]
|
||||
at.channels = if MONO[fmt] then 1 else a % 2 + 1
|
||||
at.bitsPerSample = if codec == "pcm_alaw" or codec == "pcm_mulaw" then 8 else bits
|
||||
end
|
||||
if filtered then
|
||||
at.unsupported = "encrypted audio tags"
|
||||
elseif fmt == 10 and at.soundFormat == 10 then
|
||||
if size >= 2 then
|
||||
if readu8(b, d + 1) == 0 then
|
||||
local c = copy(b, d + 2, size - 2)
|
||||
at.config = c
|
||||
local cfg = Aac.config(c)
|
||||
if cfg then
|
||||
at.sampleRate = cfg.extensionRate or cfg.sampleRate
|
||||
at.channels = cfg.channels
|
||||
end
|
||||
elseif size > 2 then
|
||||
dmx:add(at.id, ts, nil, nil, true, d + 2, size - 2)
|
||||
end
|
||||
end
|
||||
elseif fmt == 9 and at.soundFormat == 9 then
|
||||
-- Enhanced FLV: packet type, FourCC
|
||||
if size >= 5 then
|
||||
local pt = a % 16
|
||||
local fcc = buffer.readstring(b, d + 1, 4)
|
||||
at.codec = AUDIO_FOURCC[fcc] or fcc
|
||||
at.codecTag = fcc
|
||||
if pt == 0 then
|
||||
at.config = copy(b, d + 5, size - 5)
|
||||
elseif pt == 1 and size > 5 then
|
||||
dmx:add(at.id, ts, nil, nil, true, d + 5, size - 5)
|
||||
end
|
||||
end
|
||||
elseif fmt == at.soundFormat and size > 1 then
|
||||
dmx:add(at.id, ts, nil, nil, true, d + 1, size - 1)
|
||||
end
|
||||
elseif tagType == 9 and size >= 1 then
|
||||
local v = readu8(b, d)
|
||||
local enhanced = v >= 128
|
||||
local frameType = if enhanced then (v // 16) % 8 else v // 16
|
||||
if frameType ~= 5 then -- not a video info / command frame
|
||||
local codec: string?, codecTag: string? = nil, nil
|
||||
local pt, cts, q, n = 0, 0, 0, 0
|
||||
if enhanced then
|
||||
if size < 5 then
|
||||
codec = nil
|
||||
else
|
||||
local fcc = buffer.readstring(b, d + 1, 4)
|
||||
codec, codecTag = Video.fromFourcc(fcc) or fcc, fcc
|
||||
pt = v % 16
|
||||
q, n, cts = d + 5, size - 5, 0
|
||||
if pt == 1 and (fcc == "avc1" or fcc == "hvc1") then
|
||||
if n >= 3 then
|
||||
cts = s24(b, q)
|
||||
end
|
||||
q, n = q + 3, n - 3
|
||||
elseif pt == 3 then
|
||||
pt = 1 -- coded frames without a composition time
|
||||
end
|
||||
end
|
||||
else
|
||||
local id = v % 16
|
||||
codec = VIDEO_CODECS[id] or ("flv_video_" .. id)
|
||||
codecTag = "flv video " .. id
|
||||
pt, q, n, cts = 1, d + 1, size - 1, 0
|
||||
if codec == "h264" then
|
||||
if size >= 5 then
|
||||
pt = readu8(b, d + 1)
|
||||
cts = s24(b, d + 2)
|
||||
else
|
||||
pt = 2
|
||||
end
|
||||
q, n = d + 5, size - 5
|
||||
elseif codec == "vp6f" or codec == "vp6a" then
|
||||
q, n = d + 2, size - 2 -- after the adjustment byte (the track's config, as ffmpeg's extradata)
|
||||
end
|
||||
end
|
||||
if codec then
|
||||
if not vt then
|
||||
vt = { id = Flv.VIDEO_ID, kind = "video", codec = codec, codecTag = codecTag, timescale = 1000, default = true }
|
||||
table.insert(tracks, vt)
|
||||
end
|
||||
if (codec == "vp6f" or codec == "vp6a") and not vt.config and size >= 2 then
|
||||
vt.config = copy(b, d + 1, 1) -- the crop (adjustment) byte
|
||||
end
|
||||
if filtered then
|
||||
vt.unsupported = "encrypted video tags"
|
||||
elseif codec == vt.codec then
|
||||
if pt == 0 then
|
||||
if n > 0 then
|
||||
vt.config = copy(b, q, n)
|
||||
end
|
||||
elseif pt == 1 and n > 0 then
|
||||
local key = frameType == 1
|
||||
dmx:add(vt.id, ts + cts, ts, nil, key, q, n)
|
||||
if key and keyOff < 0 then
|
||||
keyOff, keyLen = q, n
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
elseif tagType == 18 and size > 0 then
|
||||
local name, value = Amf.script(Bytes.reader(b, d, size))
|
||||
if name == "onMetaData" and type(value) == "table" and meta.metadata == nil then
|
||||
meta.metadata = value
|
||||
elseif name then
|
||||
meta.scripts = meta.scripts or {}
|
||||
table.insert(meta.scripts, { name = name, time = ts / 1000, value = value })
|
||||
end
|
||||
end
|
||||
p = d + size + 4
|
||||
end
|
||||
-- the track facts onMetaData and the codec headers give
|
||||
local md: { [string]: any } = meta.metadata or {}
|
||||
if type(md.duration) == "number" and md.duration > 0 then
|
||||
meta.duration = md.duration
|
||||
end
|
||||
if vt then
|
||||
if vt.codec == "h264" and vt.config then
|
||||
local ok, info = pcall(H264.info, vt.config)
|
||||
if ok and info then
|
||||
vt.width, vt.height = info.width, info.height
|
||||
end
|
||||
elseif keyOff >= 0 then
|
||||
local w, h = frameSize(vt.codec, b, keyOff, keyLen)
|
||||
vt.width, vt.height = w, h
|
||||
end
|
||||
if not vt.width and type(md.width) == "number" and type(md.height) == "number" then
|
||||
vt.width, vt.height = math.floor(md.width), math.floor(md.height)
|
||||
end
|
||||
local fr = md.framerate or md.videoframerate
|
||||
if type(fr) == "number" and fr > 0 and fr < 1000 then
|
||||
vt.frameRate = fr
|
||||
else
|
||||
-- from the timestamps: the frames over the time they span
|
||||
local n = dmx:count(vt.id)
|
||||
local t0 = if n > 0 then dmx:info(vt.id, 1) else nil
|
||||
local t1 = if n > 1 then dmx:info(vt.id, n) else nil
|
||||
if t0 and t1 and t1 > t0 then
|
||||
vt.frameRate = math.floor((n - 1) / ((t1 - t0) / 1000) * 1000 + 0.5) / 1000
|
||||
end
|
||||
end
|
||||
end
|
||||
if at and at.codec == "aac" and not at.config then
|
||||
at.unsupported = "AAC without its AudioSpecificConfig"
|
||||
end
|
||||
dmx:finish()
|
||||
return dmx, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
-- encode(video, opts?) -> buffer | nil, Err: a VideoDecoder (F.load / F.video.open) or a Demuxer
|
||||
function Flv.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
local o: any = opts or {}
|
||||
local streams, err = Source.streams(value, o, {
|
||||
video = { copy = Mux.VIDEO_COPY },
|
||||
audio = { copy = Mux.AUDIO_COPY, pcm = true },
|
||||
})
|
||||
if not streams then
|
||||
return nil, err
|
||||
end
|
||||
-- audio FLV cannot hold (PCM at other rates): dropped, or an error with opts.audio = true
|
||||
for i = #streams, 1, -1 do
|
||||
local s = streams[i]
|
||||
local why = s.kind == "audio" and Mux.audioProblem(s)
|
||||
if why then
|
||||
if o.audio == true then
|
||||
return nil, Err.new(Err.UNSUPPORTED, why)
|
||||
end
|
||||
table.remove(streams, i)
|
||||
end
|
||||
end
|
||||
if #streams == 0 then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "nothing FLV can hold")
|
||||
end
|
||||
local ok, buf, merr = pcall(Mux.mux, streams)
|
||||
if not ok then
|
||||
return nil, Err.new(Err.ARG, "internal error: " .. tostring(buf))
|
||||
end
|
||||
return buf, merr
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ open
|
||||
-- open(r, opts?) -> a VideoDecoder (kind "video": nextFrame / seek / audio / demuxer) | nil, Err
|
||||
function Flv.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?)
|
||||
local ok, dmx, err = pcall(Flv.demux, r, opts)
|
||||
if not ok then
|
||||
return nil, Err.new(Err.CORRUPT, "internal error: " .. tostring(dmx))
|
||||
end
|
||||
if not dmx then
|
||||
return nil, err
|
||||
end
|
||||
return Video.open(dmx, opts :: Video.OpenOptions?)
|
||||
end
|
||||
|
||||
return Flv
|
||||
Reference in new issue
Block a user