diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 03a6531..2e232e2 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -50,6 +50,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | audio | wavpack | .wv | yes | - | streaming: true, seek: true, lossless: true, hybrid: true, float: true, depths: 8, 12, 16, 20, 24, 32 | `tests/audio/wavpack.luau` | | video | avi | .avi | yes | yes | streaming: true, video: "mjpeg", "mpeg1", "mpeg2", "rawvideo", audio: true, odml: true | `tests/video/avi.luau` | | video | fli | .fli .flc .flx | yes | - | streaming: true, video: "flic", depths: 8, 15, 16, 24 | `tests/video/fli.luau` | +| video | flv | .flv | yes | yes | streaming: true, remux: true, video: "flv1", "h264", audio: true, metadata: true | `tests/video/flv.luau` | | video | h264 | .h264 .264 .avc .jsv .26l .jvt | yes | yes | streaming: true, video: "h264", depths: 8 | `tests/video/h264.luau` | | video | mkv | .mkv .webm .mka .mk3d | yes | yes | streaming: true, remux: true, video: "vp8", "mjpeg", "mpeg1", "mpeg2", "theora", "rawvideo", audio: true, subtitles: true | `tests/video/mkv.luau` | | video | mp4 | .mp4 .m4v .mov .qt .3gp .3g2 .mj2 | yes | yes | streaming: true, remux: true, video: "mjpeg", "mpeg1", "mpeg2", "h264", audio: true, fragments: true | `tests/video/mp4.luau` | @@ -214,6 +215,7 @@ Codecs (layer 3, shared by formats; not loadable on their own), by domain: - codecs/text/Xml: XML 1.0 parse (DOM and pull events) and serialize, the engine data/xml, SVG, DAE, 3MF, TMX, plist, ... - **video** - codecs/video/Dsp: the 8x8 IDCT (bit-exact with ffmpeg -idct int) and half-pel motion compensation of MPEG codecs. + - codecs/video/H263: an H.263 / H.263+ and Sorenson Spark (FLV1) video decoder, bit-exact with ffmpeg -idct int. - codecs/video/H264: an H.264 / AVC (ITU-T H.264 | ISO/IEC 14496-10) video decoder in pure Luau. A codec (layer 1): the - codecs/video/Legacy: FLI / FLC, Cinepak, Microsoft Video 1, QuickTime RLE / SMC and Smacker video decoders. - codecs/video/Mpeg1: the MPEG-1 video decoder (ISO/IEC 11172-2), which is codecs/video/Mpeg2 (an MPEG-2 decoder diff --git a/docs/guide/video.md b/docs/guide/video.md index 96b9e88..2724634 100644 --- a/docs/guide/video.md +++ b/docs/guide/video.md @@ -186,6 +186,7 @@ Images and animated images save as videos too. | ogv | Theora copied (the source must be Theora: ogv or mkv) | Vorbis / Opus copied | | mkv | any codec copied, else MJPEG | copied, else PCM s16 | | mp4, mov | H.264 / HEVC / AV1 / MJPEG / MPEG-4 copied, else MJPEG | AAC / ALAC / Opus / FLAC / MP3 copied; PCM in MOV only | +| flv | H.264 (with its avcC) / Sorenson Spark / VP6 / screen video copied; nothing else (no FLV encoder) | AAC / MP3 / PCM / G.711 copied, else PCM s16 at 5512 / 11025 / 22050 / 44100 Hz | | avi | MJPEG copied, else MJPEG encoded (`quality`) | PCM s16 | | y4m | raw yuv420p | none | | h264 | an H.264 track copied as an Annex B stream | none | @@ -312,6 +313,36 @@ local mkv = assert(F.save(v, nil, { format = "mkv" })) -- Theora + Vorbis copi assert(F.video.open(mkv).codec == "theora") ``` +## FLV and H.263 + +FLV (Flash Video) opens like any other container. Its onMetaData script tag is `v.meta.metadata` (duration, width, +height, framerate, codec ids, encoder, ...). Sorenson Spark (FLV1) and H.263 (in 3GP / MP4 `s263`, AVI `H263`) +decode bit-exactly as ffmpeg decodes them; H.264 tracks carry their avcC in `track.config` and their B-frame +composition times in the pts. VP6, screen video, Flash ADPCM, Nellymoser and Speex tracks are known (and remuxable) +but not decoded: `nextFrame` / `v.audioError` say UNSUPPORTED. Writing FLV copies H.264 + AAC / MP3 from MP4, +Matroska or FLV sources (FLV has no codec here that encodes). + +```luau +local v = assert(F.video.open(flvBytes)) -- Sorenson Spark + MP3 +assert(v.format == "flv" and v.codec == "flv1" and v.width == 64 and v.height == 48) +local md = v.meta.metadata -- onMetaData (AMF0) +assert(md.duration > 0 and md.framerate == 10 and md.videocodecid == 2) +local f = assert(v:nextFrame()) -- yuv420p (BT.601, limited range) +assert(f.keyframe and f.image.format == "yuv420p") +local sound = assert(F.ops.audio.toAudio(assert(v.audio, tostring(v.audioError)))) +assert(sound.sampleRate == 44100) +local h = assert(F.video.open(h263Bytes)) -- H.263 (QCIF) + AAC in 3GP +assert(h.codec == "h263" and h.width == 176 and h:nextFrame() ~= nil) +local flv = assert(F.convert(mp4Bytes, "flv")) -- remux: H.264 + AAC copied, onMetaData written +local back = assert(F.video.open(flv)) +assert(F.detect(flv) == "flv" and back.codec == "h264" and back.demuxer:track("audio").codec == "aac") +``` + +The H.263 decoder covers baseline H.263 (sub-QCIF .. 16CIF, GOB headers, unrestricted vectors) and the H.263+ +picture header ffmpeg's `h263p` encoder writes (custom sizes, the rounding type, unrestricted vectors, slice +structure); advanced prediction, PB-frames, advanced intra coding, the deblocking filter and the other H.263+ +options are UNSUPPORTED. + ## Playing in a game loop Decode only the frames that are due, and stop when this frame's time budget is used up; a slow frame then makes @@ -355,9 +386,10 @@ editable:WritePixelsBuffer(Vector2.zero, editable.Size, v:toRGBA(frame).pixels) | Format | Read | Write | Video codecs (decode) | |---|---|---|---| -| mp4 / mov / m4v / 3gp | yes | yes | H.264, MJPEG, MPEG-1, MPEG-2 | +| mp4 / mov / m4v / 3gp | yes | yes | H.264, H.263, MJPEG, MPEG-1, MPEG-2 | | mkv / webm | yes | yes | VP8, MJPEG, MPEG-1, MPEG-2, raw, Theora (+ H.264) | | ogv (Ogg Theora) | yes | yes (Theora + Vorbis / Opus copied) | Theora | +| flv | yes | yes (copy) | Sorenson Spark, H.264 (VP6, screen video: known, not decoded) | | avi | yes | yes | MJPEG, MPEG-1, MPEG-2, raw (+ H.264) | | mpegts, mpegps | yes | - | MPEG-1, MPEG-2, H.264 | | y4m | yes | yes | raw | diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index 398f460..8d02b08 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -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", diff --git a/src/Formats/codecs/video/Dsp.luau b/src/Formats/codecs/video/Dsp.luau index 02b875d..f632ed7 100644 --- a/src/Formats/codecs/video/Dsp.luau +++ b/src/Formats/codecs/video/Dsp.luau @@ -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). diff --git a/src/Formats/codecs/video/H263/Decoder.luau b/src/Formats/codecs/video/H263/Decoder.luau new file mode 100644 index 0000000..84c8ca8 --- /dev/null +++ b/src/Formats/codecs/video/H263/Decoder.luau @@ -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 diff --git a/src/Formats/codecs/video/H263/Tables.luau b/src/Formats/codecs/video/H263/Tables.luau new file mode 100644 index 0000000..0f427db --- /dev/null +++ b/src/Formats/codecs/video/H263/Tables.luau @@ -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 diff --git a/src/Formats/codecs/video/H263/init.luau b/src/Formats/codecs/video/H263/init.luau new file mode 100644 index 0000000..be23e40 --- /dev/null +++ b/src/Formats/codecs/video/H263/init.luau @@ -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 diff --git a/src/Formats/codecs/video/Video/init.luau b/src/Formats/codecs/video/Video/init.luau index 9af2004..335d7e5 100644 --- a/src/Formats/codecs/video/Video/init.luau +++ b/src/Formats/codecs/video/Video/init.luau @@ -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") }, diff --git a/src/Formats/video/flv/Amf.luau b/src/Formats/video/flv/Amf.luau new file mode 100644 index 0000000..f66b102 --- /dev/null +++ b/src/Formats/video/flv/Amf.luau @@ -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 diff --git a/src/Formats/video/flv/Mux.luau b/src/Formats/video/flv/Mux.luau new file mode 100644 index 0000000..53657b5 --- /dev/null +++ b/src/Formats/video/flv/Mux.luau @@ -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 diff --git a/src/Formats/video/flv/init.luau b/src/Formats/video/flv/init.luau new file mode 100644 index 0000000..20ad62f --- /dev/null +++ b/src/Formats/video/flv/init.luau @@ -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 diff --git a/tests/codecs/h263.luau b/tests/codecs/h263.luau new file mode 100644 index 0000000..960066e --- /dev/null +++ b/tests/codecs/h263.luau @@ -0,0 +1,246 @@ +-- codecs/video/H263 tests. Against `ffmpeg -idct int` (tools/fixtures/h263.py): H.263 streams (sub-QCIF .. 4CIF, GOB +-- headers, DQUANT, q 1 .. high quantisers), H.263+ PLUSPTYPE streams (custom sizes, sizes that are not a multiple of +-- 16, the rounding type, unrestricted vectors with reversible codes, slice structure) and Sorenson Spark streams (standard, 8-bit and +-- 16-bit custom sizes, 11-bit escapes, high motion, disposable inter pictures) decode one picture at a time to exactly +-- ffmpeg's planes, every frame; header info; frameImage; the registry's decoders (h263, flv1); unsupported options are +-- UNSUPPORTED; truncated and corrupted pictures never throw; the fuzz no-throw pass. +local T = require("@tests/T") +local H263 = require("@formats/codecs/video/H263") +local Video = require("@formats/codecs/video/Video") +local Err = require("@formats/core/Err") +local Base64 = require("@formats/core/Base64") +local Crc32 = require("@formats/core/Crc32") +local Deflate = require("@formats/codecs/compress/Deflate") + +local STREAMS = { + require("@tests/gen/h263_qcif"), + require("@tests/gen/h263_cif_mandel"), + require("@tests/gen/h263_sqcif_scroll"), + require("@tests/gen/h263_qcif_q1"), + require("@tests/gen/h263_qcif_aq"), + require("@tests/gen/h263_cif_gob"), + require("@tests/gen/h263_4cif_gob"), + require("@tests/gen/h263_plus_custom"), + require("@tests/gen/h263_plus_odd"), + require("@tests/gen/h263_plus_umv"), + require("@tests/gen/h263_plus_slices"), + require("@tests/gen/h263_plus_slices_umv"), + require("@tests/gen/h263_flv_320"), + require("@tests/gen/h263_flv_odd"), + require("@tests/gen/h263_flv_wide"), + require("@tests/gen/h263_flv_q1"), + require("@tests/gen/h263_flv_scroll"), + require("@tests/gen/h263_flv_disposable"), +} +local BAD = require("@tests/gen/h263_bad") + +local t = T.suite("codecs/h263") +local rand = T.rng(263) + +local function b64(s: string): buffer + return Base64.decode(s) :: buffer +end + +local function planeCrc(b: buffer, stride: number, w: number, h: number): number + local row = buffer.create(w * h) + for y = 0, h - 1 do + buffer.copy(row, y * w, b, y * stride, w) + end + return Crc32.of(row) +end + +local function crcs(f: any): (number, number, number) + local w, h = f.width, f.height + local cw, ch = (w + 1) // 2, (h + 1) // 2 + return planeCrc(f.y, f.stride, w, h), planeCrc(f.cb, f.stride // 2, cw, ch), planeCrc(f.cr, f.stride // 2, cw, ch) +end + +-- differing luma samples against a reference frame (detail on a mismatch) +local function lumaDiff(f: any, ref: buffer): (number, number) + local n, first = 0, -1 + for y = 0, f.height - 1 do + for x = 0, f.width - 1 do + if buffer.readu8(f.y, y * f.stride + x) ~= buffer.readu8(ref, y * f.width + x) then + n += 1 + if first < 0 then + first = y * 65536 + x + end + end + end + end + return n, first +end + +-- 1. every stream against ffmpeg, bit-exact +local total = 0 +local disposables = 0 +for _, fx in STREAMS do + local name = fx.name + local file = b64(fx.file) + local dec = H263.new({ flv = fx.flv }) + local t0 = os.clock() + local bad, n, msg = 0, 0, "" + for k, u in fx.units do + local f, err = dec:decode(file, u[1], u[2]) + if not f then + bad += 1 + if bad == 1 then + msg = string.format(" (first: picture %d: %s)", k, tostring(err)) + end + else + n += 1 + if f.disposable then + disposables += 1 + end + local y, cb, cr = crcs(f) + local ref = fx.crcs[k] + if not ref or y ~= ref[1] or cb ~= ref[2] or cr ~= ref[3] then + bad += 1 + if bad == 1 then + local detail = "" + if k == 1 then + local nd, first = lumaDiff(f, Deflate.zlib(b64(fx.first)) :: buffer) + detail = string.format(", %d luma samples differ, first at %d,%d", nd, first % 65536, first // 65536) + end + msg = string.format(" (first: frame %d, type %d: y %s u %s v %s%s)", k, f.pictureType, + tostring(ref and y == ref[1]), tostring(ref and cb == ref[2]), tostring(ref and cr == ref[3]), detail) + end + end + end + end + local dt = os.clock() - t0 + t:eq(n, fx.frames, name .. ": frame count") + t:eq(bad, 0, name .. ": frames differing from ffmpeg" .. msg) + t:eq(dec.stats.errors, 0, name .. ": no damaged pictures") + total += n + t:note(" %-16s %4dx%-4d %3d frames %6.1f fps (with the checks)", name, fx.width, fx.height, n, n / dt) +end +t:check(disposables > 0, "disposable Sorenson pictures decoded (" .. disposables .. ")") + +-- 2. header info +do + local fx = STREAMS[8] -- plus_custom + local file = b64(fx.file) + local h = assert(H263.header(file, fx.units[1][1], fx.units[1][2])) + t:check(h.plus and h.width == 320 and h.height == 240 and h.ptype == 1, "plus_custom: PLUSPTYPE custom size, I picture") + local h2 = assert(H263.header(file, fx.units[2][1], fx.units[2][2])) + t:check(h2.ptype == 2, "plus_custom: second picture P") + fx = STREAMS[14] -- flv_odd + file = b64(fx.file) + h = assert(H263.header(file, fx.units[1][1], fx.units[1][2], true)) + t:check(h.flv and h.width == 100 and h.height == 75 and h.version == 1, "flv_odd: Sorenson 8-bit custom size, version 1") + fx = STREAMS[1] + h = assert(H263.header(b64(fx.file), 0, fx.units[1][2])) + t:check(not h.plus and h.width == 176 and h.height == 144, "qcif: PTYPE QCIF") + local _, e = H263.header(buffer.create(16)) + t:check(e ~= nil and e.code == Err.CORRUPT, "no start code: CORRUPT") +end + +-- 3. unsupported H.263+ options +for name, data in BAD do + local dec = H263.new() + local f, e = dec:decode(b64(data)) + t:check(f == nil and e ~= nil and e.code == Err.UNSUPPORTED, name .. ": UNSUPPORTED (" .. tostring(e) .. ")") +end + +-- 4. frameImage +do + local fx = STREAMS[14] + local dec = H263.new({ flv = true }) + local file = b64(fx.file) + local f = assert(dec:decode(file, fx.units[1][1], fx.units[1][2])) + local img = assert(H263.frameImage(f)) + t:check(img.format == "yuv420p" and img.width == 100 and img.height == 75, "frameImage: yuv420p 100x75") + t:eq(buffer.len(img.pixels), 100 * 75 + 2 * 50 * 38, "frameImage: plane sizes") + t:eq(Crc32.of(img.pixels, 0, 100 * 75), fx.crcs[1][1], "frameImage: luma equals ffmpeg's") + t:eq(img.meta.yuv.range, "limited", "frameImage: limited range") + t:eq(img.meta.source.format, "flv1", "frameImage: meta.source.format") + t:check(H263.frameImage({} :: any) == nil, "frameImage of a non-frame is nil") + t:check(dec:decode(42 :: any) == nil, "decode of a non-buffer is nil") +end + +-- 5. the registry's decoders +do + t:check(Video.fromFourcc("H263") == "h263" and Video.fromFourcc("s263") == "h263" and Video.fromFourcc("FLV1") == "flv1", "registry names") + t:check(Video.canDecode("h263") and Video.canDecode("flv1"), "registry decoders") + for _, idx in { 2, 15 } do + local fx = STREAMS[idx] + local file = b64(fx.file) + local dec = assert(Video.decoder({ id = 1, kind = "video", codec = if fx.flv then "flv1" else "h263", timescale = 25, width = fx.width, height = fx.height } :: any)) + local frames, same = 0, true + for i, u in fx.units do + local d = buffer.create(u[2]) + buffer.copy(d, 0, file, u[1], u[2]) + local e = dec:decode({ track = 1, pts = i, keyframe = i == 1, data = d } :: any) + t:check(e == nil, fx.name .. ": registry decode " .. tostring(e)) + while true do + local img, pts = dec:receive() + if not img then + break + end + frames += 1 + same = same and pts == i and img.meta.yuv ~= nil and Crc32.of(img.pixels, 0, fx.width * fx.height) == fx.crcs[frames][1] + end + end + t:eq(frames, fx.frames, fx.name .. ": registry frame count") + t:check(same, fx.name .. ": registry frames equal ffmpeg's") + dec:reset() + local p = buffer.create(fx.units[2][2]) + buffer.copy(p, 0, file, fx.units[2][1], fx.units[2][2]) + t:check(dec:decode({ track = 1, pts = 2, keyframe = false, data = p } :: any) ~= nil, fx.name .. ": a P picture after reset is an error") + end +end + +-- 6. robustness: truncated and corrupted pictures, garbage (never throws), the fuzz pass +do + local samples = {} + for _, idx in { 1, 6, 8, 10, 11, 13, 16 } do + local fx = STREAMS[idx] + local file = b64(fx.file) + for k = 1, 2 do + local u = fx.units[k] + local b = buffer.create(u[2]) + buffer.copy(b, 0, file, u[1], u[2]) + table.insert(samples, { b, fx.flv }) + end + end + local threw, damaged = 0, 0 + for round = 1, 40 do + local s = samples[1 + round % #samples] + local src = s[1] + local n = if round % 3 == 0 then rand(buffer.len(src)) else buffer.len(src) + local b = buffer.create(n) + buffer.copy(b, 0, src, 0, n) + for _ = 1, 1 + round % 7 do + local i = 4 + rand(math.max(1, n - 4)) - 1 + if i < n then + buffer.writeu8(b, i, bit32.bxor(buffer.readu8(b, i), bit32.lshift(1, rand(8) - 1))) + end + end + local ok = pcall(function() + local dec = H263.new({ flv = s[2] }) + dec:decode(src) + dec:decode(b) + dec:decode(b) + damaged += dec.stats.errors + end) + if not ok then + threw += 1 + end + end + t:eq(threw, 0, "corrupted pictures never throw") + t:check(damaged > 0, "corrupted pictures are counted (" .. damaged .. ")") + local fuzz = {} + for _, s in samples do + table.insert(fuzz, s[1]) + end + t:fuzz("decode", function(b: buffer) + local dec = H263.new({ flv = buffer.len(b) > 2 and bit32.band(buffer.readu8(b, 2), 0x04) ~= 0 }) + local f = dec:decode(b) + dec:decode(b) + return f + end, fuzz, { mutations = 40, garbage = 20 }) +end + +t:note(" %d frames bit-exact with ffmpeg -idct int", total) +t:done() diff --git a/tests/video/flv.luau b/tests/video/flv.luau new file mode 100644 index 0000000..70d9e01 --- /dev/null +++ b/tests/video/flv.luau @@ -0,0 +1,235 @@ +-- video/flv tests: FLV files from ffmpeg (Sorenson Spark + MP3 / PCM s16 / PCM u8 / ADPCM / Nellymoser / Speex / +-- A-law, H.264 with B-frames + AAC, Flash screen video, audio only): tracks and every packet against ffprobe +-- (composition times in the pts, keyframes), onMetaData, frames against ffmpeg (Sorenson bit-exact, H.264 PSNR), audio +-- through the api hook (PCM exact; ADPCM / Nellymoser / Speex known but UNSUPPORTED), seeking; crafted VP6 / +-- enhanced FourCC / encrypted / truncated files; our writer (FLV, MP4, Matroska sources) read back by ffprobe and +-- ffmpeg (tools/fixtures/flv.py) and by our demuxer with the source's packets; fuzz. Fixtures: tools/fixtures/flv.py. +local T = require("@tests/T") +local C = require("@tests/video/_common") +local F = require("@formats") +local Flv = require("@formats/video/flv") +local Video = require("@formats/codecs/video/Video") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Fx = require("@tests/gen/flv_cases") +local Mx = require("@tests/gen/flv_mux") +local Src = require("@tests/gen/flv_src") + +local t = T.suite("flv") +t:eq(Flv.name, "flv", "name") +t:eq(Flv.category, "video", "category") + +local EXACT_AUDIO = { pcm_s16le = true, pcm_u8 = true, pcm_alaw = true } +local NO_AUDIO_FORMAT = { adpcm_swf = true, nellymoser = true, speex = true } +local byName = {} +for _, c in Fx do + byName[c.name] = c +end + +-- every frame's CRC against ffmpeg's (codecs we decode bit-exactly), else PSNR +local function frames(v: any, c: any, label: string) + if v.codec == "flv1" then + v:reset() + local n, bad = 0, 0 + while true do + local f, err = v:nextFrame() + if not f then + t:check(err == nil, label .. ": decode error " .. tostring(err)) + break + end + n += 1 + if Crc32.of(f.image.pixels) ~= c.frames[n] then + bad += 1 + end + end + t:eq(n, #c.frames, label .. ": frame count") + t:eq(bad, 0, label .. ": Sorenson frames bit-exact with ffmpeg") + else + C.frames(t, v, c, label, 38) + end +end + +for _, c in Fx do + local label = c.name + t:check(Flv.sniff(Bytes.reader(buffer.fromstring(c.data))) == 1, label .. ": sniff") + local v, err = C.open(c.data) + t:check(v ~= nil, label .. ": open " .. tostring(err)) + if v then + local dmx = v.demuxer + t:eq(#dmx.tracks, #c.streams, label .. ": track count") + C.packets(t, dmx, c, label) + for i, s in c.streams do + local tr = dmx.tracks[i] + if s.kind == "video" then + t:check(tr.width == s.width and tr.height == s.height, label .. ": video size " .. tostring(tr.width) .. "x" .. tostring(tr.height)) + t:check(tr.codec == s.codec, label .. ": video codec " .. tr.codec .. " (" .. s.codec .. ")") + elseif s.rate then + t:check(tr.sampleRate == s.rate and tr.channels == s.channels, label .. ": audio " .. tostring(tr.sampleRate) .. " Hz x " .. tostring(tr.channels)) + end + end + local md = dmx.meta.metadata + t:check(md ~= nil and type(md.duration) == "number" and md.duration > 0, label .. ": onMetaData duration") + if c.frames then + frames(v, c, label) + C.seek(t, v, c, label, 0.5) + elseif dmx:track("video") then + local _, e = v:nextFrame() + t:check(e ~= nil and e.code == F.Err.UNSUPPORTED and not Video.canDecode(v.codec), label .. ": " .. v.codec .. " is known, decoding UNSUPPORTED") + end + local at = dmx:track("audio") + if at then + if NO_AUDIO_FORMAT[at.codec] then + t:check(v.audio == nil and v.audioError and v.audioError.code == F.Err.UNSUPPORTED, label .. ": " .. at.codec .. " audio UNSUPPORTED (" .. tostring(v.audioError) .. ")") + else + C.audio(t, v, c, label, EXACT_AUDIO[at.codec], 30) + end + end + end +end + +-- details: H.264 config and composition times, metadata, screen video size +do + local v = assert(C.open(byName["h264_aac.flv"].data)) + local vt, at = v.demuxer:track("video"), v.demuxer:track("audio") + t:check(vt.config ~= nil and buffer.readu8(vt.config, 0) == 1, "h264: avcC in track.config") + t:check(at.config ~= nil and buffer.len(at.config) >= 2, "h264: AudioSpecificConfig in track.config") + local reordered = false + for k = 1, v.demuxer:count(vt.id) do + local p = v.demuxer:get(vt.id, k) + if p and p.pts ~= p.dts then + reordered = true + end + end + t:check(reordered, "h264: B-frame composition times in the pts") + t:eq(v.frameRate, 12, "h264: frame rate from onMetaData") + local md = v.demuxer.meta.metadata + t:check(md.width == 160 and md.height == 120 and md.videocodecid == 7 and md.audiocodecid == 10, "onMetaData: width, height, codec ids") + t:check(type(md.encoder) == "string", "onMetaData: encoder string") + local s = assert(C.open(byName["screen.flv"].data)) + t:check(s.codec == "flashsv" and s.width == 64 and s.height == 48, "screen video: known codec, size from its first packet") +end + +-- crafted files: VP6 (known, UNSUPPORTED, size from its key frame header), an enhanced FourCC tag, encrypted tags, +-- truncation, not FLV +local function flv(tags: { { any } }): buffer + local w = Bytes.writer(256) + w:string("FLV") + w:u8(1) + w:u8(1) + w:u32be(9) + w:u32be(0) + for _, tg in tags do + local body: string = tg[3] + w:u8(tg[1]) + w:u24be(#body) + w:u24be(tg[2]) + w:u8(0) + w:u24be(0) + w:string(body) + w:u32be(11 + #body) + end + return w:finish() +end +do + -- VP6: frame type 1 / codec 4, adjustment 0x00, key frame header (marker 0, profile 3: no offset), 2 x 3 MBs + local key = "\20\0" .. "\0\6" .. "\2\3\2\3" .. string.rep("\0", 8) + local inter = "\36\0" .. "\128" .. string.rep("\0", 8) + local b = flv({ { 9, 0, key }, { 9, 40, inter }, { 9, 80, key } }) + local v = assert(F.video.open(b)) + t:check(v.codec == "vp6f" and v.width == 48 and v.height == 32, "vp6: codec vp6f, " .. v.width .. "x" .. v.height .. " from its header") + t:check(v.track.config ~= nil and buffer.len(v.track.config) == 1, "vp6: the adjustment byte as config") + t:eq(v.demuxer:count(1), 3, "vp6: packets") + local p = assert(v.demuxer:get(1, 1)) + t:check(buffer.len(p.data) == #key - 2 and p.keyframe, "vp6: packet after the adjustment byte, keyframe") + t:check(not assert(v.demuxer:get(1, 2)).keyframe, "vp6: inter frame") + local _, e = v:nextFrame() + t:check(e ~= nil and e.code == F.Err.UNSUPPORTED, "vp6: decoding UNSUPPORTED") + v.demuxer:seek(0.06) + t:eq(assert(v.demuxer:read(1)).pts, 0, "vp6: seek to the keyframe before") + -- remux of a copied VP6 track keeps the adjustment byte + local out = assert(F.save(v.demuxer, nil, { format = "flv" })) + local v2 = assert(F.video.open(out)) + t:check(v2.codec == "vp6f" and v2.demuxer:count(1) == 3 and buffer.tostring(assert(v2.demuxer:get(1, 1)).data) == buffer.tostring(p.data), "vp6: remuxed") + + -- enhanced FLV: an hvc1 sequence start and coded frames (with composition time) + local hv = flv({ { 9, 0, "\144hvc1" .. "\1\2\3" }, { 9, 0, "\145hvc1" .. "\0\0\40" .. "\9\9" }, { 9, 40, "\163hvc1" .. "\7\7\7" } }) + local h = assert(Flv.demux(Bytes.reader(hv))) + local vt = assert(h:track("video")) + t:check(vt.codec == "hevc" and vt.config ~= nil and buffer.len(vt.config) == 3, "enhanced: hvc1 -> hevc, sequence start as config") + local p1, p2 = assert(h:get(1, 1)), assert(h:get(1, 2)) + t:check(p1.pts == 40 and p1.dts == 0 and buffer.len(p1.data) == 2 and p1.keyframe, "enhanced: coded frames with composition time") + t:check(p2.pts == 40 and buffer.len(p2.data) == 3 and not p2.keyframe, "enhanced: coded frames X") + + -- encrypted audio tags: the track says why + local enc = flv({ { 8 + 32, 0, "\47\1\2\3" } }) + local d = assert(Flv.demux(Bytes.reader(enc))) + t:check(d:track("audio").unsupported ~= nil and d:count(2) == 0, "encrypted tags: dropped, track.unsupported") + + -- truncated: the tags before the cut + local full = buffer.fromstring(byName["sorenson_mp3.flv"].data) + local cut = buffer.create(buffer.len(full) // 2) + buffer.copy(cut, 0, full, 0, buffer.len(cut)) + local tr = assert(Flv.demux(Bytes.reader(cut))) + t:check(tr.meta.truncated == true and tr:count(1) > 0, "truncated file: meta.truncated, packets before the cut") + local _, e2 = Flv.demux(Bytes.reader(buffer.fromstring("RIFF0000AVI LIST"))) + t:check(e2 ~= nil and e2.code == F.Err.CORRUPT, "not FLV: CORRUPT") +end + +-- our writer: read back by ffprobe / ffmpeg (fixtures) and by our demuxer, packets equal to the source's +local SOURCES = { mp4 = Src.mp4, mkv = Src.mkv, ts = Src.ts } +for _, c in Mx do + local label = "write " .. c.name + if c.err then + t:check(c.source == "ts" and string.find(c.err, "UNSUPPORTED", 1, true) ~= nil, label .. ": " .. c.err) + else + local v = assert(C.open(c.data)) + t:eq(#v.demuxer.tracks, #c.streams, label .. ": ffprobe sees the same tracks") + C.packets(t, v.demuxer, c, label) + if c.frames then + frames(v, c, label) + end + local at = v.demuxer:track("audio") + if at then + C.audio(t, v, c, label, EXACT_AUDIO[at.codec], 30) + end + -- the source's packets, byte for byte + local src = assert(C.open(SOURCES[c.source] or byName[c.source].data)) + local a, b = src.demuxer, v.demuxer + local same = true + for _, kind in { "video", "audio" } do + local ta, tb = a:track(kind), b:track(kind) + if (ta == nil) ~= (tb == nil) then + same = false + elseif ta and tb then + if a:count(ta.id) ~= b:count(tb.id) then + same = false + else + for k = 1, a:count(ta.id) do + local p, q = assert(a:get(ta.id, k)), assert(b:get(tb.id, k)) + if buffer.tostring(p.data) ~= buffer.tostring(q.data) or p.keyframe ~= q.keyframe then + same = false + end + end + end + end + end + if c.name == "ts_aac.flv" then + -- MPEG-TS AAC: ADTS frames re-framed as raw frames with a made AudioSpecificConfig + local bt = assert(b:track("audio")) + t:check(bt.codec == "aac" and bt.config ~= nil and b:count(bt.id) > a:count(assert(a:track("audio")).id), label .. ": ADTS split into raw AAC frames") + else + t:check(same, label .. ": the source's packets (" .. c.source .. ")") + end + local md = b.meta.metadata + t:check(md and md.encoder == "formats-luau" and md.filesize == #c.data, label .. ": onMetaData encoder and file size") + end +end + +-- fuzz +local samples = {} +for _, n in { "sorenson_mp3.flv", "h264_aac.flv", "sorenson_pcm.flv", "screen.flv" } do + local d = byName[n].data + table.insert(samples, string.sub(d, 1, math.min(#d, 30000))) +end +t:fuzz("open", C.fuzzOpen(Flv), samples, { mutations = 6, garbage = 100 }) +t:done() diff --git a/tools/bench.luau b/tools/bench.luau index 6b3d544..7e1ef28 100644 --- a/tools/bench.luau +++ b/tools/bench.luau @@ -1736,3 +1736,37 @@ do end print(string.format("%-8s %-30s %8.2f ms %7.1f x realtime", runtime, "render 669 / med", best * 1000, frames / 44100 / best)) end +-- ------------------------------------------------------------------------------------------- ws-video2-flv: fps +do + -- H.263 / Sorenson Spark (codecs/video/H263, tools/fixtures/h263.py): CIF mandelbrot zooms (1 Mbit/s, an I picture + -- every 12), one picture per decode, planes only (frameImage copies excluded) and with the yuv420p Image copies + local H263 = require("@formats/codecs/video/H263") + local Base64 = require("@formats/core/Base64") + local HB = require("@tests/gen/h263_bench") + local function run(tag: string) + for _, c in HB do + local file = Base64.decode(c.file) :: buffer + for _, images in { false, true } do + local n = #c.units + local dt = bench(string.format("%s %dx%d%s%s", c.name, c.width, c.height, if images then " +img" else "", tag), 3, c.width * c.height * 3 // 2 * n, function() + local dec = H263.new({ flv = c.flv }) + for _, u in c.units do + if images then + dec:image(file, u[1], u[2]) + else + dec:decode(file, u[1], u[2]) + end + end + end) + print(string.format("%-8s %-30s %8.1f fps", runtime, " (" .. n .. " frames)", n / dt)) + end + end + end + jitTune(false) + run("") + if runtime == "luajit" then + jitTune(true) + run(" (jit tuned)") + jitTune(false) + end +end diff --git a/tools/fixtures/_flv_encode.luau b/tools/fixtures/_flv_encode.luau new file mode 100644 index 0000000..70ac28b --- /dev/null +++ b/tools/fixtures/_flv_encode.luau @@ -0,0 +1,43 @@ +-- tools/fixtures/_flv_encode: run by tools/fixtures/flv.py (luau, from the repo root) so ffprobe / ffmpeg can check our +-- FLV writer: remuxes FLV fixtures (tests/gen/flv_cases) and the MP4 / Matroska / MPEG-TS sources (tests/gen/flv_src) +-- and prints " " lines (or " ERR "). +local F = require("@formats") +local Cases = require("@tests/gen/flv_cases") +local Src = require("@tests/gen/flv_src") + +local function hex(b: buffer): string + local t = table.create(buffer.len(b)) + for i = 0, buffer.len(b) - 1 do + t[i + 1] = string.format("%02x", buffer.readu8(b, i)) + end + return table.concat(t) +end + +local function find(name: string): string + for _, c in Cases do + if c.name == name then + return c.data + end + end + error("no fixture " .. name) +end + +local JOBS = { + { "remux_h264_aac.flv", "h264_aac.flv", find("h264_aac.flv") }, + { "remux_sorenson_mp3.flv", "sorenson_mp3.flv", find("sorenson_mp3.flv") }, + { "remux_pcm.flv", "sorenson_pcm.flv", find("sorenson_pcm.flv") }, + { "remux_screen.flv", "screen.flv", find("screen.flv") }, + { "mp4_h264_aac.flv", "mp4", Src.mp4 }, + { "mkv_h264_mp3.flv", "mkv", Src.mkv }, + { "ts_h264_aac.flv", "ts", Src.ts }, + { "ts_aac.flv", "ts", Src.ts, { video = false } }, -- ADTS AAC re-framed +} +for _, j in JOBS do + local name, source, data = j[1], j[2], j[3] + local out, err = F.convert(buffer.fromstring(data), "flv", j[4]) + if out then + print(name .. " " .. source .. " " .. hex(out)) + else + print(name .. " " .. source .. " ERR " .. tostring(err)) + end +end diff --git a/tools/fixtures/docs_flv.py b/tools/fixtures/docs_flv.py new file mode 100644 index 0000000..347b850 --- /dev/null +++ b/tools/fixtures/docs_flv.py @@ -0,0 +1,29 @@ +# Docs inputs for the FLV / H.263 sections of docs/guide/video.md (tools/fixtures.py; tools/docs_check.py reads them): +# tiny ffmpeg clips (testsrc 64x48, 10 frames at 10 fps, with a sine track): FLV with Sorenson Spark + MP3, a 3GP with +# H.263 (QCIF, the H.263 size closest to the clip) and AAC. +# tests/gen/docs_flv.luau { files = { [name] = bytes }, vars = { flvBytes = "clip.flv", h263Bytes = "clip.3gp" } } +import importlib.util, os, shutil, subprocess, tempfile + +INPUTS = ["tools/docs_check.py"] + + +def generate(ctx): + spec = importlib.util.spec_from_file_location("docs_flv_check", os.path.join(ctx.root, "tools", "docs_check.py")) + dc = importlib.util.module_from_spec(spec) + spec.loader.exec_module(dc) + files = {} + with tempfile.TemporaryDirectory() as d: + for name, size, codec in ( + ("clip.flv", "64x48", ["-c:v", "flv", "-g", "5", "-c:a", "libmp3lame", "-b:a", "64k"]), + ("clip.3gp", "176x144", ["-c:v", "h263", "-g", "5", "-c:a", "aac", "-b:a", "32k", "-ar", "22050"]), + ): + src = ["-f", "lavfi", "-i", "testsrc=size=%s:rate=10:duration=1" % size, + "-f", "lavfi", "-i", "sine=frequency=440:sample_rate=44100:duration=1"] + out = os.path.join(d, name) + argv = ["-v", "error", "-y"] + src + codec + ["-shortest", out] + if shutil.which("ffmpeg"): + subprocess.run(["ffmpeg"] + argv, check=True, capture_output=True) + else: + ctx.nix("ffmpeg", ["ffmpeg"] + argv) + files[name] = open(out, "rb").read() + dc.emit_inputs(ctx, files, {"flvBytes": "clip.flv", "h263Bytes": "clip.3gp"}) diff --git a/tools/fixtures/flv.py b/tools/fixtures/flv.py new file mode 100644 index 0000000..53267cb --- /dev/null +++ b/tools/fixtures/flv.py @@ -0,0 +1,86 @@ +# FLV fixtures (tools/fixtures.py): files made by ffmpeg (Sorenson Spark + MP3 / PCM s16 / PCM u8 / Flash ADPCM / +# Nellymoser / Speex / A-law, H.264 with B-frames + AAC, Flash screen video), with ffprobe's streams and packets, +# ffmpeg's frames (CRC-32 of `-flags +bitexact -idct int` decoding; the first two raw) and audio (f32); then our FLV +# writer (tools/fixtures/_flv_encode.luau) remuxes FLV, MP4, Matroska and MPEG-TS sources and each output is probed, +# decoded and emitted the same way, so the test can read our files with our demuxer and compare them with ffmpeg's view. +# tests/gen/flv_cases.luau { { name, data, streams, packets, frames, yuv, pcm, pcmBytes } } +# tests/gen/flv_src.luau { mp4 = H.264 + AAC MP4, mkv = H.264 + MP3 Matroska, ts = H.264 + AAC MPEG-TS } +# tests/gen/flv_mux.luau { { name, source, data, streams, packets, frames, pcm, pcmBytes } | { name, err } } +import importlib.util, os, shutil, subprocess, tempfile + +_spec = importlib.util.spec_from_file_location("_video_helpers", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_video.py")) +V = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(V) + +INPUTS = ["tools/fixtures/_video.py", "tools/fixtures/_flv_encode.luau", "src/Formats/video/flv", "src/Formats/codecs/video/Video"] + +SRC = ["-f", "lavfi", "-i", "testsrc2=size=160x120:rate=12"] + + +def aud(rate, ch=1, freq=550): + return ["-f", "lavfi", "-i", "sine=frequency=%d:sample_rate=%d" % (freq, rate), "-ac", str(ch)] + + +def case(tmp, name, decode_audio=True): + path = os.path.join(tmp, name) + c = {"name": name, "data": open(path, "rb").read(), "streams": V.streams(path), "packets": V.packets(path)} + vs = [s for s in c["streams"] if s["kind"] == "video"] + if vs and vs[0]["codec"] in ("flv1", "h264"): + w, h = vs[0]["width"], vs[0]["height"] + raw = V.ffmpeg(["-flags", "+bitexact", "-idct", "int", "-i", path, "-map", "0:v:0", "-fps_mode", "passthrough", "-f", + "rawvideo", "-pix_fmt", "yuv420p", "-"]) + n = w * h + 2 * ((w + 1) // 2) * ((h + 1) // 2) + frames = [raw[i:i + n] for i in range(0, len(raw) - n + 1, n)] + c["frames"] = [V.crc(f) for f in frames] + c["yuv"] = frames[:2] + if decode_audio and any(s["kind"] == "audio" for s in c["streams"]): + pcm = V.pcm_f32(path) + c["pcm"] = pcm[:8192 * 4] + c["pcmBytes"] = len(pcm) + return c + + +def generate(ctx): + tmp = tempfile.mkdtemp(prefix="flvfx_") + ff = lambda *a: V.ffmpeg(list(a), cwd=tmp) + ff(*SRC, *aud(44100), "-t", "1", "-c:v", "flv", "-b:v", "300k", "-g", "6", "-c:a", "libmp3lame", "-b:a", "64k", "sorenson_mp3.flv") + ff(*SRC, *aud(44100), "-t", "1", "-c:v", "libx264", "-preset", "veryfast", "-bf", "2", "-g", "6", "-c:a", "aac", "-b:a", "96k", + "h264_aac.flv") + ff(*SRC, *aud(22050, 2), "-t", "1", "-c:v", "flv", "-g", "12", "-c:a", "pcm_s16le", "sorenson_pcm.flv") + ff(*SRC, *aud(11025), "-t", "1", "-c:v", "flv", "-g", "12", "-c:a", "pcm_u8", "sorenson_pcm8.flv") + ff(*SRC, *aud(22050), "-t", "0.5", "-c:v", "flv", "-c:a", "adpcm_swf", "sorenson_adpcm.flv") + ff(*SRC, *aud(22050), "-t", "0.5", "-c:v", "flv", "-c:a", "nellymoser", "sorenson_nelly.flv") + ff(*SRC, *aud(16000), "-t", "0.5", "-c:v", "flv", "-c:a", "libspeex", "sorenson_speex.flv") + ff(*SRC, *aud(8000), "-t", "0.5", "-c:v", "flv", "-c:a", "pcm_alaw", "sorenson_alaw.flv") + ff("-f", "lavfi", "-i", "testsrc2=size=64x48:rate=10", "-t", "0.5", "-c:v", "flashsv", "screen.flv") + ff(*aud(44100, 2), "-t", "0.5", "-c:a", "libmp3lame", "audio_only.flv") + names = ["sorenson_mp3.flv", "h264_aac.flv", "sorenson_pcm.flv", "sorenson_pcm8.flv", "sorenson_adpcm.flv", + "sorenson_nelly.flv", "sorenson_speex.flv", "sorenson_alaw.flv", "screen.flv", "audio_only.flv"] + cases = [case(tmp, n) for n in names] + ctx.emit("flv_cases", cases) + + # sources for the writer + ff(*SRC, *aud(44100), "-t", "1", "-c:v", "libx264", "-preset", "veryfast", "-bf", "2", "-g", "6", "-c:a", "aac", "src.mp4") + ff(*SRC, *aud(44100, 2), "-t", "1", "-c:v", "libx264", "-preset", "veryfast", "-bf", "0", "-g", "12", "-c:a", "libmp3lame", + "src.mkv") + ff(*SRC, *aud(44100), "-t", "1", "-c:v", "libx264", "-preset", "veryfast", "-c:a", "aac", "src.ts") + srcs = {k: open(os.path.join(tmp, "src." + k), "rb").read() for k in ("mp4", "mkv", "ts")} + ctx.emit("flv_src", srcs) + + luau = os.environ.get("LUAU") or shutil.which("luau") + cmd = [luau, "tools/fixtures/_flv_encode.luau"] if luau else ["nix", "shell", "nixpkgs#luau", "-c", "luau", "tools/fixtures/_flv_encode.luau"] + out = subprocess.run(cmd, capture_output=True, check=True, cwd=ctx.root).stdout.decode() + mux = [] + for line in out.split("\n"): + if not line.strip(): + continue + name, source, rest = line.split(" ", 2) + if rest.startswith("ERR "): + mux.append({"name": name, "source": source, "err": rest[4:]}) + continue + open(os.path.join(tmp, name), "wb").write(bytes.fromhex(rest)) + c = case(tmp, name) + c["source"] = source + c.pop("yuv", None) + mux.append(c) + ctx.emit("flv_mux", mux) diff --git a/tools/fixtures/h263.py b/tools/fixtures/h263.py new file mode 100644 index 0000000..d78f4dd --- /dev/null +++ b/tools/fixtures/h263.py @@ -0,0 +1,190 @@ +# H.263 / Sorenson Spark fixtures for codecs/video/H263 (tools/fixtures.py): streams from ffmpeg's encoders (h263: +# sub-QCIF .. 4CIF, GOB headers, adaptive quantisation (DQUANT), low and high bitrates; h263p: PLUSPTYPE with custom +# sizes, the rounding type, unrestricted vectors, slice structure; flv: Sorenson Spark with its standard, 8-bit and 16-bit custom +# sizes, 11-bit escapes, disposable inter pictures patched in), high and low motion (testsrc2, mandelbrot, scroll), +# each with `ffmpeg -flags +bitexact -idct int` decoding as the reference (the integer IDCT codecs/video/Dsp +# reproduces; bitexact: ffmpeg's x86 half-sample averages without rounding are approximations otherwise). +# tests/gen/h263_.luau { name, flv, width, height, frames, file (base64), units = { { offset, length } } (one +# picture each), crcs = { { y, u, v } } (CRC-32 of each frame's planes), first (the first +# yuv frame, base64 zlib) } +# tests/gen/h263_bad.luau { aic, obmc: one picture each with an unsupported H.263+ option (base64) } +# tests/gen/h263_bench.luau { { name, flv, width, height, file, units } }: CIF H.263 and Sorenson Spark +import base64, os, shutil, subprocess, tempfile, zlib + + +def b64(b): + return base64.b64encode(b).decode() + + +def z64(b): + return base64.b64encode(zlib.compress(b, 9)).decode() + + +FF = ["-hide_banner", "-loglevel", "error", "-y"] + + +def src(kind, w, h, t, rate=25, vf=None): + s = "%s=size=%dx%d:rate=%d" % (kind, w, h, rate) + if vf: + s += "," + vf + return ["-f", "lavfi", "-i", s, "-t", str(t)] + + +H263 = ["-c:v", "h263", "-f", "h263"] +H263P = ["-threads", "1", "-c:v", "h263p", "-f", "rawvideo"] +FLV = ["-c:v", "flv", "-f", "flv"] + +# name: (ffmpeg input + encoder args, flv) +CASES = { + "qcif": (src("testsrc2", 176, 144, 1.0) + ["-b:v", "200k", "-g", "12"] + H263, False), + "cif_mandel": (src("mandelbrot", 352, 288, 0.6) + ["-b:v", "800k", "-g", "8"] + H263, False), + "sqcif_scroll": (src("testsrc2", 128, 96, 1.0, vf="scroll=h=0.05:v=0.03") + ["-q:v", "4", "-g", "30"] + H263, False), + "qcif_q1": (src("mandelbrot", 176, 144, 0.4) + ["-qmin", "1", "-q:v", "1", "-g", "5"] + H263, False), + "qcif_aq": (src("testsrc2", 176, 144, 0.8, vf="scroll=h=0.01") + ["-b:v", "60k", "-lumi_mask", "0.3", "-dark_mask", "0.3", + "-p_mask", "0.2", "-g", "20"] + H263, False), + "cif_gob": (src("testsrc2", 352, 288, 0.6, vf="scroll=v=0.02") + ["-b:v", "500k", "-ps", "300", "-g", "10"] + H263, False), + "4cif_gob": (src("mandelbrot", 704, 576, 0.16) + ["-b:v", "2M", "-ps", "1200", "-g", "4"] + H263, False), + "plus_custom": (src("testsrc2", 320, 240, 0.8, vf="scroll=h=0.02:v=0.01") + ["-b:v", "300k", "-g", "15"] + H263P, False), + "plus_odd": (src("mandelbrot", 196, 148, 0.6) + ["-b:v", "250k", "-g", "8"] + H263P, False), + "plus_umv": (src("testsrc2", 200, 152, 0.8, vf="scroll=h=0.06:v=0.04") + ["-umv", "1", "-q:v", "5", "-g", "25"] + H263P, False), + "plus_slices": (src("mandelbrot", 352, 288, 0.48) + ["-b:v", "600k", "-g", "6"] + H263P + ["-threads", "4", "-slices", "4"], False), + "plus_slices_umv": (src("testsrc2", 176, 144, 0.8, vf="scroll=h=-0.04:v=0.05") + ["-umv", "1", "-q:v", "4", "-g", "20"] + H263P + + ["-threads", "3", "-slices", "3", "-ps", "200"], False), + "flv_320": (src("testsrc2", 320, 240, 1.0) + ["-b:v", "300k", "-g", "12"] + FLV, True), + "flv_odd": (src("mandelbrot", 100, 75, 0.6) + ["-b:v", "150k", "-g", "8"] + FLV, True), + "flv_wide": (src("testsrc2", 400, 224, 0.4, vf="scroll=h=0.03") + ["-b:v", "400k", "-g", "6"] + FLV, True), + "flv_q1": (src("mandelbrot", 160, 120, 0.4) + ["-qmin", "1", "-q:v", "1", "-g", "4"] + FLV, True), + "flv_scroll": (src("testsrc2", 176, 144, 1.0, vf="scroll=h=0.05:v=-0.04") + ["-q:v", "6", "-g", "50"] + FLV, True), +} + + +def h263_units(es): + starts = [] + i = 0 + while True: + i = es.find(b"\x00\x00", i) + if i < 0 or i + 2 >= len(es): + break + if es[i + 2] & 0xFC == 0x80: + starts.append(i) + i += 3 + else: + i += 1 + return [[s, (starts[k + 1] if k + 1 < len(starts) else len(es)) - s] for k, s in enumerate(starts)] + + +def flv_tags(data): + """the video tags of an FLV file: [(offset of the tag header, payload offset, payload length)]""" + p = int.from_bytes(data[5:9], "big") + 4 + out = [] + while p + 11 <= len(data): + kind = data[p] & 0x1F + size = int.from_bytes(data[p + 1:p + 4], "big") + if kind == 9 and size > 1: + out.append((p, p + 12, size - 1)) + p += 11 + size + 4 + return out + + +def flv_disposable(data): + """every third inter picture of a Sorenson FLV marked disposable (tag frame type 3, picture type 2)""" + b = bytearray(data) + inter = 0 + for tag, off, n in flv_tags(data): + if b[tag + 11] >> 4 != 2: + continue + inter += 1 + if inter % 3 != 0: + continue + b[tag + 11] = (3 << 4) | (b[tag + 11] & 15) + # picture size field: bits 30..32 after the start of the picture + bits = int.from_bytes(b[off:off + 8], "big") + fmt = (bits >> (64 - 33)) & 7 + p = 33 + (16 if fmt == 0 else 32 if fmt == 1 else 0) # the picture type's first bit + byte, bit = p // 8, p % 8 + word = int.from_bytes(b[off + byte:off + byte + 2], "big") + shift = 16 - bit - 2 + word = (word & ~(3 << shift)) | (2 << shift) + b[off + byte:off + byte + 2] = word.to_bytes(2, "big") + return bytes(b) + + +def generate(ctx): + ffmpeg = shutil.which("ffmpeg") or ctx.nix("ffmpeg", ["sh", "-c", "command -v ffmpeg"]).decode().strip() + ffprobe = shutil.which("ffprobe") or os.path.join(os.path.dirname(ffmpeg), "ffprobe") + + def ff(args): + subprocess.run([ffmpeg] + FF + args, check=True, capture_output=True) + + def size(path): + r = subprocess.run([ffprobe, "-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height", + "-of", "csv=p=0", path], check=True, capture_output=True) + return tuple(int(x) for x in r.stdout.decode().strip().split(",")[:2]) + + def reference(path): + out = path + ".yuv" + ff(["-flags", "+bitexact", "-idct", "int", "-i", path, "-fps_mode", "passthrough", "-f", "rawvideo", "-pix_fmt", "yuv420p", out]) + return open(out, "rb").read() + + def emit(name, path, flv): + data = open(path, "rb").read() + if flv: + tags = flv_tags(data) + file = b"".join(data[o:o + n] for _, o, n in tags) + units, o = [], 0 + for _, _, n in tags: + units.append([o, n]) + o += n + else: + file, units = data, h263_units(data) + w, h = size(path) + yuv = reference(path) + cw, ch = (w + 1) // 2, (h + 1) // 2 + fs = w * h + 2 * cw * ch + n = len(yuv) // fs + crcs = [] + for k in range(n): + f = yuv[k * fs:(k + 1) * fs] + crcs.append([zlib.crc32(f[:w * h]), zlib.crc32(f[w * h:w * h + cw * ch]), zlib.crc32(f[w * h + cw * ch:])]) + assert n == len(units), "h263 %s: %d frames for %d pictures" % (name, n, len(units)) + ctx.emit("h263_" + name, {"name": name, "flv": flv, "width": w, "height": h, "frames": n, "file": b64(file), + "units": units, "crcs": crcs, "first": z64(yuv[:fs])}) + return file, units + + with tempfile.TemporaryDirectory(prefix="formats-h263-") as tmp: + for name, (args, flv) in CASES.items(): + path = os.path.join(tmp, name + (".flv" if flv else ".h263")) + ff(args + [path]) + emit(name, path, flv) + # Sorenson disposable inter pictures (ffmpeg's encoder writes none): patched into a stream; ffmpeg's decoder + # does not keep them as references either + path = os.path.join(tmp, "disp.flv") + ff(src("testsrc2", 160, 120, 1.0, vf="scroll=h=0.02") + ["-b:v", "200k", "-g", "20"] + FLV + [path]) + patched = os.path.join(tmp, "disposable.flv") + open(patched, "wb").write(flv_disposable(open(path, "rb").read())) + emit("flv_disposable", patched, True) + + # unsupported H.263+ options: one picture each + bad = {} + for name, extra in (("aic", ["-flags", "+aic"]), ("obmc", ["-obmc", "1"])): + path = os.path.join(tmp, name + ".h263") + ff(src("testsrc2", 176, 144, 0.04) + extra + H263P + [path]) + bad[name] = b64(open(path, "rb").read()) + ctx.emit("h263_bad", bad) + + bench = [] + for name, args, flv in (("h263", H263, False), ("flv1", FLV, True)): + path = os.path.join(tmp, "bench_" + name + (".flv" if flv else ".h263")) + ff(src("mandelbrot", 352, 288, 1.2) + ["-b:v", "1M", "-g", "12"] + args + [path]) + data = open(path, "rb").read() + if flv: + tags = flv_tags(data) + file = b"".join(data[o:o + n] for _, o, n in tags) + units, o = [], 0 + for _, _, n in tags: + units.append([o, n]) + o += n + else: + file, units = data, h263_units(data) + bench.append({"name": name, "flv": flv, "width": 352, "height": 288, "file": b64(file), "units": units}) + ctx.emit("h263_bench", bench)