diff --git a/licenses/NOTICE.md b/licenses/NOTICE.md index dab5523..e8fbd68 100644 --- a/licenses/NOTICE.md +++ b/licenses/NOTICE.md @@ -24,6 +24,8 @@ | `tests/fixtures/vox/ogt_*.vox` | jpaver/opengametools `demo/vox/` (files saved by MagicaVoxel 0.99.x) | MIT: [opengametools-LICENSE.txt](opengametools-LICENSE.txt) | | `tests/fixtures/gltf/` | KhronosGroup/glTF-Sample-Assets `Models/` (one LICENSE.md per model folder; `UnicodeTest` is `Unicode❤♻Test` renamed) | CC-BY-4.0 or CC0-1.0 per model, see each folder's LICENSE.md | | `src/Formats/codecs/Vp8/` (Decode, Yuv, Tables), `src/Formats/codecs/Vp8L/Decode.luau`, `src/Formats/image/webp/` (Alpha unfilters, Anim.coalesce) | ports of libwebp 1.6.0 (Google): src/dec, src/dsp, src/utils, src/demux/anim_decode.c | BSD-3-Clause + patent grant: [libwebp-LICENSE.txt](libwebp-LICENSE.txt) | +| `src/Formats/codecs/Vp8/` inter frames (Decode: inter headers / modes / motion vectors / references, Predict, the inter tables in Tables) | Luau translations of libvpx 1.17 (WebM Project): vp8/decoder/decodeframe.c, decodemv.c, onyxd_if.c; vp8/common/findnearmv.c, reconinter.c, filter.c, vp8_loopfilter.c, entropymode.c, entropymv.c, modecont.c | BSD-3-Clause + patent grant: [libvpx-LICENSE.txt](libvpx-LICENSE.txt) | +| `tests/fixtures/vp8video/vp80-*.ivf` | the VP8 test vectors of the libvpx test data (vp80-00-comprehensive-001..018 and others) | WebM Project, BSD-3-Clause + patent grant: [libvpx-LICENSE.txt](libvpx-LICENSE.txt) | Ports of third-party code (minimp3, stb_vorbis, libopus, ...) add a row here and their upstream licence text in this folder (see docs/STYLE.md, "Absorbing an existing repo"). diff --git a/licenses/libvpx-LICENSE.txt b/licenses/libvpx-LICENSE.txt new file mode 100644 index 0000000..5a2665d --- /dev/null +++ b/licenses/libvpx-LICENSE.txt @@ -0,0 +1,56 @@ +Copyright (c) 2010, The WebM Project authors. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the + distribution. + + * Neither the name of Google, nor the WebM Project, nor the names + of its contributors may be used to endorse or promote products + derived from this software without specific prior written + permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +----- PATENTS ----- +Additional IP Rights Grant (Patents) +------------------------------------ + +"These implementations" means the copyrightable works that implement the WebM +codecs distributed by Google as part of the WebM Project. + +Google hereby grants to you a perpetual, worldwide, non-exclusive, no-charge, +royalty-free, irrevocable (except as stated in this section) patent license to +make, have made, use, offer to sell, sell, import, transfer, and otherwise +run, modify and propagate the contents of these implementations of WebM, where +such license applies only to those patent claims, both currently owned by +Google and acquired in the future, licensable by Google that are necessarily +infringed by these implementations of WebM. This grant does not include claims +that would be infringed only as a consequence of further modification of these +implementations. If you or your agent or exclusive licensee institute or order +or agree to the institution of patent litigation or any other patent +enforcement activity against any entity (including a cross-claim or +counterclaim in a lawsuit) alleging that any of these implementations of WebM +or any code incorporated within any of these implementations of WebM +constitute direct or contributory patent infringement, or inducement of +patent infringement, then any patent rights granted to you under this License +for these implementations of WebM shall terminate as of the date such +litigation is filed. diff --git a/src/Formats/codecs/Vp8/Decode.luau b/src/Formats/codecs/Vp8/Decode.luau index eacff53..a095913 100644 --- a/src/Formats/codecs/Vp8/Decode.luau +++ b/src/Formats/codecs/Vp8/Decode.luau @@ -1,16 +1,23 @@ --!strict --!native --!optimize 2 --- codecs/Vp8/Decode: the VP8 key frame decoder (RFC 6386): the boolean entropy decoder, frame / segment / filter / +-- codecs/Vp8/Decode: the VP8 frame decoder (RFC 6386): the boolean entropy decoder, frame / segment / filter / -- quantizer headers, token probability updates, intra modes, residual tokens, the inverse WHT and DCT, intra --- prediction (16x16, 4x4, chroma), and the normal and simple loop filters. A port of libwebp 1.6 src/dec/vp8_dec.c, +-- prediction (16x16, 4x4, chroma), and the normal and simple loop filters: a port of libwebp 1.6 src/dec/vp8_dec.c, -- tree_dec.c, quant_dec.c, frame_dec.c, src/dsp/dec.c and src/utils/bit_reader* (BSD-3-Clause, --- licenses/libwebp-LICENSE.txt), bit-exact with it (libwebp is deterministic; so is this). +-- licenses/libwebp-LICENSE.txt). Inter frames after libvpx 1.17 vp8/decoder/decodeframe.c, decodemv.c and +-- vp8/common/findnearmv.c, vp8_loopfilter.c (BSD-3-Clause, licenses/libvpx-LICENSE.txt): reference updates and sign +-- bias, the frame context saved around frames that do not refresh it, persistent segment maps and loop filter deltas, +-- inter modes from the near vectors, motion vectors, split macroblocks, intra macroblocks in inter frames, per +-- reference / mode loop filter levels; the prediction itself is codecs/Vp8/Predict. Bit-exact with libvpx / ffmpeg +-- (and with libwebp on key frames). Where libvpx and ffmpeg disagree on streams no encoder writes (an intermediate +-- clamp of segment filter levels, copying golden to altref and altref to golden in one frame), this follows ffmpeg. -- --- The decoder state (Decode.new) keeps what persists between frames (token probabilities, segment and filter --- headers) so inter frames can be added later for WebM: decodeFrame() returns UNSUPPORTED for them today. --- Never throws: bad data returns nil, "message" ("truncated: ..." when the data ends early). +-- The decoder state (Decode.new) keeps what persists between frames: the frame context, segment / filter headers, the +-- segment map, the last / golden / altref frames. Never throws: bad data returns nil, "message" ("truncated: ..." when +-- the data ends early). local Tables = require("@formats/codecs/Vp8/Tables") +local Predict = require("@formats/codecs/Vp8/Predict") local band, bor, rshift, lshift = bit32.band, bit32.bor, bit32.rshift, bit32.lshift local readu8, writeu8, readi16, writei16 = buffer.readu8, buffer.writeu8, buffer.readi16, buffer.writei16 @@ -105,37 +112,84 @@ end -- ------------------------------------------------------------------------------------------------ state export type Quant = { y1dc: number, y1ac: number, y2dc: number, y2ac: number, uvdc: number, uvac: number } +-- a decoded frame / reference: the macroblock aligned planes with a Predict.BORDER pixel border +export type Ref = Predict.Planes & { extended: boolean } + export type State = { - -- persistent between frames (inter frames: TODO) + -- the frame context (saved and restored around frames that do not refresh it) proba: { number }, -- 4 * 8 * 3 * 11 token probabilities + ymodeProb: { number }, -- 4 + uvmodeProb: { number }, -- 3 + mvProb: { number }, -- 2 * 19 + -- persistent between frames (reset by key frames) segProba: { number }, -- 3 useSegment: boolean, updateMap: boolean, absoluteDelta: boolean, segQuant: { number }, -- 4 segFilter: { number }, -- 4 - refLfDelta: { number }, -- 4 - modeLfDelta: { number }, -- 4 + refLfDelta: { number }, -- 4: intra, last, golden, altref + modeLfDelta: { number }, -- 4: B_PRED, zero, nearest / near / new, split + signBias: { number }, -- 4 (by reference frame + 1) + segMap: { number }, -- the segment of every macroblock width: number, height: number, + mbw: number, + mbh: number, + hasKey: boolean, -- a key frame was decoded (inter frames need one) + last: Ref?, + golden: Ref?, + alt: Ref?, + pool: { Ref }, + -- the mode info of the current inter frame, (mbw + 1) x (mbh + 1) with a zero top row and left column + miRef: { number }, + miMode: { number }, + miMvR: { number }, + miMvC: { number }, + miSubR: { number }, -- 16 per macroblock + miSubC: { number }, } function Decode.new(): State return { proba = table.clone(COEFF_PROBA0), + ymodeProb = table.clone(Tables.YMODE_PROB), + uvmodeProb = table.clone(Tables.UVMODE_PROB), + mvProb = table.clone(Tables.MV_DEFAULT), segProba = { 255, 255, 255 }, useSegment = false, updateMap = false, - absoluteDelta = true, + absoluteDelta = false, segQuant = { 0, 0, 0, 0 }, segFilter = { 0, 0, 0, 0 }, refLfDelta = { 0, 0, 0, 0 }, modeLfDelta = { 0, 0, 0, 0 }, + signBias = { 0, 0, 0, 0 }, + segMap = {}, width = 0, height = 0, + mbw = 0, + mbh = 0, + hasKey = false, + last = nil, + golden = nil, + alt = nil, + pool = {}, + miRef = {}, + miMode = {}, + miMvR = {}, + miMvC = {}, + miSubR = {}, + miSubC = {}, } end +-- reset(state): drops the references; the next frame must be a key frame +function Decode.reset(st: State) + st.hasKey = false + st.last, st.golden, st.alt = nil, nil, nil +end + -- header(buf, off, len) -> { keyFrame, profile, show, partitionLength, width, height, xscale, yscale } | nil, msg function Decode.header(buf: buffer, off: number, len: number): (any, string?) if len < 3 then @@ -779,51 +833,391 @@ local function filterLoop(b: buffer, p: number, hs: number, vs: number, size: nu end end +-- ------------------------------------------------------------------------------------------------ inter modes +local MODE_CTX = Tables.MODE_CONTEXTS +local SUB_MV_REF_PROB = Tables.SUB_MV_REF_PROB +local SPLIT_OFFSET, SPLIT_FILL, SPLIT_COUNT = Tables.SPLIT_OFFSET, Tables.SPLIT_FILL, Tables.SPLIT_COUNT +local BMODE_PROB = Tables.BMODE_PROB +local MV_UPDATE = Tables.MV_UPDATE + +-- macroblock modes (the row arrays and miMode): 0 DC, 1 TM, 2 V, 3 H (16x16 intra, libwebp's numbering), 4 B_PRED, +-- 5 ZEROMV, 6 NEARESTMV, 7 NEARMV, 8 NEWMV, 9 SPLITMV. Their loop filter mode delta index: +local MODE_LF = { 1, 1, 1, 1, 0, 1, 2, 2, 2, 3 } + +-- a 4x4 intra mode with the fixed probabilities P[o + 1 .. o + 9] (libvpx vp8_bmode_tree, libwebp's numbering) +local function readBMode(br: Br, P: { number }, o: number): number + if getBit(br, P[o + 1]) == 0 then + return 0 + elseif getBit(br, P[o + 2]) == 0 then + return 1 + elseif getBit(br, P[o + 3]) == 0 then + return 2 + elseif getBit(br, P[o + 4]) == 0 then + if getBit(br, P[o + 5]) == 0 then + return 3 + end + return if getBit(br, P[o + 6]) == 0 then 4 else 5 + elseif getBit(br, P[o + 7]) == 0 then + return 6 + elseif getBit(br, P[o + 8]) == 0 then + return 7 + end + return if getBit(br, P[o + 9]) == 0 then 8 else 9 +end + +-- one motion vector component (libvpx read_mvcomponent) with the probabilities P[o + 1 .. o + 19], in quarter pixels +local function readMvComponent(br: Br, P: { number }, o: number): number + local x + if getBit(br, P[o + 1]) == 1 then -- long: bits 0-2, then 9-4, then bit 3 (implicit when nothing above it is set) + x = getBit(br, P[o + 10]) + 2 * getBit(br, P[o + 11]) + 4 * getBit(br, P[o + 12]) + for i = 9, 4, -1 do + x += getBit(br, P[o + 10 + i]) * lshift(1, i) + end + if x < 16 or getBit(br, P[o + 13]) == 1 then + x += 8 + end + elseif getBit(br, P[o + 3]) == 0 then -- short tree + if getBit(br, P[o + 4]) == 0 then + x = getBit(br, P[o + 5]) + else + x = 2 + getBit(br, P[o + 6]) + end + elseif getBit(br, P[o + 7]) == 0 then + x = 4 + getBit(br, P[o + 8]) + else + x = 6 + getBit(br, P[o + 9]) + end + if x ~= 0 and getBit(br, P[o + 2]) == 1 then + x = -x + end + return x +end + +export type Rows = { + i4: { boolean }, -- no Y2 block (B_PRED or SPLITMV) + modes: { number }, -- 16 per macroblock: the 16x16 intra mode or the 4x4 ones + uv: { number }, + ref: { number }, -- 0 intra, 1 last, 2 golden, 3 altref + mode: { number }, -- 0..9 (see MODE_LF) + part: { number }, -- SPLITMV partitioning (0 16x8, 1 8x16, 2 8x8, 3 4x4) or -1 +} + +local nr, nc, cnt = table.create(4, 0), table.create(4, 0), table.create(4, 0) + +-- readInterMb(st, br, probs, mi, mbx, mby, rows): the modes and motion vectors of one inter frame macroblock (libvpx +-- read_mb_modes_mv with vp8_find_near_mvs); mi: its 1-based index in the mode info arrays +local function readInterMb(st: State, br: Br, probIntra: number, probLast: number, probGf: number, mi: number, mbx: number, mby: number, rows: Rows) + local miRef, miMode, miMvR, miMvC = st.miRef, st.miMode, st.miMvR, st.miMvC + local x1 = mbx + 1 + if getBit(br, probIntra) == 0 then + local P = st.ymodeProb + local ymode + if getBit(br, P[1]) == 0 then + ymode = 0 + elseif getBit(br, P[2]) == 0 then + ymode = if getBit(br, P[3]) == 0 then 2 else 3 + else + ymode = if getBit(br, P[4]) == 0 then 1 else 4 + end + local modes = rows.modes + if ymode == 4 then + for k = mbx * 16 + 1, mbx * 16 + 16 do + modes[k] = readBMode(br, BMODE_PROB, 0) + end + else + modes[mbx * 16 + 1] = ymode + end + local U = st.uvmodeProb + if getBit(br, U[1]) == 0 then + rows.uv[x1] = 0 + elseif getBit(br, U[2]) == 0 then + rows.uv[x1] = 2 + else + rows.uv[x1] = if getBit(br, U[3]) == 0 then 3 else 1 + end + rows.i4[x1] = ymode == 4 + rows.ref[x1] = 0 + rows.mode[x1] = ymode + rows.part[x1] = -1 + miRef[mi], miMode[mi], miMvR[mi], miMvC[mi] = 0, ymode, 0, 0 + return + end + local ref = 1 + if getBit(br, probLast) == 1 then + ref = 2 + getBit(br, probGf) + end + -- the near motion vectors of the above, left and above-left macroblocks, sign corrected + local bias = st.signBias + local sb = bias[ref + 1] + local a = mi - (st.mbw + 1) + local l = mi - 1 + local al = a - 1 + for k = 1, 4 do + nr[k], nc[k], cnt[k] = 0, 0, 0 + end + local n = 1 + local rf = miRef[a] + if rf ~= 0 then + local r, c = miMvR[a], miMvC[a] + if r ~= 0 or c ~= 0 then + if bias[rf + 1] ~= sb then + r, c = -r, -c + end + n = 2 + nr[2], nc[2] = r, c + end + cnt[n] += 2 + end + rf = miRef[l] + if rf ~= 0 then + local r, c = miMvR[l], miMvC[l] + if r ~= 0 or c ~= 0 then + if bias[rf + 1] ~= sb then + r, c = -r, -c + end + if r ~= nr[n] or c ~= nc[n] then + n += 1 + nr[n], nc[n] = r, c + end + cnt[n] += 2 + else + cnt[1] += 2 + end + end + rf = miRef[al] + if rf ~= 0 then + local r, c = miMvR[al], miMvC[al] + if r ~= 0 or c ~= 0 then + if bias[rf + 1] ~= sb then + r, c = -r, -c + end + if r ~= nr[n] or c ~= nc[n] then + n += 1 + nr[n], nc[n] = r, c + end + cnt[n] += 1 + else + cnt[1] += 1 + end + end + -- clamping bounds (vp8_clamp_mv2), in eighth pixels + local mbw, mbh = st.mbw, st.mbh + local toL, toR = -mbx * 128 - 128, (mbw - 1 - mbx) * 128 + 128 + local toT, toB = -mby * 128 - 128, (mbh - 1 - mby) * 128 + 128 + local mode, mvr, mvc, part = 5, 0, 0, -1 + if getBit(br, MODE_CTX[cnt[1] * 4 + 1]) == 1 then + if cnt[4] > 0 and nr[n] == nr[2] and nc[n] == nc[2] then + cnt[2] += 1 + end + if cnt[3] > cnt[2] then + cnt[2], cnt[3] = cnt[3], cnt[2] + nr[2], nr[3] = nr[3], nr[2] + nc[2], nc[3] = nc[3], nc[2] + end + local k + if getBit(br, MODE_CTX[cnt[2] * 4 + 2]) == 0 then + mode, k = 6, 2 + elseif getBit(br, MODE_CTX[cnt[3] * 4 + 3]) == 0 then + mode, k = 7, 3 + else + k = if cnt[2] >= cnt[1] then 2 else 1 + end + mvr, mvc = nr[k], nc[k] + if mvc < toL then + mvc = toL + elseif mvc > toR then + mvc = toR + end + if mvr < toT then + mvr = toT + elseif mvr > toB then + mvr = toB + end + if mode == 5 then + -- mvr, mvc: the best vector; new or split + local P = st.mvProb + local sc = (if miMode[a] == 9 then 2 else 0) + (if miMode[l] == 9 then 2 else 0) + (if miMode[al] == 9 then 1 else 0) + if getBit(br, MODE_CTX[sc * 4 + 4]) == 0 then + mode = 8 + mvr += readMvComponent(br, P, 0) * 2 + mvc += readMvComponent(br, P, 19) * 2 + else + mode = 9 + local bestR, bestC = mvr, mvc + local s, nump + if getBit(br, 110) == 1 then + if getBit(br, 111) == 1 then + s, nump = getBit(br, 150), 2 + else + s, nump = 2, 4 + end + else + s, nump = 3, 16 + end + part = s + local subR, subC = st.miSubR, st.miSubC + local sb0 = (mi - 1) * 16 + local lb, ab = (l - 1) * 16, (a - 1) * 16 + local splitL, splitA = miMode[l] == 9, miMode[a] == 9 + local count = SPLIT_COUNT[s + 1] + for j = 0, nump - 1 do + local b = SPLIT_OFFSET[s * 16 + j + 1] + local lr, lc, ar, ac + if b % 4 ~= 0 then + lr, lc = subR[sb0 + b], subC[sb0 + b] + elseif splitL then + lr, lc = subR[lb + b + 4], subC[lb + b + 4] + else + lr, lc = miMvR[l], miMvC[l] + end + if b >= 4 then + ar, ac = subR[sb0 + b - 3], subC[sb0 + b - 3] + elseif splitA then + ar, ac = subR[ab + b + 13], subC[ab + b + 13] + else + ar, ac = miMvR[a], miMvC[a] + end + local pi = ((if ar == 0 and ac == 0 then 4 else 0) + (if lr == 0 and lc == 0 then 2 else 0) + (if lr == ar and lc == ac then 1 else 0)) * 3 + local r, c + if getBit(br, SUB_MV_REF_PROB[pi + 1]) == 0 then + r, c = lr, lc + elseif getBit(br, SUB_MV_REF_PROB[pi + 2]) == 0 then + r, c = ar, ac + elseif getBit(br, SUB_MV_REF_PROB[pi + 3]) == 0 then + r, c = 0, 0 + else + r = bestR + readMvComponent(br, P, 0) * 2 + c = bestC + readMvComponent(br, P, 19) * 2 + end + local fo = s * 16 + j * count + for i = fo + 1, fo + count do + local q = sb0 + SPLIT_FILL[i] + 1 + subR[q], subC[q] = r, c + end + end + mvr, mvc = subR[sb0 + 16], subC[sb0 + 16] + end + end + end + rows.i4[x1] = mode == 9 + rows.ref[x1] = ref + rows.mode[x1] = mode + rows.part[x1] = part + miRef[mi], miMode[mi], miMvR[mi], miMvC[mi] = ref, mode, mvr, mvc +end + -- ------------------------------------------------------------------------------------------------ frame export type Frame = { width: number, height: number, - y: buffer, -- width * height - u: buffer, -- ceil(w / 2) * ceil(h / 2) - v: buffer, + ref: Ref, -- the decoded planes (the decoder keeps them as a reference: copy them out, see cropTo) header: any, } --- decodeFrame(state, buf, off, len, maxPixels) -> Frame | nil, message +local BORDER = Predict.BORDER + +local function newRef(mbw: number, mbh: number): Ref + local ys, uvs = mbw * 16 + 2 * BORDER, mbw * 8 + 2 * BORDER + return { + Y = bcreate(ys * (mbh * 16 + 2 * BORDER)), + U = bcreate(uvs * (mbh * 8 + 2 * BORDER)), + V = bcreate(uvs * (mbh * 8 + 2 * BORDER)), + ys = ys, + uvs = uvs, + yb = BORDER * ys + BORDER, + uvb = BORDER * uvs + BORDER, + mbw = mbw, + mbh = mbh, + extended = false, + } +end + +-- a frame buffer no reference uses +local function freeRef(st: State): Ref + for _, r in st.pool do + if r ~= st.last and r ~= st.golden and r ~= st.alt then + return r + end + end + local r = newRef(st.mbw, st.mbh) + table.insert(st.pool, r) + return r +end + +-- cropTo(frame, dy, oy, du, ou, dv, ov): copies the visible planes out (luma stride width, chroma ceil(width / 2)) +function Decode.cropTo(f: Frame, dy: buffer, oy: number, du: buffer, ou: number, dv: buffer, ov: number) + local r = f.ref + local w, h = f.width, f.height + local cw, chh = (w + 1) // 2, (h + 1) // 2 + local Y, U, V, ys, uvs, yb, uvb = r.Y, r.U, r.V, r.ys, r.uvs, r.yb, r.uvb + for j = 0, h - 1 do + bcopy(dy, oy + j * w, Y, yb + j * ys, w) + end + for j = 0, chh - 1 do + bcopy(du, ou + j * cw, U, uvb + j * uvs, cw) + bcopy(dv, ov + j * cw, V, uvb + j * uvs, cw) + end +end + +-- decodeFrame(state, buf, off, len, maxPixels) -> Frame | nil, message: one key or inter frame of the stream function Decode.decodeFrame(st: State, buf: buffer, off: number, len: number, maxPixels: number): (Frame?, string?) local hdr, herr = Decode.header(buf, off, len) if not hdr then return nil, herr end - if not hdr.keyFrame then - return nil, "unsupported: inter frames" + local key = hdr.keyFrame + local width, height, p, left + if key then + width, height = hdr.width, hdr.height + if width == 0 or height == 0 then + return nil, "zero frame size" + end + if width * height > maxPixels then + return nil, "limit: " .. width .. " x " .. height .. " is over maxPixels" + end + p, left = off + 10, len - 10 + else + if not st.hasKey then + return nil, "inter frame without a key frame" + end + width, height = st.width, st.height + p, left = off + 3, len - 3 end - if not hdr.show then - return nil, "unsupported: invisible frame" - end - local width, height = hdr.width, hdr.height - if width == 0 or height == 0 then - return nil, "zero frame size" - end - if width * height > maxPixels then - return nil, "limit: " .. width .. " x " .. height .. " is over maxPixels" - end - st.width, st.height = width, height - local p = off + 10 - local left = len - 10 if hdr.partitionLength > left then return nil, "truncated: first partition" end - -- key frame: reset the probabilities and the segment header - st.segProba = { 255, 255, 255 } - st.useSegment, st.updateMap, st.absoluteDelta = false, false, true - st.segQuant = { 0, 0, 0, 0 } - st.segFilter = { 0, 0, 0, 0 } + local mbw, mbh = (width + 15) // 16, (height + 15) // 16 + if key then + st.hasKey = false + if width ~= st.width or height ~= st.height then + st.width, st.height, st.mbw, st.mbh = width, height, mbw, mbh + st.last, st.golden, st.alt, st.pool = nil, nil, nil, {} + local nmi = (mbw + 1) * (mbh + 1) + st.miRef, st.miMode = table.create(nmi, 0), table.create(nmi, 0) + st.miMvR, st.miMvC = table.create(nmi, 0), table.create(nmi, 0) + st.miSubR, st.miSubC = table.create(nmi * 16, 0), table.create(nmi * 16, 0) + st.segMap = table.create(mbw * mbh, 0) + end + -- key frames reset the frame context, the segment and loop filter deltas + st.proba = table.clone(COEFF_PROBA0) + st.ymodeProb = table.clone(Tables.YMODE_PROB) + st.uvmodeProb = table.clone(Tables.UVMODE_PROB) + st.mvProb = table.clone(Tables.MV_DEFAULT) + st.segProba = { 255, 255, 255 } + st.useSegment, st.updateMap, st.absoluteDelta = false, false, false + st.segQuant = { 0, 0, 0, 0 } + st.segFilter = { 0, 0, 0, 0 } + st.refLfDelta = { 0, 0, 0, 0 } + st.modeLfDelta = { 0, 0, 0, 0 } + st.signBias = { 0, 0, 0, 0 } + end local br = newBr(buf, p, hdr.partitionLength) p += hdr.partitionLength left -= hdr.partitionLength - getValue(br, 1) -- colour space - getValue(br, 1) -- clamping type + if key then + getValue(br, 1) -- colour space + getValue(br, 1) -- clamping type + end -- segment header st.useSegment = getValue(br, 1) == 1 if st.useSegment then @@ -928,70 +1322,126 @@ function Decode.decodeFrame(st: State, buf: buffer, off: number, len: number, ma uvac = AC_TABLE[cq(q + dquvac, 127) + 1], } end - getValue(br, 1) -- refresh entropy probabilities (ignored, as libwebp does) + -- reference updates (inter frames) + local refreshGolden, refreshAlt, copyToGolden, copyToAlt = true, true, 0, 0 + if not key then + refreshGolden = getValue(br, 1) == 1 + refreshAlt = getValue(br, 1) == 1 + copyToGolden = if refreshGolden then 0 else getValue(br, 2) + copyToAlt = if refreshAlt then 0 else getValue(br, 2) + st.signBias[3] = getValue(br, 1) + st.signBias[4] = getValue(br, 1) + end + -- a frame that does not refresh the context decodes with the updates below, then the context comes back + local saved: { { number } }? = nil + if getValue(br, 1) == 0 then + saved = { table.clone(st.proba), table.clone(st.ymodeProb), table.clone(st.uvmodeProb), table.clone(st.mvProb) } + end + local refreshLast = key or getValue(br, 1) == 1 -- token probabilities local P = st.proba for i = 1, 1056 do - P[i] = if getBit(br, COEFF_UPDATE_PROBA[i]) == 1 then getValue(br, 8) else COEFF_PROBA0[i] + if getBit(br, COEFF_UPDATE_PROBA[i]) == 1 then + P[i] = getValue(br, 8) + end end local useSkip = getValue(br, 1) == 1 local skipP = if useSkip then getValue(br, 8) else 0 + local probIntra, probLast, probGf = 0, 0, 0 + if not key then + probIntra = getValue(br, 8) + probLast = getValue(br, 8) + probGf = getValue(br, 8) + if getValue(br, 1) == 1 then + for i = 1, 4 do + st.ymodeProb[i] = getValue(br, 8) + end + end + if getValue(br, 1) == 1 then + for i = 1, 3 do + st.uvmodeProb[i] = getValue(br, 8) + end + end + local M = st.mvProb + for i = 1, 38 do + if getBit(br, MV_UPDATE[i]) == 1 then + local x = getValue(br, 7) + M[i] = if x == 0 then 1 else x * 2 + end + end + end + local function fail(msg: string): (Frame?, string?) + if saved then + st.proba, st.ymodeProb, st.uvmodeProb, st.mvProb = saved[1], saved[2], saved[3], saved[4] + end + return nil, msg + end if br.eof then - return nil, "truncated: frame header" + return fail("truncated: frame header") end - -- filter strengths per segment and i4x4: { limit, ilevel, hevThresh } - local fstr: { { number } } = {} - for s = 1, 4 do - local base - if st.useSegment then - base = st.segFilter[s] - if not st.absoluteDelta then - base += level + -- loop filter levels [segment][reference][mode delta index] and, per level, the interior limit and hev threshold + local lvlTab = table.create(64, 0) + local ilTab, hevTab = table.create(64, 0), table.create(64, 0) + if filterType > 0 then + for s = 0, 3 do + local base + if st.useSegment then + base = st.segFilter[s + 1] + if not st.absoluteDelta then + base += level + end + else + base = level + end + for rf = 0, 3 do + for m = 0, 3 do + local lv = base + if useLfDelta then + lv += st.refLfDelta[rf + 1] + if rf > 0 or m == 0 then + lv += st.modeLfDelta[m + 1] + end + end + lvlTab[s * 16 + rf * 4 + m + 1] = if lv < 0 then 0 elseif lv > 63 then 63 else lv + end end - else - base = level end - for i4 = 0, 1 do - local lv = base - if useLfDelta then - lv += st.refLfDelta[1] - if i4 == 1 then - lv += st.modeLfDelta[1] + for lv = 1, 63 do + local il = lv + if sharpness > 0 then + il = rshift(il, if sharpness > 4 then 2 else 1) + if il > 9 - sharpness then + il = 9 - sharpness end end - lv = if lv < 0 then 0 elseif lv > 63 then 63 else lv - local e = { 0, 0, 0 } - if lv > 0 then - local il = lv - if sharpness > 0 then - if sharpness > 4 then - il = rshift(il, 2) - else - il = rshift(il, 1) - end - if il > 9 - sharpness then - il = 9 - sharpness - end - end - if il < 1 then - il = 1 - end - e[1] = 2 * lv + il - e[2] = il - e[3] = if lv >= 40 then 2 elseif lv >= 15 then 1 else 0 + ilTab[lv] = if il < 1 then 1 else il + if key then + hevTab[lv] = if lv >= 40 then 2 elseif lv >= 15 then 1 else 0 + else + hevTab[lv] = if lv >= 40 then 3 elseif lv >= 20 then 2 elseif lv >= 15 then 1 else 0 end - fstr[(s - 1) * 2 + i4 + 1] = e end end - -- the frame, macroblock aligned - local mbw, mbh = (width + 15) // 16, (height + 15) // 16 - local ys, uvs = mbw * 16, mbw * 8 - local Y = bcreate(ys * mbh * 16) - local U = bcreate(uvs * mbh * 8) - local V = bcreate(uvs * mbh * 8) - local topY, topU, topV = bcreate(ys), bcreate(uvs), bcreate(uvs) + -- the frame buffer (macroblock aligned, with a border) and the references + local cur = freeRef(st) + cur.extended = false + local Y, U, V, ys, uvs, yb, uvb = cur.Y, cur.U, cur.V, cur.ys, cur.uvs, cur.yb, cur.uvb + local refs: { Ref } = {} + local bil, full = hdr.profile > 0, hdr.profile == 3 + if not key then + local rl, rg, ra = st.last :: Ref, st.golden :: Ref, st.alt :: Ref + refs[1], refs[2], refs[3] = rl, rg, ra + for k = 1, 3 do + local r = refs[k] + if not r.extended then + Predict.extend(r) + r.extended = true + end + end + end + local topY, topU, topV = bcreate(mbw * 16), bcreate(mbw * 8), bcreate(mbw * 8) local yuv = bcreate(YUV_SIZE) local coeffs = bcreate(mbw * 768) local dcb = bcreate(32) @@ -1000,9 +1450,15 @@ function Decode.decodeFrame(st: State, buf: buffer, off: number, len: number, ma local intraL = table.create(4, 0) local topNz = table.create(mbw, 0) local topNzDc = table.create(mbw, 0) - local mbI4 = table.create(mbw, false) - local mbModes = table.create(mbw * 16, 0) - local mbUv = table.create(mbw, 0) + local rows: Rows = { + i4 = table.create(mbw, false), + modes = table.create(mbw * 16, 0), + uv = table.create(mbw, 0), + ref = table.create(mbw, 0), + mode = table.create(mbw, 0), + part = table.create(mbw, -1), + } + local mbI4, mbModes, mbUv, mbRef, mbMode, mbPart = rows.i4, rows.modes, rows.uv, rows.ref, rows.mode, rows.part local mbSeg = table.create(mbw, 0) local mbSkip = table.create(mbw, 0) local mbNzY = table.create(mbw, 0) @@ -1013,26 +1469,43 @@ function Decode.decodeFrame(st: State, buf: buffer, off: number, len: number, ma local fInner = table.create(mbw * mbh, 0) local fHev = table.create(mbw * mbh, 0) local segProba = st.segProba + local segMap = st.segMap + local updateMap = st.updateMap + local miMvR, miMvC, miSubR, miSubC = st.miMvR, st.miMvC, st.miSubR, st.miSubC for mby = 0, mbh - 1 do local tbr = parts[band(mby, lastPart) + 1] - -- intra modes of the row (first partition) + -- modes of the row (first partition) for k = 1, 4 do intraL[k] = 0 end for mbx = 0, mbw - 1 do - local seg = 0 - if st.updateMap then + local x1 = mbx + 1 + local si = mby * mbw + x1 + local seg + if updateMap then if getBit(br, segProba[1]) == 0 then seg = getBit(br, segProba[2]) else seg = getBit(br, segProba[3]) + 2 end + segMap[si] = seg + elseif key then + seg = 0 + segMap[si] = 0 + else + seg = segMap[si] end - mbSeg[mbx + 1] = seg - mbSkip[mbx + 1] = if useSkip then getBit(br, skipP) else 0 + mbSeg[x1] = seg + mbSkip[x1] = if useSkip then getBit(br, skipP) else 0 + if not key then + readInterMb(st, br, probIntra, probLast, probGf, (mby + 1) * (mbw + 1) + x1 + 1, mbx, mby, rows) + continue + end + mbRef[x1] = 0 + mbPart[x1] = -1 local i4 = getBit(br, 145) == 0 - mbI4[mbx + 1] = i4 + mbI4[x1] = i4 local t0 = mbx * 4 if not i4 then local ymode @@ -1042,11 +1515,13 @@ function Decode.decodeFrame(st: State, buf: buffer, off: number, len: number, ma ymode = if getBit(br, 163) == 1 then 2 else 0 end mbModes[mbx * 16 + 1] = ymode + mbMode[x1] = ymode for k = 1, 4 do intraT[t0 + k] = ymode intraL[k] = ymode end else + mbMode[x1] = 4 for y = 0, 3 do local ymode = intraL[y + 1] for x = 0, 3 do @@ -1081,15 +1556,15 @@ function Decode.decodeFrame(st: State, buf: buffer, off: number, len: number, ma end end if getBit(br, 142) == 0 then - mbUv[mbx + 1] = 0 + mbUv[x1] = 0 elseif getBit(br, 114) == 0 then - mbUv[mbx + 1] = 2 + mbUv[x1] = 2 else - mbUv[mbx + 1] = if getBit(br, 183) == 1 then 1 else 3 + mbUv[x1] = if getBit(br, 183) == 1 then 1 else 3 end end if br.eof then - return nil, "truncated: first partition (intra modes)" + return fail("truncated: first partition (modes)") end -- residuals (token partition) @@ -1103,13 +1578,14 @@ function Decode.decodeFrame(st: State, buf: buffer, off: number, len: number, ma local co = mbx * 768 bfill(coeffs, co, 0, 768) local first, acType + local dcNz = 0 if not i4 then bfill(dcb, 0, 0, 32) local ctx = topNzDc[x1] + leftNzDc local nz = getCoeffs(tbr, P, 1, ctx, q.y2dc, q.y2ac, 0, dcb, 0) - local f = if nz > 0 then 1 else 0 - topNzDc[x1] = f - leftNzDc = f + dcNz = if nz > 0 then 1 else 0 + topNzDc[x1] = dcNz + leftNzDc = dcNz if nz > 1 then transformWHT(dcb, coeffs, co) else @@ -1169,7 +1645,8 @@ function Decode.decodeFrame(st: State, buf: buffer, off: number, len: number, ma leftNz = band(outL, 255) mbNzY[x1] = nzY mbNzUv[x1] = nzUv - skip = if nzY == 0 and nzUv == 0 then 1 else 0 + -- no coefficient at all (libvpx: eobtotal == 0) skips the inner edges of the loop filter + skip = if nzY == 0 and nzUv == 0 and dcNz == 0 then 1 else 0 else topNz[x1] = 0 leftNz = 0 @@ -1181,19 +1658,24 @@ function Decode.decodeFrame(st: State, buf: buffer, off: number, len: number, ma mbNzUv[x1] = 0 end if filterType > 0 then - local e = fstr[mbSeg[x1] * 2 + (if i4 then 1 else 0) + 1] + local lv = lvlTab[mbSeg[x1] * 16 + mbRef[x1] * 4 + MODE_LF[mbMode[x1] + 1] + 1] local fi = mby * mbw + x1 - fLimit[fi] = e[1] - fIlevel[fi] = e[2] - fHev[fi] = e[3] + if lv > 0 then + local il = ilTab[lv] + fLimit[fi] = 2 * lv + il + fIlevel[fi] = il + fHev[fi] = hevTab[lv] + else + fLimit[fi] = 0 + end fInner[fi] = if i4 or skip == 0 then 1 else 0 end if tbr.eof then - return nil, "truncated: token partition" + return fail("truncated: token partition") end end - -- reconstruct the row (libwebp ReconstructRow) + -- reconstruct the row (libwebp ReconstructRow; inter macroblocks predict from the references) for j = 0, 15 do writeu8(yuv, Y_OFF + j * BPS - 1, 129) end @@ -1212,7 +1694,11 @@ function Decode.decodeFrame(st: State, buf: buffer, off: number, len: number, ma end for mbx = 0, mbw - 1 do local x1 = mbx + 1 - if mbx > 0 then + local co = mbx * 768 + local bits = mbNzY[x1] + local rf = mbRef[x1] + if rf == 0 and mbx > 0 then + -- the left context of an intra macroblock: the previous macroblock's last columns for j = -1, 15 do bcopy(yuv, Y_OFF + j * BPS - 4, yuv, Y_OFF + j * BPS + 12, 4) end @@ -1226,37 +1712,46 @@ function Decode.decodeFrame(st: State, buf: buffer, off: number, len: number, ma bcopy(yuv, U_OFF - BPS, topU, mbx * 8, 8) bcopy(yuv, V_OFF - BPS, topV, mbx * 8, 8) end - local co = mbx * 768 - local bits = mbNzY[x1] - if mbI4[x1] then - local tr = Y_OFF - BPS + 16 - if mby > 0 then - if mbx >= mbw - 1 then - bfill(yuv, tr, readu8(topY, mbx * 16 + 15), 4) - else - bcopy(yuv, tr, topY, mbx * 16 + 16, 4) - end - end - bcopy(yuv, tr + 4 * BPS, yuv, tr, 4) - bcopy(yuv, tr + 8 * BPS, yuv, tr, 4) - bcopy(yuv, tr + 12 * BPS, yuv, tr, 4) - for n = 0, 15 do - local dst = Y_OFF + (n % 4) * 4 + (n // 4) * 4 * BPS - predict4(yuv, dst, mbModes[mbx * 16 + n + 1]) - doTransform(band(rshift(bits, 30 - 2 * n), 3), coeffs, co + n * 32, yuv, dst) - end - else - predictBlock(yuv, Y_OFF, 16, checkMode(mbx, mby, mbModes[mbx * 16 + 1])) + if rf > 0 then + local mi = (mby + 1) * (mbw + 1) + x1 + 1 + Predict.mb(refs[rf], mbx, mby, miMvR[mi], miMvC[mi], mbPart[x1], miSubR, miSubC, (mi - 1) * 16, yuv, Y_OFF, U_OFF, V_OFF, bil, full) if bits ~= 0 then for n = 0, 15 do local dst = Y_OFF + (n % 4) * 4 + (n // 4) * 4 * BPS doTransform(band(rshift(bits, 30 - 2 * n), 3), coeffs, co + n * 32, yuv, dst) end end + else + if mbI4[x1] then + local tr = Y_OFF - BPS + 16 + if mby > 0 then + if mbx >= mbw - 1 then + bfill(yuv, tr, readu8(topY, mbx * 16 + 15), 4) + else + bcopy(yuv, tr, topY, mbx * 16 + 16, 4) + end + end + bcopy(yuv, tr + 4 * BPS, yuv, tr, 4) + bcopy(yuv, tr + 8 * BPS, yuv, tr, 4) + bcopy(yuv, tr + 12 * BPS, yuv, tr, 4) + for n = 0, 15 do + local dst = Y_OFF + (n % 4) * 4 + (n // 4) * 4 * BPS + predict4(yuv, dst, mbModes[mbx * 16 + n + 1]) + doTransform(band(rshift(bits, 30 - 2 * n), 3), coeffs, co + n * 32, yuv, dst) + end + else + predictBlock(yuv, Y_OFF, 16, checkMode(mbx, mby, mbModes[mbx * 16 + 1])) + if bits ~= 0 then + for n = 0, 15 do + local dst = Y_OFF + (n % 4) * 4 + (n // 4) * 4 * BPS + doTransform(band(rshift(bits, 30 - 2 * n), 3), coeffs, co + n * 32, yuv, dst) + end + end + end + local uvm = checkMode(mbx, mby, mbUv[x1]) + predictBlock(yuv, U_OFF, 8, uvm) + predictBlock(yuv, V_OFF, 8, uvm) end - local uvm = checkMode(mbx, mby, mbUv[x1]) - predictBlock(yuv, U_OFF, 8, uvm) - predictBlock(yuv, V_OFF, 8, uvm) local buv = mbNzUv[x1] doUVTransform(buv, coeffs, co + 16 * 32, yuv, U_OFF) doUVTransform(rshift(buv, 8), coeffs, co + 20 * 32, yuv, V_OFF) @@ -1265,11 +1760,11 @@ function Decode.decodeFrame(st: State, buf: buffer, off: number, len: number, ma bcopy(topU, mbx * 8, yuv, U_OFF + 7 * BPS, 8) bcopy(topV, mbx * 8, yuv, V_OFF + 7 * BPS, 8) end - local yo = mby * 16 * ys + mbx * 16 + local yo = yb + mby * 16 * ys + mbx * 16 for j = 0, 15 do bcopy(Y, yo + j * ys, yuv, Y_OFF + j * BPS, 16) end - local uo = mby * 8 * uvs + mbx * 8 + local uo = uvb + mby * 8 * uvs + mbx * 8 for j = 0, 7 do bcopy(U, uo + j * uvs, yuv, U_OFF + j * BPS, 8) bcopy(V, uo + j * uvs, yuv, V_OFF + j * BPS, 8) @@ -1285,7 +1780,7 @@ function Decode.decodeFrame(st: State, buf: buffer, off: number, len: number, ma local limit = fLimit[fi] if limit ~= 0 then local inner = fInner[fi] == 1 - local yp = mby * 16 * ys + mbx * 16 + local yp = yb + mby * 16 * ys + mbx * 16 if filterType == 1 then if mbx > 0 then simpleFilter(Y, yp, 1, ys, limit + 4) @@ -1305,7 +1800,7 @@ function Decode.decodeFrame(st: State, buf: buffer, off: number, len: number, ma end else local il, hev = fIlevel[fi], fHev[fi] - local up = mby * 8 * uvs + mbx * 8 + local up = uvb + mby * 8 * uvs + mbx * 8 if mbx > 0 then filterLoop(Y, yp, 1, ys, 16, limit + 4, il, hev, true) filterLoop(U, up, 1, uvs, 8, limit + 4, il, hev, true) @@ -1336,18 +1831,34 @@ function Decode.decodeFrame(st: State, buf: buffer, off: number, len: number, ma end end - -- crop to the frame size - local cw, chh = (width + 1) // 2, (height + 1) // 2 - local oy = bcreate(width * height) - for j = 0, height - 1 do - bcopy(oy, j * width, Y, j * ys, width) + -- the references (libvpx swap_frame_buffers; copies read the references of the previous frame, as ffmpeg does) + if key then + st.last, st.golden, st.alt = cur, cur, cur + st.hasKey = true + else + local oldLast, oldGolden, oldAlt = st.last, st.golden, st.alt + if refreshGolden then + st.golden = cur + elseif copyToGolden == 1 then + st.golden = oldLast + elseif copyToGolden == 2 then + st.golden = oldAlt + end + if refreshAlt then + st.alt = cur + elseif copyToAlt == 1 then + st.alt = oldLast + elseif copyToAlt == 2 then + st.alt = oldGolden + end + if refreshLast then + st.last = cur + end end - local ou, ov = bcreate(cw * chh), bcreate(cw * chh) - for j = 0, chh - 1 do - bcopy(ou, j * cw, U, j * uvs, cw) - bcopy(ov, j * cw, V, j * uvs, cw) + if saved then + st.proba, st.ymodeProb, st.uvmodeProb, st.mvProb = saved[1], saved[2], saved[3], saved[4] end - return { width = width, height = height, y = oy, u = ou, v = ov, header = hdr }, nil + return { width = width, height = height, ref = cur, header = hdr }, nil end return Decode diff --git a/src/Formats/codecs/Vp8/Predict.luau b/src/Formats/codecs/Vp8/Predict.luau new file mode 100644 index 0000000..3a21374 --- /dev/null +++ b/src/Formats/codecs/Vp8/Predict.luau @@ -0,0 +1,263 @@ +--!strict +--!native +--!optimize 2 +-- codecs/Vp8/Predict: VP8 inter prediction (RFC 6386 section 18): the six-tap sub-pixel filters (version 0), the +-- bilinear ones (versions 1-3; version 3 also rounds chroma vectors to full pixels), chroma vectors derived from the +-- luma ones, split macroblocks, and the reference frame borders. After libvpx 1.17 vp8/common/reconinter.c and +-- filter.c (BSD-3-Clause, licenses/libvpx-LICENSE.txt). Out-of-frame motion reads the reference as if its edge pixels +-- extended forever, which is exactly what libvpx computes with its 32 pixel border plus its motion vector clamping (the +-- clamps only kick in once every tap is in the border). The planes keep a BORDER pixel border filled by extend(); a +-- block whose taps leave it is first copied with clamped coordinates. Never throws. +local Tables = require("@formats/codecs/Vp8/Tables") + +local readu8, writeu8, bcopy, bcreate, bfill = buffer.readu8, buffer.writeu8, buffer.copy, buffer.create, buffer.fill +local rshift, band = bit32.rshift, bit32.band +local SIX, BIL = Tables.SIXTAP, Tables.BILINEAR + +local Predict = {} + +local BORDER = 32 +Predict.BORDER = BORDER + +-- the work buffer stride (codecs/Vp8/Decode: BPS) +local BPS = 32 + +local emu = bcreate(32 * 32) -- a block with its taps, edges replicated +local tmp = bcreate(32 * 32) -- the first (horizontal) pass of a two-dimensional filter + +-- the six-tap filter along rows: dst[i] = clamp((sum of src[i - 2 .. i + 3] * taps + 64) >> 7) +local function sixH(src: buffer, so: number, ss: number, dst: buffer, d: number, ds: number, w: number, h: number, f: number) + local k = f * 6 + local t0, t1, t2, t3, t4, t5 = SIX[k + 1], SIX[k + 2], SIX[k + 3], SIX[k + 4], SIX[k + 5], SIX[k + 6] + for _ = 1, h do + local p = so - 2 + local a, b, c, e, g = readu8(src, p), readu8(src, p + 1), readu8(src, p + 2), readu8(src, p + 3), readu8(src, p + 4) + p += 5 + for i = 0, w - 1 do + local q = readu8(src, p + i) + local v = a * t0 + b * t1 + c * t2 + e * t3 + g * t4 + q * t5 + 64 + writeu8(dst, d + i, if v < 0 then 0 elseif v >= 32768 then 255 else rshift(v, 7)) + a, b, c, e, g = b, c, e, g, q + end + so += ss + d += ds + end +end + +-- the six-tap filter along columns +local function sixV(src: buffer, so: number, ss: number, dst: buffer, d: number, ds: number, w: number, h: number, f: number) + local k = f * 6 + local t0, t1, t2, t3, t4, t5 = SIX[k + 1], SIX[k + 2], SIX[k + 3], SIX[k + 4], SIX[k + 5], SIX[k + 6] + for i = 0, w - 1 do + local p = so + i - 2 * ss + local a, b, c = readu8(src, p), readu8(src, p + ss), readu8(src, p + 2 * ss) + local e, g = readu8(src, p + 3 * ss), readu8(src, p + 4 * ss) + p += 5 * ss + local o = d + i + for _ = 1, h do + local q = readu8(src, p) + local v = a * t0 + b * t1 + c * t2 + e * t3 + g * t4 + q * t5 + 64 + writeu8(dst, o, if v < 0 then 0 elseif v >= 32768 then 255 else rshift(v, 7)) + a, b, c, e, g = b, c, e, g, q + p += ss + o += ds + end + end +end + +-- the bilinear filters: dst[i] = (src[i] * t0 + src[i + 1] * t1 + 64) >> 7 +local function bilH(src: buffer, so: number, ss: number, dst: buffer, d: number, ds: number, w: number, h: number, f: number) + local t0, t1 = BIL[f * 2 + 1], BIL[f * 2 + 2] + for _ = 1, h do + local a = readu8(src, so) + for i = 0, w - 1 do + local b = readu8(src, so + i + 1) + writeu8(dst, d + i, rshift(a * t0 + b * t1 + 64, 7)) + a = b + end + so += ss + d += ds + end +end + +local function bilV(src: buffer, so: number, ss: number, dst: buffer, d: number, ds: number, w: number, h: number, f: number) + local t0, t1 = BIL[f * 2 + 1], BIL[f * 2 + 2] + for i = 0, w - 1 do + local p = so + i + local a = readu8(src, p) + local o = d + i + for _ = 1, h do + p += ss + local b = readu8(src, p) + writeu8(dst, o, rshift(a * t0 + b * t1 + 64, 7)) + a = b + o += ds + end + end +end + +-- block(src, stride, base, wmax, hmax, x, y, mvx, mvy, w, h, dst, d, bil): predicts the w x h block at plane pixel +-- (x, y) moved by (mvx, mvy) eighth pixels into dst at d (stride BPS). base: the offset of plane pixel (0, 0); wmax, +-- hmax: the last pixel column / row of the (macroblock aligned) plane. +local function block(src: buffer, stride: number, base: number, wmax: number, hmax: number, x: number, y: number, mvx: number, mvy: number, w: number, h: number, dst: buffer, d: number, bil: boolean) + local fx, fy = band(mvx, 7), band(mvy, 7) + local px, py = x + (mvx - fx) // 8, y + (mvy - fy) // 8 + local sb, so, ss = src, 0, stride + if px >= 2 - BORDER and py >= 2 - BORDER and px + w + 3 <= wmax + 1 + BORDER and py + h + 3 <= hmax + 1 + BORDER then + so = base + py * stride + px + else + for r = 0, h + 4 do + local sy = py - 2 + r + if sy < 0 then + sy = 0 + elseif sy > hmax then + sy = hmax + end + local row = base + sy * stride + local o = r * 32 + for c = 0, w + 4 do + local sx = px - 2 + c + if sx < 0 then + sx = 0 + elseif sx > wmax then + sx = wmax + end + writeu8(emu, o + c, readu8(src, row + sx)) + end + end + sb, so, ss = emu, 66, 32 + end + if fx == 0 then + if fy == 0 then + for r = 0, h - 1 do + bcopy(dst, d + r * BPS, sb, so + r * ss, w) + end + elseif bil then + bilV(sb, so, ss, dst, d, BPS, w, h, fy) + else + sixV(sb, so, ss, dst, d, BPS, w, h, fy) + end + elseif fy == 0 then + if bil then + bilH(sb, so, ss, dst, d, BPS, w, h, fx) + else + sixH(sb, so, ss, dst, d, BPS, w, h, fx) + end + elseif bil then + bilH(sb, so, ss, tmp, 0, 32, w, h + 1, fx) + bilV(tmp, 0, 32, dst, d, BPS, w, h, fy) + else + sixH(sb, so - 2 * ss, ss, tmp, 0, 32, w, h + 5, fx) + sixV(tmp, 64, 32, dst, d, BPS, w, h, fy) + end +end + +local function chroma16(v: number): number + -- the chroma vector of a whole macroblock: half the luma one, rounded away from zero + return if v < 0 then -((1 - v) // 2) else (v + 1) // 2 +end + +local function chroma4(s: number): number + -- the chroma vector of a 2x2 group of luma blocks: the sum of their 4 vectors / 8, rounded half away from zero + return if s < 0 then -((4 - s) // 8) else (s + 4) // 8 +end + +export type Planes = { + Y: buffer, + U: buffer, + V: buffer, + ys: number, -- luma stride + uvs: number, -- chroma stride + yb: number, -- offset of luma pixel (0, 0) + uvb: number, + mbw: number, + mbh: number, +} + +-- mb(ref, mbx, mby, mvr, mvc, split, subR, subC, sb, dst, yo, uo, vo, bil, full): the prediction of one inter +-- macroblock into the work buffer (luma at yo, chroma at uo / vo). Not split: one vector (mvr, mvc) in eighth pixels; +-- split: the 16 block vectors subR / subC[sb + 1 .. sb + 16] (part < 3: the four 8x8 quarters share them). +function Predict.mb(ref: Planes, mbx: number, mby: number, mvr: number, mvc: number, part: number, subR: { number }, subC: { number }, sb: number, dst: buffer, yo: number, uo: number, vo: number, bil: boolean, full: boolean) + local Y, U, V, ys, uvs, yb, uvb = ref.Y, ref.U, ref.V, ref.ys, ref.uvs, ref.yb, ref.uvb + local wl, hl = ref.mbw * 16 - 1, ref.mbh * 16 - 1 + local wc, hc = ref.mbw * 8 - 1, ref.mbh * 8 - 1 + local x, y = mbx * 16, mby * 16 + local cx, cy = mbx * 8, mby * 8 + if part < 0 then + block(Y, ys, yb, wl, hl, x, y, mvc, mvr, 16, 16, dst, yo, bil) + local cr, cc = chroma16(mvr), chroma16(mvc) + if full then + cr -= band(cr, 7) + cc -= band(cc, 7) + end + block(U, uvs, uvb, wc, hc, cx, cy, cc, cr, 8, 8, dst, uo, bil) + block(V, uvs, uvb, wc, hc, cx, cy, cc, cr, 8, 8, dst, vo, bil) + return + end + if part < 3 then + for q = 0, 3 do + local bx, by = (q % 2) * 8, (q // 2) * 8 + local k = sb + by + bx // 4 + 1 + block(Y, ys, yb, wl, hl, x + bx, y + by, subC[k], subR[k], 8, 8, dst, yo + by * BPS + bx, bil) + end + else + for b = 0, 15, 2 do + local k = sb + b + 1 + local bx, by = (b % 4) * 4, (b // 4) * 4 + local r0, c0 = subR[k], subC[k] + if r0 == subR[k + 1] and c0 == subC[k + 1] then + block(Y, ys, yb, wl, hl, x + bx, y + by, c0, r0, 8, 4, dst, yo + by * BPS + bx, bil) + else + block(Y, ys, yb, wl, hl, x + bx, y + by, c0, r0, 4, 4, dst, yo + by * BPS + bx, bil) + block(Y, ys, yb, wl, hl, x + bx + 4, y + by, subC[k + 1], subR[k + 1], 4, 4, dst, yo + by * BPS + bx + 4, bil) + end + end + end + for i = 0, 1 do + local rr, rc = 0, 0 + for j = 0, 1 do + local k = sb + i * 8 + j * 2 + 1 + local cr = chroma4(subR[k] + subR[k + 1] + subR[k + 4] + subR[k + 5]) + local cc = chroma4(subC[k] + subC[k + 1] + subC[k + 4] + subC[k + 5]) + if full then + cr -= band(cr, 7) + cc -= band(cc, 7) + end + if j == 0 then + rr, rc = cr, cc + elseif cr == rr and cc == rc then + -- both 4x4 chroma blocks of the row share one vector: one 8x4 block + block(U, uvs, uvb, wc, hc, cx, cy + i * 4, cc, cr, 8, 4, dst, uo + i * 4 * BPS, bil) + block(V, uvs, uvb, wc, hc, cx, cy + i * 4, cc, cr, 8, 4, dst, vo + i * 4 * BPS, bil) + else + block(U, uvs, uvb, wc, hc, cx, cy + i * 4, rc, rr, 4, 4, dst, uo + i * 4 * BPS, bil) + block(V, uvs, uvb, wc, hc, cx, cy + i * 4, rc, rr, 4, 4, dst, vo + i * 4 * BPS, bil) + block(U, uvs, uvb, wc, hc, cx + 4, cy + i * 4, cc, cr, 4, 4, dst, uo + i * 4 * BPS + 4, bil) + block(V, uvs, uvb, wc, hc, cx + 4, cy + i * 4, cc, cr, 4, 4, dst, vo + i * 4 * BPS + 4, bil) + end + end + end +end + +-- extend(P, stride, base, w, h): fills the BORDER pixels around a w x h plane with its edge pixels +local function extend(P: buffer, stride: number, base: number, w: number, h: number) + for r = 0, h - 1 do + local o = base + r * stride + bfill(P, o - BORDER, readu8(P, o), BORDER) + bfill(P, o + w, readu8(P, o + w - 1), BORDER) + end + local top = base - BORDER + local bottom = base + (h - 1) * stride - BORDER + for r = 1, BORDER do + bcopy(P, top - r * stride, P, top, stride) + bcopy(P, bottom + r * stride, P, bottom, stride) + end +end + +function Predict.extend(ref: Planes) + extend(ref.Y, ref.ys, ref.yb, ref.mbw * 16, ref.mbh * 16) + extend(ref.U, ref.uvs, ref.uvb, ref.mbw * 8, ref.mbh * 8) + extend(ref.V, ref.uvs, ref.uvb, ref.mbw * 8, ref.mbh * 8) +end + +return Predict diff --git a/src/Formats/codecs/Vp8/Tables.luau b/src/Formats/codecs/Vp8/Tables.luau index e8a9320..21dc1cf 100644 --- a/src/Formats/codecs/Vp8/Tables.luau +++ b/src/Formats/codecs/Vp8/Tables.luau @@ -1,6 +1,9 @@ --!strict -- codecs/Vp8/Tables: the constant VP8 tables of RFC 6386 (sections 13.5, 13.4, 11.5, 14.1), copied from libwebp 1.6 --- src/dec/tree_dec.c and src/dec/quant_dec.c (BSD-3-Clause, licenses/libwebp-LICENSE.txt). Flat 1-based arrays. +-- src/dec/tree_dec.c and src/dec/quant_dec.c (BSD-3-Clause, licenses/libwebp-LICENSE.txt); the inter frame tables +-- (sections 16-18: mode / motion vector probabilities, mode contexts, split partitions, sub-pixel filters) from +-- libvpx 1.17 vp8/common (entropymode.c, vp8_entropymodedata.h, entropymv.c, modecont.c, decodemv.c, filter.c; +-- BSD-3-Clause, licenses/libvpx-LICENSE.txt). Flat 1-based arrays. local Tables = {} -- default token probabilities [type 4][band 8][ctx 3][proba 11]: index ((t * 8 + b) * 3 + c) * 11 + p + 1 @@ -177,4 +180,70 @@ Tables.CAT4 = { 176, 155, 140, 135 } Tables.CAT5 = { 180, 157, 141, 134, 130 } Tables.CAT6 = { 254, 254, 243, 230, 196, 177, 153, 140, 133, 130, 129 } +-- inter frames: default intra mode probabilities (16x16 / chroma, kept in the frame context) and the fixed 4x4 ones +Tables.YMODE_PROB = { 112, 86, 140, 37 } +Tables.UVMODE_PROB = { 162, 101, 204 } +Tables.BMODE_PROB = { 120, 90, 79, 133, 87, 85, 80, 111, 151 } + +-- motion vector probabilities, row then column (19 each): is short, sign, short tree (7), long bits (10) +Tables.MV_DEFAULT = { + 162, 128, 225, 146, 172, 147, 214, 39, 156, 128, 129, 132, 75, 145, 178, 206, 239, 254, 254, + 164, 128, 204, 170, 119, 235, 140, 230, 228, 128, 130, 130, 74, 148, 180, 203, 236, 254, 254, +} +Tables.MV_UPDATE = { + 237, 246, 253, 253, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 250, 250, 252, 254, 254, + 231, 243, 245, 253, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 251, 251, 254, 254, 254, +} + +-- mode contexts [count 0..5][tree node 0..3]: index count * 4 + node + 1 +Tables.MODE_CONTEXTS = { + 7, 1, 1, 143, + 14, 18, 14, 107, + 135, 64, 57, 68, + 60, 56, 128, 65, + 159, 134, 128, 34, + 234, 188, 128, 28, +} + +-- sub-block motion vector reference probabilities [(above zero << 2) | (left zero << 1) | (left == above)][3] +Tables.SUB_MV_REF_PROB = { + 147, 136, 18, + 223, 1, 34, + 106, 145, 1, + 208, 1, 1, + 179, 121, 1, + 223, 1, 34, + 179, 121, 1, + 208, 1, 1, +} + +-- split partitions (16x8, 8x16, 8x8, 4x4): the first block of each partition [s * 16 + j + 1], the blocks of each +-- partition in order [s * 16 + j * count + i + 1], and the number of blocks per partition +Tables.SPLIT_OFFSET = { + 0, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 2, 8, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, +} +Tables.SPLIT_FILL = { + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 0, 1, 4, 5, 8, 9, 12, 13, 2, 3, 6, 7, 10, 11, 14, 15, + 0, 1, 4, 5, 2, 3, 6, 7, 8, 9, 12, 13, 10, 11, 14, 15, + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, +} +Tables.SPLIT_COUNT = { 8, 8, 4, 1 } + +-- the six-tap sub-pixel filters [fraction 0..7][tap 0..5] and the bilinear ones [fraction][2] (versions 1-3) +Tables.SIXTAP = { + 0, 0, 128, 0, 0, 0, + 0, -6, 123, 12, -1, 0, + 2, -11, 108, 36, -8, 1, + 0, -9, 93, 50, -6, 0, + 3, -16, 77, 77, -16, 3, + 0, -6, 50, 93, -9, 0, + 1, -8, 36, 108, -11, 2, + 0, -1, 12, 123, -6, 0, +} +Tables.BILINEAR = { 128, 0, 112, 16, 96, 32, 80, 48, 64, 64, 48, 80, 32, 96, 16, 112 } + return Tables diff --git a/src/Formats/codecs/Vp8/init.luau b/src/Formats/codecs/Vp8/init.luau index 05f56f1..7048de5 100644 --- a/src/Formats/codecs/Vp8/init.luau +++ b/src/Formats/codecs/Vp8/init.luau @@ -1,16 +1,21 @@ --!strict -- codecs/Vp8: the VP8 video codec (RFC 6386), decode only. A codec (layer 1): image/webp uses it for lossy frames, the --- WebM / Matroska and IVF video tracks can use it too. A port of libwebp 1.6 (BSD-3-Clause, +-- WebM / Matroska and IVF video tracks use its decoder object. Key frames are a port of libwebp 1.6 (BSD-3-Clause, -- licenses/libwebp-LICENSE.txt), bit-exact with libwebp: the yuv420p planes equal `dwebp -yuv`, and toRgba equals --- `dwebp -pam` (fancy upsampling) or `dwebp -nofancy -pam`. --- Supports: key frames (intra 16x16 / 4x4 / chroma prediction, segments, both loop filters, token partitions, --- probability updates, skip). Not supported yet: inter frames (decodeFrame returns UNSUPPORTED; the decoder object --- keeps the cross-frame state so they can be added), the horizontal / vertical scale bits (ignored, as libwebp does). +-- `dwebp -pam` (fancy upsampling) or `dwebp -nofancy -pam`. Inter frames follow libvpx 1.17 (BSD-3-Clause, +-- licenses/libvpx-LICENSE.txt), bit-exact with libvpx / ffmpeg on the official test vectors and libvpx streams. +-- Supports: key and inter frames of every version / profile (0: six-tap filters, normal loop filter; 1-2: bilinear; +-- 3: bilinear with full pixel chroma; the loop filter type is the header's), last / golden / altref references with +-- sign bias, hidden (altref) frames, token partitions, segments, loop filter deltas, probability context save / +-- restore. Not supported: the horizontal / vertical scale bits (ignored, as libwebp and ffmpeg do), error +-- concealment (a damaged frame returns an Err). -- -- local Vp8 = require("@formats/codecs/Vp8") --- local frame, err = Vp8.decodeFrame(buf, off, len) -- a yuv420p Types.Image (+ frame.meta.source.vp8 header) +-- local frame, err = Vp8.decodeFrame(buf, off, len) -- one key frame: a yuv420p Types.Image -- local rgba = Vp8.toRgba(frame) -- rgba8 Image (libwebp's fancy upsampling) --- local dec = Vp8.newDecoder(); dec:decodeFrame(...) -- a stream of frames (WebM) +-- local dec = Vp8.newDecoder() -- a stream (WebM, IVF): key and inter frames +-- local img, err = dec:decodeFrame(buf, off, len) -- img.meta.source.show == false: a hidden frame +-- dec:reset() -- after a seek: the next frame must be a key frame -- -- Never throws: bad data returns nil, Err (core/Err codes TRUNCATED / CORRUPT / UNSUPPORTED / LIMIT / ARG). local Err = require("@formats/core/Err") @@ -67,7 +72,9 @@ function Vp8.newDecoder(): Decoder return setmetatable({ state = Decode.new() }, DecoderMeta) end --- decoder:decodeFrame(buf, off?, len?, opts?) -> a yuv420p Image | nil, Err +-- decoder:decodeFrame(buf, off?, len?, opts?) -> a yuv420p Image (a fresh buffer) | nil, Err. Key and inter frames; +-- meta.source = { format = "vp8", keyFrame, show (false: a hidden frame, decoded as a reference but not displayed), +-- profile, width, height }. An inter frame before the first key frame (or after reset) returns CORRUPT. function DecoderMeta.decodeFrame(self: Decoder, buf: buffer, off: number?, len: number?, opts: Options?): (Types.Image?, Err.Err?) if type(buf) ~= "buffer" then return nil, Err.new(Err.ARG, "decodeFrame: expected a buffer") @@ -79,14 +86,18 @@ function DecoderMeta.decodeFrame(self: Decoder, buf: buffer, off: number?, len: end local img = Types.Image.new(f.width, f.height, "yuv420p") local ny = f.width * f.height - local nc = buffer.len(f.u) - buffer.copy(img.pixels, 0, f.y, 0, ny) - buffer.copy(img.pixels, ny, f.u, 0, nc) - buffer.copy(img.pixels, ny + nc, f.v, 0, nc) - img.meta.source = { format = "vp8", keyFrame = f.header.keyFrame, profile = f.header.profile } + local nc = ((f.width + 1) // 2) * ((f.height + 1) // 2) + Decode.cropTo(f, img.pixels, 0, img.pixels, ny, img.pixels, ny + nc) + local h = f.header + img.meta.source = { format = "vp8", keyFrame = h.keyFrame, show = h.show, profile = h.profile, width = f.width, height = f.height } return img, nil end +-- decoder:reset(): drops the reference frames (after a seek); the next frame must be a key frame +function DecoderMeta.reset(self: Decoder) + Decode.reset(self.state) +end + -- decodeFrame(buf, off?, len?, opts?) -> a yuv420p Image | nil, Err (one key frame) function Vp8.decodeFrame(buf: buffer, off: number?, len: number?, opts: Options?): (Types.Image?, Err.Err?) return Vp8.newDecoder():decodeFrame(buf, off, len, opts) @@ -102,7 +113,10 @@ function Vp8.decodePlanes(buf: buffer, off: number?, len: number?, opts: Options if not f then return nil, fail(err, o) end - return f.y, f.u, f.v, f.width, f.height + local nc = ((f.width + 1) // 2) * ((f.height + 1) // 2) + local y, u, v = buffer.create(f.width * f.height), buffer.create(nc), buffer.create(nc) + Decode.cropTo(f, y, 0, u, 0, v, 0) + return y, u, v, f.width, f.height end -- planes(img) -> y, u, v offsets in img.pixels and the chroma width / height diff --git a/tests/codecs/vp8.luau b/tests/codecs/vp8.luau index 484c3f1..8b24ae9 100644 --- a/tests/codecs/vp8.luau +++ b/tests/codecs/vp8.luau @@ -56,7 +56,7 @@ do local inter = buffer.fromstring(frames[1]) buffer.writeu8(inter, 0, bit32.bor(buffer.readu8(inter, 0), 1)) local _, e1 = Vp8.decodeFrame(inter) - t:check(e1 and e1.code == Err.UNSUPPORTED, "inter frame: " .. tostring(e1)) + t:check(e1 and e1.code == Err.CORRUPT, "inter frame without a key frame: " .. tostring(e1)) local bad = buffer.fromstring(frames[1]) buffer.writeu8(bad, 3, 0) local _, e2 = Vp8.decodeFrame(bad) diff --git a/tests/codecs/vp8video.luau b/tests/codecs/vp8video.luau new file mode 100644 index 0000000..92c1cfd --- /dev/null +++ b/tests/codecs/vp8video.luau @@ -0,0 +1,129 @@ +-- codecs/Vp8 video tests: whole IVF streams through one decoder object, every shown frame bit-exact against ffmpeg's +-- native vp8 decoder (yuv420p CRC32): the official VP8 test vectors (vp80-00-comprehensive-001..018 and others) and +-- libvpx clips at many settings (alt-ref / hidden frames, golden, token partitions, error resilience, profiles 1-3, +-- sharpness, segmentation, q extremes, short key frame intervals, motion off the frame, odd sizes). Also hidden +-- frames, reset() and inter frames without a key frame, and the fuzz no-throw pass over damaged streams. +-- Fixtures: tools/fixtures/vp8video.py. +local T = require("@tests/T") +local Vp8 = require("@formats/codecs/Vp8") +local Crc32 = require("@formats/core/Crc32") +local Err = require("@formats/core/Err") +local Cases = require("@tests/gen/vp8video_cases") + +local t = T.suite("vp8video") + +-- the frames of an IVF file: { offset, length } +local function ivfFrames(b: buffer): { { number } } + local out = {} + local p = buffer.readu16(b, 6) -- header length (32) + while p + 12 <= buffer.len(b) do + local n = buffer.readu32(b, p) + if p + 12 + n > buffer.len(b) then + break + end + table.insert(out, { p + 12, n }) + p += 12 + n + end + return out +end + +local total, hidden, vectors = 0, 0, 0 +local samples: { buffer } = {} +for _, c in Cases do + local b = buffer.fromstring(c.ivf) + local fr = ivfFrames(b) + local dec = Vp8.newDecoder() + local shown, bad, firstBad = 0, 0, "" + local ok = true + for i, f in fr do + local img, err = dec:decodeFrame(b, f[1], f[2]) + if not img then + ok = false + firstBad = "frame " .. i .. ": " .. tostring(err) + break + end + local src = img.meta.source + if src.show then + shown += 1 + if buffer.len(img.pixels) ~= c.sizes[shown] or Crc32.of(img.pixels) ~= c.crcs[shown] then + bad += 1 + if bad == 1 then + firstBad = string.format("frame %d (shown %d, %s)", i, shown, if src.keyFrame then "key" else "inter") + end + end + else + hidden += 1 + end + end + t:check(ok and bad == 0 and shown == #c.crcs, string.format("%s: %d / %d frames bit-exact, %d shown of %d; first bad: %s", c.name, shown - bad, #c.crcs, shown, #fr, firstBad)) + total += shown + if string.sub(c.name, 1, 5) == "vp80-" then + vectors += 1 + end + if #samples < 6 and #c.ivf < 40000 then + table.insert(samples, b) + end +end +t:note("%d streams (%d official test vectors), %d shown frames bit-exact with ffmpeg, %d hidden frames", #Cases, vectors, total, hidden) + +-- hidden frames, reset(), inter frames without a key frame +do + local c + for _, x in Cases do + if x.name == "altref_352x288" then + c = x + end + end + local b = buffer.fromstring(c.ivf) + local fr = ivfFrames(b) + local dec = Vp8.newDecoder() + local _, e0 = dec:decodeFrame(b, fr[2][1], fr[2][2]) + t:check(e0 and e0.code == Err.CORRUPT, "inter frame first: " .. tostring(e0)) + local key = dec:decodeFrame(b, fr[1][1], fr[1][2]) :: any + t:check(key and key.meta.source.keyFrame and key.meta.source.show and key.meta.source.format == "vp8", "key frame meta") + local sawHidden = false + for i = 2, #fr do + local img = dec:decodeFrame(b, fr[i][1], fr[i][2]) :: any + if img and not img.meta.source.show then + sawHidden = true + t:check(not img.meta.source.keyFrame and img.width == c.width, "hidden frame is an Image") + end + end + t:check(sawHidden, "the alt-ref stream has a hidden frame") + -- the returned planes are a copy: decoding more frames leaves an earlier image alone + local d2 = Vp8.newDecoder() + local first = d2:decodeFrame(b, fr[1][1], fr[1][2]) :: any + local crc = Crc32.of(first.pixels) + d2:decodeFrame(b, fr[2][1], fr[2][2]) + d2:decodeFrame(b, fr[3][1], fr[3][2]) + t:eq(Crc32.of(first.pixels), crc, "images are fresh buffers") + dec:reset() + local _, e1 = dec:decodeFrame(b, fr[3][1], fr[3][2]) + t:check(e1 and e1.code == Err.CORRUPT, "inter frame after reset: " .. tostring(e1)) + local again = dec:decodeFrame(b, fr[1][1], fr[1][2]) :: any + t:eq(again and Crc32.of(again.pixels), c.crcs[1], "key frame after reset") + local nxt = dec:decodeFrame(b, fr[2][1], fr[2][2]) :: any + t:check(nxt ~= nil, "inter frame after the key frame") + local _, e2 = Vp8.decodeFrame(b, fr[2][1], fr[2][2]) + t:check(e2 and e2.code == Err.CORRUPT, "one-shot decodeFrame of an inter frame") + local _, e3 = dec:decodeFrame(b, fr[2][1], 2) + t:check(e3 and e3.code == Err.TRUNCATED, "truncated frame tag: " .. tostring(e3)) +end + +-- fuzz: whole damaged streams through one decoder (truncated / mutated frames after valid ones) +local function feed(b: buffer) + local dec = Vp8.newDecoder() + local any = false + local p, n = 32, buffer.len(b) + while p + 12 <= n do + local len = math.min(buffer.readu32(b, p), n - p - 12) + local img = dec:decodeFrame(b, p + 12, len, { maxPixels = 2 ^ 20 }) + any = any or img ~= nil + p += 12 + len + end + return any, nil +end +t:fuzz("stream", feed, samples, { mutations = 6, keepHeader = 32 }) +t:fuzz("stream (more damage)", feed, samples, { mutations = 30, keepHeader = 32, garbage = 20 }) + +t:done() diff --git a/tests/fixtures/vp8video/vp80-00-comprehensive-001.ivf b/tests/fixtures/vp8video/vp80-00-comprehensive-001.ivf new file mode 100644 index 0000000..d7a7cd5 Binary files /dev/null and b/tests/fixtures/vp8video/vp80-00-comprehensive-001.ivf differ diff --git a/tests/fixtures/vp8video/vp80-00-comprehensive-002.ivf b/tests/fixtures/vp8video/vp80-00-comprehensive-002.ivf new file mode 100644 index 0000000..06e208d Binary files /dev/null and b/tests/fixtures/vp8video/vp80-00-comprehensive-002.ivf differ diff --git a/tests/fixtures/vp8video/vp80-00-comprehensive-003.ivf b/tests/fixtures/vp8video/vp80-00-comprehensive-003.ivf new file mode 100644 index 0000000..1009450 Binary files /dev/null and b/tests/fixtures/vp8video/vp80-00-comprehensive-003.ivf differ diff --git a/tests/fixtures/vp8video/vp80-00-comprehensive-004.ivf b/tests/fixtures/vp8video/vp80-00-comprehensive-004.ivf new file mode 100644 index 0000000..70b49fe Binary files /dev/null and b/tests/fixtures/vp8video/vp80-00-comprehensive-004.ivf differ diff --git a/tests/fixtures/vp8video/vp80-00-comprehensive-005.ivf b/tests/fixtures/vp8video/vp80-00-comprehensive-005.ivf new file mode 100644 index 0000000..5388a61 Binary files /dev/null and b/tests/fixtures/vp8video/vp80-00-comprehensive-005.ivf differ diff --git a/tests/fixtures/vp8video/vp80-00-comprehensive-006.ivf b/tests/fixtures/vp8video/vp80-00-comprehensive-006.ivf new file mode 100644 index 0000000..5a78d4f Binary files /dev/null and b/tests/fixtures/vp8video/vp80-00-comprehensive-006.ivf differ diff --git a/tests/fixtures/vp8video/vp80-00-comprehensive-007.ivf b/tests/fixtures/vp8video/vp80-00-comprehensive-007.ivf new file mode 100644 index 0000000..3aafdeb Binary files /dev/null and b/tests/fixtures/vp8video/vp80-00-comprehensive-007.ivf differ diff --git a/tests/fixtures/vp8video/vp80-00-comprehensive-008.ivf b/tests/fixtures/vp8video/vp80-00-comprehensive-008.ivf new file mode 100644 index 0000000..d31941a Binary files /dev/null and b/tests/fixtures/vp8video/vp80-00-comprehensive-008.ivf differ diff --git a/tests/fixtures/vp8video/vp80-00-comprehensive-009.ivf b/tests/fixtures/vp8video/vp80-00-comprehensive-009.ivf new file mode 100644 index 0000000..1e7cf89 Binary files /dev/null and b/tests/fixtures/vp8video/vp80-00-comprehensive-009.ivf differ diff --git a/tests/fixtures/vp8video/vp80-00-comprehensive-010.ivf b/tests/fixtures/vp8video/vp80-00-comprehensive-010.ivf new file mode 100644 index 0000000..b5f8285 Binary files /dev/null and b/tests/fixtures/vp8video/vp80-00-comprehensive-010.ivf differ diff --git a/tests/fixtures/vp8video/vp80-00-comprehensive-011.ivf b/tests/fixtures/vp8video/vp80-00-comprehensive-011.ivf new file mode 100644 index 0000000..8a347eb Binary files /dev/null and b/tests/fixtures/vp8video/vp80-00-comprehensive-011.ivf differ diff --git a/tests/fixtures/vp8video/vp80-00-comprehensive-012.ivf b/tests/fixtures/vp8video/vp80-00-comprehensive-012.ivf new file mode 100644 index 0000000..9182f48 Binary files /dev/null and b/tests/fixtures/vp8video/vp80-00-comprehensive-012.ivf differ diff --git a/tests/fixtures/vp8video/vp80-00-comprehensive-013.ivf b/tests/fixtures/vp8video/vp80-00-comprehensive-013.ivf new file mode 100644 index 0000000..6873b35 Binary files /dev/null and b/tests/fixtures/vp8video/vp80-00-comprehensive-013.ivf differ diff --git a/tests/fixtures/vp8video/vp80-00-comprehensive-014.ivf b/tests/fixtures/vp8video/vp80-00-comprehensive-014.ivf new file mode 100644 index 0000000..366fd54 Binary files /dev/null and b/tests/fixtures/vp8video/vp80-00-comprehensive-014.ivf differ diff --git a/tests/fixtures/vp8video/vp80-00-comprehensive-015.ivf b/tests/fixtures/vp8video/vp80-00-comprehensive-015.ivf new file mode 100644 index 0000000..31c0e76 Binary files /dev/null and b/tests/fixtures/vp8video/vp80-00-comprehensive-015.ivf differ diff --git a/tests/fixtures/vp8video/vp80-00-comprehensive-016.ivf b/tests/fixtures/vp8video/vp80-00-comprehensive-016.ivf new file mode 100644 index 0000000..74bdc9d Binary files /dev/null and b/tests/fixtures/vp8video/vp80-00-comprehensive-016.ivf differ diff --git a/tests/fixtures/vp8video/vp80-00-comprehensive-017.ivf b/tests/fixtures/vp8video/vp80-00-comprehensive-017.ivf new file mode 100644 index 0000000..b6820c1 Binary files /dev/null and b/tests/fixtures/vp8video/vp80-00-comprehensive-017.ivf differ diff --git a/tests/fixtures/vp8video/vp80-00-comprehensive-018.ivf b/tests/fixtures/vp8video/vp80-00-comprehensive-018.ivf new file mode 100644 index 0000000..7da25e8 Binary files /dev/null and b/tests/fixtures/vp8video/vp80-00-comprehensive-018.ivf differ diff --git a/tests/fixtures/vp8video/vp80-02-inter-1418.ivf b/tests/fixtures/vp8video/vp80-02-inter-1418.ivf new file mode 100644 index 0000000..cd5b6f4 Binary files /dev/null and b/tests/fixtures/vp8video/vp80-02-inter-1418.ivf differ diff --git a/tests/fixtures/vp8video/vp80-03-segmentation-03.ivf b/tests/fixtures/vp8video/vp80-03-segmentation-03.ivf new file mode 100644 index 0000000..447e0b6 Binary files /dev/null and b/tests/fixtures/vp8video/vp80-03-segmentation-03.ivf differ diff --git a/tests/fixtures/vp8video/vp80-03-segmentation-1407.ivf b/tests/fixtures/vp8video/vp80-03-segmentation-1407.ivf new file mode 100644 index 0000000..ec9d645 Binary files /dev/null and b/tests/fixtures/vp8video/vp80-03-segmentation-1407.ivf differ diff --git a/tests/fixtures/vp8video/vp80-03-segmentation-1436.ivf b/tests/fixtures/vp8video/vp80-03-segmentation-1436.ivf new file mode 100644 index 0000000..55c9219 Binary files /dev/null and b/tests/fixtures/vp8video/vp80-03-segmentation-1436.ivf differ diff --git a/tests/fixtures/vp8video/vp80-03-segmentation-1437.ivf b/tests/fixtures/vp8video/vp80-03-segmentation-1437.ivf new file mode 100644 index 0000000..a1484bb Binary files /dev/null and b/tests/fixtures/vp8video/vp80-03-segmentation-1437.ivf differ diff --git a/tests/fixtures/vp8video/vp80-03-segmentation-1441.ivf b/tests/fixtures/vp8video/vp80-03-segmentation-1441.ivf new file mode 100644 index 0000000..83bf2d0 Binary files /dev/null and b/tests/fixtures/vp8video/vp80-03-segmentation-1441.ivf differ diff --git a/tests/fixtures/vp8video/vp80-04-partitions-1405.ivf b/tests/fixtures/vp8video/vp80-04-partitions-1405.ivf new file mode 100644 index 0000000..4578736 Binary files /dev/null and b/tests/fixtures/vp8video/vp80-04-partitions-1405.ivf differ diff --git a/tests/fixtures/vp8video/vp80-05-sharpness-1438.ivf b/tests/fixtures/vp8video/vp80-05-sharpness-1438.ivf new file mode 100644 index 0000000..5a5eb41 Binary files /dev/null and b/tests/fixtures/vp8video/vp80-05-sharpness-1438.ivf differ diff --git a/tests/fixtures/vp8video/vp80-06-smallsize.ivf b/tests/fixtures/vp8video/vp80-06-smallsize.ivf new file mode 100644 index 0000000..3f24bb3 Binary files /dev/null and b/tests/fixtures/vp8video/vp80-06-smallsize.ivf differ diff --git a/tools/fixtures/vp8video.py b/tools/fixtures/vp8video.py new file mode 100644 index 0000000..1a01039 --- /dev/null +++ b/tools/fixtures/vp8video.py @@ -0,0 +1,133 @@ +# VP8 video fixtures (tools/fixtures.py) for tests/codecs/vp8video.luau and tools/bench.luau. Clips are encoded by +# ffmpeg's libvpx into IVF (many encoder settings: alt-ref / hidden frames, golden refreshes, token partitions, error +# resilience, profiles 1-3, sharpness, segmentation, q extremes, short key frame intervals, motion off the frame edges), +# plus the official VP8 test vectors (tests/fixtures/vp8video/vp80-*.ivf, from the libvpx test data, BSD: +# licenses/libvpx-LICENSE.txt). The reference output is ffmpeg's native vp8 decoder (bit-exact with libvpx): +# `ffmpeg -c:v vp8 -i x.ivf -noautoscale -fps_mode passthrough -f framehash -hash crc32 -`: the CRC32 of every +# shown yuv420p frame (and its size: key frames may change it). +# tests/gen/vp8video_cases.luau { name, ivf, width, height (of the first frame), crcs, sizes (bytes) } +# tests/gen/vp8video_bench.luau { { name, ivf, width, height, frames, crcs, sizes } } for tools/bench.luau +import os, shutil, subprocess, tempfile, zlib + +INPUTS = ["tests/fixtures/vp8video"] + +VECTORS = "tests/fixtures/vp8video" + + +def ffmpeg(ctx, args): + """runs ffmpeg (the one on PATH when it has libvpx, else nixpkgs#ffmpeg) and returns stdout""" + exe = shutil.which("ffmpeg") + if exe: + enc = subprocess.run([exe, "-hide_banner", "-encoders"], capture_output=True).stdout + if b"libvpx " in enc: + return subprocess.run([exe, "-hide_banner", "-loglevel", "error"] + args, capture_output=True, check=True).stdout + return ctx.nix("ffmpeg", ["ffmpeg", "-hide_banner", "-loglevel", "error"] + args) + + +def ivf_size(data): + return data[12] | data[13] << 8, data[14] | data[15] << 8 + + +def reference(ctx, path): + """ffmpeg's decode: (crc32, byte size) of each shown yuv420p frame (sizes may change at key frames)""" + out = ffmpeg(ctx, ["-c:v", "vp8", "-i", path, "-noautoscale", "-fps_mode", "passthrough", "-f", "framehash", + "-hash", "crc32", "-"]) + frames = [] + for line in out.decode().splitlines(): + if line and not line.startswith("#"): + f = [x.strip() for x in line.split(",")] + frames.append((int(f[5], 16), int(f[4]))) + return frames + + +# (name, lavfi source, frames, encoder options) +SRC_320 = "testsrc2=s=320x240:r=25" +PAN = "testsrc2=s=480x360:r=25,crop=w=320:h=240:x='80+70*sin(t*3)':y='60+50*cos(t*2)'" +CLIPS = [ + ("default_320x240", SRC_320, 20, ["-b:v", "400k"]), + ("odd_173x95", "mandelbrot=s=173x95:r=25", 16, ["-b:v", "200k"]), + ("pan_320x240", PAN, 24, ["-b:v", "300k", "-g", "100"]), + ("altref_352x288", "testsrc2=s=352x288:r=25", 30, + ["-b:v", "300k", "-auto-alt-ref", "1", "-lag-in-frames", "16", "-arnr-maxframes", "7", "-arnr-strength", "5", + "-arnr-type", "3", "2pass"]), + ("altref_pan", PAN, 30, ["-b:v", "250k", "-auto-alt-ref", "1", "-lag-in-frames", "25", "-g", "200", "2pass"]), + ("tokenparts3", SRC_320, 12, ["-b:v", "500k", "-slices", "8"]), + ("tokenparts1_odd", "mandelbrot=s=201x77:r=25", 12, ["-b:v", "300k", "-slices", "2"]), + ("error_resilient", PAN, 16, ["-b:v", "300k", "-error-resilient", "1"]), + ("profile1", PAN, 16, ["-b:v", "300k", "-profile:v", "1"]), + ("profile2", PAN, 16, ["-b:v", "300k", "-profile:v", "2"]), + ("profile3", PAN, 16, ["-b:v", "300k", "-profile:v", "3"]), + ("sharpness7", PAN, 12, ["-b:v", "200k", "-sharpness", "7"]), + ("sharpness3", "mandelbrot=s=160x120:r=25", 12, ["-b:v", "150k", "-sharpness", "3"]), + ("realtime_cyclic", PAN, 24, + ["-deadline", "realtime", "-cpu-used", "8", "-b:v", "200k", "-static-thresh", "100", "-screen-content-mode", "1"]), + ("realtime_noise", "testsrc2=s=320x240:r=25,noise=alls=30:allf=t", 16, + ["-deadline", "realtime", "-cpu-used", "4", "-b:v", "400k"]), + ("best_split", "testsrc2=s=176x144:r=25,rotate=a='t*0.4':c=black", 16, ["-deadline", "best", "-b:v", "250k"]), + ("cellauto_split", "cellauto=s=176x144:rule=110:r=25,scale=176:144", 16, ["-b:v", "300k", "-cpu-used", "0"]), + ("q_high", PAN, 10, ["-qmin", "0", "-qmax", "2", "-b:v", "20M"]), + ("q_low", PAN, 16, ["-qmin", "60", "-qmax", "63", "-b:v", "20k"]), + ("keyint5", PAN, 16, ["-b:v", "300k", "-g", "5"]), + ("golden", "testsrc2=s=240x160:r=25", 40, ["-b:v", "150k", "-g", "300", "-auto-alt-ref", "0"]), + ("big_motion", "testsrc2=s=640x480:r=25,crop=w=192:h=144:x='224+200*sin(t*9)':y='168+150*cos(t*7)'", 16, + ["-b:v", "300k"]), + ("tiny_24x18", "testsrc2=s=24x18:r=25", 12, ["-b:v", "50k"]), + ("temporal_layers", PAN, 16, + ["-deadline", "realtime", "-b:v", "300k", "-ts-parameters", + "ts_number_layers=2:ts_target_bitrate=150,300:ts_rate_decimator=2,1:ts_periodicity=2:ts_layer_id=0,1"]), +] + +BENCH = [ + ("bench_320x240", "testsrc2=s=480x360:r=25,crop=w=320:h=240:x='80+70*sin(t*3)':y='60+50*cos(t*2)'", 40, + ["-b:v", "500k"]), + ("bench_640x480", "testsrc2=s=960x720:r=25,crop=w=640:h=480:x='160+150*sin(t*3)':y='120+100*cos(t*2)'", 30, + ["-b:v", "1200k"]), +] + + +def encode(ctx, tmp, name, src, frames, opts): + path = os.path.join(tmp, name + ".ivf") + base = ["-f", "lavfi", "-i", src, "-frames:v", str(frames), "-pix_fmt", "yuv420p", "-c:v", "libvpx"] + try: + if "2pass" in opts: # alt-ref frames need the two-pass encoder + opts = [o for o in opts if o != "2pass"] + log = os.path.join(tmp, name + "-pass") + ffmpeg(ctx, base + opts + ["-pass", "1", "-passlogfile", log, "-f", "null", "-"]) + opts = opts + ["-pass", "2", "-passlogfile", log] + ffmpeg(ctx, base + opts + ["-f", "ivf", "-y", path]) + except subprocess.CalledProcessError as e: + if name == "temporal_layers": # optional: depends on the libvpx wrapper's options + return None + raise RuntimeError("vp8video: %s: %s" % (name, e.stderr.decode(errors="replace"))) + return path + + +def case(ctx, name, path): + with open(path, "rb") as f: + data = f.read() + w, h = ivf_size(data) + ref = reference(ctx, path) + return {"name": name, "ivf": data, "width": w, "height": h, "crcs": [r[0] for r in ref], "sizes": [r[1] for r in ref]} + + +def generate(ctx): + tmp = tempfile.mkdtemp(prefix="vp8video") + try: + cases = [] + vec = os.path.join(ctx.root, VECTORS) + for f in sorted(os.listdir(vec)): + if f.endswith(".ivf"): + cases.append(case(ctx, f[:-4], os.path.join(vec, f))) + for name, src, frames, opts in CLIPS: + path = encode(ctx, tmp, name, src, frames, opts) + if path: + cases.append(case(ctx, name, path)) + ctx.emit("vp8video_cases", cases) + bench = [] + for name, src, frames, opts in BENCH: + c = case(ctx, name, encode(ctx, tmp, name, src, frames, opts)) + c["frames"] = len(c["crcs"]) + bench.append(c) + ctx.emit("vp8video_bench", bench) + finally: + shutil.rmtree(tmp)