ws-video: merge ws/video-vp8 (VP8 inter frames)

This commit is contained in:
4DBug committed 2026-10-31 10:05:56 -05:00
commit 582191a739
36 files changed
+1560 -262

No files matched your search

+2
View File
@@ -34,6 +34,8 @@
| `src/Formats/codecs/Tracker/`, `src/Formats/music/{mod,s3m,xm,it}/` | written for this library from the format documents: ProTracker 2.3 effect docs, the XM specification (Mr.H / Triton) and FT2 behaviour notes, ST3 TECH.DOC (Sami Tammilehto / Future Crew), ITTECH.TXT (Jeffrey Lim); OpenMPT (libopenmpt, BSD) was used only as the reference player in the tests, and its documented playback quirks (mix levels, MOD panning, FT2 E6x / tremor / instrument behaviour) are matched | no third-party code |
| `tools/fixtures/{mod,s3m,xm,it}.py` test modules | generated by the fixture scripts (synthesized samples) | no third-party data |
| `src/Formats/codecs/SoundFont/` (Synth, the zone merging in Parse) | port of TinySoundFont v0.9 (tsf.h) by Bernhard Schelling, based on SFZero by Steve Folta | MIT: [TinySoundFont-LICENSE.txt](TinySoundFont-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").
+56
View File
@@ -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.
File diff suppressed because it is too large. Load diff
+274
View File
@@ -0,0 +1,274 @@
--!strict
--!native
--!optimize 2
-- codecs/Vp8/Predict: VP8 inter prediction (RFC 6386 section 18): the six-tap sub-pixel filters (version 0), the
-- bilinear ones (versions 1-3; version 3 also rounds chroma vectors to full pixels), chroma vectors derived from the
-- luma ones, split macroblocks, and the reference frame borders. After libvpx 1.17 vp8/common/reconinter.c and
-- filter.c (BSD-3-Clause, licenses/libvpx-LICENSE.txt). Out-of-frame motion reads the reference as if its edge pixels
-- extended forever, which is exactly what libvpx computes with its 32 pixel border plus its motion vector clamping (the
-- clamps only kick in once every tap is in the border). The planes keep a BORDER pixel border filled by extend(); a
-- block whose taps leave it is first copied with clamped coordinates. Never throws.
local Tables = require("@formats/codecs/Vp8/Tables")
local readu8, writeu8, bcopy, bcreate, bfill = buffer.readu8, buffer.writeu8, buffer.copy, buffer.create, buffer.fill
local readu32, writeu32 = buffer.readu32, buffer.writeu32
local rshift, band = bit32.rshift, bit32.band
local SIX, BIL = Tables.SIXTAP, Tables.BILINEAR
local Predict = {}
local BORDER = 32
Predict.BORDER = BORDER
-- the work buffer stride (codecs/Vp8/Decode: BPS)
local BPS = 32
local emu = bcreate(32 * 32) -- a block with its taps, edges replicated
local tmp = bcreate(32 * 32) -- the first (horizontal) pass of a two-dimensional filter
-- the six-tap filter along rows: dst[i] = clamp((sum of src[i - 2 .. i + 3] * taps + 64) >> 7). Each output reads
-- its six pixels (a sliding window of locals is no faster in Luau and stops LuaJIT's register allocator).
local function sixH(src: buffer, so: number, ss: number, dst: buffer, d: number, ds: number, w: number, h: number, f: number)
local k = f * 6
local t0, t1, t2, t3, t4, t5 = SIX[k + 1], SIX[k + 2], SIX[k + 3], SIX[k + 4], SIX[k + 5], SIX[k + 6]
for _ = 1, h do
for i = so - 2, so + w - 3 do
local v = readu8(src, i) * t0 + readu8(src, i + 1) * t1 + readu8(src, i + 2) * t2 + readu8(src, i + 3) * t3
+ readu8(src, i + 4) * t4 + readu8(src, i + 5) * t5 + 64
writeu8(dst, d + i - so + 2, if v < 0 then 0 elseif v >= 32768 then 255 else rshift(v, 7))
end
so += ss
d += ds
end
end
-- the six-tap filter along columns
local function sixV(src: buffer, so: number, ss: number, dst: buffer, d: number, ds: number, w: number, h: number, f: number)
local k = f * 6
local t0, t1, t2, t3, t4, t5 = SIX[k + 1], SIX[k + 2], SIX[k + 3], SIX[k + 4], SIX[k + 5], SIX[k + 6]
local s1, s2, s3 = ss, 2 * ss, 3 * ss
for _ = 1, h do
local p = so - s2
for i = 0, w - 1 do
local q = p + i
local v = readu8(src, q) * t0 + readu8(src, q + s1) * t1 + readu8(src, q + s2) * t2 + readu8(src, q + s3) * t3
+ readu8(src, q + s2 + s2) * t4 + readu8(src, q + s2 + s3) * t5 + 64
writeu8(dst, d + i, if v < 0 then 0 elseif v >= 32768 then 255 else rshift(v, 7))
end
so += ss
d += ds
end
end
-- the bilinear filters: dst[i] = (src[i] * t0 + src[i + 1] * t1 + 64) >> 7
local function bilH(src: buffer, so: number, ss: number, dst: buffer, d: number, ds: number, w: number, h: number, f: number)
local t0, t1 = BIL[f * 2 + 1], BIL[f * 2 + 2]
for _ = 1, h do
for i = 0, w - 1 do
writeu8(dst, d + i, rshift(readu8(src, so + i) * t0 + readu8(src, so + i + 1) * t1 + 64, 7))
end
so += ss
d += ds
end
end
local function bilV(src: buffer, so: number, ss: number, dst: buffer, d: number, ds: number, w: number, h: number, f: number)
local t0, t1 = BIL[f * 2 + 1], BIL[f * 2 + 2]
for _ = 1, h do
for i = 0, w - 1 do
writeu8(dst, d + i, rshift(readu8(src, so + i) * t0 + readu8(src, so + ss + i) * t1 + 64, 7))
end
so += ss
d += ds
end
end
-- block(src, stride, base, wmax, hmax, x, y, mvx, mvy, w, h, dst, d, bil): predicts the w x h block at plane pixel
-- (x, y) moved by (mvx, mvy) eighth pixels into dst at d (stride BPS). base: the offset of plane pixel (0, 0); wmax,
-- hmax: the last pixel column / row of the (macroblock aligned) plane.
local function block(src: buffer, stride: number, base: number, wmax: number, hmax: number, x: number, y: number, mvx: number, mvy: number, w: number, h: number, dst: buffer, d: number, bil: boolean)
local fx, fy = band(mvx, 7), band(mvy, 7)
local px, py = x + (mvx - fx) // 8, y + (mvy - fy) // 8
local sb, so, ss = src, 0, stride
if px >= 2 - BORDER and py >= 2 - BORDER and px + w + 3 <= wmax + 1 + BORDER and py + h + 3 <= hmax + 1 + BORDER then
so = base + py * stride + px
else
for r = 0, h + 4 do
local sy = py - 2 + r
if sy < 0 then
sy = 0
elseif sy > hmax then
sy = hmax
end
local row = base + sy * stride
local o = r * 32
for c = 0, w + 4 do
local sx = px - 2 + c
if sx < 0 then
sx = 0
elseif sx > wmax then
sx = wmax
end
writeu8(emu, o + c, readu8(src, row + sx))
end
end
sb, so, ss = emu, 66, 32
end
if fx == 0 then
if fy == 0 then
for _ = 1, h do
for i = 0, w - 4, 4 do
writeu32(dst, d + i, readu32(sb, so + i))
end
so += ss
d += BPS
end
elseif bil then
bilV(sb, so, ss, dst, d, BPS, w, h, fy)
else
sixV(sb, so, ss, dst, d, BPS, w, h, fy)
end
elseif fy == 0 then
if bil then
bilH(sb, so, ss, dst, d, BPS, w, h, fx)
else
sixH(sb, so, ss, dst, d, BPS, w, h, fx)
end
elseif bil then
bilH(sb, so, ss, tmp, 0, 32, w, h + 1, fx)
bilV(tmp, 0, 32, dst, d, BPS, w, h, fy)
else
sixH(sb, so - 2 * ss, ss, tmp, 0, 32, w, h + 5, fx)
sixV(tmp, 64, 32, dst, d, BPS, w, h, fy)
end
end
local function chroma16(v: number): number
-- the chroma vector of a whole macroblock: half the luma one, rounded away from zero
if v < 0 then
return -((1 - v) // 2)
end
return (v + 1) // 2
end
local function chroma4(s: number): number
-- the chroma vector of a 2x2 group of luma blocks: the sum of their 4 vectors / 8, rounded half away from zero
if s < 0 then
return -((4 - s) // 8)
end
return (s + 4) // 8
end
export type Planes = {
Y: buffer,
U: buffer,
V: buffer,
ys: number, -- luma stride
uvs: number, -- chroma stride
yb: number, -- offset of luma pixel (0, 0)
uvb: number,
mbw: number,
mbh: number,
}
-- mb(ref, mbx, mby, mvr, mvc, split, subR, subC, sb, dst, yo, uo, vo, bil, full): the prediction of one inter
-- macroblock into the work buffer (luma at yo, chroma at uo / vo). Not split: one vector (mvr, mvc) in eighth pixels;
-- split: the 16 block vectors subR / subC[sb + 1 .. sb + 16] (part < 3: the four 8x8 quarters share them).
function Predict.mb(ref: Planes, mbx: number, mby: number, mvr: number, mvc: number, part: number, subR: { number }, subC: { number }, sb: number, dst: buffer, yo: number, uo: number, vo: number, bil: boolean, full: boolean)
local Y, U, V, ys, uvs, yb, uvb = ref.Y, ref.U, ref.V, ref.ys, ref.uvs, ref.yb, ref.uvb
local wl, hl = ref.mbw * 16 - 1, ref.mbh * 16 - 1
local wc, hc = ref.mbw * 8 - 1, ref.mbh * 8 - 1
local x, y = mbx * 16, mby * 16
local cx, cy = mbx * 8, mby * 8
if part < 0 then
block(Y, ys, yb, wl, hl, x, y, mvc, mvr, 16, 16, dst, yo, bil)
local cr, cc = chroma16(mvr), chroma16(mvc)
if full then
cr -= band(cr, 7)
cc -= band(cc, 7)
end
block(U, uvs, uvb, wc, hc, cx, cy, cc, cr, 8, 8, dst, uo, bil)
block(V, uvs, uvb, wc, hc, cx, cy, cc, cr, 8, 8, dst, vo, bil)
return
end
if part < 3 then
for q = 0, 3 do
local bx, by = (q % 2) * 8, (q // 2) * 8
local k = sb + by + bx // 4 + 1
block(Y, ys, yb, wl, hl, x + bx, y + by, subC[k], subR[k], 8, 8, dst, yo + by * BPS + bx, bil)
end
else
for b = 0, 15, 2 do
local k = sb + b + 1
local bx, by = (b % 4) * 4, (b // 4) * 4
local r0, c0 = subR[k], subC[k]
if r0 == subR[k + 1] and c0 == subC[k + 1] then
block(Y, ys, yb, wl, hl, x + bx, y + by, c0, r0, 8, 4, dst, yo + by * BPS + bx, bil)
else
block(Y, ys, yb, wl, hl, x + bx, y + by, c0, r0, 4, 4, dst, yo + by * BPS + bx, bil)
block(Y, ys, yb, wl, hl, x + bx + 4, y + by, subC[k + 1], subR[k + 1], 4, 4, dst, yo + by * BPS + bx + 4, bil)
end
end
end
for i = 0, 1 do
local rr, rc = 0, 0
for j = 0, 1 do
local k = sb + i * 8 + j * 2 + 1
local cr = chroma4(subR[k] + subR[k + 1] + subR[k + 4] + subR[k + 5])
local cc = chroma4(subC[k] + subC[k + 1] + subC[k + 4] + subC[k + 5])
if full then
cr -= band(cr, 7)
cc -= band(cc, 7)
end
if j == 0 then
rr, rc = cr, cc
elseif cr == rr and cc == rc then
-- both 4x4 chroma blocks of the row share one vector: one 8x4 block
block(U, uvs, uvb, wc, hc, cx, cy + i * 4, cc, cr, 8, 4, dst, uo + i * 4 * BPS, bil)
block(V, uvs, uvb, wc, hc, cx, cy + i * 4, cc, cr, 8, 4, dst, vo + i * 4 * BPS, bil)
else
block(U, uvs, uvb, wc, hc, cx, cy + i * 4, rc, rr, 4, 4, dst, uo + i * 4 * BPS, bil)
block(V, uvs, uvb, wc, hc, cx, cy + i * 4, rc, rr, 4, 4, dst, vo + i * 4 * BPS, bil)
block(U, uvs, uvb, wc, hc, cx + 4, cy + i * 4, cc, cr, 4, 4, dst, uo + i * 4 * BPS + 4, bil)
block(V, uvs, uvb, wc, hc, cx + 4, cy + i * 4, cc, cr, 4, 4, dst, vo + i * 4 * BPS + 4, bil)
end
end
end
end
-- row(refs, mby, mbw, ref, part, miMvR, miMvC, miSubR, miSubC, mi0, pred, chunk, yo, uo, vo, bil, full): predicts the
-- inter macroblocks of a row (ref[mbx + 1] > 0: refs[ref]) into pred, macroblock mbx at mbx * chunk + yo / uo / vo;
-- mi0 + mbx + 1: the mode info index of macroblock mbx. A loop of its own (LuaJIT traces it apart from the decoder).
function Predict.row(refs: { Planes }, mby: number, mbw: number, ref: { number }, part: { number }, miMvR: { number }, miMvC: { number }, miSubR: { number }, miSubC: { number }, mi0: number, pred: buffer, chunk: number, yo: number, uo: number, vo: number, bil: boolean, full: boolean)
for mbx = 0, mbw - 1 do
local rf = ref[mbx + 1]
if rf > 0 then
local mi = mi0 + mbx + 1
local o = mbx * chunk
Predict.mb(refs[rf], mbx, mby, miMvR[mi], miMvC[mi], part[mbx + 1], miSubR, miSubC, (mi - 1) * 16, pred, o + yo, o + uo, o + vo, bil, full)
end
end
end
-- extend(P, stride, base, w, h): fills the BORDER pixels around a w x h plane with its edge pixels
local function extend(P: buffer, stride: number, base: number, w: number, h: number)
for r = 0, h - 1 do
local o = base + r * stride
bfill(P, o - BORDER, readu8(P, o), BORDER)
bfill(P, o + w, readu8(P, o + w - 1), BORDER)
end
local top = base - BORDER
local bottom = base + (h - 1) * stride - BORDER
for r = 1, BORDER do
bcopy(P, top - r * stride, P, top, stride)
bcopy(P, bottom + r * stride, P, bottom, stride)
end
end
function Predict.extend(ref: Planes)
extend(ref.Y, ref.ys, ref.yb, ref.mbw * 16, ref.mbh * 16)
extend(ref.U, ref.uvs, ref.uvb, ref.mbw * 8, ref.mbh * 8)
extend(ref.V, ref.uvs, ref.uvb, ref.mbw * 8, ref.mbh * 8)
end
return Predict
+70 -1
View File
@@ -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
+28 -14
View File
@@ -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
+1 -1
View File
@@ -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)
+129
View File
@@ -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()
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+133
View File
@@ -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)