ws-cleanup: merge master (ws/h264)
This commit is contained in:
commit
6b26845afe
28 files changed
+7345
-1
No files matched your search
@@ -28,6 +28,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build
|
||||
| audio | vorbis | .ogg .oga | yes | yes | streaming: true, seek: true, lossy: true, channels: 255 | `tests/audio/vorbis.luau` |
|
||||
| audio | wav | .wav .wave .rf64 .bw64 | yes | yes | streaming: true, depths: 8, 16, 24, 32, float: true, rf64: true | `tests/audio/wav.luau` |
|
||||
| video | avi | .avi | yes | yes | streaming: true, video: "mjpeg", "mpeg1", "rawvideo", audio: true, odml: true | `tests/video/avi.luau` |
|
||||
| video | h264 | .h264 .264 .avc .jsv .26l .jvt | yes | yes | streaming: true, video: "h264", depths: 8 | `tests/video/h264.luau` |
|
||||
| video | mkv | .mkv .webm .mka .mk3d | yes | yes | streaming: true, remux: true, video: "vp8", "mjpeg", "mpeg1", "rawvideo", audio: true, subtitles: true | `tests/video/mkv.luau` |
|
||||
| video | mp4 | .mp4 .m4v .mov .qt .3gp .3g2 .mj2 | yes | yes | streaming: true, remux: true, video: "mjpeg", "mpeg1", "h264", audio: true, fragments: true | `tests/video/mp4.luau` |
|
||||
| video | mpegps | .mpg .mpeg .vob .m1v .mpv .dat | yes | - | streaming: true, video: "mpeg1", audio: true | `tests/video/mpegps.luau` |
|
||||
@@ -92,6 +93,7 @@ Codecs (layer 1, shared by formats; not loadable on their own):
|
||||
- codecs/Cff: Compact Font Format (Adobe TN #5176) and Type 2 charstrings (TN #5177): the outlines of OpenType fonts
|
||||
- codecs/Dct: the 8x8 DCTs JPEG, Motion-JPEG and MPEG-1 share (native; never throws).
|
||||
- codecs/Deflate: DEFLATE (RFC 1951) decoder and compressor, with the zlib (RFC 1950) and gzip (RFC 1952) wrappers.
|
||||
- codecs/H264: an H.264 / AVC (ITU-T H.264 | ISO/IEC 14496-10) video decoder in pure Luau. A codec (layer 1): the
|
||||
- codecs/Jpeg: the JPEG codec (ITU T.81) on byte ranges: image/jpeg is a thin format over it, and the Motion-JPEG
|
||||
- codecs/Json: JSON (RFC 8259 / ECMA-404) parse and serialize, the engine data/json, glTF, TMJ, ... use. New code.
|
||||
- codecs/Lzma: LZMA and LZMA2 decoders, the .lzma ("LZMA alone") wrapper and the .xz container. A codec (layer 3):
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
function love.conf(t)
|
||||
t.identity = "formats-luau-smoke"
|
||||
t.window.width, t.window.height = 800, 600
|
||||
end
|
||||
@@ -0,0 +1,121 @@
|
||||
-- LÖVE smoke test / example for the LuaJIT build (tools/build.py luajit), run from the repo root:
|
||||
-- love examples/love (a window: images, a voxel model, a tone)
|
||||
-- FORMATS_SMOKE=1 xvfb-run love examples/love (headless: checks, a screenshot, then quits; exit code 1 on
|
||||
-- failure)
|
||||
-- It decodes repo fixtures (PNG suite, a MagicaVoxel model, a glTF box), round-trips an image through PNG / JPEG /
|
||||
-- WebP / GIF / QOI / BMP and a tone through FLAC / WAV / Vorbis / MP3, and shows them with love.graphics / love.audio
|
||||
-- through the host's toImageData / toSoundData.
|
||||
local root = (love.filesystem.getSource():gsub("/examples/love/?$", ""))
|
||||
package.path = root .. "/build/luajit/?.lua;" .. root .. "/build/luajit/?/init.lua;" .. package.path
|
||||
local F = require("formats")
|
||||
require("formats._compat").install() -- buffer / bit32 globals for this file (the library itself does not need them)
|
||||
|
||||
local SMOKE = os.getenv("FORMATS_SMOKE") == "1"
|
||||
if SMOKE then -- headless: print the error and exit instead of showing LÖVE's error screen
|
||||
function love.errorhandler(msg)
|
||||
print("formats-luau love smoke: ERROR " .. tostring(msg) .. "\n" .. debug.traceback())
|
||||
os.exit(1)
|
||||
end
|
||||
end
|
||||
local results, failed = {}, 0
|
||||
local function check(ok, label, detail)
|
||||
results[#results + 1] = (ok and "ok " or "FAIL ") .. label .. (detail and (" " .. tostring(detail)) or "")
|
||||
if not ok then failed = failed + 1 end
|
||||
print(results[#results])
|
||||
return ok
|
||||
end
|
||||
|
||||
local function errstr(e) return e and (type(e) == "table" and (tostring(e.code) .. ": " .. tostring(e.message)) or tostring(e)) or "" end
|
||||
|
||||
local tiles, sound, voxelInfo = {}, nil, ""
|
||||
|
||||
local function tile(name, img)
|
||||
local data = F.host.toImageData(img)
|
||||
tiles[#tiles + 1] = { name = name, image = love.graphics.newImage(data), w = img.width, h = img.height }
|
||||
end
|
||||
|
||||
function love.load()
|
||||
love.window.setTitle("formats-luau on LÖVE " .. table.concat({ love.getVersion() }, ".", 1, 3))
|
||||
check(F.host.name == "love", "host detected", F.host.name)
|
||||
|
||||
-- a decoded fixture
|
||||
local png, e = F.load(root .. "/tests/fixtures/pngsuite/basn6a08.png")
|
||||
if check(png ~= nil and png.width == 32, "png fixture", errstr(e)) then tile("basn6a08.png", png) end
|
||||
|
||||
-- a generated image, saved and reloaded through every image writer
|
||||
local Types = require("formats.Types")
|
||||
local img = Types.Image.new(96, 64, "rgba8")
|
||||
for y = 0, 63 do
|
||||
for x = 0, 95 do
|
||||
local o = (y * 96 + x) * 4
|
||||
buffer.writeu8(img.pixels, o, math.floor(x * 255 / 95))
|
||||
buffer.writeu8(img.pixels, o + 1, math.floor(y * 255 / 63))
|
||||
buffer.writeu8(img.pixels, o + 2, ((math.floor(x / 8) + math.floor(y / 8)) % 2) * 255)
|
||||
buffer.writeu8(img.pixels, o + 3, 255)
|
||||
end
|
||||
end
|
||||
for _, fmt in ipairs({ "png", "jpeg", "webp", "gif", "qoi", "bmp", "tga" }) do
|
||||
local buf, se = F.save(img, nil, { format = fmt })
|
||||
local back, le = buf and F.load(buf)
|
||||
if check(back ~= nil and back.width == 96 and back.height == 64, fmt .. " round trip", errstr(se or le)) then
|
||||
tile(fmt, back)
|
||||
end
|
||||
end
|
||||
|
||||
-- a voxel model: decode, mesh it, report
|
||||
local vox, ve = F.load(root .. "/tests/fixtures/vox/chr_knight.vox")
|
||||
if check(vox ~= nil and vox.kind == "scene", "vox fixture", errstr(ve)) then
|
||||
local n = 0
|
||||
for _ in pairs(vox.nodes or {}) do n = n + 1 end
|
||||
voxelInfo = "chr_knight.vox: " .. n .. " nodes"
|
||||
end
|
||||
local box, ge = F.load(root .. "/tests/fixtures/gltf/Box/glTF-Binary/Box.glb")
|
||||
check(box ~= nil and box.kind == "scene" and #box.meshes >= 1, "glb fixture", errstr(ge))
|
||||
|
||||
-- a tone through the audio writers, played with love.audio
|
||||
local sr, n = 44100, 22050
|
||||
local audio = Types.Audio and Types.Audio.new and Types.Audio.new(sr, 1, n)
|
||||
if audio then
|
||||
for i = 0, n - 1 do
|
||||
buffer.writef32(audio.samples, i * 4, math.sin(i * 2 * math.pi * 440 / sr) * 0.3)
|
||||
end
|
||||
for _, fmt in ipairs({ "flac", "wav", "vorbis", "mp3" }) do
|
||||
local buf, se = F.save(audio, nil, { format = fmt })
|
||||
local back, le = buf and F.load(buf, { category = "audio" })
|
||||
check(back ~= nil and back.sampleRate == sr, fmt .. " round trip", errstr(se or le))
|
||||
if fmt == "flac" and back then
|
||||
local sd = F.host.toSoundData(back)
|
||||
check(sd ~= nil and sd:getSampleCount() > 0, "toSoundData")
|
||||
sound = love.audio.newSource(sd, "static")
|
||||
if not SMOKE then sound:play() end
|
||||
end
|
||||
end
|
||||
else
|
||||
check(false, "Types.Audio.new")
|
||||
end
|
||||
end
|
||||
|
||||
local frames = 0
|
||||
function love.draw()
|
||||
love.graphics.clear(0.12, 0.12, 0.14)
|
||||
local x, y = 8, 8
|
||||
for _, t in ipairs(tiles) do
|
||||
love.graphics.draw(t.image, x, y, 0, 96 / math.max(t.w, t.h) * 1.0)
|
||||
love.graphics.print(t.name, x, y + 100)
|
||||
x = x + 110
|
||||
if x > 680 then x, y = 8, y + 124 end
|
||||
end
|
||||
love.graphics.print(voxelInfo, 8, 300)
|
||||
for i, line in ipairs(results) do
|
||||
love.graphics.print(line, 8, 320 + i * 14)
|
||||
end
|
||||
frames = frames + 1
|
||||
if SMOKE and frames == 3 then
|
||||
love.graphics.captureScreenshot(function(data)
|
||||
data:encode("png", "formats_smoke.png")
|
||||
print("screenshot: " .. love.filesystem.getSaveDirectory() .. "/formats_smoke.png")
|
||||
print(failed == 0 and "formats-luau love smoke: all passed" or ("formats-luau love smoke: " .. failed .. " FAILED"))
|
||||
love.event.quit(failed == 0 and 0 or 1)
|
||||
end)
|
||||
end
|
||||
end
|
||||
@@ -36,6 +36,8 @@
|
||||
| `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) |
|
||||
| `src/Formats/codecs/H264/` (Tables: CAVLC / CABAC / deblocking / scaling constant tables of ITU-T H.264, extracted from openh264 sources; the decoder itself is written from the spec) | openh264 2.x (Cisco) | BSD-2-Clause: [openh264-LICENSE.txt](openh264-LICENSE.txt) |
|
||||
| `tests/gen/h264_jvt` (downloaded at fixture time, not committed) | ITU-T H.264.1 / JVT conformance bitstreams (itu.int) | ITU-T test data |
|
||||
|
||||
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").
|
||||
@@ -0,0 +1,23 @@
|
||||
Copyright (c) 2013, Cisco Systems
|
||||
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.
|
||||
|
||||
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.
|
||||
@@ -290,6 +290,18 @@ local list: { Entry } = {
|
||||
return require("@formats/video/avi")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "h264",
|
||||
category = "video",
|
||||
path = "video/h264",
|
||||
extensions = { "h264", "264", "avc", "jsv", "26l", "jvt" },
|
||||
mime = { "video/h264" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "containers/Demux", "codecs/Video", "codecs/Video/Source", "codecs/H264" },
|
||||
caps = { decode = true, encode = true, streaming = true, video = { "h264" }, depths = { 8 } },
|
||||
load = function()
|
||||
return require("@formats/video/h264")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "mkv",
|
||||
category = "video",
|
||||
|
||||
@@ -0,0 +1,293 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- codecs/H264/Bitstream: NAL unit framing and the RBSP bit reader of ITU-T H.264 (7.3 / 7.4 / 9.1): Annex B start
|
||||
-- code splitting, AVCC length-prefixed samples, avcC (AVCDecoderConfigurationRecord, ISO/IEC 14496-15 5.3.3)
|
||||
-- parsing, emulation-prevention removal, and the u(n) / ue(v) / se(v) / te(v) readers. Written from the spec.
|
||||
-- Never throws: reads past the end of an RBSP return zero bits (the buffer carries 8 zero bytes of padding and every
|
||||
-- read is range-checked), and callers check `r.pos > r.size` once per syntax structure.
|
||||
local Bitstream = {}
|
||||
|
||||
local readu8 = buffer.readu8
|
||||
local band, lshift = bit32.band, bit32.lshift
|
||||
|
||||
export type Reader = {
|
||||
buf: buffer, -- the RBSP (emulation prevention removed) followed by 8 zero bytes
|
||||
pos: number, -- bit position
|
||||
size: number, -- RBSP length in bits (up to the end of the data, trailing bits included)
|
||||
stop: number, -- bit position of the rbsp_stop_one_bit (size when there is none)
|
||||
n: number, -- buffer length in bytes
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ framing
|
||||
-- splitAnnexB(buf, off, len) -> { off1, len1, off2, len2, ... }: NAL unit payload ranges between start codes
|
||||
-- (00 00 01, with any leading zero bytes); trailing zero bytes of a NAL are dropped.
|
||||
function Bitstream.splitAnnexB(buf: buffer, off: number, len: number): { number }
|
||||
local out = {}
|
||||
local e = off + len
|
||||
local i = off
|
||||
local start = -1
|
||||
while i + 2 < e do
|
||||
local b2 = readu8(buf, i + 2)
|
||||
if b2 > 1 then
|
||||
i += 3
|
||||
elseif readu8(buf, i + 1) ~= 0 then
|
||||
i += 2
|
||||
elseif b2 == 1 and readu8(buf, i) == 0 then
|
||||
if start >= 0 then
|
||||
local j = i
|
||||
while j > start and readu8(buf, j - 1) == 0 do
|
||||
j -= 1
|
||||
end
|
||||
if j > start then
|
||||
table.insert(out, start)
|
||||
table.insert(out, j - start)
|
||||
end
|
||||
end
|
||||
start = i + 3
|
||||
i += 3
|
||||
else
|
||||
i += 1
|
||||
end
|
||||
end
|
||||
if start >= 0 then
|
||||
local j = e
|
||||
while j > start and readu8(buf, j - 1) == 0 do
|
||||
j -= 1
|
||||
end
|
||||
if j > start then
|
||||
table.insert(out, start)
|
||||
table.insert(out, j - start)
|
||||
end
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
-- isAnnexB(buf, off, len) -> true when the data starts with a start code (00 00 01 or 00 00 00 01)
|
||||
function Bitstream.isAnnexB(buf: buffer, off: number, len: number): boolean
|
||||
if len >= 3 and readu8(buf, off) == 0 and readu8(buf, off + 1) == 0 then
|
||||
local b2 = readu8(buf, off + 2)
|
||||
if b2 == 1 then
|
||||
return true
|
||||
end
|
||||
return b2 == 0 and len >= 4 and readu8(buf, off + 3) == 1
|
||||
end
|
||||
return false
|
||||
end
|
||||
|
||||
-- splitLength(buf, off, len, size) -> NAL ranges of a length-prefixed (AVCC / MP4 sample) buffer, or nil when a
|
||||
-- length runs past the end (the NALs before it are kept in the second result)
|
||||
function Bitstream.splitLength(buf: buffer, off: number, len: number, size: number): ({ number }?, { number })
|
||||
local out = {}
|
||||
local e = off + len
|
||||
local p = off
|
||||
while p + size <= e do
|
||||
local n = 0
|
||||
for k = 0, size - 1 do
|
||||
n = n * 256 + readu8(buf, p + k)
|
||||
end
|
||||
p += size
|
||||
if n > e - p then
|
||||
return nil, out
|
||||
end
|
||||
if n > 0 then
|
||||
table.insert(out, p)
|
||||
table.insert(out, n)
|
||||
end
|
||||
p += n
|
||||
end
|
||||
return out, out
|
||||
end
|
||||
|
||||
-- parseAvcC(buf, off, len) -> { lengthSize, profile, level, nals = { off, len, ... } (SPS then PPS, + SPS ext) } |
|
||||
-- nil, message
|
||||
function Bitstream.parseAvcC(buf: buffer, off: number, len: number): (any, string?)
|
||||
if len < 7 then
|
||||
return nil, "truncated: avcC shorter than 7 bytes"
|
||||
end
|
||||
if readu8(buf, off) ~= 1 then
|
||||
return nil, "avcC configurationVersion is not 1"
|
||||
end
|
||||
local cfg = {
|
||||
profile = readu8(buf, off + 1),
|
||||
compat = readu8(buf, off + 2),
|
||||
level = readu8(buf, off + 3),
|
||||
lengthSize = band(readu8(buf, off + 4), 3) + 1,
|
||||
nals = {} :: { number },
|
||||
}
|
||||
local p = off + 5
|
||||
local e = off + len
|
||||
for pass = 1, 2 do
|
||||
if p >= e then
|
||||
return nil, "truncated: avcC parameter set count"
|
||||
end
|
||||
local count = if pass == 1 then band(readu8(buf, p), 31) else readu8(buf, p)
|
||||
p += 1
|
||||
for _ = 1, count do
|
||||
if p + 2 > e then
|
||||
return nil, "truncated: avcC parameter set length"
|
||||
end
|
||||
local n = readu8(buf, p) * 256 + readu8(buf, p + 1)
|
||||
p += 2
|
||||
if p + n > e then
|
||||
return nil, "truncated: avcC parameter set"
|
||||
end
|
||||
table.insert(cfg.nals, p)
|
||||
table.insert(cfg.nals, n)
|
||||
p += n
|
||||
end
|
||||
end
|
||||
return cfg, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ rbsp
|
||||
-- reader(buf, off, len, skip) -> Reader over the RBSP of a NAL unit's bytes [off, off + len), the first `skip`
|
||||
-- bytes (the NAL header) left out; emulation_prevention_three_byte (00 00 03) removed.
|
||||
function Bitstream.reader(buf: buffer, off: number, len: number, skip: number): Reader
|
||||
local out = buffer.create(len + 8)
|
||||
local o = 0
|
||||
local zeros = 0
|
||||
for i = off + skip, off + len - 1 do
|
||||
local b = readu8(buf, i)
|
||||
if zeros >= 2 and b == 3 then
|
||||
zeros = 0
|
||||
else
|
||||
buffer.writeu8(out, o, b)
|
||||
o += 1
|
||||
if b == 0 then
|
||||
zeros += 1
|
||||
else
|
||||
zeros = 0
|
||||
end
|
||||
end
|
||||
end
|
||||
-- the rbsp_stop_one_bit: the last set bit of the last non-zero byte
|
||||
local stop = o * 8
|
||||
local j = o - 1
|
||||
while j >= 0 and readu8(out, j) == 0 do
|
||||
j -= 1
|
||||
end
|
||||
if j >= 0 then
|
||||
local b = readu8(out, j)
|
||||
local k = 0
|
||||
while band(b, lshift(1, k)) == 0 do
|
||||
k += 1
|
||||
end
|
||||
stop = j * 8 + 7 - k
|
||||
end
|
||||
return { buf = out, pos = 0, size = o * 8, stop = stop, n = o + 8 }
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ bits
|
||||
-- Plain arithmetic instead of bit32 (LuaJIT runs bit32 through compat wrappers whose sign fix-ups split traces).
|
||||
local P2 = table.create(33, 1) -- P2[k + 1] = 2^k
|
||||
for k = 0, 32 do
|
||||
P2[k + 1] = 2 ^ k
|
||||
end
|
||||
Bitstream.P2 = P2
|
||||
local LZ8 = table.create(256, 0) -- LZ8[x + 1] = leading zero bits of the byte x (8 for 0)
|
||||
for x = 0, 255 do
|
||||
local n, v = 0, x
|
||||
while n < 8 and v < 128 do
|
||||
v *= 2
|
||||
n += 1
|
||||
end
|
||||
LZ8[x + 1] = n
|
||||
end
|
||||
Bitstream.LZ8 = LZ8
|
||||
|
||||
-- clz32(v) -> leading zero bits of a 32-bit value
|
||||
local function clz32(v: number): number
|
||||
if v >= 16777216 then
|
||||
return LZ8[v // 16777216 + 1]
|
||||
elseif v >= 65536 then
|
||||
return 8 + LZ8[v // 65536 + 1]
|
||||
elseif v >= 256 then
|
||||
return 16 + LZ8[v // 256 + 1]
|
||||
end
|
||||
return 24 + LZ8[v + 1]
|
||||
end
|
||||
Bitstream.clz32 = clz32
|
||||
|
||||
-- peekAt(b, n, pos) -> the 32 bits at bit position pos of buffer b (n bytes), zeros past the end
|
||||
local function peekAt(b: buffer, n: number, pos: number): number
|
||||
local p = pos // 8
|
||||
if p + 5 > n then
|
||||
return 0
|
||||
end
|
||||
local s = pos - p * 8
|
||||
local w = readu8(b, p) * 16777216 + readu8(b, p + 1) * 65536 + readu8(b, p + 2) * 256 + readu8(b, p + 3)
|
||||
if s == 0 then
|
||||
return w
|
||||
end
|
||||
return (w * P2[s + 1]) % 4294967296 + readu8(b, p + 4) // P2[9 - s]
|
||||
end
|
||||
Bitstream.peekAt = peekAt
|
||||
|
||||
-- peek32(r) -> the next 32 bits (zeros past the end)
|
||||
local function peek32(r: Reader): number
|
||||
return peekAt(r.buf, r.n, r.pos)
|
||||
end
|
||||
Bitstream.peek32 = peek32
|
||||
|
||||
-- u(r, n) -> n bits (n 1..32) as an unsigned number
|
||||
function Bitstream.u(r: Reader, n: number): number
|
||||
local v = peekAt(r.buf, r.n, r.pos)
|
||||
r.pos += n
|
||||
return v // P2[33 - n]
|
||||
end
|
||||
|
||||
-- u1(r) -> one bit
|
||||
function Bitstream.u1(r: Reader): number
|
||||
local pos = r.pos
|
||||
r.pos = pos + 1
|
||||
local p = pos // 8
|
||||
if p >= r.n then
|
||||
return 0
|
||||
end
|
||||
return (readu8(r.buf, p) // P2[8 - (pos - p * 8)]) % 2
|
||||
end
|
||||
|
||||
-- ue(r) -> ue(v); a code with more than 31 leading zeros returns 2^32 (out of range for every syntax element)
|
||||
local function ue(r: Reader): number
|
||||
local v = peekAt(r.buf, r.n, r.pos)
|
||||
if v == 0 then
|
||||
r.pos += 32
|
||||
return 4294967296
|
||||
end
|
||||
local lz = clz32(v)
|
||||
if lz < 16 then
|
||||
local n = 2 * lz + 1
|
||||
r.pos += n
|
||||
return v // P2[33 - n] - 1
|
||||
end
|
||||
r.pos += lz
|
||||
v = peekAt(r.buf, r.n, r.pos)
|
||||
r.pos += lz + 1
|
||||
return v // P2[32 - lz] - 1
|
||||
end
|
||||
Bitstream.ue = ue
|
||||
|
||||
-- se(r) -> se(v)
|
||||
function Bitstream.se(r: Reader): number
|
||||
local k = ue(r)
|
||||
if k % 2 == 1 then
|
||||
return (k + 1) // 2
|
||||
end
|
||||
return -(k // 2)
|
||||
end
|
||||
|
||||
-- te(r, range) -> te(v) with the given range (max value)
|
||||
function Bitstream.te(r: Reader, range: number): number
|
||||
if range == 1 then
|
||||
return 1 - Bitstream.u1(r)
|
||||
end
|
||||
return ue(r)
|
||||
end
|
||||
|
||||
-- moreData(r) -> more_rbsp_data()
|
||||
function Bitstream.moreData(r: Reader): boolean
|
||||
return r.pos < r.stop
|
||||
end
|
||||
|
||||
return Bitstream
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,772 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- codecs/H264/Cavlc: slice data and macroblock layer with CAVLC entropy coding (ITU-T H.264 7.3.4, 7.3.5, 9.2):
|
||||
-- mb_skip_run, mb_type / sub_mb_type, intra modes, ref_idx (te), mvd, coded_block_pattern (me), mb_qp_delta and
|
||||
-- residual_block_cavlc (coeff_token, level_prefix / suffix, total_zeros, run_before) with the 8x8 interleaving.
|
||||
-- Coefficients are dequantised as they are placed. Written from the spec; VLC tables from Tables.
|
||||
-- Never throws: returns false, "message" on bad data.
|
||||
local Bitstream = require("@formats/codecs/H264/Bitstream")
|
||||
local Tables = require("@formats/codecs/H264/Tables")
|
||||
local Mb = require("@formats/codecs/H264/Mb")
|
||||
|
||||
local u, u1, ue, se = Bitstream.u, Bitstream.u1, Bitstream.ue, Bitstream.se
|
||||
|
||||
local K_I4, K_I8, K_I16, K_PCM, K_P, K_PSKIP, K_B, K_BSKIP, K_BDIRECT = Mb.K_I4, Mb.K_I8, Mb.K_I16, Mb.K_PCM, Mb.K_P, Mb.K_PSKIP, Mb.K_B, Mb.K_BSKIP, Mb.K_BDIRECT
|
||||
local BLK_X, BLK_Y = Mb.BLK_X, Mb.BLK_Y
|
||||
|
||||
local Cavlc = {}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ vlc tables
|
||||
-- build(entries) -> l1, l2: a two-level lookup on 16 peeked bits. l1[(v >> 8) + 1] = value * 32 + length, or
|
||||
-- -(base) of a second-level block l2[base + (v & 255)]; 0 = no code
|
||||
local function build(entries: { { number } }): ({ number }, { number })
|
||||
local l1 = table.create(256, 0)
|
||||
local l2 = {}
|
||||
local nsub = 0
|
||||
for _, e in entries do
|
||||
local code, len, val = e[1], e[2], e[3]
|
||||
local packed = val * 32 + len
|
||||
if len <= 8 then
|
||||
local s = code * 2 ^ (8 - len)
|
||||
for k = 0, 2 ^ (8 - len) - 1 do
|
||||
l1[s + k + 1] = packed
|
||||
end
|
||||
else
|
||||
local prefix = code // 2 ^ (len - 8)
|
||||
local base = -l1[prefix + 1]
|
||||
if base <= 0 then
|
||||
base = nsub * 256 + 1
|
||||
nsub += 1
|
||||
for k = 0, 255 do
|
||||
l2[base + k] = 0
|
||||
end
|
||||
l1[prefix + 1] = -base
|
||||
end
|
||||
local s = (code % 2 ^ (len - 8)) * 2 ^ (16 - len)
|
||||
for k = 0, 2 ^ (16 - len) - 1 do
|
||||
l2[base + s + k] = packed
|
||||
end
|
||||
end
|
||||
end
|
||||
return l1, l2
|
||||
end
|
||||
|
||||
-- coeff_token: CT1[class + 1], CT2[class + 1]; value = TotalCoeff * 4 + TrailingOnes
|
||||
local CT1, CT2 = {}, {}
|
||||
for t = 0, 4 do
|
||||
local src = (Tables :: any)["COEFF_TOKEN_" .. t]
|
||||
local entries = {}
|
||||
for i = 1, #src, 4 do
|
||||
table.insert(entries, { src[i], src[i + 1], src[i + 2] * 4 + src[i + 3] })
|
||||
end
|
||||
CT1[t + 1], CT2[t + 1] = build(entries)
|
||||
end
|
||||
|
||||
-- total_zeros by tzVlcIndex (luma 1..15, chroma DC 1..3), run_before by min(zerosLeft, 7)
|
||||
local function group(src: { number }, n: number): ({ { number } }, { { number } })
|
||||
local per = {}
|
||||
for i = 1, n do
|
||||
per[i] = {}
|
||||
end
|
||||
for i = 1, #src, 4 do
|
||||
table.insert(per[src[i]], { src[i + 1], src[i + 2], src[i + 3] })
|
||||
end
|
||||
local a, b = {}, {}
|
||||
for i = 1, n do
|
||||
a[i], b[i] = build(per[i])
|
||||
end
|
||||
return a, b
|
||||
end
|
||||
local TZ1, TZ2 = group(Tables.TOTAL_ZEROS, 15)
|
||||
local TZC1, TZC2 = group(Tables.TOTAL_ZEROS_CDC, 3)
|
||||
local RB1, RB2 = group(Tables.RUN_BEFORE, 7)
|
||||
|
||||
-- scans: coefficient index (1-based) -> raster position (0-based)
|
||||
local ZZ4 = Tables.ZIGZAG4
|
||||
local ZZAC = table.create(15, 0)
|
||||
for i = 1, 15 do
|
||||
ZZAC[i] = ZZ4[i + 1]
|
||||
end
|
||||
local ZZ8I = {} -- [i4 + 1][k + 1] = raster position in the 8x8 block of the k-th coefficient of interleaved list i4
|
||||
for i4 = 0, 3 do
|
||||
local t = table.create(16, 0)
|
||||
for k = 0, 15 do
|
||||
t[k + 1] = Tables.ZIGZAG8[4 * k + i4 + 1]
|
||||
end
|
||||
ZZ8I[i4 + 1] = t
|
||||
end
|
||||
local IDENT = { 0, 1, 2, 3 }
|
||||
|
||||
local INTRA_CBP, INTER_CBP = Tables.INTRA_CBP, Tables.INTER_CBP
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ residual
|
||||
local LEVEL = table.create(16, 0)
|
||||
local RUN = table.create(16, 0)
|
||||
|
||||
local peek = Bitstream.peekAt
|
||||
local clz32 = Bitstream.clz32
|
||||
local P2 = Bitstream.P2
|
||||
|
||||
-- residual(r, nC, maxCoeff, out, base, scan, mul, div) -> TotalCoeff, or -1 on a bad code. Levels go to
|
||||
-- out[base + scan[i] + 1] dequantised as (level * mul[pos + 1] + div / 2) // div (mul nil: raw levels)
|
||||
local function residual(r: Bitstream.Reader, nC: number, maxCoeff: number, out: { number }, base: number, scan: { number }, mul: { number }?, div: number): number
|
||||
local b, n = r.buf, r.n
|
||||
local pos = r.pos
|
||||
local cls
|
||||
if nC < 0 then
|
||||
cls = 5
|
||||
elseif nC < 2 then
|
||||
cls = 1
|
||||
elseif nC < 4 then
|
||||
cls = 2
|
||||
elseif nC < 8 then
|
||||
cls = 3
|
||||
else
|
||||
cls = 4
|
||||
end
|
||||
local v = peek(b, n, pos) // 65536
|
||||
local e = CT1[cls][v // 256 + 1]
|
||||
if e < 0 then
|
||||
e = CT2[cls][-e + v % 256]
|
||||
end
|
||||
if e == 0 then
|
||||
return -1
|
||||
end
|
||||
pos += e % 32
|
||||
local tok = e // 32
|
||||
local tc = tok // 4
|
||||
local t1 = tok % 4
|
||||
if tc == 0 then
|
||||
r.pos = pos
|
||||
return 0
|
||||
end
|
||||
if tc > maxCoeff then
|
||||
return -1
|
||||
end
|
||||
-- levels
|
||||
local w = peek(b, n, pos)
|
||||
for i = 0, t1 - 1 do
|
||||
LEVEL[i + 1] = 1 - 2 * ((w // P2[32 - i]) % 2)
|
||||
end
|
||||
pos += t1
|
||||
local suffixLength = ((tc > 10 and t1 < 3) and (1) or (0))
|
||||
for i = t1, tc - 1 do
|
||||
w = peek(b, n, pos)
|
||||
local prefix = if w == 0 then 32 else clz32(w)
|
||||
if prefix > 28 then
|
||||
return -1
|
||||
end
|
||||
pos += prefix + 1
|
||||
local size = suffixLength
|
||||
if prefix == 14 and suffixLength == 0 then
|
||||
size = 4
|
||||
elseif prefix >= 15 then
|
||||
size = prefix - 3
|
||||
end
|
||||
local levelCode = (((prefix < 15) and (prefix) or (15))) * 2 ^ suffixLength
|
||||
if size > 0 then
|
||||
levelCode += peek(b, n, pos) // P2[33 - size]
|
||||
pos += size
|
||||
end
|
||||
if prefix >= 15 and suffixLength == 0 then
|
||||
levelCode += 15
|
||||
end
|
||||
if prefix >= 16 then
|
||||
levelCode += 2 ^ (prefix - 3) - 4096
|
||||
end
|
||||
if i == t1 and t1 < 3 then
|
||||
levelCode += 2
|
||||
end
|
||||
local level
|
||||
if levelCode % 2 == 0 then
|
||||
level = (levelCode + 2) // 2
|
||||
else
|
||||
level = -((levelCode + 1) // 2)
|
||||
end
|
||||
LEVEL[i + 1] = level
|
||||
if suffixLength == 0 then
|
||||
suffixLength = 1
|
||||
end
|
||||
local a = ((level < 0) and (-level) or (level))
|
||||
if a > 3 * 2 ^ (suffixLength - 1) and suffixLength < 6 then
|
||||
suffixLength += 1
|
||||
end
|
||||
end
|
||||
-- total_zeros
|
||||
local zerosLeft = 0
|
||||
if tc < maxCoeff then
|
||||
v = peek(b, n, pos) // 65536
|
||||
local l1, l2
|
||||
if maxCoeff == 4 then
|
||||
l1, l2 = TZC1[tc], TZC2[tc]
|
||||
else
|
||||
l1, l2 = TZ1[tc], TZ2[tc]
|
||||
end
|
||||
e = l1[v // 256 + 1]
|
||||
if e < 0 then
|
||||
e = l2[-e + v % 256]
|
||||
end
|
||||
if e == 0 then
|
||||
return -1
|
||||
end
|
||||
pos += e % 32
|
||||
zerosLeft = e // 32
|
||||
if zerosLeft + tc > maxCoeff then
|
||||
return -1
|
||||
end
|
||||
end
|
||||
-- run_before
|
||||
for i = 0, tc - 2 do
|
||||
local run = 0
|
||||
if zerosLeft > 0 then
|
||||
local t = ((zerosLeft > 7) and (7) or (zerosLeft))
|
||||
v = peek(b, n, pos) // 65536
|
||||
e = RB1[t][v // 256 + 1]
|
||||
if e < 0 then
|
||||
e = RB2[t][-e + v % 256]
|
||||
end
|
||||
if e == 0 then
|
||||
return -1
|
||||
end
|
||||
pos += e % 32
|
||||
run = e // 32
|
||||
if run > zerosLeft then
|
||||
return -1
|
||||
end
|
||||
end
|
||||
RUN[i + 1] = run
|
||||
zerosLeft -= run
|
||||
end
|
||||
RUN[tc] = zerosLeft
|
||||
r.pos = pos
|
||||
-- place (highest frequency first)
|
||||
local k = -1
|
||||
local half = div // 2
|
||||
for i = tc - 1, 0, -1 do
|
||||
k += RUN[i + 1] + 1
|
||||
local p = scan[k + 1]
|
||||
if mul then
|
||||
out[base + p + 1] = (LEVEL[i + 1] * mul[p + 1] + half) // div
|
||||
else
|
||||
out[base + p + 1] = LEVEL[i + 1]
|
||||
end
|
||||
end
|
||||
return tc
|
||||
end
|
||||
Cavlc.residual = residual
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ macroblock
|
||||
local SUBB_PF = { 0, 1, 2, 3, 1, 1, 2, 2, 3, 3, 1, 2, 3 }
|
||||
local SUBB_SHAPE = { 0, 0, 0, 0, 1, 2, 1, 2, 1, 2, 3, 3, 3 }
|
||||
local SUB_N = { 1, 2, 2, 4 }
|
||||
local BPAIR0 = { 1, 2, 1, 2, 1, 2, 3, 3, 3 }
|
||||
local BPAIR1 = { 1, 2, 2, 1, 3, 3, 1, 2, 3 }
|
||||
|
||||
local function refIdx(r: Bitstream.Reader, n: number): number
|
||||
if n <= 1 then
|
||||
return 0
|
||||
end
|
||||
local v
|
||||
if n == 2 then
|
||||
v = 1 - u1(r)
|
||||
else
|
||||
v = ue(r)
|
||||
end
|
||||
if v >= n then
|
||||
return -1
|
||||
end
|
||||
return v
|
||||
end
|
||||
|
||||
-- the residual of the parsed macroblock
|
||||
local function residuals(S: any, M: any, r: Bitstream.Reader): (boolean, string?)
|
||||
local kind = M.kind
|
||||
local cbp = M.cbp
|
||||
local intra = kind <= K_PCM
|
||||
local dq = S.dq
|
||||
local qp = M.qp
|
||||
local w4, g0 = S.w4, M.g0
|
||||
local grid = S.nzc
|
||||
local nz = M.nz
|
||||
local c4 = M.c4
|
||||
if kind == K_I16 then
|
||||
local tc = residual(r, Mb.nC(S, M, 0, 0), 16, M.dcY, 0, ZZ4, nil, 1)
|
||||
if tc < 0 then
|
||||
return false, "bad Intra16x16 DC residual"
|
||||
end
|
||||
M.hasDcY = tc > 0
|
||||
end
|
||||
local mul4 = dq.d4[((intra) and (1) or (4))][qp + 1]
|
||||
if M.t8 == 1 then
|
||||
local mul8 = dq.d8[((intra) and (1) or (2))][qp + 1]
|
||||
local c8 = M.c8
|
||||
for i8 = 0, 3 do
|
||||
local bx0, by0 = (i8 % 2) * 2, (i8 // 2) * 2
|
||||
local sum = 0
|
||||
for i4 = 0, 3 do
|
||||
local bx, by = bx0 + i4 % 2, by0 + i4 // 2
|
||||
local tc = 0
|
||||
if (cbp // P2[i8 + 1]) % 2 ~= 0 then
|
||||
tc = residual(r, Mb.nC(S, M, bx, by), 16, c8, i8 * 64, ZZ8I[i4 + 1], mul8, 64)
|
||||
if tc < 0 then
|
||||
return false, "bad 8x8 luma residual"
|
||||
end
|
||||
end
|
||||
grid[g0 + by * w4 + bx] = tc
|
||||
sum += tc
|
||||
end
|
||||
nz[by0 * 4 + bx0 + 1] = sum
|
||||
nz[by0 * 4 + bx0 + 2] = sum
|
||||
nz[by0 * 4 + bx0 + 5] = sum
|
||||
nz[by0 * 4 + bx0 + 6] = sum
|
||||
end
|
||||
else
|
||||
local ac = kind == K_I16
|
||||
for i = 0, 15 do
|
||||
local bx, by = BLK_X[i + 1], BLK_Y[i + 1]
|
||||
local blk = by * 4 + bx
|
||||
local tc = 0
|
||||
if (cbp // P2[i // 4 + 1]) % 2 ~= 0 then
|
||||
if ac then
|
||||
tc = residual(r, Mb.nC(S, M, bx, by), 15, c4, blk * 16, ZZAC, mul4, 16)
|
||||
else
|
||||
tc = residual(r, Mb.nC(S, M, bx, by), 16, c4, blk * 16, ZZ4, mul4, 16)
|
||||
end
|
||||
if tc < 0 then
|
||||
return false, "bad luma residual"
|
||||
end
|
||||
end
|
||||
grid[g0 + by * w4 + bx] = tc
|
||||
nz[blk + 1] = tc
|
||||
end
|
||||
end
|
||||
-- chroma
|
||||
local chroma = cbp // 16
|
||||
local cw, c0 = S.cw4, M.c0
|
||||
local nzcCb, nzcCr = S.nzcCb, S.nzcCr
|
||||
local nzc = M.nzc
|
||||
if chroma ~= 0 then
|
||||
local any = false
|
||||
for plane = 0, 1 do
|
||||
local tc = residual(r, -1, 4, M.dcC, plane * 4, IDENT, nil, 1)
|
||||
if tc < 0 then
|
||||
return false, "bad chroma DC residual"
|
||||
end
|
||||
if tc > 0 then
|
||||
any = true
|
||||
end
|
||||
end
|
||||
M.hasDcC = any
|
||||
end
|
||||
local cc = M.cc
|
||||
for plane = 0, 1 do
|
||||
local tab = ((plane == 0) and (nzcCb) or (nzcCr))
|
||||
local mulc = dq.d4[(((intra) and (2) or (5))) + plane][(((plane == 0) and (M.qpc) or (M.qpc2))) + 1]
|
||||
for blk = 0, 3 do
|
||||
local bx, by = blk % 2, blk // 2
|
||||
local tc = 0
|
||||
if chroma == 2 then
|
||||
tc = residual(r, Mb.nCc(S, M, tab, bx, by), 15, cc, (plane * 4 + blk) * 16, ZZAC, mulc, 16)
|
||||
if tc < 0 then
|
||||
return false, "bad chroma AC residual"
|
||||
end
|
||||
end
|
||||
tab[c0 + by * cw + bx] = tc
|
||||
nzc[plane * 4 + blk + 1] = tc
|
||||
end
|
||||
end
|
||||
return true
|
||||
end
|
||||
|
||||
local function setQp(S: any, M: any, delta: number): boolean
|
||||
if delta < -26 or delta > 25 then
|
||||
return false
|
||||
end
|
||||
local qp = (S.qp + delta + 52) % 52
|
||||
S.qp = qp
|
||||
M.qp = qp
|
||||
M.qpc = S.qpcOf[qp + 1]
|
||||
M.qpc2 = S.qpc2Of[qp + 1]
|
||||
return true
|
||||
end
|
||||
|
||||
local function clearLumaGrids(S: any, M: any, intra: boolean)
|
||||
-- the CABAC-only grids stay zero for CAVLC; intra modes for non-NxN macroblocks are written by Mb.recon
|
||||
local _ = intra
|
||||
local nz = M.nz
|
||||
for i = 1, 16 do
|
||||
nz[i] = 0
|
||||
end
|
||||
local nzc = M.nzc
|
||||
for i = 1, 8 do
|
||||
nzc[i] = 0
|
||||
end
|
||||
end
|
||||
|
||||
-- intra(S, M, r, t): the intra macroblock types 0..25 (table 7-11)
|
||||
local function intraMb(S: any, M: any, r: Bitstream.Reader, t: number): (boolean, string?)
|
||||
local addr = M.addr + 1
|
||||
if t == 25 then
|
||||
M.kind = K_PCM
|
||||
r.pos = (r.pos + 7) // 8 * 8
|
||||
local p = r.pos // 8
|
||||
if p + 384 > r.size // 8 then
|
||||
return false, "truncated: I_PCM samples"
|
||||
end
|
||||
buffer.copy(M.pcm, 0, r.buf, p, 384)
|
||||
r.pos += 3072
|
||||
M.qp = S.qp
|
||||
M.qpc, M.qpc2 = 0, 0
|
||||
M.cbp = 0x2f
|
||||
local w4, g0 = S.w4, M.g0
|
||||
for j = 0, 3 do
|
||||
for i = 0, 3 do
|
||||
S.nzc[g0 + j * w4 + i] = 16
|
||||
end
|
||||
end
|
||||
local cw, c0 = S.cw4, M.c0
|
||||
for j = 0, 1 do
|
||||
for i = 0, 1 do
|
||||
S.nzcCb[c0 + j * cw + i] = 16
|
||||
S.nzcCr[c0 + j * cw + i] = 16
|
||||
end
|
||||
end
|
||||
S.cbpTab[addr] = 0x2f
|
||||
S.dcTab[addr] = 7
|
||||
S.cpmTab[addr] = 0
|
||||
S.qpdTab[addr] = 0
|
||||
Mb.recon(S, M)
|
||||
return true
|
||||
end
|
||||
clearLumaGrids(S, M, true)
|
||||
if t == 0 then
|
||||
M.kind = K_I4
|
||||
if S.t8mode and u1(r) == 1 then
|
||||
M.kind = K_I8
|
||||
M.t8 = 1
|
||||
end
|
||||
local ipm = M.ipm
|
||||
local grid = S.ipm
|
||||
local w4, g0 = S.w4, M.g0
|
||||
if M.t8 == 1 then
|
||||
for i8 = 0, 3 do
|
||||
local bx, by = (i8 % 2) * 2, (i8 // 2) * 2
|
||||
local pred = Mb.predMode(S, M, bx, by)
|
||||
local mode = pred
|
||||
if u1(r) == 0 then
|
||||
local rem = u(r, 3)
|
||||
mode = ((rem < pred) and (rem) or (rem + 1))
|
||||
end
|
||||
ipm[by * 4 + bx + 1] = mode
|
||||
local g = g0 + by * w4 + bx
|
||||
grid[g], grid[g + 1], grid[g + w4], grid[g + w4 + 1] = mode, mode, mode, mode
|
||||
end
|
||||
else
|
||||
for i = 0, 15 do
|
||||
local bx, by = BLK_X[i + 1], BLK_Y[i + 1]
|
||||
local pred = Mb.predMode(S, M, bx, by)
|
||||
local mode = pred
|
||||
if u1(r) == 0 then
|
||||
local rem = u(r, 3)
|
||||
mode = ((rem < pred) and (rem) or (rem + 1))
|
||||
end
|
||||
ipm[by * 4 + bx + 1] = mode
|
||||
grid[g0 + by * w4 + bx] = mode
|
||||
end
|
||||
end
|
||||
M.cpm = ue(r)
|
||||
if M.cpm > 3 then
|
||||
return false, "intra_chroma_pred_mode out of range"
|
||||
end
|
||||
local code = ue(r)
|
||||
if code > 47 then
|
||||
return false, "coded_block_pattern out of range"
|
||||
end
|
||||
M.cbp = INTRA_CBP[code + 1]
|
||||
elseif t <= 24 then
|
||||
M.kind = K_I16
|
||||
M.i16 = (t - 1) % 4
|
||||
M.cbp = ((t - 1) // 4) % 3 * 16 + (((t >= 13) and (15) or (0)))
|
||||
M.cpm = ue(r)
|
||||
if M.cpm > 3 then
|
||||
return false, "intra_chroma_pred_mode out of range"
|
||||
end
|
||||
else
|
||||
return false, "mb_type out of range"
|
||||
end
|
||||
S.cpmTab[addr] = M.cpm
|
||||
S.cbpTab[addr] = M.cbp
|
||||
if M.cbp > 0 or M.kind == K_I16 then
|
||||
if not setQp(S, M, Bitstream.se(r)) then
|
||||
return false, "mb_qp_delta out of range"
|
||||
end
|
||||
else
|
||||
setQp(S, M, 0)
|
||||
end
|
||||
if r.pos > r.size then
|
||||
return false, "truncated: macroblock"
|
||||
end
|
||||
local ok, err = residuals(S, M, r)
|
||||
if not ok then
|
||||
return false, err
|
||||
end
|
||||
Mb.recon(S, M)
|
||||
return true
|
||||
end
|
||||
|
||||
-- inter(S, M, r, t, isB): the P (0..4) and B (0..22) inter macroblock types
|
||||
local function interMb(S: any, M: any, r: Bitstream.Reader, t: number, isB: boolean): (boolean, string?)
|
||||
clearLumaGrids(S, M, false)
|
||||
local n0, n1 = S.n0, S.n1
|
||||
local pf, sub, dir, ref0, ref1, mvd0, mvd1 = M.pf, M.sub, M.dir, M.ref0, M.ref1, M.mvd0, M.mvd1
|
||||
for i = 1, 4 do
|
||||
dir[i] = false
|
||||
ref0[i], ref1[i] = 0, 0
|
||||
end
|
||||
for i = 1, 32 do
|
||||
mvd0[i], mvd1[i] = 0, 0
|
||||
end
|
||||
local noSmall = true
|
||||
if not isB then
|
||||
M.kind = K_P
|
||||
if t > 4 then
|
||||
return false, "mb_type out of range"
|
||||
end
|
||||
M.part = ((t >= 3) and (3) or (t))
|
||||
pf[1], pf[2], pf[3], pf[4] = 1, 1, 1, 1
|
||||
if M.part == 3 then
|
||||
for i = 1, 4 do
|
||||
local s = ue(r)
|
||||
if s > 3 then
|
||||
return false, "sub_mb_type out of range"
|
||||
end
|
||||
sub[i] = s
|
||||
if s > 0 then
|
||||
noSmall = false
|
||||
end
|
||||
end
|
||||
for i = 1, 4 do
|
||||
local v = ((t == 4) and (0) or (refIdx(r, n0)))
|
||||
if v < 0 then
|
||||
return false, "ref_idx_l0 out of range"
|
||||
end
|
||||
ref0[i] = v
|
||||
end
|
||||
for i = 0, 3 do
|
||||
for k = 0, SUB_N[sub[i + 1] + 1] - 1 do
|
||||
local p = i * 4 + k + 1
|
||||
mvd0[2 * p - 1] = se(r)
|
||||
mvd0[2 * p] = se(r)
|
||||
end
|
||||
end
|
||||
else
|
||||
local n = ((M.part == 0) and (1) or (2))
|
||||
for p = 1, n do
|
||||
local v = refIdx(r, n0)
|
||||
if v < 0 then
|
||||
return false, "ref_idx_l0 out of range"
|
||||
end
|
||||
ref0[p] = v
|
||||
end
|
||||
for p = 1, n do
|
||||
mvd0[2 * p - 1] = se(r)
|
||||
mvd0[2 * p] = se(r)
|
||||
end
|
||||
end
|
||||
else
|
||||
if t == 0 then
|
||||
M.kind = K_BDIRECT
|
||||
M.part = 0
|
||||
if not S.direct8x8 then
|
||||
noSmall = false
|
||||
end
|
||||
elseif t <= 21 then
|
||||
M.kind = K_B
|
||||
if t <= 3 then
|
||||
M.part = 0
|
||||
pf[1] = t
|
||||
else
|
||||
M.part = ((t % 2 == 0) and (1) or (2))
|
||||
local k = (t - 4) // 2 + 1
|
||||
pf[1], pf[2] = BPAIR0[k], BPAIR1[k]
|
||||
end
|
||||
local n = ((M.part == 0) and (1) or (2))
|
||||
for p = 1, n do
|
||||
if pf[p] % 2 == 1 then
|
||||
local v = refIdx(r, n0)
|
||||
if v < 0 then
|
||||
return false, "ref_idx_l0 out of range"
|
||||
end
|
||||
ref0[p] = v
|
||||
end
|
||||
end
|
||||
for p = 1, n do
|
||||
if pf[p] >= 2 then
|
||||
local v = refIdx(r, n1)
|
||||
if v < 0 then
|
||||
return false, "ref_idx_l1 out of range"
|
||||
end
|
||||
ref1[p] = v
|
||||
end
|
||||
end
|
||||
for p = 1, n do
|
||||
if pf[p] % 2 == 1 then
|
||||
mvd0[2 * p - 1] = se(r)
|
||||
mvd0[2 * p] = se(r)
|
||||
end
|
||||
end
|
||||
for p = 1, n do
|
||||
if pf[p] >= 2 then
|
||||
mvd1[2 * p - 1] = se(r)
|
||||
mvd1[2 * p] = se(r)
|
||||
end
|
||||
end
|
||||
elseif t == 22 then
|
||||
M.kind = K_B
|
||||
M.part = 3
|
||||
for i = 1, 4 do
|
||||
local s = ue(r)
|
||||
if s > 12 then
|
||||
return false, "sub_mb_type out of range"
|
||||
end
|
||||
pf[i] = SUBB_PF[s + 1]
|
||||
sub[i] = SUBB_SHAPE[s + 1]
|
||||
dir[i] = s == 0
|
||||
if s == 0 then
|
||||
if not S.direct8x8 then
|
||||
noSmall = false
|
||||
end
|
||||
elseif SUB_N[sub[i] + 1] > 1 then
|
||||
noSmall = false
|
||||
end
|
||||
end
|
||||
for i = 1, 4 do
|
||||
if not dir[i] and pf[i] % 2 == 1 then
|
||||
local v = refIdx(r, n0)
|
||||
if v < 0 then
|
||||
return false, "ref_idx_l0 out of range"
|
||||
end
|
||||
ref0[i] = v
|
||||
end
|
||||
end
|
||||
for i = 1, 4 do
|
||||
if not dir[i] and pf[i] >= 2 then
|
||||
local v = refIdx(r, n1)
|
||||
if v < 0 then
|
||||
return false, "ref_idx_l1 out of range"
|
||||
end
|
||||
ref1[i] = v
|
||||
end
|
||||
end
|
||||
for l = 0, 1 do
|
||||
local mvd = ((l == 0) and (mvd0) or (mvd1))
|
||||
for i = 0, 3 do
|
||||
local uses = pf[i + 1] >= 2
|
||||
if l == 0 then
|
||||
uses = pf[i + 1] % 2 == 1
|
||||
end
|
||||
if uses and not dir[i + 1] then
|
||||
for k = 0, SUB_N[sub[i + 1] + 1] - 1 do
|
||||
local p = i * 4 + k + 1
|
||||
mvd[2 * p - 1] = se(r)
|
||||
mvd[2 * p] = se(r)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
else
|
||||
return false, "mb_type out of range"
|
||||
end
|
||||
end
|
||||
local code = ue(r)
|
||||
if code > 47 then
|
||||
return false, "coded_block_pattern out of range"
|
||||
end
|
||||
M.cbp = INTER_CBP[code + 1]
|
||||
M.t8 = 0
|
||||
if M.cbp % 16 ~= 0 and S.t8mode and noSmall then
|
||||
M.t8 = u1(r)
|
||||
end
|
||||
local addr = M.addr + 1
|
||||
S.cbpTab[addr] = M.cbp
|
||||
S.cpmTab[addr] = 0
|
||||
if M.cbp > 0 then
|
||||
if not setQp(S, M, se(r)) then
|
||||
return false, "mb_qp_delta out of range"
|
||||
end
|
||||
else
|
||||
setQp(S, M, 0)
|
||||
end
|
||||
if r.pos > r.size then
|
||||
return false, "truncated: macroblock"
|
||||
end
|
||||
local ok, err = residuals(S, M, r)
|
||||
if not ok then
|
||||
return false, err
|
||||
end
|
||||
Mb.recon(S, M)
|
||||
return true
|
||||
end
|
||||
|
||||
-- macroblock(S, M, r) -> true | false, message
|
||||
local function macroblock(S: any, M: any, r: Bitstream.Reader): (boolean, string?)
|
||||
local t = ue(r)
|
||||
local st = S.type
|
||||
if st == 2 then
|
||||
return intraMb(S, M, r, t)
|
||||
elseif st == 0 then
|
||||
if t >= 5 then
|
||||
return intraMb(S, M, r, t - 5)
|
||||
end
|
||||
return interMb(S, M, r, t, false)
|
||||
end
|
||||
if t >= 23 then
|
||||
return intraMb(S, M, r, t - 23)
|
||||
end
|
||||
return interMb(S, M, r, t, true)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ slice data
|
||||
-- slice(S, M, r) -> true | false, message: decodes macroblocks from S.firstMb until the end of the slice data
|
||||
function Cavlc.slice(S: any, M: any, r: Bitstream.Reader): (boolean, string?)
|
||||
local addr = S.firstMb
|
||||
local total = S.mbW * S.mbH
|
||||
local st = S.type
|
||||
local skipKind = ((st == 1) and (K_BSKIP) or (K_PSKIP))
|
||||
local more = true
|
||||
repeat
|
||||
if st ~= 2 then
|
||||
local run = ue(r)
|
||||
if run > total - addr then
|
||||
return false, "mb_skip_run past the end of the picture"
|
||||
end
|
||||
for _ = 1, run do
|
||||
Mb.start(S, M, addr)
|
||||
Mb.skip(S, M, skipKind)
|
||||
addr += 1
|
||||
end
|
||||
if run > 0 then
|
||||
more = Bitstream.moreData(r)
|
||||
end
|
||||
end
|
||||
if more then
|
||||
if addr >= total then
|
||||
return false, "slice data past the end of the picture"
|
||||
end
|
||||
Mb.start(S, M, addr)
|
||||
local ok, err = macroblock(S, M, r)
|
||||
if not ok then
|
||||
return false, err
|
||||
end
|
||||
addr += 1
|
||||
if r.pos > r.size then
|
||||
return false, "truncated: slice data"
|
||||
end
|
||||
more = Bitstream.moreData(r)
|
||||
end
|
||||
until not more
|
||||
return true
|
||||
end
|
||||
|
||||
return Cavlc
|
||||
@@ -0,0 +1,260 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- codecs/H264/Deblock: the in-loop deblocking filter of ITU-T H.264 8.7 for frame macroblocks, 8-bit 4:2:0:
|
||||
-- boundary strengths (8.7.2.1, from the per-4x4 intra / coefficient / reference / motion grids), alpha / beta / tC0
|
||||
-- (tables 8-16 / 8-17), the bS < 4 and bS = 4 luma and chroma filters, disable_deblocking_filter_idc 0 / 1 / 2 and the
|
||||
-- slice alpha / beta offsets. Written from the spec. Runs over the whole picture in macroblock order once all its
|
||||
-- slices are decoded (the result equals filtering each macroblock as it is decoded).
|
||||
-- Never throws.
|
||||
local Tables = require("@formats/codecs/H264/Tables")
|
||||
|
||||
local readu8, writeu8 = buffer.readu8, buffer.writeu8
|
||||
local ALPHA, BETA, TC0 = Tables.ALPHA, Tables.BETA, Tables.TC0
|
||||
|
||||
local Deblock = {}
|
||||
|
||||
local BS = table.create(4, 0)
|
||||
|
||||
local min, max = math.min, math.max
|
||||
local function clip3(lo: number, hi: number, v: number): number
|
||||
return min(max(v, lo), hi)
|
||||
end
|
||||
|
||||
local abs = math.abs
|
||||
|
||||
-- luma(b, o, across, along, qp, aOff, bOff): filters the 16 samples of one luma edge; `across` steps from q0 to q1
|
||||
-- (1 for vertical edges, the stride for horizontal ones), `along` to the next sample of the edge; BS holds the four
|
||||
-- strengths
|
||||
local function luma(b: buffer, o: number, across: number, along: number, qp: number, aOff: number, bOff: number)
|
||||
local indexA = clip3(0, 51, qp + aOff)
|
||||
local alpha = ALPHA[indexA + 13]
|
||||
local beta = BETA[clip3(0, 51, qp + bOff) + 13]
|
||||
if alpha == 0 or beta == 0 then
|
||||
return
|
||||
end
|
||||
for seg = 0, 3 do
|
||||
local bS = BS[seg + 1]
|
||||
if bS > 0 then
|
||||
local tc0 = TC0[(indexA + 12) * 4 + bS + 1]
|
||||
for k = 0, 3 do
|
||||
local q = o + (seg * 4 + k) * along
|
||||
local p0 = readu8(b, q - across)
|
||||
local q0 = readu8(b, q)
|
||||
local p1 = readu8(b, q - 2 * across)
|
||||
local q1 = readu8(b, q + across)
|
||||
if abs(p0 - q0) < alpha and abs(p1 - p0) < beta and abs(q1 - q0) < beta then
|
||||
local p2 = readu8(b, q - 3 * across)
|
||||
local q2 = readu8(b, q + 2 * across)
|
||||
local ap = abs(p2 - p0)
|
||||
local aq = abs(q2 - q0)
|
||||
if bS < 4 then
|
||||
local tc = tc0 + (((ap < beta) and (1) or (0))) + (((aq < beta) and (1) or (0)))
|
||||
local delta = clip3(-tc, tc, ((q0 - p0) * 4 + (p1 - q1) + 4) // 8)
|
||||
writeu8(b, q - across, clip3(0, 255, p0 + delta))
|
||||
writeu8(b, q, clip3(0, 255, q0 - delta))
|
||||
if ap < beta then
|
||||
writeu8(b, q - 2 * across, p1 + clip3(-tc0, tc0, (p2 + (p0 + q0 + 1) // 2 - 2 * p1) // 2))
|
||||
end
|
||||
if aq < beta then
|
||||
writeu8(b, q + across, q1 + clip3(-tc0, tc0, (q2 + (p0 + q0 + 1) // 2 - 2 * q1) // 2))
|
||||
end
|
||||
else
|
||||
local strong = abs(p0 - q0) < alpha // 4 + 2
|
||||
if ap < beta and strong then
|
||||
local p3 = readu8(b, q - 4 * across)
|
||||
writeu8(b, q - across, (p2 + 2 * p1 + 2 * p0 + 2 * q0 + q1 + 4) // 8)
|
||||
writeu8(b, q - 2 * across, (p2 + p1 + p0 + q0 + 2) // 4)
|
||||
writeu8(b, q - 3 * across, (2 * p3 + 3 * p2 + p1 + p0 + q0 + 4) // 8)
|
||||
else
|
||||
writeu8(b, q - across, (2 * p1 + p0 + q1 + 2) // 4)
|
||||
end
|
||||
if aq < beta and strong then
|
||||
local q3 = readu8(b, q + 3 * across)
|
||||
writeu8(b, q, (p1 + 2 * p0 + 2 * q0 + 2 * q1 + q2 + 4) // 8)
|
||||
writeu8(b, q + across, (p0 + q0 + q1 + q2 + 2) // 4)
|
||||
writeu8(b, q + 2 * across, (2 * q3 + 3 * q2 + q1 + q0 + p0 + 4) // 8)
|
||||
else
|
||||
writeu8(b, q, (2 * q1 + q0 + p1 + 2) // 4)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- chroma(b, o, across, along, qp, aOff, bOff): the 8 samples of one chroma edge (bS of luma segment i // 2)
|
||||
local function chroma(b: buffer, o: number, across: number, along: number, qp: number, aOff: number, bOff: number)
|
||||
local indexA = clip3(0, 51, qp + aOff)
|
||||
local alpha = ALPHA[indexA + 13]
|
||||
local beta = BETA[clip3(0, 51, qp + bOff) + 13]
|
||||
if alpha == 0 or beta == 0 then
|
||||
return
|
||||
end
|
||||
for i = 0, 7 do
|
||||
local bS = BS[i // 2 + 1]
|
||||
if bS > 0 then
|
||||
local q = o + i * along
|
||||
local p0 = readu8(b, q - across)
|
||||
local q0 = readu8(b, q)
|
||||
local p1 = readu8(b, q - 2 * across)
|
||||
local q1 = readu8(b, q + across)
|
||||
if abs(p0 - q0) < alpha and abs(p1 - p0) < beta and abs(q1 - q0) < beta then
|
||||
if bS < 4 then
|
||||
local tc = TC0[(indexA + 12) * 4 + bS + 1] + 1
|
||||
local delta = clip3(-tc, tc, ((q0 - p0) * 4 + (p1 - q1) + 4) // 8)
|
||||
writeu8(b, q - across, clip3(0, 255, p0 + delta))
|
||||
writeu8(b, q, clip3(0, 255, q0 - delta))
|
||||
else
|
||||
writeu8(b, q - across, (2 * p1 + p0 + q1 + 2) // 4)
|
||||
writeu8(b, q, (2 * q1 + q0 + p1 + 2) // 4)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- motionDiffers(pic, p, q) -> true when the 4x4 blocks p and q (grid indices) need bS 1 (8.7.2.1)
|
||||
local function mvDiff(mvA: { number }, a: number, mvB: { number }, b: number): boolean
|
||||
return abs(mvA[2 * a - 1] - mvB[2 * b - 1]) >= 4 or abs(mvA[2 * a] - mvB[2 * b]) >= 4
|
||||
end
|
||||
|
||||
local function motionDiffers(pic: any, p: number, q: number): boolean
|
||||
local uid0, uid1, mv0, mv1 = pic.uid0, pic.uid1, pic.mv0, pic.mv1
|
||||
local pa, pb, qa, qb = uid0[p], uid1[p], uid0[q], uid1[q]
|
||||
local np = (((pa >= 0) and (1) or (0))) + (((pb >= 0) and (1) or (0)))
|
||||
local nq = (((qa >= 0) and (1) or (0))) + (((qb >= 0) and (1) or (0)))
|
||||
if np ~= nq then
|
||||
return true
|
||||
end
|
||||
if np == 1 then
|
||||
local pr, pm = pa, mv0
|
||||
if pa < 0 then
|
||||
pr, pm = pb, mv1
|
||||
end
|
||||
local qr, qm = qa, mv0
|
||||
if qa < 0 then
|
||||
qr, qm = qb, mv1
|
||||
end
|
||||
if pr ~= qr then
|
||||
return true
|
||||
end
|
||||
return mvDiff(pm, p, qm, q)
|
||||
elseif np == 0 then
|
||||
return false
|
||||
end
|
||||
if not ((pa == qa and pb == qb) or (pa == qb and pb == qa)) then
|
||||
return true
|
||||
end
|
||||
if pa ~= pb then
|
||||
if pa == qa then
|
||||
return mvDiff(mv0, p, mv0, q) or mvDiff(mv1, p, mv1, q)
|
||||
end
|
||||
return mvDiff(mv0, p, mv1, q) or mvDiff(mv1, p, mv0, q)
|
||||
end
|
||||
return (mvDiff(mv0, p, mv0, q) or mvDiff(mv1, p, mv1, q)) and (mvDiff(mv0, p, mv1, q) or mvDiff(mv1, p, mv0, q))
|
||||
end
|
||||
|
||||
-- picture(S, pic, params): deblocks the whole picture. params[sliceNum] = { idc, alphaOffset, betaOffset }
|
||||
function Deblock.picture(S: any, pic: any, params: { any })
|
||||
local mbW, mbH = S.mbW, S.mbH
|
||||
local w4 = S.w4
|
||||
local kind, sliceTab, qpTab, qpcTab, qpc2Tab, t8Tab = S.kind, S.sliceTab, S.qpTab, S.qpcTab, S.qpc2Tab, S.t8Tab
|
||||
local nzDb = S.nzDb
|
||||
local ys, cs = pic.ys, pic.cs
|
||||
local Y, U, V = pic.y, pic.u, pic.v
|
||||
for my = 0, mbH - 1 do
|
||||
for mx = 0, mbW - 1 do
|
||||
local addr = my * mbW + mx + 1
|
||||
local sn = sliceTab[addr]
|
||||
local prm = params[sn]
|
||||
if sn == 0 or not prm or prm[1] == 1 then
|
||||
continue
|
||||
end
|
||||
local idc, aOff, bOff = prm[1], prm[2], prm[3]
|
||||
local intraQ = kind[addr] <= 4
|
||||
local t8 = t8Tab[addr] == 1
|
||||
local qpQ, qpcQ, qpc2Q = qpTab[addr], qpcTab[addr], qpc2Tab[addr]
|
||||
local g0 = my * 4 * w4 + mx * 4 + 1
|
||||
local lo = pic.yo + my * 16 * ys + mx * 16
|
||||
local co = pic.co + my * 8 * cs + mx * 8
|
||||
for dir = 0, 1 do
|
||||
-- dir 0: vertical edges (left neighbour), dir 1: horizontal edges (top neighbour)
|
||||
local nAddr = ((dir == 0) and (addr - 1) or (addr - mbW))
|
||||
local edgeOk = my > 0
|
||||
if dir == 0 then
|
||||
edgeOk = mx > 0
|
||||
end
|
||||
if edgeOk and idc == 2 and sliceTab[nAddr] ~= sn then
|
||||
edgeOk = false
|
||||
end
|
||||
if edgeOk and sliceTab[nAddr] == 0 then
|
||||
edgeOk = false
|
||||
end
|
||||
for e = 0, 3 do
|
||||
if e == 0 and not edgeOk then
|
||||
continue
|
||||
end
|
||||
if t8 and (e == 1 or e == 3) then
|
||||
continue
|
||||
end
|
||||
-- strengths of the four segments
|
||||
local intraP = intraQ
|
||||
local qpP, qpcP, qpc2P = qpQ, qpcQ, qpc2Q
|
||||
if e == 0 then
|
||||
intraP = kind[nAddr] <= 4
|
||||
qpP, qpcP, qpc2P = qpTab[nAddr], qpcTab[nAddr], qpc2Tab[nAddr]
|
||||
end
|
||||
local any = false
|
||||
for k = 0, 3 do
|
||||
local qg, pg
|
||||
if dir == 0 then
|
||||
qg = g0 + k * w4 + e
|
||||
pg = qg - 1
|
||||
else
|
||||
qg = g0 + e * w4 + k
|
||||
pg = qg - w4
|
||||
end
|
||||
local bS
|
||||
if intraP or intraQ then
|
||||
bS = ((e == 0) and (4) or (3))
|
||||
elseif nzDb[qg] ~= 0 or nzDb[pg] ~= 0 then
|
||||
bS = 2
|
||||
elseif motionDiffers(pic, pg, qg) then
|
||||
bS = 1
|
||||
else
|
||||
bS = 0
|
||||
end
|
||||
BS[k + 1] = bS
|
||||
if bS > 0 then
|
||||
any = true
|
||||
end
|
||||
end
|
||||
if not any then
|
||||
continue
|
||||
end
|
||||
local qpav = (qpP + qpQ + 1) // 2
|
||||
if dir == 0 then
|
||||
luma(Y, lo + e * 4, 1, ys, qpav, aOff, bOff)
|
||||
else
|
||||
luma(Y, lo + e * 4 * ys, ys, 1, qpav, aOff, bOff)
|
||||
end
|
||||
if e % 2 == 0 then
|
||||
local qc = (qpcP + qpcQ + 1) // 2
|
||||
local qc2 = (qpc2P + qpc2Q + 1) // 2
|
||||
if dir == 0 then
|
||||
chroma(U, co + e * 2, 1, cs, qc, aOff, bOff)
|
||||
chroma(V, co + e * 2, 1, cs, qc2, aOff, bOff)
|
||||
else
|
||||
chroma(U, co + e * 2 * cs, cs, 1, qc, aOff, bOff)
|
||||
chroma(V, co + e * 2 * cs, cs, 1, qc2, aOff, bOff)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
return Deblock
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,266 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- codecs/H264/Inter: inter prediction sample interpolation and weighting (ITU-T H.264 8.4.2.2 / 8.4.2.3): the 6-tap
|
||||
-- quarter-sample luma filter, eighth-sample bilinear chroma, default / explicit / implicit weighted sample
|
||||
-- prediction, and the picture border extension that makes out-of-picture reference reads equal to the clamped
|
||||
-- sample positions of 8.4.2.2.1. Written from the spec.
|
||||
-- Reference planes carry a border of PAD (luma) / PADC (chroma) replicated samples; callers clamp block positions
|
||||
-- with Inter.clampLuma / clampChroma so every read is inside the buffer. Never throws.
|
||||
local readu8, writeu8 = buffer.readu8, buffer.writeu8
|
||||
|
||||
local Inter = {}
|
||||
|
||||
Inter.PAD = 32
|
||||
Inter.PADC = 16
|
||||
|
||||
local min, max = math.min, math.max
|
||||
local function clip(v: number): number
|
||||
return min(max(v, 0), 255)
|
||||
end
|
||||
|
||||
-- scratch rows of horizontal 6-tap intermediates (unrounded), 21 rows x 16 (+1) columns
|
||||
local B1 = table.create(24 * 17, 0)
|
||||
|
||||
-- the six-tap filter cases, each a small function (LuaJIT keeps small loops in one trace); sliding windows read each
|
||||
-- sample once per row / column
|
||||
local function lumaCopy(ref: buffer, s: number, base: number, w: number, h: number, P: { number })
|
||||
for r = 0, h - 1 do
|
||||
local o = base + r * s
|
||||
local d = r * 16 + 1
|
||||
for c = 0, w - 1 do
|
||||
P[d + c] = readu8(ref, o + c)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- horizontal half sample b; avg 0: b, 1: (G + b + 1) >> 1, 2: (b + H + 1) >> 1
|
||||
local function lumaH(ref: buffer, s: number, base: number, w: number, h: number, P: { number }, avg: number)
|
||||
for r = 0, h - 1 do
|
||||
local o = base + r * s
|
||||
local d = r * 16 + 1
|
||||
local a0, a1, a2, a3, a4 = readu8(ref, o - 2), readu8(ref, o - 1), readu8(ref, o), readu8(ref, o + 1), readu8(ref, o + 2)
|
||||
for c = 0, w - 1 do
|
||||
local a5 = readu8(ref, o + c + 3)
|
||||
local v = min(max((a0 - 5 * a1 + 20 * a2 + 20 * a3 - 5 * a4 + a5 + 16) // 32, 0), 255)
|
||||
if avg == 1 then
|
||||
v = (v + a2 + 1) // 2
|
||||
elseif avg == 2 then
|
||||
v = (v + a3 + 1) // 2
|
||||
end
|
||||
P[d + c] = v
|
||||
a0, a1, a2, a3, a4 = a1, a2, a3, a4, a5
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- vertical half sample h; avg 0: h, 1: (G + h + 1) >> 1, 2: (h + G below + 1) >> 1
|
||||
local function lumaV(ref: buffer, s: number, base: number, w: number, h: number, P: { number }, avg: number)
|
||||
for c = 0, w - 1 do
|
||||
local o = base + c
|
||||
local a0, a1, a2, a3, a4 = readu8(ref, o - 2 * s), readu8(ref, o - s), readu8(ref, o), readu8(ref, o + s), readu8(ref, o + 2 * s)
|
||||
local d = c + 1
|
||||
for r = 0, h - 1 do
|
||||
local a5 = readu8(ref, o + (r + 3) * s)
|
||||
local v = min(max((a0 - 5 * a1 + 20 * a2 + 20 * a3 - 5 * a4 + a5 + 16) // 32, 0), 255)
|
||||
if avg == 1 then
|
||||
v = (v + a2 + 1) // 2
|
||||
elseif avg == 2 then
|
||||
v = (v + a3 + 1) // 2
|
||||
end
|
||||
P[d + r * 16] = v
|
||||
a0, a1, a2, a3, a4 = a1, a2, a3, a4, a5
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- B1 rows -2 .. h + 2, columns 0 .. w (unrounded horizontal intermediates), stride 17
|
||||
local function horizontal1(ref: buffer, s: number, base: number, w: number, h: number)
|
||||
for r = -2, h + 2 do
|
||||
local o = base + r * s
|
||||
local d = (r + 2) * 17 + 1
|
||||
local a0, a1, a2, a3, a4 = readu8(ref, o - 2), readu8(ref, o - 1), readu8(ref, o), readu8(ref, o + 1), readu8(ref, o + 2)
|
||||
for c = 0, w do
|
||||
local a5 = readu8(ref, o + c + 3)
|
||||
B1[d + c] = a0 - 5 * a1 + 20 * a2 + 20 * a3 - 5 * a4 + a5
|
||||
a0, a1, a2, a3, a4 = a1, a2, a3, a4, a5
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- centre j; with = 0: j, 1: (b + j + 1) >> 1 (b of this row), 2: (s + j + 1) >> 1 (b of the next row)
|
||||
local function lumaJ(ref: buffer, s: number, base: number, w: number, h: number, P: { number }, with: number)
|
||||
horizontal1(ref, s, base, w, h)
|
||||
for c = 0, w - 1 do
|
||||
local k = 2 * 17 + 1 + c
|
||||
local a0, a1, a2, a3, a4 = B1[k - 34], B1[k - 17], B1[k], B1[k + 17], B1[k + 34]
|
||||
for r = 0, h - 1 do
|
||||
local a5 = B1[k + 51]
|
||||
local v = min(max((a0 - 5 * a1 + 20 * a2 + 20 * a3 - 5 * a4 + a5 + 512) // 1024, 0), 255)
|
||||
if with == 1 then
|
||||
v = (v + min(max((a2 + 16) // 32, 0), 255) + 1) // 2
|
||||
elseif with == 2 then
|
||||
v = (v + min(max((a3 + 16) // 32, 0), 255) + 1) // 2
|
||||
end
|
||||
P[r * 16 + c + 1] = v
|
||||
a0, a1, a2, a3, a4 = a1, a2, a3, a4, a5
|
||||
k += 17
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- (j + h + 1) >> 1 with h at column c + co (co 0: i, 1: k)
|
||||
local function lumaJV(ref: buffer, s: number, base: number, w: number, h: number, P: { number }, co: number)
|
||||
lumaJ(ref, s, base, w, h, P, 0)
|
||||
for c = 0, w - 1 do
|
||||
local o = base + c + co
|
||||
local a0, a1, a2, a3, a4 = readu8(ref, o - 2 * s), readu8(ref, o - s), readu8(ref, o), readu8(ref, o + s), readu8(ref, o + 2 * s)
|
||||
for r = 0, h - 1 do
|
||||
local a5 = readu8(ref, o + (r + 3) * s)
|
||||
local hv = min(max((a0 - 5 * a1 + 20 * a2 + 20 * a3 - 5 * a4 + a5 + 16) // 32, 0), 255)
|
||||
local d = r * 16 + c + 1
|
||||
P[d] = (P[d] + hv + 1) // 2
|
||||
a0, a1, a2, a3, a4 = a1, a2, a3, a4, a5
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- diagonal quarter samples e, g, p, r: (b or s) averaged with (h or m)
|
||||
local function lumaDiag(ref: buffer, s: number, base: number, w: number, h: number, P: { number }, ro: number, co: number)
|
||||
lumaH(ref, s, base + ro, w, h, P, 0)
|
||||
for c = 0, w - 1 do
|
||||
local o = base + c + co
|
||||
local a0, a1, a2, a3, a4 = readu8(ref, o - 2 * s), readu8(ref, o - s), readu8(ref, o), readu8(ref, o + s), readu8(ref, o + 2 * s)
|
||||
for r = 0, h - 1 do
|
||||
local a5 = readu8(ref, o + (r + 3) * s)
|
||||
local vb = min(max((a0 - 5 * a1 + 20 * a2 + 20 * a3 - 5 * a4 + a5 + 16) // 32, 0), 255)
|
||||
local d = r * 16 + c + 1
|
||||
P[d] = (P[d] + vb + 1) // 2
|
||||
a0, a1, a2, a3, a4 = a1, a2, a3, a4, a5
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- luma(ref, s, base, fx, fy, w, h, P): the w x h luma prediction for a block whose integer sample (0, 0) is at
|
||||
-- ref[base] and whose fractional offset is (fx, fy) quarter samples; P[r * 16 + c + 1] receives the samples
|
||||
function Inter.luma(ref: buffer, s: number, base: number, fx: number, fy: number, w: number, h: number, P: { number })
|
||||
if fy == 0 then
|
||||
if fx == 0 then
|
||||
lumaCopy(ref, s, base, w, h, P)
|
||||
else
|
||||
lumaH(ref, s, base, w, h, P, if fx == 2 then 0 elseif fx == 1 then 1 else 2)
|
||||
end
|
||||
elseif fx == 0 then
|
||||
lumaV(ref, s, base, w, h, P, if fy == 2 then 0 elseif fy == 1 then 1 else 2)
|
||||
elseif fx == 2 then
|
||||
lumaJ(ref, s, base, w, h, P, if fy == 2 then 0 elseif fy == 1 then 1 else 2)
|
||||
elseif fy == 2 then
|
||||
lumaJV(ref, s, base, w, h, P, if fx == 3 then 1 else 0)
|
||||
else
|
||||
lumaDiag(ref, s, base, w, h, P, if fy == 3 then s else 0, if fx == 3 then 1 else 0)
|
||||
end
|
||||
end
|
||||
|
||||
-- chroma(ref, s, base, fx, fy, w, h, P): eighth-sample bilinear chroma prediction
|
||||
function Inter.chroma(ref: buffer, s: number, base: number, fx: number, fy: number, w: number, h: number, P: { number })
|
||||
if fx == 0 and fy == 0 then
|
||||
for r = 0, h - 1 do
|
||||
local o = base + r * s
|
||||
local d = r * 16 + 1
|
||||
for c = 0, w - 1 do
|
||||
P[d + c] = readu8(ref, o + c)
|
||||
end
|
||||
end
|
||||
return
|
||||
end
|
||||
local wa = (8 - fx) * (8 - fy)
|
||||
local wb = fx * (8 - fy)
|
||||
local wc = (8 - fx) * fy
|
||||
local wd = fx * fy
|
||||
for r = 0, h - 1 do
|
||||
local o = base + r * s
|
||||
local d = r * 16 + 1
|
||||
for c = 0, w - 1 do
|
||||
local p = o + c
|
||||
P[d + c] = (wa * readu8(ref, p) + wb * readu8(ref, p + 1) + wc * readu8(ref, p + s) + wd * readu8(ref, p + s + 1) + 32) // 64
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ weighting
|
||||
-- put(P, w, h, b, o, s): P into the picture
|
||||
function Inter.put(P: { number }, w: number, h: number, b: buffer, o: number, s: number)
|
||||
for r = 0, h - 1 do
|
||||
local d = r * 16 + 1
|
||||
local q = o + r * s
|
||||
for c = 0, w - 1 do
|
||||
writeu8(b, q + c, P[d + c])
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- avg(P0, P1, w, h, b, o, s): default bi-prediction (P0 + P1 + 1) >> 1
|
||||
function Inter.avg(P0: { number }, P1: { number }, w: number, h: number, b: buffer, o: number, s: number)
|
||||
for r = 0, h - 1 do
|
||||
local d = r * 16 + 1
|
||||
local q = o + r * s
|
||||
for c = 0, w - 1 do
|
||||
writeu8(b, q + c, (P0[d + c] + P1[d + c] + 1) // 2)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- weight1(P, w, h, b, o, s, logWD, wt, off): explicit single-list weighting (8-270 / 8-271)
|
||||
function Inter.weight1(P: { number }, w: number, h: number, b: buffer, o: number, s: number, logWD: number, wt: number, off: number)
|
||||
if logWD >= 1 then
|
||||
local rnd = 2 ^ (logWD - 1)
|
||||
local div = 2 ^ logWD
|
||||
for r = 0, h - 1 do
|
||||
local d = r * 16 + 1
|
||||
local q = o + r * s
|
||||
for c = 0, w - 1 do
|
||||
writeu8(b, q + c, clip((P[d + c] * wt + rnd) // div + off))
|
||||
end
|
||||
end
|
||||
else
|
||||
for r = 0, h - 1 do
|
||||
local d = r * 16 + 1
|
||||
local q = o + r * s
|
||||
for c = 0, w - 1 do
|
||||
writeu8(b, q + c, clip(P[d + c] * wt + off))
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- weight2(P0, P1, w, h, b, o, s, logWD, w0, w1, off): explicit / implicit bi-prediction weighting (8-272);
|
||||
-- off = (o0 + o1 + 1) >> 1
|
||||
function Inter.weight2(P0: { number }, P1: { number }, w: number, h: number, b: buffer, o: number, s: number, logWD: number, w0: number, w1: number, off: number)
|
||||
local rnd = 2 ^ logWD
|
||||
local div = 2 ^ (logWD + 1)
|
||||
for r = 0, h - 1 do
|
||||
local d = r * 16 + 1
|
||||
local q = o + r * s
|
||||
for c = 0, w - 1 do
|
||||
writeu8(b, q + c, clip((P0[d + c] * w0 + P1[d + c] * w1 + rnd) // div + off))
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ borders
|
||||
-- extend(b, o, s, w, h, pad): replicate the edge samples of the w x h plane at b[o] (stride s) into its border
|
||||
function Inter.extend(b: buffer, o: number, s: number, w: number, h: number, pad: number)
|
||||
for y = 0, h - 1 do
|
||||
local r = o + y * s
|
||||
buffer.fill(b, r - pad, readu8(b, r), pad)
|
||||
buffer.fill(b, r + w, readu8(b, r + w - 1), pad)
|
||||
end
|
||||
local top = o - pad
|
||||
local bottom = o + (h - 1) * s - pad
|
||||
for y = 1, pad do
|
||||
buffer.copy(b, top - y * s, b, top, w + 2 * pad)
|
||||
buffer.copy(b, bottom + y * s, b, bottom, w + 2 * pad)
|
||||
end
|
||||
end
|
||||
|
||||
return Inter
|
||||
@@ -0,0 +1,410 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- codecs/H264/Intra: intra prediction (ITU-T H.264 8.3): Intra_4x4 and Intra_8x8 (nine directional modes, with the
|
||||
-- 8x8 reference sample filter of 8.3.2.2.1), Intra_16x16 and chroma (DC / horizontal / vertical / plane), 8-bit.
|
||||
-- Written from the spec. Predictions are written straight into the picture plane (row stride `s`, block origin `o`).
|
||||
-- Never throws: every sample read is inside the padded plane (callers pass availability for the edges).
|
||||
local readu8, writeu8 = buffer.readu8, buffer.writeu8
|
||||
|
||||
local Intra = {}
|
||||
|
||||
local E = table.create(40, 0) -- reference samples: p[-1, y] = E[N - y], p[-1, -1] = E[N + 1], p[x, -1] = E[N + 2 + x]
|
||||
local F = table.create(40, 0) -- filtered 8x8 references, same layout
|
||||
|
||||
local min, max = math.min, math.max
|
||||
local function clip(v: number): number
|
||||
return min(max(v, 0), 255)
|
||||
end
|
||||
|
||||
-- predNxN: the directional modes 3..8 over the edge array R (N = 4 or 8)
|
||||
local function directional(R: { number }, N: number, mode: number, b: buffer, o: number, s: number)
|
||||
local c = N + 1 -- R[c] = p[-1, -1]; p[x, -1] = R[c + 1 + x]; p[-1, y] = R[c - 1 - y]
|
||||
for y = 0, N - 1 do
|
||||
local row = o + y * s
|
||||
for x = 0, N - 1 do
|
||||
local v
|
||||
if mode == 3 then -- diagonal down left
|
||||
if x == N - 1 and y == N - 1 then
|
||||
v = (R[c + 2 * N - 1] + 3 * R[c + 2 * N] + 2) // 4
|
||||
else
|
||||
local i = c + 1 + x + y
|
||||
v = (R[i] + 2 * R[i + 1] + R[i + 2] + 2) // 4
|
||||
end
|
||||
elseif mode == 4 then -- diagonal down right
|
||||
if x > y then
|
||||
local i = c + 1 + x - y
|
||||
v = (R[i - 2] + 2 * R[i - 1] + R[i] + 2) // 4
|
||||
elseif x < y then
|
||||
local i = c - 1 - (y - x)
|
||||
v = (R[i + 2] + 2 * R[i + 1] + R[i] + 2) // 4
|
||||
else
|
||||
v = (R[c + 1] + 2 * R[c] + R[c - 1] + 2) // 4
|
||||
end
|
||||
elseif mode == 5 then -- vertical right
|
||||
local z = 2 * x - y
|
||||
if z >= 0 and z % 2 == 0 then
|
||||
local i = c + 1 + x - y // 2
|
||||
v = (R[i - 1] + R[i] + 1) // 2
|
||||
elseif z > 0 then
|
||||
local i = c + 1 + x - y // 2
|
||||
v = (R[i - 2] + 2 * R[i - 1] + R[i] + 2) // 4
|
||||
elseif z == -1 then
|
||||
v = (R[c - 1] + 2 * R[c] + R[c + 1] + 2) // 4
|
||||
else
|
||||
local i = c - 1 - (y - 2 * x - 1) -- p[-1, y - 2x - 1]
|
||||
v = (R[i] + 2 * R[i + 1] + R[i + 2] + 2) // 4
|
||||
end
|
||||
elseif mode == 6 then -- horizontal down
|
||||
local z = 2 * y - x
|
||||
if z >= 0 and z % 2 == 0 then
|
||||
local i = c - 1 - (y - x // 2) -- p[-1, y - (x >> 1)]
|
||||
v = (R[i + 1] + R[i] + 1) // 2
|
||||
elseif z > 0 then
|
||||
local i = c - 1 - (y - x // 2)
|
||||
v = (R[i + 2] + 2 * R[i + 1] + R[i] + 2) // 4
|
||||
elseif z == -1 then
|
||||
v = (R[c - 1] + 2 * R[c] + R[c + 1] + 2) // 4
|
||||
else
|
||||
local i = c + 1 + (x - 2 * y - 1) -- p[x - 2y - 1, -1]
|
||||
v = (R[i] + 2 * R[i - 1] + R[i - 2] + 2) // 4
|
||||
end
|
||||
elseif mode == 7 then -- vertical left
|
||||
local i = c + 1 + x + y // 2
|
||||
if y % 2 == 0 then
|
||||
v = (R[i] + R[i + 1] + 1) // 2
|
||||
else
|
||||
v = (R[i] + 2 * R[i + 1] + R[i + 2] + 2) // 4
|
||||
end
|
||||
else -- horizontal up
|
||||
local z = x + 2 * y
|
||||
local i = c - 1 - (y + x // 2) -- p[-1, y + (x >> 1)]
|
||||
if z > 2 * N - 3 then
|
||||
v = R[c - N]
|
||||
elseif z == 2 * N - 3 then
|
||||
v = (R[c - N + 1] + 3 * R[c - N] + 2) // 4
|
||||
elseif z % 2 == 0 then
|
||||
v = (R[i] + R[i - 1] + 1) // 2
|
||||
else
|
||||
v = (R[i] + 2 * R[i - 1] + R[i - 2] + 2) // 4
|
||||
end
|
||||
end
|
||||
writeu8(b, row + x, v)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- pred4x4(b, o, s, mode, left, top, topRight, topLeft): Intra_4x4 at plane offset o. Unavailable top-right samples
|
||||
-- repeat p[3, -1].
|
||||
function Intra.pred4x4(b: buffer, o: number, s: number, mode: number, left: boolean, top: boolean, topRight: boolean, topLeft: boolean)
|
||||
if mode == 0 then
|
||||
local t = o - s
|
||||
local a0, a1, a2, a3 = readu8(b, t), readu8(b, t + 1), readu8(b, t + 2), readu8(b, t + 3)
|
||||
for y = 0, 3 do
|
||||
local r = o + y * s
|
||||
writeu8(b, r, a0)
|
||||
writeu8(b, r + 1, a1)
|
||||
writeu8(b, r + 2, a2)
|
||||
writeu8(b, r + 3, a3)
|
||||
end
|
||||
return
|
||||
elseif mode == 1 then
|
||||
for y = 0, 3 do
|
||||
local r = o + y * s
|
||||
local v = readu8(b, r - 1)
|
||||
writeu8(b, r, v)
|
||||
writeu8(b, r + 1, v)
|
||||
writeu8(b, r + 2, v)
|
||||
writeu8(b, r + 3, v)
|
||||
end
|
||||
return
|
||||
elseif mode == 2 then
|
||||
local sum, n = 0, 0
|
||||
if top then
|
||||
local t = o - s
|
||||
sum += readu8(b, t) + readu8(b, t + 1) + readu8(b, t + 2) + readu8(b, t + 3)
|
||||
n += 1
|
||||
end
|
||||
if left then
|
||||
sum += readu8(b, o - 1) + readu8(b, o + s - 1) + readu8(b, o + 2 * s - 1) + readu8(b, o + 3 * s - 1)
|
||||
n += 1
|
||||
end
|
||||
local v = 128
|
||||
if n == 2 then
|
||||
v = (sum + 4) // 8
|
||||
elseif n == 1 then
|
||||
v = (sum + 2) // 4
|
||||
end
|
||||
for y = 0, 3 do
|
||||
local r = o + y * s
|
||||
writeu8(b, r, v)
|
||||
writeu8(b, r + 1, v)
|
||||
writeu8(b, r + 2, v)
|
||||
writeu8(b, r + 3, v)
|
||||
end
|
||||
return
|
||||
end
|
||||
-- edges: E[1..4] = p[-1, 3..0], E[5] = p[-1, -1], E[6..13] = p[0..7, -1]
|
||||
if left then
|
||||
for y = 0, 3 do
|
||||
E[4 - y] = readu8(b, o + y * s - 1)
|
||||
end
|
||||
end
|
||||
if topLeft then
|
||||
E[5] = readu8(b, o - s - 1)
|
||||
end
|
||||
if top then
|
||||
local t = o - s
|
||||
for x = 0, 3 do
|
||||
E[6 + x] = readu8(b, t + x)
|
||||
end
|
||||
if topRight then
|
||||
for x = 4, 7 do
|
||||
E[6 + x] = readu8(b, t + x)
|
||||
end
|
||||
else
|
||||
local v = E[9]
|
||||
E[10], E[11], E[12], E[13] = v, v, v, v
|
||||
end
|
||||
end
|
||||
directional(E, 4, mode, b, o, s)
|
||||
end
|
||||
|
||||
-- pred8x8(b, o, s, mode, left, top, topRight, topLeft): Intra_8x8 with the reference sample filter
|
||||
function Intra.pred8x8(b: buffer, o: number, s: number, mode: number, left: boolean, top: boolean, topRight: boolean, topLeft: boolean)
|
||||
-- unfiltered edges into E: E[1..8] = p[-1, 7..0], E[9] = p[-1, -1], E[10..25] = p[0..15, -1]
|
||||
if left then
|
||||
for y = 0, 7 do
|
||||
E[8 - y] = readu8(b, o + y * s - 1)
|
||||
end
|
||||
end
|
||||
local tl = 0
|
||||
if topLeft then
|
||||
tl = readu8(b, o - s - 1)
|
||||
E[9] = tl
|
||||
end
|
||||
if top then
|
||||
local t = o - s
|
||||
for x = 0, 7 do
|
||||
E[10 + x] = readu8(b, t + x)
|
||||
end
|
||||
if topRight then
|
||||
for x = 8, 15 do
|
||||
E[10 + x] = readu8(b, t + x)
|
||||
end
|
||||
else
|
||||
local v = E[17]
|
||||
for x = 8, 15 do
|
||||
E[10 + x] = v
|
||||
end
|
||||
end
|
||||
-- filtered top
|
||||
if topLeft then
|
||||
F[10] = (tl + 2 * E[10] + E[11] + 2) // 4
|
||||
else
|
||||
F[10] = (3 * E[10] + E[11] + 2) // 4
|
||||
end
|
||||
for x = 1, 14 do
|
||||
F[10 + x] = (E[9 + x] + 2 * E[10 + x] + E[11 + x] + 2) // 4
|
||||
end
|
||||
F[25] = (E[24] + 3 * E[25] + 2) // 4
|
||||
end
|
||||
if topLeft then
|
||||
if top and left then
|
||||
F[9] = (E[10] + 2 * tl + E[8] + 2) // 4
|
||||
elseif top then
|
||||
F[9] = (3 * tl + E[10] + 2) // 4
|
||||
elseif left then
|
||||
F[9] = (3 * tl + E[8] + 2) // 4
|
||||
else
|
||||
F[9] = tl
|
||||
end
|
||||
end
|
||||
if left then
|
||||
if topLeft then
|
||||
F[8] = (tl + 2 * E[8] + E[7] + 2) // 4
|
||||
else
|
||||
F[8] = (3 * E[8] + E[7] + 2) // 4
|
||||
end
|
||||
for y = 1, 6 do
|
||||
F[8 - y] = (E[9 - y] + 2 * E[8 - y] + E[7 - y] + 2) // 4
|
||||
end
|
||||
F[1] = (E[2] + 3 * E[1] + 2) // 4
|
||||
end
|
||||
if mode == 0 then
|
||||
for y = 0, 7 do
|
||||
local r = o + y * s
|
||||
for x = 0, 7 do
|
||||
writeu8(b, r + x, F[10 + x])
|
||||
end
|
||||
end
|
||||
elseif mode == 1 then
|
||||
for y = 0, 7 do
|
||||
local r = o + y * s
|
||||
local v = F[8 - y]
|
||||
for x = 0, 7 do
|
||||
writeu8(b, r + x, v)
|
||||
end
|
||||
end
|
||||
elseif mode == 2 then
|
||||
local sum, n = 0, 0
|
||||
if top then
|
||||
for x = 0, 7 do
|
||||
sum += F[10 + x]
|
||||
end
|
||||
n += 1
|
||||
end
|
||||
if left then
|
||||
for y = 0, 7 do
|
||||
sum += F[8 - y]
|
||||
end
|
||||
n += 1
|
||||
end
|
||||
local v = 128
|
||||
if n == 2 then
|
||||
v = (sum + 8) // 16
|
||||
elseif n == 1 then
|
||||
v = (sum + 4) // 8
|
||||
end
|
||||
for y = 0, 7 do
|
||||
local r = o + y * s
|
||||
for x = 0, 7 do
|
||||
writeu8(b, r + x, v)
|
||||
end
|
||||
end
|
||||
else
|
||||
directional(F, 8, mode, b, o, s)
|
||||
end
|
||||
end
|
||||
|
||||
-- pred16x16(b, o, s, mode, left, top, topLeft)
|
||||
function Intra.pred16x16(b: buffer, o: number, s: number, mode: number, left: boolean, top: boolean, topLeft: boolean)
|
||||
if mode == 0 then
|
||||
local t = o - s
|
||||
for y = 0, 15 do
|
||||
buffer.copy(b, o + y * s, b, t, 16)
|
||||
end
|
||||
elseif mode == 1 then
|
||||
for y = 0, 15 do
|
||||
local r = o + y * s
|
||||
buffer.fill(b, r, readu8(b, r - 1), 16)
|
||||
end
|
||||
elseif mode == 2 then
|
||||
local sum, n = 0, 0
|
||||
if top then
|
||||
local t = o - s
|
||||
for x = 0, 15 do
|
||||
sum += readu8(b, t + x)
|
||||
end
|
||||
n += 1
|
||||
end
|
||||
if left then
|
||||
for y = 0, 15 do
|
||||
sum += readu8(b, o + y * s - 1)
|
||||
end
|
||||
n += 1
|
||||
end
|
||||
local v = 128
|
||||
if n == 2 then
|
||||
v = (sum + 16) // 32
|
||||
elseif n == 1 then
|
||||
v = (sum + 8) // 16
|
||||
end
|
||||
for y = 0, 15 do
|
||||
buffer.fill(b, o + y * s, v, 16)
|
||||
end
|
||||
else
|
||||
local t = o - s
|
||||
local H, V = 0, 0
|
||||
for i = 0, 7 do
|
||||
H += (i + 1) * (readu8(b, t + 8 + i) - readu8(b, t + 6 - i))
|
||||
V += (i + 1) * (readu8(b, o + (8 + i) * s - 1) - readu8(b, o + (6 - i) * s - 1))
|
||||
end
|
||||
local a = 16 * (readu8(b, o + 15 * s - 1) + readu8(b, t + 15))
|
||||
local bb = (5 * H + 32) // 64
|
||||
local cc = (5 * V + 32) // 64
|
||||
for y = 0, 15 do
|
||||
local r = o + y * s
|
||||
local base = a + cc * (y - 7) + 16 - 7 * bb
|
||||
for x = 0, 15 do
|
||||
writeu8(b, r + x, clip((base + bb * x) // 32))
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
local function fill4(b: buffer, o: number, s: number, v: number)
|
||||
for y = 0, 3 do
|
||||
local r = o + y * s
|
||||
writeu8(b, r, v)
|
||||
writeu8(b, r + 1, v)
|
||||
writeu8(b, r + 2, v)
|
||||
writeu8(b, r + 3, v)
|
||||
end
|
||||
end
|
||||
|
||||
-- predChroma(b, o, s, mode, left, top, topLeft): 8x8 chroma (4:2:0); mode 0 DC, 1 horizontal, 2 vertical, 3 plane
|
||||
function Intra.predChroma(b: buffer, o: number, s: number, mode: number, left: boolean, top: boolean, topLeft: boolean)
|
||||
if mode == 0 then
|
||||
local t = o - s
|
||||
local st0, st1, sl0, sl1 = 0, 0, 0, 0
|
||||
if top then
|
||||
st0 = readu8(b, t) + readu8(b, t + 1) + readu8(b, t + 2) + readu8(b, t + 3)
|
||||
st1 = readu8(b, t + 4) + readu8(b, t + 5) + readu8(b, t + 6) + readu8(b, t + 7)
|
||||
end
|
||||
if left then
|
||||
sl0 = readu8(b, o - 1) + readu8(b, o + s - 1) + readu8(b, o + 2 * s - 1) + readu8(b, o + 3 * s - 1)
|
||||
sl1 = readu8(b, o + 4 * s - 1) + readu8(b, o + 5 * s - 1) + readu8(b, o + 6 * s - 1) + readu8(b, o + 7 * s - 1)
|
||||
end
|
||||
local v00, v10, v01, v11 = 128, 128, 128, 128
|
||||
if top and left then
|
||||
v00 = (st0 + sl0 + 4) // 8
|
||||
v11 = (st1 + sl1 + 4) // 8
|
||||
v10 = (st1 + 2) // 4
|
||||
v01 = (sl1 + 2) // 4
|
||||
elseif left then
|
||||
v00 = (sl0 + 2) // 4
|
||||
v11 = (sl1 + 2) // 4
|
||||
v10 = v00
|
||||
v01 = v11
|
||||
elseif top then
|
||||
v00 = (st0 + 2) // 4
|
||||
v11 = (st1 + 2) // 4
|
||||
v10 = v11
|
||||
v01 = v00
|
||||
end
|
||||
fill4(b, o, s, v00)
|
||||
fill4(b, o + 4, s, v10)
|
||||
fill4(b, o + 4 * s, s, v01)
|
||||
fill4(b, o + 4 * s + 4, s, v11)
|
||||
elseif mode == 1 then
|
||||
for y = 0, 7 do
|
||||
local r = o + y * s
|
||||
buffer.fill(b, r, readu8(b, r - 1), 8)
|
||||
end
|
||||
elseif mode == 2 then
|
||||
local t = o - s
|
||||
for y = 0, 7 do
|
||||
buffer.copy(b, o + y * s, b, t, 8)
|
||||
end
|
||||
else
|
||||
local t = o - s
|
||||
local H, V = 0, 0
|
||||
for i = 0, 3 do
|
||||
H += (i + 1) * (readu8(b, t + 4 + i) - readu8(b, t + 2 - i))
|
||||
V += (i + 1) * (readu8(b, o + (4 + i) * s - 1) - readu8(b, o + (2 - i) * s - 1))
|
||||
end
|
||||
local a = 16 * (readu8(b, o + 7 * s - 1) + readu8(b, t + 7))
|
||||
local bb = (34 * H + 32) // 64
|
||||
local cc = (34 * V + 32) // 64
|
||||
for y = 0, 7 do
|
||||
local r = o + y * s
|
||||
local base = a + cc * (y - 3) + 16 - 3 * bb
|
||||
for x = 0, 7 do
|
||||
writeu8(b, r + x, clip((base + bb * x) // 32))
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
return Intra
|
||||
@@ -0,0 +1,930 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- codecs/H264/Mb: macroblock reconstruction shared by the CAVLC and CABAC parsers (ITU-T H.264 8.3 - 8.5):
|
||||
-- neighbour availability (6.4.11), Intra4x4 / Intra8x8 mode prediction (8.3.1.1 / 8.3.2.1), motion vector prediction
|
||||
-- (8.4.1.3), P_Skip (8.4.1.1), B direct spatial and temporal (8.4.1.2), motion compensation with weighting, intra
|
||||
-- prediction and the residual. Written from the spec; the per-4x4 motion / mode grids follow the usual decoder layout
|
||||
-- (picture-wide arrays, one entry per 4x4 luma block, 1-based).
|
||||
-- Never throws: every index is in range by construction; reference indices past the list use the first entry.
|
||||
local Intra = require("@formats/codecs/H264/Intra")
|
||||
local Transform = require("@formats/codecs/H264/Transform")
|
||||
local Inter = require("@formats/codecs/H264/Inter")
|
||||
|
||||
local Mb = {}
|
||||
|
||||
-- macroblock kinds (S.kind per macroblock)
|
||||
local K_I4, K_I8, K_I16, K_PCM, K_P, K_PSKIP, K_B, K_BSKIP, K_BDIRECT = 1, 2, 3, 4, 5, 6, 7, 8, 9
|
||||
Mb.K_I4, Mb.K_I8, Mb.K_I16, Mb.K_PCM, Mb.K_P, Mb.K_PSKIP, Mb.K_B, Mb.K_BSKIP, Mb.K_BDIRECT = K_I4, K_I8, K_I16, K_PCM, K_P, K_PSKIP, K_B, K_BSKIP, K_BDIRECT
|
||||
|
||||
local UNAVAIL = -2
|
||||
local min, max = math.min, math.max
|
||||
|
||||
local add4, addDc4, add8 = Transform.add4, Transform.addDc4, Transform.add8
|
||||
local PAD, PADC = Inter.PAD, Inter.PADC
|
||||
|
||||
-- raster 4x4 block (bx + 4 by) of the decoding-order block index 0..15 (6.4.3)
|
||||
local BLK_X = { 0, 1, 0, 1, 2, 3, 2, 3, 0, 1, 0, 1, 2, 3, 2, 3 }
|
||||
local BLK_Y = { 0, 0, 1, 1, 0, 0, 1, 1, 2, 2, 3, 3, 2, 2, 3, 3 }
|
||||
Mb.BLK_X, Mb.BLK_Y = BLK_X, BLK_Y
|
||||
|
||||
-- new() -> M, the per-macroblock scratch state
|
||||
function Mb.new(): any
|
||||
return {
|
||||
addr = 0,
|
||||
x = 0,
|
||||
y = 0,
|
||||
g0 = 1, -- grid index of the macroblock's 4x4 block (0, 0)
|
||||
c0 = 1, -- chroma 4x4 grid index of its block (0, 0)
|
||||
aL = false,
|
||||
aT = false,
|
||||
aTR = false,
|
||||
aTL = false,
|
||||
iL = false, -- intra sample availability (constrained_intra_pred aware)
|
||||
iT = false,
|
||||
iTR = false,
|
||||
iTL = false,
|
||||
kind = 0,
|
||||
t8 = 0,
|
||||
i16 = 0,
|
||||
cpm = 0,
|
||||
cbp = 0,
|
||||
qp = 0,
|
||||
qpd = 0, -- mb_qp_delta
|
||||
part = 0, -- 0 16x16, 1 16x8, 2 8x16, 3 8x8
|
||||
pf = { 0, 0, 0, 0 }, -- prediction flags per partition: 1 L0, 2 L1, 3 Bi
|
||||
sub = { 0, 0, 0, 0 }, -- sub-macroblock shape: 0 8x8, 1 8x4, 2 4x8, 3 4x4
|
||||
dir = { false, false, false, false }, -- B_Direct_8x8 sub-macroblocks
|
||||
ref0 = { 0, 0, 0, 0 },
|
||||
ref1 = { 0, 0, 0, 0 },
|
||||
mvd0 = table.create(32, 0),
|
||||
mvd1 = table.create(32, 0),
|
||||
ipm = table.create(16, 2), -- intra 4x4 / 8x8 modes by raster block
|
||||
c4 = table.create(256, 0), -- luma 4x4 coefficients (dequantised), raster block * 16 + raster position
|
||||
c8 = table.create(256, 0), -- luma 8x8 coefficients, 8x8 block * 64 + raster position
|
||||
cc = table.create(128, 0), -- chroma: (plane * 4 + block) * 16 + position
|
||||
dcY = table.create(16, 0),
|
||||
dcC = table.create(8, 0),
|
||||
nz = table.create(16, 0), -- coefficients per luma 4x4 block (raster)
|
||||
nzc = table.create(8, 0), -- coefficients per chroma AC block (plane * 4 + block)
|
||||
hasDcY = false,
|
||||
hasDcC = false,
|
||||
done = table.create(16, false),
|
||||
reg = table.create(64, 0), -- motion compensation regions: x, y, w, h (4x4 units)
|
||||
nreg = 0,
|
||||
P0 = table.create(256, 0),
|
||||
P1 = table.create(256, 0),
|
||||
pcm = buffer.create(384),
|
||||
}
|
||||
end
|
||||
|
||||
-- grids(mbW, mbH) -> the per-picture decoding grids (shared by the slices of one picture)
|
||||
function Mb.grids(mbW: number, mbH: number): any
|
||||
local n = mbW * mbH
|
||||
local n4 = n * 16
|
||||
local nc = n * 4
|
||||
return {
|
||||
sliceTab = table.create(n, 0),
|
||||
kind = table.create(n, 0),
|
||||
cbpTab = table.create(n, 0),
|
||||
qpTab = table.create(n, 0), -- QPY for deblocking (0 for I_PCM)
|
||||
qpcTab = table.create(n, 0), -- QPc (Cb)
|
||||
qpc2Tab = table.create(n, 0), -- QPc (Cr)
|
||||
t8Tab = table.create(n, 0),
|
||||
cpmTab = table.create(n, 0),
|
||||
dcTab = table.create(n, 0), -- CABAC coded_block_flag of the DC blocks: 1 luma, 2 Cb, 4 Cr
|
||||
qpdTab = table.create(n, 0), -- mb_qp_delta ~= 0
|
||||
nzc = table.create(n4, 0),
|
||||
nzcCb = table.create(nc, 0),
|
||||
nzcCr = table.create(nc, 0),
|
||||
nzDb = table.create(n4, 0),
|
||||
ipm = table.create(n4, 2),
|
||||
mvd0 = table.create(n4 * 2, 0),
|
||||
mvd1 = table.create(n4 * 2, 0),
|
||||
rgt0 = table.create(n4, 0),
|
||||
rgt1 = table.create(n4, 0),
|
||||
}
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ neighbours
|
||||
-- start(S, M, addr): position and neighbour availability of macroblock addr
|
||||
function Mb.start(S: any, M: any, addr: number)
|
||||
local mbW = S.mbW
|
||||
local x, y = addr % mbW, addr // mbW
|
||||
M.addr, M.x, M.y = addr, x, y
|
||||
local w4 = S.w4
|
||||
M.g0 = y * 4 * w4 + x * 4 + 1
|
||||
M.c0 = y * 2 * S.cw4 + x * 2 + 1
|
||||
local st, sl = S.sliceTab, S.slice
|
||||
local aL = x > 0 and st[addr] == sl -- addr is 0-based: st[addr] is macroblock addr - 1
|
||||
local aT = y > 0 and st[addr - mbW + 1] == sl
|
||||
local aTR = y > 0 and x < mbW - 1 and st[addr - mbW + 2] == sl
|
||||
local aTL = y > 0 and x > 0 and st[addr - mbW] == sl
|
||||
M.aL, M.aT, M.aTR, M.aTL = aL, aT, aTR, aTL
|
||||
if S.constrainedIntra then
|
||||
local k = S.kind
|
||||
M.iL = aL and k[addr] <= K_PCM
|
||||
M.iT = aT and k[addr - mbW + 1] <= K_PCM
|
||||
M.iTR = aTR and k[addr - mbW + 2] <= K_PCM
|
||||
M.iTL = aTL and k[addr - mbW] <= K_PCM
|
||||
else
|
||||
M.iL, M.iT, M.iTR, M.iTL = aL, aT, aTR, aTL
|
||||
end
|
||||
local done = M.done
|
||||
for i = 1, 16 do
|
||||
done[i] = false
|
||||
end
|
||||
M.nreg = 0
|
||||
M.hasDcY, M.hasDcC = false, false
|
||||
M.t8 = 0
|
||||
M.qpd = 0
|
||||
end
|
||||
|
||||
-- nC(S, M, bx, by) -> nC of luma block (bx, by) (9.2.1)
|
||||
function Mb.nC(S: any, M: any, bx: number, by: number): number
|
||||
local g = M.g0 + by * S.w4 + bx
|
||||
local nzc = S.nzc
|
||||
local la = bx > 0 or M.aL
|
||||
local ta = by > 0 or M.aT
|
||||
if la and ta then
|
||||
return (nzc[g - 1] + nzc[g - S.w4] + 1) // 2
|
||||
elseif la then
|
||||
return nzc[g - 1]
|
||||
elseif ta then
|
||||
return nzc[g - S.w4]
|
||||
end
|
||||
return 0
|
||||
end
|
||||
|
||||
-- nCc(S, M, tab, bx, by) -> nC of chroma AC block (bx, by) of the plane whose counts are in tab
|
||||
function Mb.nCc(S: any, M: any, tab: { number }, bx: number, by: number): number
|
||||
local cw = S.cw4
|
||||
local g = M.c0 + by * cw + bx
|
||||
local la = bx > 0 or M.aL
|
||||
local ta = by > 0 or M.aT
|
||||
if la and ta then
|
||||
return (tab[g - 1] + tab[g - cw] + 1) // 2
|
||||
elseif la then
|
||||
return tab[g - 1]
|
||||
elseif ta then
|
||||
return tab[g - cw]
|
||||
end
|
||||
return 0
|
||||
end
|
||||
|
||||
-- predMode(S, M, bx, by) -> predIntra4x4PredMode / predIntra8x8PredMode of the block whose top-left 4x4 is (bx, by)
|
||||
function Mb.predMode(S: any, M: any, bx: number, by: number): number
|
||||
local la = bx > 0 or M.iL
|
||||
local ta = by > 0 or M.iT
|
||||
if not (la and ta) then
|
||||
return 2
|
||||
end
|
||||
local ipm = S.ipm
|
||||
local g = M.g0 + by * S.w4 + bx
|
||||
local a, b = ipm[g - 1], ipm[g - S.w4]
|
||||
return ((a < b) and (a) or (b))
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ motion vectors
|
||||
-- neighbour(S, M, list, nx, ny) -> ref (UNAVAIL when not available), mvx, mvy of the 4x4 at (nx, ny) relative to the
|
||||
-- macroblock (nx, ny in -1 .. 4)
|
||||
local function neighbour(S: any, M: any, refs: { number }, mvs: { number }, nx: number, ny: number): (number, number, number)
|
||||
local ok
|
||||
if ny < 0 then
|
||||
if nx < 0 then
|
||||
ok = M.aTL
|
||||
elseif nx < 4 then
|
||||
ok = M.aT
|
||||
else
|
||||
ok = M.aTR
|
||||
end
|
||||
elseif nx < 0 then
|
||||
ok = M.aL
|
||||
elseif nx >= 4 then
|
||||
ok = false
|
||||
else
|
||||
ok = M.done[ny * 4 + nx + 1]
|
||||
end
|
||||
if not ok then
|
||||
return UNAVAIL, 0, 0
|
||||
end
|
||||
local g = M.g0 + ny * S.w4 + nx
|
||||
local r = refs[g]
|
||||
if r < 0 then
|
||||
return -1, 0, 0
|
||||
end
|
||||
return r, mvs[2 * g - 1], mvs[2 * g]
|
||||
end
|
||||
|
||||
local function median(a: number, b: number, c: number): number
|
||||
return max(min(a, b), min(max(a, b), c))
|
||||
end
|
||||
|
||||
-- mvp(S, M, list, x, y, w, ref, shape) -> mvpLX for the partition at (x, y) (4x4 units) of width w with reference
|
||||
-- index ref. shape: 0 generic, 1 = 16x8 upper, 2 = 16x8 lower, 3 = 8x16 left, 4 = 8x16 right
|
||||
local function mvp(S: any, M: any, list: number, x: number, y: number, w: number, ref: number, shape: number): (number, number)
|
||||
local pic = S.pic
|
||||
local refs = ((list == 0) and (pic.ref0) or (pic.ref1))
|
||||
local mvs = ((list == 0) and (pic.mv0) or (pic.mv1))
|
||||
local rA, ax, ay = neighbour(S, M, refs, mvs, x - 1, y)
|
||||
local rB, bx, by = neighbour(S, M, refs, mvs, x, y - 1)
|
||||
local rC, cx, cy = neighbour(S, M, refs, mvs, x + w, y - 1)
|
||||
if rC == UNAVAIL then
|
||||
rC, cx, cy = neighbour(S, M, refs, mvs, x - 1, y - 1)
|
||||
end
|
||||
if shape == 1 then
|
||||
if rB == ref then
|
||||
return bx, by
|
||||
end
|
||||
elseif shape == 2 then
|
||||
if rA == ref then
|
||||
return ax, ay
|
||||
end
|
||||
elseif shape == 3 then
|
||||
if rA == ref then
|
||||
return ax, ay
|
||||
end
|
||||
elseif shape == 4 then
|
||||
if rC == ref then
|
||||
return cx, cy
|
||||
end
|
||||
end
|
||||
if rB == UNAVAIL and rC == UNAVAIL and rA ~= UNAVAIL then
|
||||
rB, bx, by = rA, ax, ay
|
||||
rC, cx, cy = rA, ax, ay
|
||||
end
|
||||
local n = 0
|
||||
if rA == ref then
|
||||
n += 1
|
||||
end
|
||||
if rB == ref then
|
||||
n += 2
|
||||
end
|
||||
if rC == ref then
|
||||
n += 4
|
||||
end
|
||||
if n == 1 then
|
||||
return ax, ay
|
||||
elseif n == 2 then
|
||||
return bx, by
|
||||
elseif n == 4 then
|
||||
return cx, cy
|
||||
end
|
||||
return median(ax, bx, cx), median(ay, by, cy)
|
||||
end
|
||||
Mb.mvp = mvp
|
||||
|
||||
-- set(S, M, x, y, w, h, r0, m0x, m0y, r1, m1x, m1y): motion data of a region into the picture grids
|
||||
local function set(S: any, M: any, x: number, y: number, w: number, h: number, r0: number, m0x: number, m0y: number, r1: number, m1x: number, m1y: number)
|
||||
local pic = S.pic
|
||||
local ref0, ref1, mv0, mv1, uid0, uid1 = pic.ref0, pic.ref1, pic.mv0, pic.mv1, pic.uid0, pic.uid1
|
||||
local u0 = ((r0 >= 0) and (S.uids0[r0 + 1] or -1) or (-1))
|
||||
local u1 = ((r1 >= 0) and (S.uids1[r1 + 1] or -1) or (-1))
|
||||
local w4 = S.w4
|
||||
local done = M.done
|
||||
for j = y, y + h - 1 do
|
||||
local g = M.g0 + j * w4 + x
|
||||
for i = x, x + w - 1 do
|
||||
ref0[g] = r0
|
||||
ref1[g] = r1
|
||||
mv0[2 * g - 1], mv0[2 * g] = m0x, m0y
|
||||
mv1[2 * g - 1], mv1[2 * g] = m1x, m1y
|
||||
uid0[g] = u0
|
||||
uid1[g] = u1
|
||||
done[j * 4 + i + 1] = true
|
||||
g += 1
|
||||
end
|
||||
end
|
||||
local k = M.nreg * 4
|
||||
local reg = M.reg
|
||||
reg[k + 1], reg[k + 2], reg[k + 3], reg[k + 4] = x, y, w, h
|
||||
M.nreg += 1
|
||||
end
|
||||
|
||||
-- clipping helpers
|
||||
local function clip3(lo: number, hi: number, v: number): number
|
||||
return min(max(v, lo), hi)
|
||||
end
|
||||
|
||||
local function tdiv(a: number, b: number): number
|
||||
local q = a / b
|
||||
if q >= 0 then
|
||||
return math.floor(q)
|
||||
end
|
||||
return -math.floor(-q)
|
||||
end
|
||||
|
||||
-- distScale(cur, poc0, poc1) -> DistScaleFactor (8-195 .. 8-198), or nil when td is 0
|
||||
function Mb.distScale(cur: number, poc0: number, poc1: number): number?
|
||||
local tb = clip3(-128, 127, cur - poc0)
|
||||
local td = clip3(-128, 127, poc1 - poc0)
|
||||
if td == 0 then
|
||||
return nil
|
||||
end
|
||||
local tx = tdiv(16384 + math.abs(tdiv(td, 2)), td)
|
||||
return clip3(-1024, 1023, (tb * tx + 32) // 64)
|
||||
end
|
||||
|
||||
-- pskip(S, M): P_Skip motion (8.4.1.1)
|
||||
local function pskip(S: any, M: any)
|
||||
local mx, my = 0, 0
|
||||
if M.aL and M.aT then
|
||||
local pic = S.pic
|
||||
local rA, ax, ay = neighbour(S, M, pic.ref0, pic.mv0, -1, 0)
|
||||
local rB, bx, by = neighbour(S, M, pic.ref0, pic.mv0, 0, -1)
|
||||
if not ((rA == 0 and ax == 0 and ay == 0) or (rB == 0 and bx == 0 and by == 0)) then
|
||||
mx, my = mvp(S, M, 0, 0, 0, 4, 0, 0)
|
||||
end
|
||||
end
|
||||
set(S, M, 0, 0, 4, 4, 0, mx, my, -1, 0, 0)
|
||||
end
|
||||
|
||||
-- colocated(S, M, bx, by) -> refIdxCol (-1: intra / none), mvCol x, y, uid of the referenced picture (8.4.1.2.1)
|
||||
local function colocated(S: any, M: any, bx: number, by: number): (number, number, number, number)
|
||||
local col = S.colPic
|
||||
if S.direct8x8 then
|
||||
bx = ((bx < 2) and (0) or (3))
|
||||
by = ((by < 2) and (0) or (3))
|
||||
end
|
||||
if col.mbIntra[M.addr + 1] then
|
||||
return -1, 0, 0, -1
|
||||
end
|
||||
local g = M.g0 + by * S.w4 + bx
|
||||
local r = col.ref0[g]
|
||||
if r >= 0 then
|
||||
return r, col.mv0[2 * g - 1], col.mv0[2 * g], col.uid0[g]
|
||||
end
|
||||
r = col.ref1[g]
|
||||
if r >= 0 then
|
||||
return r, col.mv1[2 * g - 1], col.mv1[2 * g], col.uid1[g]
|
||||
end
|
||||
return -1, 0, 0, -1
|
||||
end
|
||||
|
||||
local function minPositive(a: number, b: number): number
|
||||
if a >= 0 and b >= 0 then
|
||||
return ((a < b) and (a) or (b))
|
||||
end
|
||||
return ((a > b) and (a) or (b))
|
||||
end
|
||||
|
||||
-- spatialRefs(S, M): the macroblock-level references and predictors of spatial direct (8.4.1.2.2), cached in M
|
||||
local function spatialRefs(S: any, M: any)
|
||||
local pic = S.pic
|
||||
local r0, r1 = -1, -1
|
||||
for l = 0, 1 do
|
||||
local refs = ((l == 0) and (pic.ref0) or (pic.ref1))
|
||||
local mvs = ((l == 0) and (pic.mv0) or (pic.mv1))
|
||||
local rA = neighbour(S, M, refs, mvs, -1, 0)
|
||||
local rB = neighbour(S, M, refs, mvs, 0, -1)
|
||||
local rC = neighbour(S, M, refs, mvs, 4, -1)
|
||||
if rC == UNAVAIL then
|
||||
rC = neighbour(S, M, refs, mvs, -1, -1)
|
||||
end
|
||||
local r = minPositive(rA, minPositive(rB, rC))
|
||||
if r < -1 then
|
||||
r = -1
|
||||
end
|
||||
if l == 0 then
|
||||
r0 = r
|
||||
else
|
||||
r1 = r
|
||||
end
|
||||
end
|
||||
M.dZero = false
|
||||
if r0 < 0 and r1 < 0 then
|
||||
r0, r1 = 0, 0
|
||||
M.dZero = true
|
||||
end
|
||||
M.dr0, M.dr1 = r0, r1
|
||||
M.d0x, M.d0y, M.d1x, M.d1y = 0, 0, 0, 0
|
||||
if not M.dZero then
|
||||
if r0 >= 0 then
|
||||
M.d0x, M.d0y = mvp(S, M, 0, 0, 0, 4, r0, 0)
|
||||
end
|
||||
if r1 >= 0 then
|
||||
M.d1x, M.d1y = mvp(S, M, 1, 0, 0, 4, r1, 0)
|
||||
end
|
||||
end
|
||||
M.dReady = true
|
||||
end
|
||||
|
||||
-- direct8(S, M, i8): direct motion of 8x8 quadrant i8 (B_Skip, B_Direct_16x16, B_Direct_8x8)
|
||||
local function direct8(S: any, M: any, i8: number)
|
||||
local x0, y0 = (i8 % 2) * 2, (i8 // 2) * 2
|
||||
local step = ((S.direct8x8) and (2) or (1))
|
||||
if S.directSpatial then
|
||||
if not M.dReady then
|
||||
spatialRefs(S, M)
|
||||
end
|
||||
local r0, r1 = M.dr0, M.dr1
|
||||
local l1short = S.colShort
|
||||
for y = y0, y0 + 1, step do
|
||||
for x = x0, x0 + 1, step do
|
||||
local m0x, m0y, m1x, m1y = M.d0x, M.d0y, M.d1x, M.d1y
|
||||
if not M.dZero and l1short then
|
||||
local rc, cx, cy = colocated(S, M, x, y)
|
||||
if rc == 0 and cx >= -1 and cx <= 1 and cy >= -1 and cy <= 1 then
|
||||
if r0 == 0 then
|
||||
m0x, m0y = 0, 0
|
||||
end
|
||||
if r1 == 0 then
|
||||
m1x, m1y = 0, 0
|
||||
end
|
||||
end
|
||||
end
|
||||
set(S, M, x, y, step, step, r0, m0x, m0y, r1, m1x, m1y)
|
||||
end
|
||||
end
|
||||
else
|
||||
for y = y0, y0 + 1, step do
|
||||
for x = x0, x0 + 1, step do
|
||||
local rc, cx, cy, cu = colocated(S, M, x, y)
|
||||
local r0 = 0
|
||||
if rc >= 0 then
|
||||
r0 = S.uidToRef0[cu] or 0
|
||||
end
|
||||
local m0x, m0y, m1x, m1y = cx, cy, 0, 0
|
||||
local dsf = S.dsf[r0 + 1]
|
||||
if dsf then
|
||||
m0x = (dsf * cx + 128) // 256
|
||||
m0y = (dsf * cy + 128) // 256
|
||||
m1x = m0x - cx
|
||||
m1y = m0y - cy
|
||||
end
|
||||
set(S, M, x, y, step, step, r0, m0x, m0y, 0, m1x, m1y)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- partition geometry (4x4 units) of the sub-macroblock shapes
|
||||
local SUB_N = { 1, 2, 2, 4 }
|
||||
local SUB_W = { 2, 2, 1, 1 }
|
||||
local SUB_H = { 2, 1, 2, 1 }
|
||||
|
||||
-- motion(S, M): motion vectors of an inter macroblock into the grids, and its MC regions
|
||||
local function motion(S: any, M: any)
|
||||
local kind = M.kind
|
||||
M.dReady = false
|
||||
if kind == K_PSKIP then
|
||||
pskip(S, M)
|
||||
return
|
||||
end
|
||||
if kind == K_BSKIP or kind == K_BDIRECT then
|
||||
for i8 = 0, 3 do
|
||||
direct8(S, M, i8)
|
||||
end
|
||||
return
|
||||
end
|
||||
local part = M.part
|
||||
local mvd0, mvd1 = M.mvd0, M.mvd1
|
||||
if part < 3 then
|
||||
local n = ((part == 0) and (1) or (2))
|
||||
for p = 1, n do
|
||||
local x, y, w, h = 0, 0, 4, 4
|
||||
local shape = 0
|
||||
if part == 1 then
|
||||
y, h = (p - 1) * 2, 2
|
||||
shape = p
|
||||
elseif part == 2 then
|
||||
x, w = (p - 1) * 2, 2
|
||||
shape = 2 + p
|
||||
end
|
||||
local pf = M.pf[p]
|
||||
local r0, r1 = -1, -1
|
||||
local m0x, m0y, m1x, m1y = 0, 0, 0, 0
|
||||
if pf % 2 == 1 then
|
||||
r0 = M.ref0[p]
|
||||
m0x, m0y = mvp(S, M, 0, x, y, w, r0, shape)
|
||||
m0x += mvd0[2 * p - 1]
|
||||
m0y += mvd0[2 * p]
|
||||
end
|
||||
if pf >= 2 then
|
||||
r1 = M.ref1[p]
|
||||
m1x, m1y = mvp(S, M, 1, x, y, w, r1, shape)
|
||||
m1x += mvd1[2 * p - 1]
|
||||
m1y += mvd1[2 * p]
|
||||
end
|
||||
set(S, M, x, y, w, h, r0, m0x, m0y, r1, m1x, m1y)
|
||||
end
|
||||
return
|
||||
end
|
||||
for i8 = 0, 3 do
|
||||
if M.dir[i8 + 1] then
|
||||
direct8(S, M, i8)
|
||||
else
|
||||
local x0, y0 = (i8 % 2) * 2, (i8 // 2) * 2
|
||||
local sub = M.sub[i8 + 1]
|
||||
local pf = M.pf[i8 + 1]
|
||||
local w, h = SUB_W[sub + 1], SUB_H[sub + 1]
|
||||
for k = 0, SUB_N[sub + 1] - 1 do
|
||||
local x, y = x0, y0
|
||||
if sub == 1 then
|
||||
y += k
|
||||
elseif sub == 2 then
|
||||
x += k
|
||||
elseif sub == 3 then
|
||||
x += k % 2
|
||||
y += k // 2
|
||||
end
|
||||
local p = i8 * 4 + k + 1
|
||||
local r0, r1 = -1, -1
|
||||
local m0x, m0y, m1x, m1y = 0, 0, 0, 0
|
||||
if pf % 2 == 1 then
|
||||
r0 = M.ref0[i8 + 1]
|
||||
m0x, m0y = mvp(S, M, 0, x, y, w, r0, 0)
|
||||
m0x += mvd0[2 * p - 1]
|
||||
m0y += mvd0[2 * p]
|
||||
end
|
||||
if pf >= 2 then
|
||||
r1 = M.ref1[i8 + 1]
|
||||
m1x, m1y = mvp(S, M, 1, x, y, w, r1, 0)
|
||||
m1x += mvd1[2 * p - 1]
|
||||
m1y += mvd1[2 * p]
|
||||
end
|
||||
set(S, M, x, y, w, h, r0, m0x, m0y, r1, m1x, m1y)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
Mb.motion = motion
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ motion compensation
|
||||
-- predict(S, M, pic, P, list, x, y, w, h, mvx, mvy, plane): one list's prediction samples of a region into P
|
||||
local function predLuma(S: any, ref: any, P: { number }, px: number, py: number, w: number, h: number, mvx: number, mvy: number)
|
||||
local W, H = S.mbW * 16, S.mbH * 16
|
||||
local ix = px + mvx // 4
|
||||
local iy = py + mvy // 4
|
||||
ix = clip3(2 - PAD, W + PAD - w - 4, ix)
|
||||
iy = clip3(2 - PAD, H + PAD - h - 4, iy)
|
||||
local s = ref.ys
|
||||
Inter.luma(ref.y, s, ref.yo + iy * s + ix, mvx % 4, mvy % 4, w, h, P)
|
||||
end
|
||||
|
||||
local function predChroma(S: any, ref: any, P: { number }, plane: buffer, px: number, py: number, w: number, h: number, mvx: number, mvy: number)
|
||||
local W, H = S.mbW * 8, S.mbH * 8
|
||||
local ix = px + mvx // 8
|
||||
local iy = py + mvy // 8
|
||||
ix = clip3(-PADC, W + PADC - 1 - w, ix)
|
||||
iy = clip3(-PADC, H + PADC - 1 - h, iy)
|
||||
local s = ref.cs
|
||||
Inter.chroma(plane, s, ref.co + iy * s + ix, mvx % 8, mvy % 8, w, h, P)
|
||||
end
|
||||
|
||||
local function refPic(list: { any }, r: number): any
|
||||
return list[r + 1] or list[1]
|
||||
end
|
||||
|
||||
-- mc(S, M): inter prediction of every region of the macroblock into the current picture
|
||||
local function mc(S: any, M: any)
|
||||
local pic = S.pic
|
||||
local reg = M.reg
|
||||
local P0, P1 = M.P0, M.P1
|
||||
local ys, cs = pic.ys, pic.cs
|
||||
local wm = S.weightMode
|
||||
local list0, list1 = S.list0, S.list1
|
||||
for k = 0, M.nreg - 1 do
|
||||
local x, y, w, h = reg[k * 4 + 1], reg[k * 4 + 2], reg[k * 4 + 3], reg[k * 4 + 4]
|
||||
local g = M.g0 + y * S.w4 + x
|
||||
local r0, r1 = pic.ref0[g], pic.ref1[g]
|
||||
local m0x, m0y, m1x, m1y = pic.mv0[2 * g - 1], pic.mv0[2 * g], pic.mv1[2 * g - 1], pic.mv1[2 * g]
|
||||
local ref0 = ((r0 >= 0) and (refPic(list0, r0)) or (nil))
|
||||
local ref1 = ((r1 >= 0) and (refPic(list1, r1)) or (nil))
|
||||
if ref0 == nil and ref1 == nil then
|
||||
ref0 = list0[1] or list1[1]
|
||||
r0 = 0
|
||||
if ref0 == nil then
|
||||
continue
|
||||
end
|
||||
end
|
||||
local px, py = M.x * 16 + x * 4, M.y * 16 + y * 4
|
||||
local lw, lh = w * 4, h * 4
|
||||
local lo = pic.yo + py * ys + px
|
||||
local cx, cy, cw, ch = M.x * 8 + x * 2, M.y * 8 + y * 2, w * 2, h * 2
|
||||
local co = pic.co + cy * cs + cx
|
||||
-- weights for this pair
|
||||
local bi = ref0 ~= nil and ref1 ~= nil
|
||||
local explicit = wm == 1
|
||||
local implicitW0, implicitW1 = 32, 32
|
||||
if wm == 2 then
|
||||
if bi then
|
||||
local iw = S.implicit[r0 * 32 + r1 + 1]
|
||||
implicitW0, implicitW1 = 64 - iw, iw
|
||||
else
|
||||
explicit = false
|
||||
end
|
||||
end
|
||||
local W0, W1 = S.weights0, S.weights1
|
||||
for plane = 0, 2 do
|
||||
local dst, o, s, bw, bh = pic.y, lo, ys, lw, lh
|
||||
if plane == 1 then
|
||||
dst, o, s, bw, bh = pic.u, co, cs, cw, ch
|
||||
elseif plane == 2 then
|
||||
dst, o, s, bw, bh = pic.v, co, cs, cw, ch
|
||||
end
|
||||
if ref0 then
|
||||
if plane == 0 then
|
||||
predLuma(S, ref0, P0, px, py, lw, lh, m0x, m0y)
|
||||
else
|
||||
predChroma(S, ref0, P0, ((plane == 1) and (ref0.u) or (ref0.v)), cx, cy, cw, ch, m0x, m0y)
|
||||
end
|
||||
end
|
||||
if ref1 then
|
||||
if plane == 0 then
|
||||
predLuma(S, ref1, P1, px, py, lw, lh, m1x, m1y)
|
||||
else
|
||||
predChroma(S, ref1, P1, ((plane == 1) and (ref1.u) or (ref1.v)), cx, cy, cw, ch, m1x, m1y)
|
||||
end
|
||||
end
|
||||
if wm == 2 and bi then
|
||||
Inter.weight2(P0, P1, bw, bh, dst, o, s, 5, implicitW0, implicitW1, 0)
|
||||
elseif explicit then
|
||||
local logWD = ((plane == 0) and (S.lumaDenom) or (S.chromaDenom))
|
||||
local wi = plane * 2 + 1
|
||||
if bi then
|
||||
local b0, b1 = r0 * 8, r1 * 8
|
||||
Inter.weight2(P0, P1, bw, bh, dst, o, s, logWD, W0[b0 + wi] or 1, W1[b1 + wi] or 1, ((W0[b0 + wi + 1] or 0) + (W1[b1 + wi + 1] or 0) + 1) // 2)
|
||||
elseif ref0 then
|
||||
local b0 = r0 * 8
|
||||
Inter.weight1(P0, bw, bh, dst, o, s, logWD, W0[b0 + wi] or 1, W0[b0 + wi + 1] or 0)
|
||||
else
|
||||
local b1 = r1 * 8
|
||||
Inter.weight1(P1, bw, bh, dst, o, s, logWD, W1[b1 + wi] or 1, W1[b1 + wi + 1] or 0)
|
||||
end
|
||||
elseif bi then
|
||||
Inter.avg(P0, P1, bw, bh, dst, o, s)
|
||||
elseif ref0 then
|
||||
Inter.put(P0, bw, bh, dst, o, s)
|
||||
else
|
||||
Inter.put(P1, bw, bh, dst, o, s)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ residual
|
||||
local function lumaResidual(S: any, M: any)
|
||||
local pic = S.pic
|
||||
local b, s = pic.y, pic.ys
|
||||
local o = pic.yo + M.y * 16 * s + M.x * 16
|
||||
local nz, c4, c8 = M.nz, M.c4, M.c8
|
||||
if M.t8 == 1 then
|
||||
for i8 = 0, 3 do
|
||||
local bx, by = (i8 % 2) * 2, (i8 // 2) * 2
|
||||
if nz[by * 4 + bx + 1] > 0 then
|
||||
add8(c8, i8 * 64, b, o + by * 4 * s + bx * 4, s)
|
||||
end
|
||||
end
|
||||
return
|
||||
end
|
||||
for blk = 0, 15 do
|
||||
if nz[blk + 1] > 0 then
|
||||
local bx, by = blk % 4, blk // 4
|
||||
add4(c4, blk * 16, b, o + by * 4 * s + bx * 4, s)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
local function chromaResidual(S: any, M: any)
|
||||
if not M.hasDcC and M.cbp < 32 then
|
||||
return
|
||||
end
|
||||
local pic = S.pic
|
||||
local s = pic.cs
|
||||
local o = pic.co + M.y * 8 * s + M.x * 8
|
||||
local cc, nzc = M.cc, M.nzc
|
||||
if M.hasDcC then
|
||||
local dq = S.dq.d4
|
||||
local intra = M.kind <= K_PCM
|
||||
Transform.chromaDc(M.dcC, 0, dq[((intra) and (2) or (5))][M.qpc + 1][1], cc, 0)
|
||||
Transform.chromaDc(M.dcC, 4, dq[((intra) and (3) or (6))][M.qpc2 + 1][1], cc, 64)
|
||||
end
|
||||
for plane = 0, 1 do
|
||||
local b = ((plane == 0) and (pic.u) or (pic.v))
|
||||
for blk = 0, 3 do
|
||||
local base = (plane * 4 + blk) * 16
|
||||
local q = o + (blk // 2) * 4 * s + (blk % 2) * 4
|
||||
if nzc[plane * 4 + blk + 1] > 0 then
|
||||
add4(cc, base, b, q, s)
|
||||
elseif cc[base + 1] ~= 0 then
|
||||
addDc4(cc[base + 1], b, q, s)
|
||||
cc[base + 1] = 0
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ intra
|
||||
local function intraLuma(S: any, M: any)
|
||||
local pic = S.pic
|
||||
local b, s = pic.y, pic.ys
|
||||
local o = pic.yo + M.y * 16 * s + M.x * 16
|
||||
local kind = M.kind
|
||||
local ipm = M.ipm
|
||||
if kind == K_I16 then
|
||||
Intra.pred16x16(b, o, s, M.i16, M.iL, M.iT, M.iTL)
|
||||
local c4, nz = M.c4, M.nz
|
||||
if M.hasDcY then
|
||||
Transform.lumaDc(M.dcY, S.dq.d4[1][M.qp + 1][1], c4)
|
||||
end
|
||||
for blk = 0, 15 do
|
||||
local bx, by = blk % 4, blk // 4
|
||||
local q = o + by * 4 * s + bx * 4
|
||||
if nz[blk + 1] > 0 then
|
||||
add4(c4, blk * 16, b, q, s)
|
||||
elseif c4[blk * 16 + 1] ~= 0 then
|
||||
addDc4(c4[blk * 16 + 1], b, q, s)
|
||||
c4[blk * 16 + 1] = 0
|
||||
end
|
||||
end
|
||||
elseif kind == K_I8 then
|
||||
local nz, c8 = M.nz, M.c8
|
||||
for i8 = 0, 3 do
|
||||
local bx, by = (i8 % 2) * 2, (i8 // 2) * 2
|
||||
local left = bx > 0 or M.iL
|
||||
local top = by > 0 or M.iT
|
||||
local tr, tl
|
||||
if i8 == 0 then
|
||||
tr, tl = M.iT, M.iTL
|
||||
elseif i8 == 1 then
|
||||
tr, tl = M.iTR, M.iT
|
||||
elseif i8 == 2 then
|
||||
tr, tl = true, M.iL
|
||||
else
|
||||
tr, tl = false, true
|
||||
end
|
||||
local q = o + by * 4 * s + bx * 4
|
||||
Intra.pred8x8(b, q, s, ipm[by * 4 + bx + 1], left, top, tr, tl)
|
||||
if nz[by * 4 + bx + 1] > 0 then
|
||||
add8(c8, i8 * 64, b, q, s)
|
||||
end
|
||||
end
|
||||
else
|
||||
local nz, c4 = M.nz, M.c4
|
||||
for i = 0, 15 do
|
||||
local bx, by = BLK_X[i + 1], BLK_Y[i + 1]
|
||||
local blk = by * 4 + bx
|
||||
local left = bx > 0 or M.iL
|
||||
local top = by > 0 or M.iT
|
||||
local tl
|
||||
if bx > 0 and by > 0 then
|
||||
tl = true
|
||||
elseif bx > 0 then
|
||||
tl = M.iT
|
||||
elseif by > 0 then
|
||||
tl = M.iL
|
||||
else
|
||||
tl = M.iTL
|
||||
end
|
||||
local tr
|
||||
if by == 0 then
|
||||
if bx < 3 then
|
||||
tr = M.iT
|
||||
else
|
||||
tr = M.iTR
|
||||
end
|
||||
else
|
||||
tr = not (bx == 3 or (bx == 1 and (by == 1 or by == 3)))
|
||||
end
|
||||
local q = o + by * 4 * s + bx * 4
|
||||
Intra.pred4x4(b, q, s, ipm[blk + 1], left, top, tr, tl)
|
||||
if nz[blk + 1] > 0 then
|
||||
add4(c4, blk * 16, b, q, s)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
local function intraChroma(S: any, M: any)
|
||||
local pic = S.pic
|
||||
local s = pic.cs
|
||||
local o = pic.co + M.y * 8 * s + M.x * 8
|
||||
Intra.predChroma(pic.u, o, s, M.cpm, M.iL, M.iT, M.iTL)
|
||||
Intra.predChroma(pic.v, o, s, M.cpm, M.iL, M.iT, M.iTL)
|
||||
end
|
||||
|
||||
local function pcm(S: any, M: any)
|
||||
local pic = S.pic
|
||||
local src = M.pcm
|
||||
local s = pic.ys
|
||||
local o = pic.yo + M.y * 16 * s + M.x * 16
|
||||
for y = 0, 15 do
|
||||
buffer.copy(pic.y, o + y * s, src, y * 16, 16)
|
||||
end
|
||||
s = pic.cs
|
||||
o = pic.co + M.y * 8 * s + M.x * 8
|
||||
for y = 0, 7 do
|
||||
buffer.copy(pic.u, o + y * s, src, 256 + y * 8, 8)
|
||||
buffer.copy(pic.v, o + y * s, src, 320 + y * 8, 8)
|
||||
end
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ macroblock
|
||||
-- recon(S, M): reconstruct the parsed macroblock and store what later macroblocks / deblocking need
|
||||
function Mb.recon(S: any, M: any)
|
||||
local kind = M.kind
|
||||
local addr = M.addr + 1
|
||||
local pic = S.pic
|
||||
local w4 = S.w4
|
||||
S.kind[addr] = kind
|
||||
S.sliceTab[addr] = S.slice
|
||||
S.t8Tab[addr] = M.t8
|
||||
S.qpTab[addr] = ((kind == K_PCM) and (0) or (M.qp))
|
||||
S.qpcTab[addr] = ((kind == K_PCM) and (S.qpcOf[1]) or (M.qpc))
|
||||
S.qpc2Tab[addr] = ((kind == K_PCM) and (S.qpc2Of[1]) or (M.qpc2))
|
||||
pic.mbIntra[addr] = kind <= K_PCM
|
||||
local nzDb = S.nzDb
|
||||
local g0 = M.g0
|
||||
if kind <= K_PCM then
|
||||
-- intra: no motion
|
||||
local ref0, ref1, uid0, uid1 = pic.ref0, pic.ref1, pic.uid0, pic.uid1
|
||||
for j = 0, 3 do
|
||||
local g = g0 + j * w4
|
||||
for i = 0, 3 do
|
||||
ref0[g + i], ref1[g + i], uid0[g + i], uid1[g + i] = -1, -1, -1, -1
|
||||
end
|
||||
end
|
||||
if kind == K_PCM or kind == K_I16 then
|
||||
local ipm = S.ipm
|
||||
for j = 0, 3 do
|
||||
local g = g0 + j * w4
|
||||
ipm[g], ipm[g + 1], ipm[g + 2], ipm[g + 3] = 2, 2, 2, 2
|
||||
end
|
||||
end
|
||||
if kind == K_PCM then
|
||||
pcm(S, M)
|
||||
return
|
||||
end
|
||||
intraLuma(S, M)
|
||||
intraChroma(S, M)
|
||||
chromaResidual(S, M)
|
||||
return
|
||||
end
|
||||
local ipm = S.ipm
|
||||
for j = 0, 3 do
|
||||
local g = g0 + j * w4
|
||||
ipm[g], ipm[g + 1], ipm[g + 2], ipm[g + 3] = 2, 2, 2, 2
|
||||
end
|
||||
motion(S, M)
|
||||
mc(S, M)
|
||||
local nz = M.nz
|
||||
if M.t8 == 1 then
|
||||
for i8 = 0, 3 do
|
||||
local bx, by = (i8 % 2) * 2, (i8 // 2) * 2
|
||||
local v = ((nz[by * 4 + bx + 1] > 0) and (1) or (0))
|
||||
local g = g0 + by * w4 + bx
|
||||
nzDb[g], nzDb[g + 1], nzDb[g + w4], nzDb[g + w4 + 1] = v, v, v, v
|
||||
end
|
||||
else
|
||||
for blk = 0, 15 do
|
||||
nzDb[g0 + (blk // 4) * w4 + blk % 4] = ((nz[blk + 1] > 0) and (1) or (0))
|
||||
end
|
||||
end
|
||||
if M.cbp % 16 ~= 0 then
|
||||
lumaResidual(S, M)
|
||||
end
|
||||
chromaResidual(S, M)
|
||||
end
|
||||
|
||||
-- skip(S, M, kind): a P_Skip / B_Skip macroblock (no residual)
|
||||
function Mb.skip(S: any, M: any, kind: number)
|
||||
M.kind = kind
|
||||
M.cbp = 0
|
||||
M.t8 = 0
|
||||
M.qp = S.qp
|
||||
M.qpc = S.qpcOf[S.qp + 1]
|
||||
M.qpc2 = S.qpc2Of[S.qp + 1]
|
||||
local addr = M.addr + 1
|
||||
S.cbpTab[addr] = 0
|
||||
S.dcTab[addr] = 0
|
||||
S.cpmTab[addr] = 0
|
||||
S.qpdTab[addr] = 0
|
||||
local nz = M.nz
|
||||
for i = 1, 16 do
|
||||
nz[i] = 0
|
||||
end
|
||||
local nzc = M.nzc
|
||||
for i = 1, 8 do
|
||||
nzc[i] = 0
|
||||
end
|
||||
local w4, g0 = S.w4, M.g0
|
||||
local grid, mvd0, mvd1, rgt0, rgt1 = S.nzc, S.mvd0, S.mvd1, S.rgt0, S.rgt1
|
||||
for j = 0, 3 do
|
||||
local g = g0 + j * w4
|
||||
for i = 0, 3 do
|
||||
grid[g + i] = 0
|
||||
mvd0[2 * (g + i) - 1], mvd0[2 * (g + i)] = 0, 0
|
||||
mvd1[2 * (g + i) - 1], mvd1[2 * (g + i)] = 0, 0
|
||||
rgt0[g + i], rgt1[g + i] = 0, 0
|
||||
end
|
||||
end
|
||||
local cw, c0 = S.cw4, M.c0
|
||||
local cb, cr = S.nzcCb, S.nzcCr
|
||||
cb[c0], cb[c0 + 1], cb[c0 + cw], cb[c0 + cw + 1] = 0, 0, 0, 0
|
||||
cr[c0], cr[c0 + 1], cr[c0 + cw], cr[c0 + cw + 1] = 0, 0, 0, 0
|
||||
M.hasDcC = false
|
||||
Mb.recon(S, M)
|
||||
end
|
||||
|
||||
return Mb
|
||||
@@ -0,0 +1,453 @@
|
||||
--!strict
|
||||
--!native
|
||||
-- codecs/H264/Params: sequence and picture parameter sets (ITU-T H.264 7.3.2.1 / 7.3.2.2 / E.1), scaling lists with
|
||||
-- the fall-back rules A and B (7.4.2.1.1 / table 7-2), and the dequantisation tables built from them (8.5.9: the
|
||||
-- LevelScale4x4 / LevelScale8x8 functions, premultiplied by 2^(qP / 6)). Written from the spec.
|
||||
-- Never throws: parse functions return nil, "message".
|
||||
local Bitstream = require("@formats/codecs/H264/Bitstream")
|
||||
local Tables = require("@formats/codecs/H264/Tables")
|
||||
|
||||
local u, u1, ue, se = Bitstream.u, Bitstream.u1, Bitstream.ue, Bitstream.se
|
||||
|
||||
local Params = {}
|
||||
|
||||
local HIGH_PROFILES = { [100] = true, [110] = true, [122] = true, [244] = true, [44] = true, [83] = true, [86] = true, [118] = true, [128] = true, [138] = true, [139] = true, [134] = true, [135] = true }
|
||||
|
||||
-- MaxDpbMbs by level_idc (table A-1); level 9 is level 1b
|
||||
local MAX_DPB_MBS = { [9] = 396, [10] = 396, [11] = 900, [12] = 2376, [13] = 2376, [20] = 2376, [21] = 4752, [22] = 8100, [30] = 8100, [31] = 18000, [32] = 20480, [40] = 32768, [41] = 32768, [42] = 34816, [50] = 110400, [51] = 184320, [52] = 184320, [60] = 696320, [61] = 696320, [62] = 696320 }
|
||||
|
||||
local ZIGZAG4, ZIGZAG8 = Tables.ZIGZAG4, Tables.ZIGZAG8
|
||||
|
||||
-- scaling_list(): returns the list in raster order, or "default" (useDefaultScalingMatrixFlag)
|
||||
local function scalingList(r: Bitstream.Reader, size: number): any
|
||||
local list = table.create(size, 0)
|
||||
local last, nxt = 8, 8
|
||||
local zz = if size == 16 then ZIGZAG4 else ZIGZAG8
|
||||
for j = 0, size - 1 do
|
||||
if nxt ~= 0 then
|
||||
local d = se(r)
|
||||
if d < -128 or d > 127 then
|
||||
return nil
|
||||
end
|
||||
nxt = (last + d + 256) % 256
|
||||
if j == 0 and nxt == 0 then
|
||||
return "default"
|
||||
end
|
||||
end
|
||||
local v = if nxt == 0 then last else nxt
|
||||
list[zz[j + 1] + 1] = v
|
||||
last = v
|
||||
end
|
||||
return list
|
||||
end
|
||||
|
||||
-- lists: 12 entries (false = not present, "default", or a raster list)
|
||||
local function scalingMatrix(r: Bitstream.Reader, count: number): { any }?
|
||||
local lists = table.create(12, false)
|
||||
for i = 1, count do
|
||||
if u1(r) == 1 then
|
||||
local l = scalingList(r, if i <= 6 then 16 else 64)
|
||||
if l == nil then
|
||||
return nil
|
||||
end
|
||||
lists[i] = l
|
||||
end
|
||||
end
|
||||
return lists
|
||||
end
|
||||
|
||||
local function default(i: number): { number }
|
||||
local out = {}
|
||||
if i <= 6 then
|
||||
local base = if i <= 3 then 0 else 16
|
||||
for k = 1, 16 do
|
||||
out[k] = Tables.DEFAULT_4x4[base + k]
|
||||
end
|
||||
else
|
||||
local base = if (i - 7) % 2 == 0 then 0 else 64
|
||||
for k = 1, 64 do
|
||||
out[k] = Tables.DEFAULT_8x8[base + k]
|
||||
end
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
local FLAT16, FLAT64 = table.create(16, 16), table.create(64, 16)
|
||||
|
||||
-- resolve(lists, fallback) -> 12 raster lists. fallback: nil = rule A (defaults), else the 12 lists of the SPS (rule B)
|
||||
local function resolve(lists: { any }, fallback: { { number } }?): { { number } }
|
||||
local out = {}
|
||||
for i = 1, 12 do
|
||||
local l = lists[i]
|
||||
if l == "default" then
|
||||
out[i] = default(i)
|
||||
elseif l then
|
||||
out[i] = l
|
||||
elseif i == 1 or i == 4 or i == 7 or i == 8 then
|
||||
out[i] = if fallback then fallback[i] else default(i)
|
||||
elseif i <= 6 then
|
||||
out[i] = out[i - 1]
|
||||
else
|
||||
out[i] = out[i - 2]
|
||||
end
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ vui
|
||||
local function hrd(r: Bitstream.Reader)
|
||||
local cnt = ue(r)
|
||||
if cnt > 31 then
|
||||
return false
|
||||
end
|
||||
u(r, 8)
|
||||
for _ = 0, cnt do
|
||||
ue(r)
|
||||
ue(r)
|
||||
u1(r)
|
||||
end
|
||||
u(r, 20)
|
||||
return true
|
||||
end
|
||||
|
||||
local function vui(r: Bitstream.Reader, sps: any)
|
||||
if u1(r) == 1 then
|
||||
local idc = u(r, 8)
|
||||
if idc == 255 then
|
||||
sps.sarW = u(r, 16)
|
||||
sps.sarH = u(r, 16)
|
||||
end
|
||||
sps.aspectIdc = idc
|
||||
end
|
||||
if u1(r) == 1 then
|
||||
u1(r)
|
||||
end
|
||||
if u1(r) == 1 then
|
||||
u(r, 3)
|
||||
sps.fullRange = u1(r) == 1
|
||||
if u1(r) == 1 then
|
||||
sps.colourPrimaries = u(r, 8)
|
||||
sps.transfer = u(r, 8)
|
||||
sps.matrix = u(r, 8)
|
||||
end
|
||||
end
|
||||
if u1(r) == 1 then
|
||||
ue(r)
|
||||
ue(r)
|
||||
end
|
||||
if u1(r) == 1 then
|
||||
sps.unitsInTick = u(r, 32)
|
||||
sps.timeScale = u(r, 32)
|
||||
sps.fixedRate = u1(r) == 1
|
||||
end
|
||||
local nal = u1(r) == 1
|
||||
if nal and not hrd(r) then
|
||||
return
|
||||
end
|
||||
local vcl = u1(r) == 1
|
||||
if vcl and not hrd(r) then
|
||||
return
|
||||
end
|
||||
if nal or vcl then
|
||||
u1(r)
|
||||
end
|
||||
u1(r)
|
||||
if u1(r) == 1 then
|
||||
u1(r)
|
||||
ue(r)
|
||||
ue(r)
|
||||
ue(r)
|
||||
ue(r)
|
||||
local reorder = ue(r)
|
||||
local dpb = ue(r)
|
||||
if r.pos <= r.size and reorder <= 16 and dpb <= 16 then
|
||||
sps.numReorderFrames = reorder
|
||||
sps.maxDecFrameBuffering = dpb
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sps
|
||||
-- sps(r) -> the SPS table | nil, message. r is positioned after the NAL header.
|
||||
function Params.sps(r: Bitstream.Reader): (any, string?)
|
||||
local sps: any = {}
|
||||
sps.profile = u(r, 8)
|
||||
sps.constraints = u(r, 8)
|
||||
sps.level = u(r, 8)
|
||||
sps.id = ue(r)
|
||||
if sps.id > 31 then
|
||||
return nil, "seq_parameter_set_id out of range"
|
||||
end
|
||||
sps.chromaFormat = 1
|
||||
sps.bitDepth = 8
|
||||
sps.bitDepthC = 8
|
||||
sps.bypass = false
|
||||
sps.scaling = nil
|
||||
if HIGH_PROFILES[sps.profile] then
|
||||
sps.chromaFormat = ue(r)
|
||||
if sps.chromaFormat > 3 then
|
||||
return nil, "chroma_format_idc out of range"
|
||||
end
|
||||
if sps.chromaFormat == 3 then
|
||||
sps.separatePlanes = u1(r) == 1
|
||||
end
|
||||
sps.bitDepth = ue(r) + 8
|
||||
sps.bitDepthC = ue(r) + 8
|
||||
if sps.bitDepth > 14 or sps.bitDepthC > 14 then
|
||||
return nil, "bit depth out of range"
|
||||
end
|
||||
sps.bypass = u1(r) == 1
|
||||
if u1(r) == 1 then
|
||||
local lists = scalingMatrix(r, if sps.chromaFormat ~= 3 then 8 else 12)
|
||||
if not lists then
|
||||
return nil, "bad scaling list"
|
||||
end
|
||||
sps.scaling = resolve(lists, nil)
|
||||
end
|
||||
end
|
||||
sps.log2MaxFrameNum = ue(r) + 4
|
||||
if sps.log2MaxFrameNum > 16 then
|
||||
return nil, "log2_max_frame_num out of range"
|
||||
end
|
||||
sps.pocType = ue(r)
|
||||
if sps.pocType == 0 then
|
||||
sps.log2MaxPocLsb = ue(r) + 4
|
||||
if sps.log2MaxPocLsb > 16 then
|
||||
return nil, "log2_max_pic_order_cnt_lsb out of range"
|
||||
end
|
||||
elseif sps.pocType == 1 then
|
||||
sps.deltaPocAlwaysZero = u1(r) == 1
|
||||
sps.offsetNonRef = se(r)
|
||||
sps.offsetTopToBottom = se(r)
|
||||
local n = ue(r)
|
||||
if n > 255 then
|
||||
return nil, "num_ref_frames_in_pic_order_cnt_cycle out of range"
|
||||
end
|
||||
sps.offsetsForRefFrame = {}
|
||||
local expected = 0
|
||||
for i = 1, n do
|
||||
sps.offsetsForRefFrame[i] = se(r)
|
||||
expected += sps.offsetsForRefFrame[i]
|
||||
end
|
||||
sps.expectedDeltaPerCycle = expected
|
||||
elseif sps.pocType ~= 2 then
|
||||
return nil, "pic_order_cnt_type out of range"
|
||||
end
|
||||
sps.maxRefFrames = ue(r)
|
||||
if sps.maxRefFrames > 16 then
|
||||
return nil, "max_num_ref_frames out of range"
|
||||
end
|
||||
sps.gapsAllowed = u1(r) == 1
|
||||
sps.mbWidth = ue(r) + 1
|
||||
sps.mbHeightMap = ue(r) + 1
|
||||
sps.frameMbsOnly = u1(r) == 1
|
||||
if not sps.frameMbsOnly then
|
||||
sps.mbaff = u1(r) == 1
|
||||
end
|
||||
sps.mbHeight = if sps.frameMbsOnly then sps.mbHeightMap else sps.mbHeightMap * 2
|
||||
if sps.mbWidth > 1024 or sps.mbHeight > 1024 then
|
||||
return nil, "limit: picture too large"
|
||||
end
|
||||
sps.direct8x8 = u1(r) == 1
|
||||
sps.cropLeft, sps.cropRight, sps.cropTop, sps.cropBottom = 0, 0, 0, 0
|
||||
if u1(r) == 1 then
|
||||
sps.cropLeft = ue(r)
|
||||
sps.cropRight = ue(r)
|
||||
sps.cropTop = ue(r)
|
||||
sps.cropBottom = ue(r)
|
||||
end
|
||||
if r.pos > r.size then
|
||||
return nil, "truncated: sequence parameter set"
|
||||
end
|
||||
if u1(r) == 1 then
|
||||
local save = r.pos
|
||||
vui(r, sps)
|
||||
if r.pos > r.size then
|
||||
r.pos = save
|
||||
end
|
||||
end
|
||||
-- derived sizes (4:2:0 crop units: 2 x 2; monochrome / 4:4:4 are rejected later)
|
||||
local cux, cuy = 2, 2 * (if sps.frameMbsOnly then 1 else 2)
|
||||
if sps.chromaFormat == 0 or sps.chromaFormat == 3 then
|
||||
cux, cuy = 1, (if sps.frameMbsOnly then 1 else 2)
|
||||
elseif sps.chromaFormat == 2 then
|
||||
cux, cuy = 2, (if sps.frameMbsOnly then 1 else 2)
|
||||
end
|
||||
local w, h = sps.mbWidth * 16, sps.mbHeight * 16
|
||||
sps.width = w - cux * (sps.cropLeft + sps.cropRight)
|
||||
sps.height = h - cuy * (sps.cropTop + sps.cropBottom)
|
||||
sps.cropX = cux * sps.cropLeft
|
||||
sps.cropY = cuy * sps.cropTop
|
||||
if sps.width <= 0 or sps.height <= 0 then
|
||||
return nil, "cropping larger than the picture"
|
||||
end
|
||||
local maxMbs = MAX_DPB_MBS[sps.level] or 696320
|
||||
if sps.level == 11 and sps.constraints % 32 >= 16 and sps.profile ~= 100 then
|
||||
maxMbs = 396 -- level 1b
|
||||
end
|
||||
sps.maxDpbFrames = math.clamp(maxMbs // (sps.mbWidth * sps.mbHeight), 1, 16)
|
||||
return sps, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ pps
|
||||
-- pps(r, spsTable) -> the PPS | nil, message. spsTable: id -> SPS (needed for the scaling list count)
|
||||
function Params.pps(r: Bitstream.Reader, spsTable: { [number]: any }): (any, string?)
|
||||
local pps: any = {}
|
||||
pps.id = ue(r)
|
||||
if pps.id > 255 then
|
||||
return nil, "pic_parameter_set_id out of range"
|
||||
end
|
||||
pps.spsId = ue(r)
|
||||
local sps = spsTable[pps.spsId]
|
||||
if not sps then
|
||||
return nil, "pps refers to a missing sps"
|
||||
end
|
||||
pps.cabac = u1(r) == 1
|
||||
pps.bottomFieldPocPresent = u1(r) == 1
|
||||
pps.sliceGroups = ue(r) + 1
|
||||
if pps.sliceGroups > 1 then
|
||||
return nil, "unsupported: slice groups (FMO)"
|
||||
end
|
||||
pps.numRefIdxL0 = ue(r) + 1
|
||||
pps.numRefIdxL1 = ue(r) + 1
|
||||
if pps.numRefIdxL0 > 32 or pps.numRefIdxL1 > 32 then
|
||||
return nil, "num_ref_idx_default_active out of range"
|
||||
end
|
||||
pps.weightedPred = u1(r) == 1
|
||||
pps.weightedBipred = u(r, 2)
|
||||
pps.initQp = 26 + se(r)
|
||||
pps.initQs = 26 + se(r)
|
||||
pps.chromaQpOffset = se(r)
|
||||
if pps.initQp < 0 or pps.initQp > 51 or pps.chromaQpOffset < -12 or pps.chromaQpOffset > 12 then
|
||||
return nil, "pic_init_qp / chroma_qp_index_offset out of range"
|
||||
end
|
||||
pps.deblockingControl = u1(r) == 1
|
||||
pps.constrainedIntra = u1(r) == 1
|
||||
pps.redundantPicCnt = u1(r) == 1
|
||||
pps.transform8x8 = false
|
||||
pps.chromaQpOffset2 = pps.chromaQpOffset
|
||||
pps.scalingLists = nil
|
||||
if r.pos > r.size then
|
||||
return nil, "truncated: picture parameter set"
|
||||
end
|
||||
if Bitstream.moreData(r) then
|
||||
pps.transform8x8 = u1(r) == 1
|
||||
if u1(r) == 1 then
|
||||
local n = 6 + (if pps.transform8x8 then (if sps.chromaFormat ~= 3 then 2 else 6) else 0)
|
||||
local lists = scalingMatrix(r, n)
|
||||
if not lists then
|
||||
return nil, "bad scaling list"
|
||||
end
|
||||
pps.scalingLists = lists
|
||||
end
|
||||
pps.chromaQpOffset2 = se(r)
|
||||
if pps.chromaQpOffset2 < -12 or pps.chromaQpOffset2 > 12 then
|
||||
return nil, "second_chroma_qp_index_offset out of range"
|
||||
end
|
||||
if r.pos > r.size then
|
||||
return nil, "truncated: picture parameter set"
|
||||
end
|
||||
end
|
||||
return pps, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ dequantisation
|
||||
local V4 = { { 10, 16, 13 }, { 11, 18, 14 }, { 13, 20, 16 }, { 14, 23, 18 }, { 16, 25, 20 }, { 18, 29, 23 } }
|
||||
local V8 = {
|
||||
{ 20, 18, 32, 19, 25, 24 },
|
||||
{ 22, 19, 35, 21, 28, 26 },
|
||||
{ 26, 23, 42, 24, 33, 31 },
|
||||
{ 28, 25, 45, 26, 35, 33 },
|
||||
{ 32, 28, 51, 30, 40, 38 },
|
||||
{ 36, 32, 58, 34, 46, 43 },
|
||||
}
|
||||
|
||||
local function norm4(m: number, i: number, j: number): number
|
||||
local v = V4[m + 1]
|
||||
if i % 2 == 0 and j % 2 == 0 then
|
||||
return v[1]
|
||||
elseif i % 2 == 1 and j % 2 == 1 then
|
||||
return v[2]
|
||||
end
|
||||
return v[3]
|
||||
end
|
||||
|
||||
local function norm8(m: number, i: number, j: number): number
|
||||
local v = V8[m + 1]
|
||||
if i % 4 == 0 and j % 4 == 0 then
|
||||
return v[1]
|
||||
elseif i % 2 == 1 and j % 2 == 1 then
|
||||
return v[2]
|
||||
elseif i % 4 == 2 and j % 4 == 2 then
|
||||
return v[3]
|
||||
elseif (i % 4 == 0 and j % 2 == 1) or (i % 2 == 1 and j % 4 == 0) then
|
||||
return v[4]
|
||||
elseif (i % 4 == 0 and j % 4 == 2) or (i % 4 == 2 and j % 4 == 0) then
|
||||
return v[5]
|
||||
end
|
||||
return v[6]
|
||||
end
|
||||
|
||||
-- dequant tables: dq.d4[list][qp + 1] = 16 multipliers (raster), list 1..6 = Y/Cb/Cr intra, Y/Cb/Cr inter;
|
||||
-- dq.d8[list][qp + 1] = 64 multipliers, list 1 = Y intra, 2 = Y inter. A 4x4 coefficient c dequantises to
|
||||
-- (c * m + 8) >> 4, an 8x8 one to (c * m + 32) >> 6 (8.5.12.1 / 8.5.13.1 with LevelScale * 2^(qP / 6)).
|
||||
local function build(lists: { { number } }): any
|
||||
local d4, d8 = {}, {}
|
||||
for l = 1, 6 do
|
||||
local w = lists[l]
|
||||
local per = {}
|
||||
for qp = 0, 51 do
|
||||
local m, sh = qp % 6, 2 ^ (qp // 6)
|
||||
local t = table.create(16, 0)
|
||||
for k = 0, 15 do
|
||||
local i, j = k % 4, k // 4
|
||||
t[k + 1] = w[k + 1] * norm4(m, i, j) * sh
|
||||
end
|
||||
per[qp + 1] = t
|
||||
end
|
||||
d4[l] = per
|
||||
end
|
||||
for l = 1, 2 do
|
||||
local w = lists[6 + l]
|
||||
local per = {}
|
||||
for qp = 0, 51 do
|
||||
local m, sh = qp % 6, 2 ^ (qp // 6)
|
||||
local t = table.create(64, 0)
|
||||
for k = 0, 63 do
|
||||
local i, j = k % 8, k // 8
|
||||
t[k + 1] = w[k + 1] * norm8(m, i, j) * sh
|
||||
end
|
||||
per[qp + 1] = t
|
||||
end
|
||||
d8[l] = per
|
||||
end
|
||||
return { d4 = d4, d8 = d8 }
|
||||
end
|
||||
|
||||
-- dequant(sps, pps, cache) -> the dequant tables for this pair (cache: a table kept by the decoder, by content)
|
||||
function Params.dequant(sps: any, pps: any, cache: { [string]: any }): any
|
||||
local lists: { { number } }
|
||||
if pps.scalingLists then
|
||||
lists = resolve(pps.scalingLists, sps.scaling)
|
||||
elseif sps.scaling then
|
||||
lists = sps.scaling
|
||||
else
|
||||
lists = {}
|
||||
for i = 1, 12 do
|
||||
lists[i] = if i <= 6 then FLAT16 else FLAT64
|
||||
end
|
||||
end
|
||||
local parts = {}
|
||||
for i = 1, 8 do
|
||||
parts[i] = table.concat(lists[i], ",")
|
||||
end
|
||||
local key = table.concat(parts, ";")
|
||||
local dq = cache[key]
|
||||
if not dq then
|
||||
dq = build(lists)
|
||||
cache[key] = dq
|
||||
end
|
||||
return dq
|
||||
end
|
||||
|
||||
return Params
|
||||
@@ -0,0 +1,251 @@
|
||||
--!strict
|
||||
--!native
|
||||
-- codecs/H264/Slice: the slice header (ITU-T H.264 7.3.3): ref_pic_list_modification, pred_weight_table and
|
||||
-- dec_ref_pic_marking. Written from the spec. Frame coding only: field pictures (field_pic_flag = 1), MBAFF,
|
||||
-- SP / SI slices, separate colour planes and redundant pictures return "unsupported: ...".
|
||||
-- Never throws: header() returns nil, "message".
|
||||
local Bitstream = require("@formats/codecs/H264/Bitstream")
|
||||
|
||||
local u, u1, ue, se = Bitstream.u, Bitstream.u1, Bitstream.ue, Bitstream.se
|
||||
|
||||
local Slice = {}
|
||||
|
||||
Slice.P, Slice.B, Slice.I, Slice.SP, Slice.SI = 0, 1, 2, 3, 4
|
||||
|
||||
local function modifications(r: Bitstream.Reader): { number }?
|
||||
local ops = {}
|
||||
if u1(r) == 1 then
|
||||
for _ = 1, 100 do
|
||||
local idc = ue(r)
|
||||
if idc == 3 then
|
||||
return ops
|
||||
end
|
||||
if idc > 5 then
|
||||
return nil
|
||||
end
|
||||
table.insert(ops, idc)
|
||||
table.insert(ops, ue(r))
|
||||
if r.pos > r.size then
|
||||
return nil
|
||||
end
|
||||
end
|
||||
return nil
|
||||
end
|
||||
return ops
|
||||
end
|
||||
|
||||
local function weights(r: Bitstream.Reader, n: number, lw: number, cw: number, chroma: boolean): { number }?
|
||||
-- per entry: lumaW, lumaO, cbW, cbO, crW, crO, lumaFlag, chromaFlag (8 numbers)
|
||||
local t = table.create(n * 8, 0)
|
||||
for i = 0, n - 1 do
|
||||
local b = i * 8
|
||||
t[b + 1], t[b + 2], t[b + 3], t[b + 4], t[b + 5], t[b + 6] = lw, 0, cw, 0, cw, 0
|
||||
if u1(r) == 1 then
|
||||
t[b + 1] = se(r)
|
||||
t[b + 2] = se(r)
|
||||
t[b + 7] = 1
|
||||
if t[b + 1] < -128 or t[b + 1] > 127 or t[b + 2] < -128 or t[b + 2] > 127 then
|
||||
return nil
|
||||
end
|
||||
end
|
||||
if chroma and u1(r) == 1 then
|
||||
for k = 0, 1 do
|
||||
t[b + 3 + k * 2] = se(r)
|
||||
t[b + 4 + k * 2] = se(r)
|
||||
if t[b + 3 + k * 2] < -128 or t[b + 3 + k * 2] > 127 or t[b + 4 + k * 2] < -128 or t[b + 4 + k * 2] > 127 then
|
||||
return nil
|
||||
end
|
||||
end
|
||||
t[b + 8] = 1
|
||||
end
|
||||
end
|
||||
return t
|
||||
end
|
||||
|
||||
-- header(r, nalType, nalRefIdc, spsTable, ppsTable) -> sh | nil, message
|
||||
function Slice.header(r: Bitstream.Reader, nalType: number, nalRefIdc: number, spsTable: { [number]: any }, ppsTable: { [number]: any }): (any, string?)
|
||||
local sh: any = {}
|
||||
sh.nalType = nalType
|
||||
sh.nalRefIdc = nalRefIdc
|
||||
sh.idr = nalType == 5
|
||||
sh.firstMb = ue(r)
|
||||
local st = ue(r)
|
||||
if st > 9 then
|
||||
return nil, "slice_type out of range"
|
||||
end
|
||||
sh.type = st % 5
|
||||
if sh.type == Slice.SP or sh.type == Slice.SI then
|
||||
return nil, "unsupported: SP / SI slices (Extended profile)"
|
||||
end
|
||||
sh.ppsId = ue(r)
|
||||
local pps = ppsTable[sh.ppsId]
|
||||
if not pps then
|
||||
return nil, "slice refers to a missing pps"
|
||||
end
|
||||
local sps = spsTable[pps.spsId]
|
||||
if not sps then
|
||||
return nil, "slice refers to a missing sps"
|
||||
end
|
||||
sh.pps, sh.sps = pps, sps
|
||||
if sps.separatePlanes then
|
||||
return nil, "unsupported: separate colour planes"
|
||||
end
|
||||
sh.frameNum = u(r, sps.log2MaxFrameNum)
|
||||
if not sps.frameMbsOnly then
|
||||
if u1(r) == 1 then
|
||||
return nil, "unsupported: field pictures (PAFF)"
|
||||
end
|
||||
if sps.mbaff then
|
||||
return nil, "unsupported: MBAFF"
|
||||
end
|
||||
end
|
||||
if sh.idr then
|
||||
sh.idrPicId = ue(r)
|
||||
end
|
||||
sh.pocLsb, sh.deltaPocBottom, sh.deltaPoc0, sh.deltaPoc1 = 0, 0, 0, 0
|
||||
if sps.pocType == 0 then
|
||||
sh.pocLsb = u(r, sps.log2MaxPocLsb)
|
||||
if pps.bottomFieldPocPresent then
|
||||
sh.deltaPocBottom = se(r)
|
||||
end
|
||||
elseif sps.pocType == 1 and not sps.deltaPocAlwaysZero then
|
||||
sh.deltaPoc0 = se(r)
|
||||
if pps.bottomFieldPocPresent then
|
||||
sh.deltaPoc1 = se(r)
|
||||
end
|
||||
end
|
||||
if pps.redundantPicCnt then
|
||||
sh.redundantPicCnt = ue(r)
|
||||
end
|
||||
sh.numRefIdxL0, sh.numRefIdxL1 = 0, 0
|
||||
if sh.type == Slice.B then
|
||||
sh.directSpatial = u1(r) == 1
|
||||
end
|
||||
if sh.type ~= Slice.I then
|
||||
sh.numRefIdxL0 = pps.numRefIdxL0
|
||||
sh.numRefIdxL1 = if sh.type == Slice.B then pps.numRefIdxL1 else 0
|
||||
if u1(r) == 1 then
|
||||
sh.numRefIdxL0 = ue(r) + 1
|
||||
if sh.type == Slice.B then
|
||||
sh.numRefIdxL1 = ue(r) + 1
|
||||
end
|
||||
end
|
||||
if sh.numRefIdxL0 > 32 or sh.numRefIdxL1 > 32 then
|
||||
return nil, "num_ref_idx_active out of range"
|
||||
end
|
||||
local m = modifications(r)
|
||||
if not m then
|
||||
return nil, "bad ref_pic_list_modification"
|
||||
end
|
||||
sh.mod0 = m
|
||||
if sh.type == Slice.B then
|
||||
m = modifications(r)
|
||||
if not m then
|
||||
return nil, "bad ref_pic_list_modification"
|
||||
end
|
||||
sh.mod1 = m
|
||||
end
|
||||
end
|
||||
sh.weightMode = 0 -- 0 default, 1 explicit, 2 implicit
|
||||
if (pps.weightedPred and sh.type == Slice.P) or (pps.weightedBipred == 1 and sh.type == Slice.B) then
|
||||
sh.weightMode = 1
|
||||
sh.lumaDenom = ue(r)
|
||||
if sh.lumaDenom > 7 then
|
||||
return nil, "luma_log2_weight_denom out of range"
|
||||
end
|
||||
local chroma = sps.chromaFormat ~= 0
|
||||
sh.chromaDenom = 0
|
||||
if chroma then
|
||||
sh.chromaDenom = ue(r)
|
||||
if sh.chromaDenom > 7 then
|
||||
return nil, "chroma_log2_weight_denom out of range"
|
||||
end
|
||||
end
|
||||
local w = weights(r, sh.numRefIdxL0, 2 ^ sh.lumaDenom, 2 ^ sh.chromaDenom, chroma)
|
||||
if not w then
|
||||
return nil, "bad pred_weight_table"
|
||||
end
|
||||
sh.weights0 = w
|
||||
if sh.type == Slice.B then
|
||||
w = weights(r, sh.numRefIdxL1, 2 ^ sh.lumaDenom, 2 ^ sh.chromaDenom, chroma)
|
||||
if not w then
|
||||
return nil, "bad pred_weight_table"
|
||||
end
|
||||
sh.weights1 = w
|
||||
end
|
||||
elseif pps.weightedBipred == 2 and sh.type == Slice.B then
|
||||
sh.weightMode = 2
|
||||
end
|
||||
if nalRefIdc ~= 0 then
|
||||
if sh.idr then
|
||||
sh.noOutputOfPriorPics = u1(r) == 1
|
||||
sh.longTermReference = u1(r) == 1
|
||||
else
|
||||
sh.adaptive = u1(r) == 1
|
||||
if sh.adaptive then
|
||||
local ops = {}
|
||||
for _ = 1, 100 do
|
||||
local op = ue(r)
|
||||
if op == 0 then
|
||||
break
|
||||
end
|
||||
if op > 6 then
|
||||
return nil, "bad memory_management_control_operation"
|
||||
end
|
||||
local a, b = 0, 0
|
||||
if op == 1 or op == 3 then
|
||||
a = ue(r) + 1 -- difference_of_pic_nums
|
||||
end
|
||||
if op == 2 then
|
||||
a = ue(r) -- long_term_pic_num
|
||||
end
|
||||
if op == 3 or op == 6 then
|
||||
b = ue(r) -- long_term_frame_idx
|
||||
end
|
||||
if op == 4 then
|
||||
a = ue(r) -- max_long_term_frame_idx_plus1
|
||||
end
|
||||
if r.pos > r.size then
|
||||
return nil, "truncated: dec_ref_pic_marking"
|
||||
end
|
||||
table.insert(ops, op)
|
||||
table.insert(ops, a)
|
||||
table.insert(ops, b)
|
||||
end
|
||||
sh.mmco = ops
|
||||
end
|
||||
end
|
||||
end
|
||||
sh.cabacInit = 0
|
||||
if pps.cabac and sh.type ~= Slice.I then
|
||||
sh.cabacInit = ue(r)
|
||||
if sh.cabacInit > 2 then
|
||||
return nil, "cabac_init_idc out of range"
|
||||
end
|
||||
end
|
||||
sh.qp = pps.initQp + se(r)
|
||||
if sh.qp < 0 or sh.qp > 51 then
|
||||
return nil, "slice QP out of range"
|
||||
end
|
||||
sh.deblock = 0
|
||||
sh.alphaOffset, sh.betaOffset = 0, 0
|
||||
if pps.deblockingControl then
|
||||
sh.deblock = ue(r)
|
||||
if sh.deblock > 2 then
|
||||
return nil, "disable_deblocking_filter_idc out of range"
|
||||
end
|
||||
if sh.deblock ~= 1 then
|
||||
sh.alphaOffset = se(r) * 2
|
||||
sh.betaOffset = se(r) * 2
|
||||
if sh.alphaOffset < -12 or sh.alphaOffset > 12 or sh.betaOffset < -12 or sh.betaOffset > 12 then
|
||||
return nil, "slice_alpha / beta_offset out of range"
|
||||
end
|
||||
end
|
||||
end
|
||||
if r.pos > r.size then
|
||||
return nil, "truncated: slice header"
|
||||
end
|
||||
return sh, nil
|
||||
end
|
||||
|
||||
return Slice
|
||||
@@ -0,0 +1,42 @@
|
||||
--!strict
|
||||
--!native
|
||||
-- codecs/H264/Tables: the constant tables of ITU-T H.264 (CAVLC code tables 9-5, 9-7, 9-8, 9-9, 9-10; CABAC context
|
||||
-- initialisation tables 9-12..9-24, rangeTabLPS 9-44 and the state transitions 9-45; the chroma QP table 8-15; the
|
||||
-- me(v) coded_block_pattern mapping 9-4; default scaling lists 7-3 / 7-4; zig-zag scans 8-12 / 8-13; table 9-43; the
|
||||
-- deblocking alpha / beta / tC0 tables 8-16 / 8-17). Values extracted from openh264 2.x (BSD-2-Clause,
|
||||
-- licenses/openh264-LICENSE.txt): encoder_data_tables.cpp, common_tables.cpp, decoder_data_tables.cpp,
|
||||
-- wels_common_basis.h, deblocking.cpp. Flat 1-based arrays; the layouts are noted at each table.
|
||||
local T = {}
|
||||
|
||||
-- coeff_token per nC class (0: 0<=nC<2, 1: 2<=nC<4, 2: 4<=nC<8, 3: 8<=nC, 4: nC=-1 chroma DC): { code, len, TotalCoeff,
|
||||
-- TrailingOnes } quads. TOTAL_ZEROS / TOTAL_ZEROS_CDC / RUN_BEFORE: { tzVlcIndex | zerosLeft, code, len, value } quads.
|
||||
-- CABAC_INIT: [ctxIdx * 8 + model * 2 + 1] = m, [... + 2] = n; model 0 = I slices, 1..3 = cabac_init_idc 0..2.
|
||||
-- RANGE_LPS: [pStateIdx * 4 + qCodIRangeIdx + 1]. TRANS: [pStateIdx * 2 + 1] = transIdxLPS, [+ 2] = transIdxMPS.
|
||||
-- DEFAULT_4x4 / DEFAULT_8x8: intra list then inter list, raster order. ZIGZAG4 / ZIGZAG8: scan index -> raster index.
|
||||
-- SIG8 / LAST8: 8x8 significant / last ctxIdxInc by scan index (frame coded). ALPHA / BETA: [indexA + 13] (index
|
||||
-- -12..63); TC0: [(indexA + 12) * 4 + bS + 1] (bS 0..3; bS 0 is unused).
|
||||
T.COEFF_TOKEN_0 = { 1, 1, 0, 0, 5, 6, 1, 0, 1, 2, 1, 1, 7, 8, 2, 0, 4, 6, 2, 1, 1, 3, 2, 2, 7, 9, 3, 0, 6, 8, 3, 1, 5, 7, 3, 2, 3, 5, 3, 3, 7, 10, 4, 0, 6, 9, 4, 1, 5, 8, 4, 2, 3, 6, 4, 3, 7, 11, 5, 0, 6, 10, 5, 1, 5, 9, 5, 2, 4, 7, 5, 3, 15, 13, 6, 0, 6, 11, 6, 1, 5, 10, 6, 2, 4, 8, 6, 3, 11, 13, 7, 0, 14, 13, 7, 1, 5, 11, 7, 2, 4, 9, 7, 3, 8, 13, 8, 0, 10, 13, 8, 1, 13, 13, 8, 2, 4, 10, 8, 3, 15, 14, 9, 0, 14, 14, 9, 1, 9, 13, 9, 2, 4, 11, 9, 3, 11, 14, 10, 0, 10, 14, 10, 1, 13, 14, 10, 2, 12, 13, 10, 3, 15, 15, 11, 0, 14, 15, 11, 1, 9, 14, 11, 2, 12, 14, 11, 3, 11, 15, 12, 0, 10, 15, 12, 1, 13, 15, 12, 2, 8, 14, 12, 3, 15, 16, 13, 0, 1, 15, 13, 1, 9, 15, 13, 2, 12, 15, 13, 3, 11, 16, 14, 0, 14, 16, 14, 1, 13, 16, 14, 2, 8, 15, 14, 3, 7, 16, 15, 0, 10, 16, 15, 1, 9, 16, 15, 2, 12, 16, 15, 3, 4, 16, 16, 0, 6, 16, 16, 1, 5, 16, 16, 2, 8, 16, 16, 3 }
|
||||
T.COEFF_TOKEN_1 = { 3, 2, 0, 0, 11, 6, 1, 0, 2, 2, 1, 1, 7, 6, 2, 0, 7, 5, 2, 1, 3, 3, 2, 2, 7, 7, 3, 0, 10, 6, 3, 1, 9, 6, 3, 2, 5, 4, 3, 3, 7, 8, 4, 0, 6, 6, 4, 1, 5, 6, 4, 2, 4, 4, 4, 3, 4, 8, 5, 0, 6, 7, 5, 1, 5, 7, 5, 2, 6, 5, 5, 3, 7, 9, 6, 0, 6, 8, 6, 1, 5, 8, 6, 2, 8, 6, 6, 3, 15, 11, 7, 0, 6, 9, 7, 1, 5, 9, 7, 2, 4, 6, 7, 3, 11, 11, 8, 0, 14, 11, 8, 1, 13, 11, 8, 2, 4, 7, 8, 3, 15, 12, 9, 0, 10, 11, 9, 1, 9, 11, 9, 2, 4, 9, 9, 3, 11, 12, 10, 0, 14, 12, 10, 1, 13, 12, 10, 2, 12, 11, 10, 3, 8, 12, 11, 0, 10, 12, 11, 1, 9, 12, 11, 2, 8, 11, 11, 3, 15, 13, 12, 0, 14, 13, 12, 1, 13, 13, 12, 2, 12, 12, 12, 3, 11, 13, 13, 0, 10, 13, 13, 1, 9, 13, 13, 2, 12, 13, 13, 3, 7, 13, 14, 0, 11, 14, 14, 1, 6, 13, 14, 2, 8, 13, 14, 3, 9, 14, 15, 0, 8, 14, 15, 1, 10, 14, 15, 2, 1, 13, 15, 3, 7, 14, 16, 0, 6, 14, 16, 1, 5, 14, 16, 2, 4, 14, 16, 3 }
|
||||
T.COEFF_TOKEN_2 = { 15, 4, 0, 0, 15, 6, 1, 0, 14, 4, 1, 1, 11, 6, 2, 0, 15, 5, 2, 1, 13, 4, 2, 2, 8, 6, 3, 0, 12, 5, 3, 1, 14, 5, 3, 2, 12, 4, 3, 3, 15, 7, 4, 0, 10, 5, 4, 1, 11, 5, 4, 2, 11, 4, 4, 3, 11, 7, 5, 0, 8, 5, 5, 1, 9, 5, 5, 2, 10, 4, 5, 3, 9, 7, 6, 0, 14, 6, 6, 1, 13, 6, 6, 2, 9, 4, 6, 3, 8, 7, 7, 0, 10, 6, 7, 1, 9, 6, 7, 2, 8, 4, 7, 3, 15, 8, 8, 0, 14, 7, 8, 1, 13, 7, 8, 2, 13, 5, 8, 3, 11, 8, 9, 0, 14, 8, 9, 1, 10, 7, 9, 2, 12, 6, 9, 3, 15, 9, 10, 0, 10, 8, 10, 1, 13, 8, 10, 2, 12, 7, 10, 3, 11, 9, 11, 0, 14, 9, 11, 1, 9, 8, 11, 2, 12, 8, 11, 3, 8, 9, 12, 0, 10, 9, 12, 1, 13, 9, 12, 2, 8, 8, 12, 3, 13, 10, 13, 0, 7, 9, 13, 1, 9, 9, 13, 2, 12, 9, 13, 3, 9, 10, 14, 0, 12, 10, 14, 1, 11, 10, 14, 2, 10, 10, 14, 3, 5, 10, 15, 0, 8, 10, 15, 1, 7, 10, 15, 2, 6, 10, 15, 3, 1, 10, 16, 0, 4, 10, 16, 1, 3, 10, 16, 2, 2, 10, 16, 3 }
|
||||
T.COEFF_TOKEN_3 = { 3, 6, 0, 0, 0, 6, 1, 0, 1, 6, 1, 1, 4, 6, 2, 0, 5, 6, 2, 1, 6, 6, 2, 2, 8, 6, 3, 0, 9, 6, 3, 1, 10, 6, 3, 2, 11, 6, 3, 3, 12, 6, 4, 0, 13, 6, 4, 1, 14, 6, 4, 2, 15, 6, 4, 3, 16, 6, 5, 0, 17, 6, 5, 1, 18, 6, 5, 2, 19, 6, 5, 3, 20, 6, 6, 0, 21, 6, 6, 1, 22, 6, 6, 2, 23, 6, 6, 3, 24, 6, 7, 0, 25, 6, 7, 1, 26, 6, 7, 2, 27, 6, 7, 3, 28, 6, 8, 0, 29, 6, 8, 1, 30, 6, 8, 2, 31, 6, 8, 3, 32, 6, 9, 0, 33, 6, 9, 1, 34, 6, 9, 2, 35, 6, 9, 3, 36, 6, 10, 0, 37, 6, 10, 1, 38, 6, 10, 2, 39, 6, 10, 3, 40, 6, 11, 0, 41, 6, 11, 1, 42, 6, 11, 2, 43, 6, 11, 3, 44, 6, 12, 0, 45, 6, 12, 1, 46, 6, 12, 2, 47, 6, 12, 3, 48, 6, 13, 0, 49, 6, 13, 1, 50, 6, 13, 2, 51, 6, 13, 3, 52, 6, 14, 0, 53, 6, 14, 1, 54, 6, 14, 2, 55, 6, 14, 3, 56, 6, 15, 0, 57, 6, 15, 1, 58, 6, 15, 2, 59, 6, 15, 3, 60, 6, 16, 0, 61, 6, 16, 1, 62, 6, 16, 2, 63, 6, 16, 3 }
|
||||
T.COEFF_TOKEN_4 = { 1, 2, 0, 0, 7, 6, 1, 0, 1, 1, 1, 1, 4, 6, 2, 0, 6, 6, 2, 1, 1, 3, 2, 2, 3, 6, 3, 0, 3, 7, 3, 1, 2, 7, 3, 2, 5, 6, 3, 3, 2, 6, 4, 0, 3, 8, 4, 1, 2, 8, 4, 2, 0, 7, 4, 3 }
|
||||
T.TOTAL_ZEROS = { 1, 1, 1, 0, 1, 3, 3, 1, 1, 2, 3, 2, 1, 3, 4, 3, 1, 2, 4, 4, 1, 3, 5, 5, 1, 2, 5, 6, 1, 3, 6, 7, 1, 2, 6, 8, 1, 3, 7, 9, 1, 2, 7, 10, 1, 3, 8, 11, 1, 2, 8, 12, 1, 3, 9, 13, 1, 2, 9, 14, 1, 1, 9, 15, 2, 7, 3, 0, 2, 6, 3, 1, 2, 5, 3, 2, 2, 4, 3, 3, 2, 3, 3, 4, 2, 5, 4, 5, 2, 4, 4, 6, 2, 3, 4, 7, 2, 2, 4, 8, 2, 3, 5, 9, 2, 2, 5, 10, 2, 3, 6, 11, 2, 2, 6, 12, 2, 1, 6, 13, 2, 0, 6, 14, 3, 5, 4, 0, 3, 7, 3, 1, 3, 6, 3, 2, 3, 5, 3, 3, 3, 4, 4, 4, 3, 3, 4, 5, 3, 4, 3, 6, 3, 3, 3, 7, 3, 2, 4, 8, 3, 3, 5, 9, 3, 2, 5, 10, 3, 1, 6, 11, 3, 1, 5, 12, 3, 0, 6, 13, 4, 3, 5, 0, 4, 7, 3, 1, 4, 5, 4, 2, 4, 4, 4, 3, 4, 6, 3, 4, 4, 5, 3, 5, 4, 4, 3, 6, 4, 3, 4, 7, 4, 3, 3, 8, 4, 2, 4, 9, 4, 2, 5, 10, 4, 1, 5, 11, 4, 0, 5, 12, 5, 5, 4, 0, 5, 4, 4, 1, 5, 3, 4, 2, 5, 7, 3, 3, 5, 6, 3, 4, 5, 5, 3, 5, 5, 4, 3, 6, 5, 3, 3, 7, 5, 2, 4, 8, 5, 1, 5, 9, 5, 1, 4, 10, 5, 0, 5, 11, 6, 1, 6, 0, 6, 1, 5, 1, 6, 7, 3, 2, 6, 6, 3, 3, 6, 5, 3, 4, 6, 4, 3, 5, 6, 3, 3, 6, 6, 2, 3, 7, 6, 1, 4, 8, 6, 1, 3, 9, 6, 0, 6, 10, 7, 1, 6, 0, 7, 1, 5, 1, 7, 5, 3, 2, 7, 4, 3, 3, 7, 3, 3, 4, 7, 3, 2, 5, 7, 2, 3, 6, 7, 1, 4, 7, 7, 1, 3, 8, 7, 0, 6, 9, 8, 1, 6, 0, 8, 1, 4, 1, 8, 1, 5, 2, 8, 3, 3, 3, 8, 3, 2, 4, 8, 2, 2, 5, 8, 2, 3, 6, 8, 1, 3, 7, 8, 0, 6, 8, 9, 1, 6, 0, 9, 0, 6, 1, 9, 1, 4, 2, 9, 3, 2, 3, 9, 2, 2, 4, 9, 1, 3, 5, 9, 1, 2, 6, 9, 1, 5, 7, 10, 1, 5, 0, 10, 0, 5, 1, 10, 1, 3, 2, 10, 3, 2, 3, 10, 2, 2, 4, 10, 1, 2, 5, 10, 1, 4, 6, 11, 0, 4, 0, 11, 1, 4, 1, 11, 1, 3, 2, 11, 2, 3, 3, 11, 1, 1, 4, 11, 3, 3, 5, 12, 0, 4, 0, 12, 1, 4, 1, 12, 1, 2, 2, 12, 1, 1, 3, 12, 1, 3, 4, 13, 0, 3, 0, 13, 1, 3, 1, 13, 1, 1, 2, 13, 1, 2, 3, 14, 0, 2, 0, 14, 1, 2, 1, 14, 1, 1, 2, 15, 0, 1, 0, 15, 1, 1, 1 }
|
||||
T.TOTAL_ZEROS_CDC = { 1, 1, 1, 0, 1, 1, 2, 1, 1, 1, 3, 2, 1, 0, 3, 3, 2, 1, 1, 0, 2, 1, 2, 1, 2, 0, 2, 2, 3, 1, 1, 0, 3, 0, 1, 1 }
|
||||
T.RUN_BEFORE = { 1, 1, 1, 0, 1, 0, 1, 1, 2, 1, 1, 0, 2, 1, 2, 1, 2, 0, 2, 2, 3, 3, 2, 0, 3, 2, 2, 1, 3, 1, 2, 2, 3, 0, 2, 3, 4, 3, 2, 0, 4, 2, 2, 1, 4, 1, 2, 2, 4, 1, 3, 3, 4, 0, 3, 4, 5, 3, 2, 0, 5, 2, 2, 1, 5, 3, 3, 2, 5, 2, 3, 3, 5, 1, 3, 4, 5, 0, 3, 5, 6, 3, 2, 0, 6, 0, 3, 1, 6, 1, 3, 2, 6, 3, 3, 3, 6, 2, 3, 4, 6, 5, 3, 5, 6, 4, 3, 6, 7, 7, 3, 0, 7, 6, 3, 1, 7, 5, 3, 2, 7, 4, 3, 3, 7, 3, 3, 4, 7, 2, 3, 5, 7, 1, 3, 6, 7, 1, 4, 7, 7, 1, 5, 8, 7, 1, 6, 9, 7, 1, 7, 10, 7, 1, 8, 11, 7, 1, 9, 12, 7, 1, 10, 13, 7, 1, 11, 14 }
|
||||
T.CABAC_INIT = { 20, -15, 20, -15, 20, -15, 20, -15, 2, 54, 2, 54, 2, 54, 2, 54, 3, 74, 3, 74, 3, 74, 3, 74, 20, -15, 20, -15, 20, -15, 20, -15, 2, 54, 2, 54, 2, 54, 2, 54, 3, 74, 3, 74, 3, 74, 3, 74, -28, 127, -28, 127, -28, 127, -28, 127, -23, 104, -23, 104, -23, 104, -23, 104, -6, 53, -6, 53, -6, 53, -6, 53, -1, 54, -1, 54, -1, 54, -1, 54, 7, 51, 7, 51, 7, 51, 7, 51, 0, 0, 23, 33, 22, 25, 29, 16, 0, 0, 23, 2, 34, 0, 25, 0, 0, 0, 21, 0, 16, 0, 14, 0, 0, 0, 1, 9, -2, 9, -10, 51, 0, 0, 0, 49, 4, 41, -3, 62, 0, 0, -37, 118, -29, 118, -27, 99, 0, 0, 5, 57, 2, 65, 26, 16, 0, 0, -13, 78, -6, 71, -4, 85, 0, 0, -11, 65, -13, 79, -24, 102, 0, 0, 1, 62, 5, 52, 5, 57, 0, 0, 12, 49, 9, 50, 6, 57, 0, 0, -4, 73, -3, 70, -17, 73, 0, 0, 17, 50, 10, 54, 14, 57, 0, 0, 18, 64, 26, 34, 20, 40, 0, 0, 9, 43, 19, 22, 20, 10, 0, 0, 29, 0, 40, 0, 29, 0, 0, 0, 26, 67, 57, 2, 54, 0, 0, 0, 16, 90, 41, 36, 37, 42, 0, 0, 9, 104, 26, 69, 12, 97, 0, 0, -46, 127, -45, 127, -32, 127, 0, 0, -20, 104, -15, 101, -22, 117, 0, 0, 1, 67, -4, 76, -2, 74, 0, 0, -13, 78, -6, 71, -4, 85, 0, 0, -11, 65, -13, 79, -24, 102, 0, 0, 1, 62, 5, 52, 5, 57, 0, 0, -6, 86, 6, 69, -6, 93, 0, 0, -17, 95, -13, 90, -14, 88, 0, 0, -6, 61, 0, 52, -6, 44, 0, 0, 9, 45, 8, 43, 4, 55, 0, 0, -3, 69, -2, 69, -11, 89, 0, 0, -6, 81, -5, 82, -15, 103, 0, 0, -11, 96, -10, 96, -21, 116, 0, 0, 6, 55, 2, 59, 19, 57, 0, 0, 7, 67, 2, 75, 20, 58, 0, 0, -5, 86, -3, 87, 4, 84, 0, 0, 2, 88, -3, 100, 6, 96, 0, 0, 0, 58, 1, 56, 1, 63, 0, 0, -3, 76, -3, 74, -5, 85, 0, 0, -10, 94, -6, 85, -13, 106, 0, 0, 5, 54, 0, 59, 5, 63, 0, 0, 4, 69, -3, 81, 6, 75, 0, 0, -3, 81, -7, 86, -3, 90, 0, 0, 0, 88, -5, 95, -1, 101, 0, 0, -7, 67, -1, 66, 3, 55, 0, 0, -5, 74, -1, 77, -4, 79, 0, 0, -4, 74, 1, 70, -2, 75, 0, 0, -5, 80, -2, 86, -12, 97, 0, 0, -7, 72, -5, 72, -7, 50, 0, 0, 1, 58, 0, 61, 1, 60, 0, 41, 0, 41, 0, 41, 0, 41, 0, 63, 0, 63, 0, 63, 0, 63, 0, 63, 0, 63, 0, 63, 0, 63, 0, 63, 0, 63, 0, 63, 0, 63, -9, 83, -9, 83, -9, 83, -9, 83, 4, 86, 4, 86, 4, 86, 4, 86, 0, 97, 0, 97, 0, 97, 0, 97, -7, 72, -7, 72, -7, 72, -7, 72, 13, 41, 13, 41, 13, 41, 13, 41, 3, 62, 3, 62, 3, 62, 3, 62, 0, 11, 0, 45, 13, 15, 7, 34, 1, 55, -4, 78, 7, 51, -9, 88, 0, 69, -3, 96, 2, 80, -20, 127, -17, 127, -27, 126, -39, 127, -36, 127, -13, 102, -28, 98, -18, 91, -17, 91, 0, 82, -25, 101, -17, 96, -14, 95, -7, 74, -23, 67, -26, 81, -25, 84, -21, 107, -28, 82, -35, 98, -25, 86, -27, 127, -20, 94, -24, 102, -12, 89, -31, 127, -16, 83, -23, 97, -17, 91, -24, 127, -22, 110, -27, 119, -31, 127, -18, 95, -21, 91, -24, 99, -14, 76, -27, 127, -18, 102, -21, 110, -18, 103, -21, 114, -13, 93, -18, 102, -13, 90, -30, 127, -29, 127, -36, 127, -37, 127, -17, 123, -7, 92, 0, 80, 11, 80, -12, 115, -5, 89, -5, 89, 5, 76, -16, 122, -7, 96, -7, 94, 2, 84, -11, 115, -13, 108, -4, 92, 5, 78, -12, 63, -3, 46, 0, 39, -6, 55, -2, 68, -1, 65, 0, 65, 4, 61, -15, 84, -1, 57, -15, 84, -14, 83, -13, 104, -9, 93, -35, 127, -37, 127, -3, 70, -3, 74, -2, 73, -5, 79, -8, 93, -9, 92, -12, 104, -11, 104, -10, 90, -8, 87, -9, 91, -11, 91, -30, 127, -23, 126, -31, 127, -30, 127, -1, 74, 5, 54, 3, 55, 0, 65, -6, 97, 6, 60, 7, 56, -2, 79, -7, 91, 6, 59, 7, 55, 0, 72, -20, 127, 6, 69, 8, 61, -4, 92, -4, 56, -1, 48, -3, 53, -6, 56, -5, 82, 0, 68, 0, 68, 3, 68, -7, 76, -4, 69, -7, 74, -8, 71, -22, 125, -8, 88, -9, 88, -13, 98, -7, 93, -2, 85, -13, 103, -4, 86, -11, 87, -6, 78, -13, 91, -12, 88, -3, 77, -1, 75, -9, 89, -5, 82, -5, 71, -7, 77, -14, 92, -3, 72, -4, 63, 2, 54, -8, 76, -4, 67, -4, 68, 5, 50, -12, 87, -8, 72, -12, 84, -3, 68, -23, 110, -16, 89, -7, 62, 1, 50, -24, 105, -9, 69, -7, 65, 6, 42, -10, 78, -1, 59, 8, 61, -4, 81, -20, 112, 5, 66, 5, 56, 1, 63, -17, 99, 4, 57, -2, 66, -4, 70, -78, 127, -4, 71, 1, 64, 0, 67, -70, 127, -2, 71, 0, 61, 2, 57, -50, 127, 2, 58, -2, 78, -2, 76, -46, 127, -1, 74, 1, 50, 11, 35, -4, 66, -4, 44, 7, 52, 4, 64, -5, 78, -1, 69, 10, 35, 1, 61, -4, 71, 0, 62, 0, 44, 11, 35, -8, 72, -7, 51, 11, 38, 18, 25, 2, 59, -4, 47, 1, 45, 12, 24, -1, 55, -6, 42, 0, 46, 13, 29, -7, 70, -3, 41, 5, 44, 13, 36, -6, 75, -6, 53, 31, 17, -10, 93, -8, 89, 8, 76, 1, 51, -7, 73, -34, 119, -9, 78, 7, 50, -2, 73, -3, 75, -11, 83, 28, 19, 13, 46, 32, 20, 9, 52, 16, 33, 9, 49, 30, 22, 0, 67, 14, 62, -7, 100, -44, 127, -5, 90, -13, 108, 9, 53, 0, 54, 1, 67, -15, 100, 2, 53, -5, 61, -15, 72, -13, 101, 5, 53, 0, 58, -5, 75, -13, 91, -2, 61, -1, 60, -8, 80, -12, 94, 0, 56, -3, 61, -21, 83, -10, 88, 0, 56, -8, 67, -21, 64, -16, 84, -13, 63, -25, 84, -13, 31, -10, 86, -5, 60, -14, 74, -25, 64, -7, 83, -1, 62, -5, 65, -29, 94, -13, 87, 4, 57, 5, 52, 9, 75, -19, 94, -6, 69, 2, 57, 17, 63, 1, 70, 4, 57, 0, 61, -8, 74, 0, 72, 14, 39, -9, 69, -5, 35, -5, 74, 4, 51, -11, 70, -2, 27, 18, 59, 13, 68, 18, 55, 13, 91, -8, 102, 3, 64, -4, 71, 3, 65, -15, 100, 1, 61, 0, 58, -7, 69, 0, 95, 9, 63, 7, 61, 8, 77, -4, 75, 7, 50, 9, 41, -10, 66, 2, 72, 16, 39, 18, 25, 3, 62, -11, 75, 5, 44, 9, 32, -3, 68, -3, 71, 4, 52, 5, 43, -20, 81, 15, 46, 11, 48, 9, 47, 0, 30, -13, 69, -Line truncated
|
||||
T.RANGE_LPS = { 128, 176, 208, 240, 128, 167, 197, 227, 128, 158, 187, 216, 123, 150, 178, 205, 116, 142, 169, 195, 111, 135, 160, 185, 105, 128, 152, 175, 100, 122, 144, 166, 95, 116, 137, 158, 90, 110, 130, 150, 85, 104, 123, 142, 81, 99, 117, 135, 77, 94, 111, 128, 73, 89, 105, 122, 69, 85, 100, 116, 66, 80, 95, 110, 62, 76, 90, 104, 59, 72, 86, 99, 56, 69, 81, 94, 53, 65, 77, 89, 51, 62, 73, 85, 48, 59, 69, 80, 46, 56, 66, 76, 43, 53, 63, 72, 41, 50, 59, 69, 39, 48, 56, 65, 37, 45, 54, 62, 35, 43, 51, 59, 33, 41, 48, 56, 32, 39, 46, 53, 30, 37, 43, 50, 29, 35, 41, 48, 27, 33, 39, 45, 26, 31, 37, 43, 24, 30, 35, 41, 23, 28, 33, 39, 22, 27, 32, 37, 21, 26, 30, 35, 20, 24, 29, 33, 19, 23, 27, 31, 18, 22, 26, 30, 17, 21, 25, 28, 16, 20, 23, 27, 15, 19, 22, 25, 14, 18, 21, 24, 14, 17, 20, 23, 13, 16, 19, 22, 12, 15, 18, 21, 12, 14, 17, 20, 11, 14, 16, 19, 11, 13, 15, 18, 10, 12, 15, 17, 10, 12, 14, 16, 9, 11, 13, 15, 9, 11, 12, 14, 8, 10, 12, 14, 8, 9, 11, 13, 7, 9, 11, 12, 7, 9, 10, 12, 7, 8, 10, 11, 6, 8, 9, 11, 6, 7, 9, 10, 6, 7, 8, 9, 2, 2, 2, 2 }
|
||||
T.TRANS = { 0, 1, 0, 2, 1, 3, 2, 4, 2, 5, 4, 6, 4, 7, 5, 8, 6, 9, 7, 10, 8, 11, 9, 12, 9, 13, 11, 14, 11, 15, 12, 16, 13, 17, 13, 18, 15, 19, 15, 20, 16, 21, 16, 22, 18, 23, 18, 24, 19, 25, 19, 26, 21, 27, 21, 28, 22, 29, 22, 30, 23, 31, 24, 32, 24, 33, 25, 34, 26, 35, 26, 36, 27, 37, 27, 38, 28, 39, 29, 40, 29, 41, 30, 42, 30, 43, 30, 44, 31, 45, 32, 46, 32, 47, 33, 48, 33, 49, 33, 50, 34, 51, 34, 52, 35, 53, 35, 54, 35, 55, 36, 56, 36, 57, 36, 58, 37, 59, 37, 60, 37, 61, 38, 62, 38, 62, 63, 63 }
|
||||
T.CHROMA_QP = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 29, 30, 31, 32, 32, 33, 34, 34, 35, 35, 36, 36, 37, 37, 37, 38, 38, 38, 39, 39, 39, 39 }
|
||||
T.INTRA_CBP = { 47, 31, 15, 0, 23, 27, 29, 30, 7, 11, 13, 14, 39, 43, 45, 46, 16, 3, 5, 10, 12, 19, 21, 26, 28, 35, 37, 42, 44, 1, 2, 4, 8, 17, 18, 20, 24, 6, 9, 22, 25, 32, 33, 34, 36, 40, 38, 41 }
|
||||
T.INTER_CBP = { 0, 16, 1, 2, 4, 8, 32, 3, 5, 10, 12, 15, 47, 7, 11, 13, 14, 6, 9, 31, 35, 37, 42, 44, 33, 34, 36, 40, 39, 43, 45, 46, 17, 18, 20, 24, 19, 21, 26, 28, 23, 27, 29, 30, 22, 25, 38, 41 }
|
||||
T.DEFAULT_4x4 = { 6, 13, 20, 28, 13, 20, 28, 32, 20, 28, 32, 37, 28, 32, 37, 42, 10, 14, 20, 24, 14, 20, 24, 27, 20, 24, 27, 30, 24, 27, 30, 34 }
|
||||
T.DEFAULT_8x8 = { 6, 10, 13, 16, 18, 23, 25, 27, 10, 11, 16, 18, 23, 25, 27, 29, 13, 16, 18, 23, 25, 27, 29, 31, 16, 18, 23, 25, 27, 29, 31, 33, 18, 23, 25, 27, 29, 31, 33, 36, 23, 25, 27, 29, 31, 33, 36, 38, 25, 27, 29, 31, 33, 36, 38, 40, 27, 29, 31, 33, 36, 38, 40, 42, 9, 13, 15, 17, 19, 21, 22, 24, 13, 13, 17, 19, 21, 22, 24, 25, 15, 17, 19, 21, 22, 24, 25, 27, 17, 19, 21, 22, 24, 25, 27, 28, 19, 21, 22, 24, 25, 27, 28, 30, 21, 22, 24, 25, 27, 28, 30, 32, 22, 24, 25, 27, 28, 30, 32, 33, 24, 25, 27, 28, 30, 32, 33, 35 }
|
||||
T.ZIGZAG4 = { 0, 1, 4, 8, 5, 2, 3, 6, 9, 12, 13, 10, 7, 11, 14, 15 }
|
||||
T.ZIGZAG8 = { 0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13, 6, 7, 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51, 58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63 }
|
||||
T.SIG8 = { 0, 1, 2, 3, 4, 5, 5, 4, 4, 3, 3, 4, 4, 4, 5, 5, 4, 4, 4, 4, 3, 3, 6, 7, 7, 7, 8, 9, 10, 9, 8, 7, 7, 6, 11, 12, 13, 11, 6, 7, 8, 9, 14, 10, 9, 8, 6, 11, 12, 13, 11, 6, 9, 14, 10, 9, 11, 12, 13, 11, 14, 10, 12, 14 }
|
||||
T.LAST8 = { 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8 }
|
||||
T.ALPHA = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 5, 6, 7, 8, 9, 10, 12, 13, 15, 17, 20, 22, 25, 28, 32, 36, 40, 45, 50, 56, 63, 71, 80, 90, 101, 113, 127, 144, 162, 182, 203, 226, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 }
|
||||
T.BETA = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15, 16, 16, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18 }
|
||||
T.TC0 = { -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 1, -1, 0, 0, 1, -1, 0, 0, 1, -1, 0, 0, 1, -1, 0, 1, 1, -1, 0, 1, 1, -1, 1, 1, 1, -1, 1, 1, 1, -1, 1, 1, 1, -1, 1, 1, 1, -1, 1, 1, 2, -1, 1, 1, 2, -1, 1, 1, 2, -1, 1, 1, 2, -1, 1, 2, 3, -1, 1, 2, 3, -1, 2, 2, 3, -1, 2, 2, 4, -1, 2, 3, 4, -1, 2, 3, 4, -1, 3, 3, 5, -1, 3, 4, 6, -1, 3, 4, 6, -1, 4, 5, 7, -1, 4, 5, 8, -1, 4, 6, 9, -1, 5, 7, 10, -1, 6, 8, 11, -1, 6, 8, 13, -1, 7, 10, 14, -1, 8, 11, 16, -1, 9, 12, 18, -1, 10, 13, 20, -1, 11, 15, 23, -1, 13, 17, 25, -1, 13, 17, 25, -1, 13, 17, 25, -1, 13, 17, 25, -1, 13, 17, 25, -1, 13, 17, 25, -1, 13, 17, 25, -1, 13, 17, 25, -1, 13, 17, 25, -1, 13, 17, 25, -1, 13, 17, 25, -1, 13, 17, 25, -1, 13, 17, 25 }
|
||||
|
||||
return T
|
||||
@@ -0,0 +1,174 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- codecs/H264/Transform: the inverse transforms of ITU-T H.264 8.5: the 4x4 and 8x8 integer IDCTs with the residual
|
||||
-- added to the prediction in the plane (8.5.12.2 / 8.5.13.2 / 8.5.14), the 4x4 luma DC and 2x2 chroma DC Hadamard
|
||||
-- transforms with their scaling (8.5.10 / 8.5.11.2). Written from the spec. Coefficients are dequantised already
|
||||
-- (Params.dequant), raster order, in a 1-based table at `base + 1 ...`; the functions zero what they read.
|
||||
-- Never throws.
|
||||
local readu8, writeu8 = buffer.readu8, buffer.writeu8
|
||||
|
||||
local Transform = {}
|
||||
|
||||
local min, max = math.min, math.max
|
||||
local function clip(v: number): number
|
||||
return min(max(v, 0), 255)
|
||||
end
|
||||
|
||||
-- add4(c, base, b, o, s): inverse 4x4 transform of c[base + 1 .. base + 16], added to the 4x4 block at b[o] (stride s)
|
||||
function Transform.add4(c: { number }, base: number, b: buffer, o: number, s: number)
|
||||
-- rows
|
||||
for i = 0, 3 do
|
||||
local k = base + i * 4
|
||||
local d0, d1, d2, d3 = c[k + 1], c[k + 2], c[k + 3], c[k + 4]
|
||||
local e = d0 + d2
|
||||
local f = d0 - d2
|
||||
local g = d1 // 2 - d3
|
||||
local h = d1 + d3 // 2
|
||||
c[k + 1] = e + h
|
||||
c[k + 2] = f + g
|
||||
c[k + 3] = f - g
|
||||
c[k + 4] = e - h
|
||||
end
|
||||
-- columns
|
||||
for j = 0, 3 do
|
||||
local k = base + j
|
||||
local d0, d1, d2, d3 = c[k + 1], c[k + 5], c[k + 9], c[k + 13]
|
||||
local e = d0 + d2
|
||||
local f = d0 - d2
|
||||
local g = d1 // 2 - d3
|
||||
local h = d1 + d3 // 2
|
||||
c[k + 1], c[k + 5], c[k + 9], c[k + 13] = 0, 0, 0, 0
|
||||
local p = o + j
|
||||
writeu8(b, p, clip(readu8(b, p) + (e + h + 32) // 64))
|
||||
p += s
|
||||
writeu8(b, p, clip(readu8(b, p) + (f + g + 32) // 64))
|
||||
p += s
|
||||
writeu8(b, p, clip(readu8(b, p) + (f - g + 32) // 64))
|
||||
p += s
|
||||
writeu8(b, p, clip(readu8(b, p) + (e - h + 32) // 64))
|
||||
end
|
||||
end
|
||||
|
||||
-- addDc4(dc, b, o, s): a 4x4 block whose only coefficient is the (dequantised) DC
|
||||
function Transform.addDc4(dc: number, b: buffer, o: number, s: number)
|
||||
local v = (dc + 32) // 64
|
||||
if v == 0 then
|
||||
return
|
||||
end
|
||||
for y = 0, 3 do
|
||||
local p = o + y * s
|
||||
writeu8(b, p, clip(readu8(b, p) + v))
|
||||
writeu8(b, p + 1, clip(readu8(b, p + 1) + v))
|
||||
writeu8(b, p + 2, clip(readu8(b, p + 2) + v))
|
||||
writeu8(b, p + 3, clip(readu8(b, p + 3) + v))
|
||||
end
|
||||
end
|
||||
|
||||
local T8 = table.create(64, 0)
|
||||
|
||||
-- add8(c, base, b, o, s): inverse 8x8 transform of c[base + 1 .. base + 64] added to the 8x8 block at b[o]
|
||||
function Transform.add8(c: { number }, base: number, b: buffer, o: number, s: number)
|
||||
for pass = 0, 1 do
|
||||
for i = 0, 7 do
|
||||
-- pass 0: rows of c into T8; pass 1: columns of T8
|
||||
local d0, d1, d2, d3, d4, d5, d6, d7
|
||||
if pass == 0 then
|
||||
local k = base + i * 8
|
||||
d0, d1, d2, d3, d4, d5, d6, d7 = c[k + 1], c[k + 2], c[k + 3], c[k + 4], c[k + 5], c[k + 6], c[k + 7], c[k + 8]
|
||||
c[k + 1], c[k + 2], c[k + 3], c[k + 4], c[k + 5], c[k + 6], c[k + 7], c[k + 8] = 0, 0, 0, 0, 0, 0, 0, 0
|
||||
else
|
||||
d0, d1, d2, d3, d4, d5, d6, d7 = T8[i + 1], T8[i + 9], T8[i + 17], T8[i + 25], T8[i + 33], T8[i + 41], T8[i + 49], T8[i + 57]
|
||||
end
|
||||
local a0 = d0 + d4
|
||||
local a4 = d0 - d4
|
||||
local a2 = d2 // 2 - d6
|
||||
local a6 = d2 + d6 // 2
|
||||
local b0 = a0 + a6
|
||||
local b2 = a4 + a2
|
||||
local b4 = a4 - a2
|
||||
local b6 = a0 - a6
|
||||
local a1 = -d3 + d5 - d7 - d7 // 2
|
||||
local a3 = d1 + d7 - d3 - d3 // 2
|
||||
local a5 = -d1 + d7 + d5 + d5 // 2
|
||||
local a7 = d3 + d5 + d1 + d1 // 2
|
||||
local b1 = a1 + a7 // 4
|
||||
local b7 = a7 - a1 // 4
|
||||
local b3 = a3 + a5 // 4
|
||||
local b5 = a3 // 4 - a5
|
||||
if pass == 0 then
|
||||
local k = i * 8
|
||||
T8[k + 1] = b0 + b7
|
||||
T8[k + 2] = b2 + b5
|
||||
T8[k + 3] = b4 + b3
|
||||
T8[k + 4] = b6 + b1
|
||||
T8[k + 5] = b6 - b1
|
||||
T8[k + 6] = b4 - b3
|
||||
T8[k + 7] = b2 - b5
|
||||
T8[k + 8] = b0 - b7
|
||||
else
|
||||
local p = o + i
|
||||
writeu8(b, p, clip(readu8(b, p) + (b0 + b7 + 32) // 64))
|
||||
p += s
|
||||
writeu8(b, p, clip(readu8(b, p) + (b2 + b5 + 32) // 64))
|
||||
p += s
|
||||
writeu8(b, p, clip(readu8(b, p) + (b4 + b3 + 32) // 64))
|
||||
p += s
|
||||
writeu8(b, p, clip(readu8(b, p) + (b6 + b1 + 32) // 64))
|
||||
p += s
|
||||
writeu8(b, p, clip(readu8(b, p) + (b6 - b1 + 32) // 64))
|
||||
p += s
|
||||
writeu8(b, p, clip(readu8(b, p) + (b4 - b3 + 32) // 64))
|
||||
p += s
|
||||
writeu8(b, p, clip(readu8(b, p) + (b2 - b5 + 32) // 64))
|
||||
p += s
|
||||
writeu8(b, p, clip(readu8(b, p) + (b0 - b7 + 32) // 64))
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- lumaDc(dc, m, c): the Intra_16x16 DC levels dc[1..16] (raster 4x4 matrix) -> inverse Hadamard, scaled with the
|
||||
-- DC multiplier m (LevelScale4x4(qP % 6, 0, 0) * 2^(qP / 6)), stored at c[blk * 16 + 1] (blk = raster block index)
|
||||
function Transform.lumaDc(dc: { number }, m: number, c: { number })
|
||||
for i = 0, 3 do
|
||||
local k = i * 4
|
||||
local d0, d1, d2, d3 = dc[k + 1], dc[k + 2], dc[k + 3], dc[k + 4]
|
||||
local e = d0 + d1
|
||||
local f = d0 - d1
|
||||
local g = d2 + d3
|
||||
local h = d2 - d3
|
||||
dc[k + 1] = e + g
|
||||
dc[k + 2] = e - g
|
||||
dc[k + 3] = f - h
|
||||
dc[k + 4] = f + h
|
||||
end
|
||||
for j = 0, 3 do
|
||||
local d0, d1, d2, d3 = dc[j + 1], dc[j + 5], dc[j + 9], dc[j + 13]
|
||||
local e = d0 + d1
|
||||
local f = d0 - d1
|
||||
local g = d2 + d3
|
||||
local h = d2 - d3
|
||||
dc[j + 1], dc[j + 5], dc[j + 9], dc[j + 13] = 0, 0, 0, 0
|
||||
c[j * 16 + 1] = ((e + g) * m + 32) // 64
|
||||
c[(4 + j) * 16 + 1] = ((e - g) * m + 32) // 64
|
||||
c[(8 + j) * 16 + 1] = ((f - h) * m + 32) // 64
|
||||
c[(12 + j) * 16 + 1] = ((f + h) * m + 32) // 64
|
||||
end
|
||||
end
|
||||
|
||||
-- chromaDc(dc, base, m, c, cbase): the 2x2 chroma DC levels dc[base + 1 .. base + 4] -> c[cbase + blk * 16 + 1]
|
||||
function Transform.chromaDc(dc: { number }, base: number, m: number, c: { number }, cbase: number)
|
||||
local c0, c1, c2, c3 = dc[base + 1], dc[base + 2], dc[base + 3], dc[base + 4]
|
||||
dc[base + 1], dc[base + 2], dc[base + 3], dc[base + 4] = 0, 0, 0, 0
|
||||
local e = c0 + c1
|
||||
local f = c0 - c1
|
||||
local g = c2 + c3
|
||||
local h = c2 - c3
|
||||
c[cbase + 1] = ((e + g) * m) // 32
|
||||
c[cbase + 17] = ((f + h) * m) // 32
|
||||
c[cbase + 33] = ((e - g) * m) // 32
|
||||
c[cbase + 49] = ((f - h) * m) // 32
|
||||
end
|
||||
|
||||
return Transform
|
||||
@@ -0,0 +1,413 @@
|
||||
--!strict
|
||||
-- codecs/H264: an H.264 / AVC (ITU-T H.264 | ISO/IEC 14496-10) video decoder in pure Luau. A codec (layer 1): the
|
||||
-- video/h264 format (raw Annex B streams) and the MP4 / MKV / AVI / TS video tracks use it. Clean-room, written from the
|
||||
-- spec; constant tables taken from openh264 (BSD-2-Clause, licenses/openh264-LICENSE.txt). Bit-exact with the
|
||||
-- reference decoder (checked against ffmpeg per frame).
|
||||
-- Supports: Annex B and AVCC (length-prefixed, with avcC extradata) input; SPS / PPS / slices; CAVLC and CABAC; I, P and
|
||||
-- B slices; every intra mode (4x4, 8x8, 16x16, chroma), quarter-sample luma / eighth-sample chroma motion
|
||||
-- compensation, explicit and implicit weighted prediction, direct spatial and temporal prediction; the 4x4 and 8x8
|
||||
-- transforms with scaling matrices; the deblocking filter; multiple reference frames, long-term references, MMCO and
|
||||
-- the sliding window, frame_num gaps; POC types 0 / 1 / 2 and output reordering; 8-bit 4:2:0 Constrained Baseline,
|
||||
-- Main, Extended-without-SP/data-partitioning and High profiles; cropping. Corrupt slices are skipped and their
|
||||
-- macroblocks concealed (copied from the latest reference picture).
|
||||
-- Not supported (UNSUPPORTED): interlaced coding (field pictures, MBAFF), 4:0:0 / 4:2:2 / 4:4:4, bit depths above 8,
|
||||
-- lossless (transform bypass), FMO / ASO slice groups, SP / SI slices, data partitioning, SVC / MVC enhancement layers
|
||||
-- (their NAL units are ignored).
|
||||
--
|
||||
-- local H264 = require("@formats/codecs/H264")
|
||||
-- local dec = H264.newDecoder() -- or { avcC = buffer } for MP4 samples (length-prefixed)
|
||||
-- for _, au in accessUnits do
|
||||
-- local frames, err = dec:decode(au, pts) -- frames: { { image (yuv420p Types.Image), pts, poc, keyframe } }
|
||||
-- end
|
||||
-- local rest = dec:flush() -- the frames still held for reordering
|
||||
--
|
||||
-- Speed (one Zen 5 core, tools/bench.luau, libx264 crf 23 clips): Luau --codegen ~220-425 fps at 320x240 and ~75-135
|
||||
-- fps at 640x360; LuaJIT with the api's trace limits (host/init.luau) about the same or faster, but with LuaJIT's default
|
||||
-- limits (maxtrace=1000) the trace cache thrashes and it drops to ~30-190 fps. Real-time is comfortable at 320x240 and
|
||||
-- feasible at 640x360 for typical bitrates; high-bitrate CIF conformance streams run ~100-150 fps (Luau).
|
||||
-- Never throws: bad data returns nil, Err (core/Err codes ARG / UNSUPPORTED / LIMIT), or frames with the bad slices
|
||||
-- concealed (dec.errors counts them, dec.lastError says why).
|
||||
local Err = require("@formats/core/Err")
|
||||
local Types = require("@formats/Types")
|
||||
local Bitstream = require("@formats/codecs/H264/Bitstream")
|
||||
local Decoder = require("@formats/codecs/H264/Decoder")
|
||||
local Params = require("@formats/codecs/H264/Params")
|
||||
|
||||
local H264 = {}
|
||||
|
||||
export type Options = {
|
||||
avcC: buffer?, -- AVCDecoderConfigurationRecord (MP4 'avcC', Matroska CodecPrivate): samples are length-prefixed
|
||||
lengthSize: number?, -- NAL length field size for length-prefixed input without avcC (1, 2 or 4)
|
||||
maxPixels: number?, -- largest picture (default 2^22 luma samples)
|
||||
lowDelay: boolean?, -- output in decoding order, no reordering delay (streams without B frames / reordering)
|
||||
deblock: boolean?, -- false skips the deblocking filter (faster, not conformant); default true
|
||||
}
|
||||
|
||||
export type Frame = {
|
||||
image: Types.Image, -- yuv420p, cropped to the display size; image.meta.source = { format = "h264", poc, ... }
|
||||
pts: number, -- the pts passed with the access unit holding the picture (default: its decoding index)
|
||||
duration: number,
|
||||
poc: number,
|
||||
keyframe: boolean,
|
||||
}
|
||||
|
||||
local DecoderMeta = {}
|
||||
DecoderMeta.__index = DecoderMeta
|
||||
|
||||
export type H264Decoder = typeof(setmetatable({} :: { state: any, lengthSize: number?, errors: number, lastError: string? }, DecoderMeta))
|
||||
|
||||
local function toBuffer(data: any): buffer?
|
||||
if type(data) == "buffer" then
|
||||
return data
|
||||
elseif type(data) == "string" then
|
||||
return buffer.fromstring(data)
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
local function status(self: H264Decoder): Err.Err?
|
||||
local st = self.state
|
||||
self.errors = st.errors
|
||||
self.lastError = st.lastError
|
||||
if st.fatal then
|
||||
local m = st.fatal
|
||||
if string.sub(m, 1, 7) == "limit: " then
|
||||
return Err.new(Err.LIMIT, string.sub(m, 8))
|
||||
end
|
||||
return Err.new(Err.CORRUPT, m)
|
||||
end
|
||||
if st.unsupported then
|
||||
return Err.new(Err.UNSUPPORTED, st.unsupported)
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
-- newDecoder(opts?) -> H264Decoder | nil, Err
|
||||
function H264.newDecoder(opts: Options?): (H264Decoder?, Err.Err?)
|
||||
local o = opts or {}
|
||||
if type(o) ~= "table" then
|
||||
return nil, Err.new(Err.ARG, "newDecoder: options must be a table")
|
||||
end
|
||||
local st = Decoder.new(o :: any)
|
||||
local self = setmetatable({ state = st, lengthSize = o.lengthSize, errors = 0, lastError = nil :: string? }, DecoderMeta)
|
||||
if o.avcC then
|
||||
local ok, err = self:configure(o.avcC)
|
||||
if not ok then
|
||||
return nil, err
|
||||
end
|
||||
end
|
||||
return self, nil
|
||||
end
|
||||
|
||||
-- decoder:configure(avcC) -> true | nil, Err: reads an AVCDecoderConfigurationRecord (its SPS / PPS) and switches to
|
||||
-- length-prefixed input
|
||||
function DecoderMeta.configure(self: H264Decoder, avcC: any): (boolean?, Err.Err?)
|
||||
local b = toBuffer(avcC)
|
||||
if not b then
|
||||
return nil, Err.new(Err.ARG, "configure: expected a buffer or string")
|
||||
end
|
||||
local cfg, err = Bitstream.parseAvcC(b, 0, buffer.len(b))
|
||||
if not cfg then
|
||||
local m = err or "bad avcC"
|
||||
if string.sub(m, 1, 11) == "truncated: " then
|
||||
return nil, Err.new(Err.TRUNCATED, string.sub(m, 12))
|
||||
end
|
||||
return nil, Err.new(Err.CORRUPT, m)
|
||||
end
|
||||
self.lengthSize = cfg.lengthSize
|
||||
local nals = cfg.nals
|
||||
for i = 1, #nals, 2 do
|
||||
Decoder.nal(self.state, b, nals[i], nals[i + 1], nil)
|
||||
end
|
||||
local e = status(self)
|
||||
if e and e.code ~= Err.CORRUPT then
|
||||
return nil, e
|
||||
end
|
||||
return true, nil
|
||||
end
|
||||
|
||||
-- decoder:decode(data, pts?, off?, len?) -> { Frame } | nil, Err. data: an access unit or any run of NAL units:
|
||||
-- length-prefixed (after configure / with opts.lengthSize), else Annex B (start codes) or one bare NAL unit.
|
||||
function DecoderMeta.decode(self: H264Decoder, data: any, pts: number?, off: number?, len: number?): ({ Frame }?, Err.Err?)
|
||||
local b = toBuffer(data)
|
||||
if not b then
|
||||
return nil, Err.new(Err.ARG, "decode: expected a buffer or string")
|
||||
end
|
||||
local n = buffer.len(b)
|
||||
local o = math.clamp(off or 0, 0, n)
|
||||
local l = math.clamp(len or (n - o), 0, n - o)
|
||||
local st = self.state
|
||||
local nals
|
||||
if self.lengthSize then
|
||||
local all, partial = Bitstream.splitLength(b, o, l, self.lengthSize)
|
||||
nals = all or partial
|
||||
if not all then
|
||||
st.errors += 1
|
||||
st.lastError = "NAL length past the end of the sample"
|
||||
end
|
||||
elseif Bitstream.isAnnexB(b, o, l) then
|
||||
nals = Bitstream.splitAnnexB(b, o, l)
|
||||
else
|
||||
nals = { o, l }
|
||||
end
|
||||
for i = 1, #nals, 2 do
|
||||
Decoder.nal(st, b, nals[i], nals[i + 1], pts)
|
||||
if st.fatal or st.unsupported then
|
||||
break
|
||||
end
|
||||
end
|
||||
local frames = Decoder.take(st)
|
||||
local e = status(self)
|
||||
if e then
|
||||
return nil, e
|
||||
end
|
||||
return frames, nil
|
||||
end
|
||||
|
||||
-- decoder:flush() -> { Frame }: ends the stream (the current picture and every picture held for reordering)
|
||||
function DecoderMeta.flush(self: H264Decoder): { Frame }
|
||||
Decoder.flush(self.state)
|
||||
status(self)
|
||||
return Decoder.take(self.state)
|
||||
end
|
||||
|
||||
-- decodeAll(data, opts?) -> { Frame } | nil, Err: a whole Annex B (or length-prefixed with opts.avcC) stream
|
||||
function H264.decodeAll(data: any, opts: Options?): ({ Frame }?, Err.Err?)
|
||||
local dec, err = H264.newDecoder(opts)
|
||||
if not dec then
|
||||
return nil, err
|
||||
end
|
||||
local frames, e = dec:decode(data)
|
||||
if not frames then
|
||||
return nil, e
|
||||
end
|
||||
for _, f in dec:flush() do
|
||||
table.insert(frames, f)
|
||||
end
|
||||
return frames, nil
|
||||
end
|
||||
|
||||
-- parseAvcC(buf) -> { lengthSize, profile, level, nals } | nil, Err
|
||||
function H264.parseAvcC(data: any): (any, Err.Err?)
|
||||
local b = toBuffer(data)
|
||||
if not b then
|
||||
return nil, Err.new(Err.ARG, "parseAvcC: expected a buffer or string")
|
||||
end
|
||||
local cfg, err = Bitstream.parseAvcC(b, 0, buffer.len(b))
|
||||
if not cfg then
|
||||
return nil, Err.new(Err.CORRUPT, err or "bad avcC")
|
||||
end
|
||||
return cfg, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ video layer
|
||||
-- newVideoDecoder(track, opts?) -> a Types.VideoCodecDecoder (the codecs/Video registry entry for "h264"):
|
||||
-- track.config = avcC (MP4 / Matroska; packets length-prefixed) or nil (Annex B packets: MPEG-TS, AVI, raw .h264).
|
||||
-- Pictures come out in display order with the packet timestamps sorted (display order); a track with
|
||||
-- `ptsInOutputOrder` (raw Annex B, no timestamps) numbers them in output order instead.
|
||||
function H264.newVideoDecoder(track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?)
|
||||
local o: Options = { maxPixels = opts and opts.maxPixels, deblock = opts and opts.deblock, lowDelay = opts and opts.lowDelay }
|
||||
local function make(): (H264Decoder?, Err.Err?)
|
||||
local d, err = H264.newDecoder(o)
|
||||
if d and track.config then
|
||||
local ok, e = d:configure(track.config)
|
||||
if not ok then
|
||||
return nil, e
|
||||
end
|
||||
end
|
||||
return d, err
|
||||
end
|
||||
local dec, err = make()
|
||||
if not dec then
|
||||
return nil, err
|
||||
end
|
||||
local queue: { any } = {}
|
||||
local pool: { number } = {}
|
||||
local outIndex: number? = if track.ptsInOutputOrder then 0 else nil
|
||||
local self: any = {}
|
||||
local function push(frames: { Frame })
|
||||
for _, f in frames do
|
||||
local pts = f.pts
|
||||
if track.ptsInOutputOrder then
|
||||
pts = outIndex or 0
|
||||
outIndex = pts + 1
|
||||
elseif #pool > 0 then
|
||||
-- pictures leave in display order: they take the packet timestamps in increasing order (right for
|
||||
-- MP4 / MKV / TS pts, and for AVI whose packets only carry decode-order times)
|
||||
pts = table.remove(pool, 1)
|
||||
end
|
||||
table.insert(queue, { f.image, pts, f.keyframe })
|
||||
end
|
||||
end
|
||||
function self.decode(_: any, packet: Types.Packet): Err.Err?
|
||||
if not dec then
|
||||
return Err.new(Err.CORRUPT, "decoder not available")
|
||||
end
|
||||
if outIndex == nil and track.ptsInOutputOrder then
|
||||
outIndex = packet.pts
|
||||
end
|
||||
if packet.pts ~= nil and not track.ptsInOutputOrder then
|
||||
local i = #pool
|
||||
while i > 0 and pool[i] > packet.pts do
|
||||
i -= 1
|
||||
end
|
||||
table.insert(pool, i + 1, packet.pts)
|
||||
end
|
||||
local frames, e = (dec :: H264Decoder):decode(packet.data, packet.pts)
|
||||
if not frames then
|
||||
return e
|
||||
end
|
||||
push(frames)
|
||||
return nil
|
||||
end
|
||||
function self.receive(_: any): (Types.Image?, number?, boolean?)
|
||||
local q = table.remove(queue, 1)
|
||||
if q then
|
||||
return q[1], q[2], q[3]
|
||||
end
|
||||
return nil
|
||||
end
|
||||
function self.flush(_: any)
|
||||
if dec then
|
||||
push((dec :: H264Decoder):flush())
|
||||
end
|
||||
end
|
||||
function self.reset(_: any)
|
||||
dec = make()
|
||||
table.clear(queue)
|
||||
table.clear(pool)
|
||||
if track.ptsInOutputOrder then
|
||||
outIndex = nil
|
||||
end
|
||||
end
|
||||
return self, nil
|
||||
end
|
||||
|
||||
-- accessUnits(buf, off?, len?) -> { off, len, keyframe, ... } (triples): an Annex B stream cut into access units
|
||||
-- (7.4.1.2.3: a new unit starts at an AUD, SPS, PPS or SEI after a slice, or at a slice with first_mb_in_slice 0
|
||||
-- after a slice). keyframe: the unit holds an IDR slice.
|
||||
function H264.accessUnits(data: any, off: number?, len: number?): { any }
|
||||
local b = toBuffer(data)
|
||||
local out = {}
|
||||
if not b then
|
||||
return out
|
||||
end
|
||||
local n = buffer.len(b)
|
||||
local o = math.clamp(off or 0, 0, n)
|
||||
local l = math.clamp(len or (n - o), 0, n - o)
|
||||
local nals = Bitstream.splitAnnexB(b, o, l)
|
||||
local start, hasSlice, key = o, false, false
|
||||
for i = 1, #nals, 2 do
|
||||
local p, nl = nals[i], nals[i + 1]
|
||||
local t = buffer.readu8(b, p) % 32
|
||||
local isSlice = t == 1 or t == 5
|
||||
local boundary = false
|
||||
if hasSlice then
|
||||
if t == 9 or t == 7 or t == 8 or t == 6 or (t >= 14 and t <= 18) then
|
||||
boundary = true
|
||||
elseif isSlice and nl > 1 and buffer.readu8(b, p + 1) >= 128 then
|
||||
boundary = true
|
||||
end
|
||||
end
|
||||
if boundary then
|
||||
-- the unit ends where this NAL's start code begins
|
||||
local s = p
|
||||
while s > start and buffer.readu8(b, s - 1) ~= 1 do
|
||||
s -= 1
|
||||
end
|
||||
s -= 1
|
||||
while s > start and buffer.readu8(b, s - 1) == 0 do
|
||||
s -= 1
|
||||
end
|
||||
table.insert(out, start)
|
||||
table.insert(out, s - start)
|
||||
table.insert(out, key)
|
||||
start, hasSlice, key = s, false, false
|
||||
end
|
||||
if isSlice then
|
||||
hasSlice = true
|
||||
if t == 5 then
|
||||
key = true
|
||||
end
|
||||
end
|
||||
end
|
||||
if hasSlice and o + l > start then
|
||||
table.insert(out, start)
|
||||
table.insert(out, o + l - start)
|
||||
table.insert(out, key)
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
-- toAnnexB(config, sample) -> buffer: a length-prefixed sample (MP4 / Matroska) as Annex B; with config (avcC) the
|
||||
-- parameter sets are prepended (pass it for the first sample / keyframes). nil, Err on a bad avcC / sample
|
||||
function H264.toAnnexB(config: buffer?, sample: buffer): (buffer?, Err.Err?)
|
||||
local parts = {}
|
||||
local lengthSize = 4
|
||||
if config then
|
||||
local cfg, err = Bitstream.parseAvcC(config, 0, buffer.len(config))
|
||||
if not cfg then
|
||||
return nil, Err.new(Err.CORRUPT, err or "bad avcC")
|
||||
end
|
||||
lengthSize = cfg.lengthSize
|
||||
for i = 1, #cfg.nals, 2 do
|
||||
table.insert(parts, "\0\0\0\1" .. buffer.readstring(config, cfg.nals[i], cfg.nals[i + 1]))
|
||||
end
|
||||
end
|
||||
local nals = Bitstream.splitLength(sample, 0, buffer.len(sample), lengthSize)
|
||||
if not nals then
|
||||
return nil, Err.new(Err.CORRUPT, "NAL length past the end of the sample")
|
||||
end
|
||||
for i = 1, #nals, 2 do
|
||||
table.insert(parts, "\0\0\0\1" .. buffer.readstring(sample, nals[i], nals[i + 1]))
|
||||
end
|
||||
return buffer.fromstring(table.concat(parts)), nil
|
||||
end
|
||||
|
||||
-- info(data) -> { width, height, profile, level, frameRate?, ... } of the first SPS of an Annex B stream or avcC | nil
|
||||
function H264.info(data: any): any
|
||||
local b = toBuffer(data)
|
||||
if not b then
|
||||
return nil
|
||||
end
|
||||
local nals
|
||||
if buffer.len(b) > 6 and buffer.readu8(b, 0) == 1 then
|
||||
local cfg = Bitstream.parseAvcC(b, 0, buffer.len(b))
|
||||
nals = if cfg then cfg.nals else {}
|
||||
else
|
||||
nals = Bitstream.splitAnnexB(b, 0, buffer.len(b))
|
||||
end
|
||||
for i = 1, #nals, 2 do
|
||||
if buffer.readu8(b, nals[i]) % 32 == 7 then
|
||||
local sps = Params.sps(Bitstream.reader(b, nals[i], nals[i + 1], 1))
|
||||
if sps then
|
||||
local fps = nil
|
||||
if sps.unitsInTick and sps.timeScale and sps.unitsInTick > 0 then
|
||||
fps = sps.timeScale / (2 * sps.unitsInTick)
|
||||
end
|
||||
return {
|
||||
width = sps.width,
|
||||
height = sps.height,
|
||||
profile = sps.profile,
|
||||
level = sps.level,
|
||||
chromaFormat = sps.chromaFormat,
|
||||
bitDepth = sps.bitDepth,
|
||||
interlaced = not sps.frameMbsOnly,
|
||||
frameRate = fps,
|
||||
maxRefFrames = sps.maxRefFrames,
|
||||
numReorderFrames = sps.numReorderFrames,
|
||||
}
|
||||
end
|
||||
end
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
-- planes(img) -> y, u, v offsets in img.pixels and the chroma width / height
|
||||
function H264.planes(img: Types.Image): (number, number, number, number, number)
|
||||
local cw, ch = (img.width + 1) // 2, (img.height + 1) // 2
|
||||
local ny = img.width * img.height
|
||||
return 0, ny, ny + cw * ch, cw, ch
|
||||
end
|
||||
|
||||
return H264
|
||||
@@ -287,6 +287,13 @@ local function mpeg1Decoder(_track: Types.Track, opts: any?): (Types.VideoCodecD
|
||||
return self :: any, nil
|
||||
end
|
||||
|
||||
-- H.264 / AVC (codecs/H264): avcC from track.config (MP4 / Matroska) or Annex B packets (MPEG-TS, AVI, raw .h264);
|
||||
-- pictures in display order with the pts of their packet
|
||||
local function h264Decoder(track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?)
|
||||
local H264 = require("@formats/codecs/H264")
|
||||
return H264.newVideoDecoder(track, opts)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ registry
|
||||
-- the codecs known by name (decoders where `new` is set). FourCCs compare case-sensitively first, then upper-cased.
|
||||
local BUILTIN: { Entry } = {
|
||||
@@ -296,7 +303,7 @@ local BUILTIN: { Entry } = {
|
||||
{ id = "rawvideo", name = "raw video", fourcc = { "\0\0\0\0", "I420", "IYUV", "YV12", "raw ", "DIB " }, matroska = { "V_UNCOMPRESSED" }, new = rawDecoder },
|
||||
{ id = "mpeg2", name = "MPEG-2 video", fourcc = { "mpg2", "MPG2", "MPEG", "mp2v" }, matroska = { "V_MPEG2" } },
|
||||
{ id = "mpeg4", name = "MPEG-4 part 2", fourcc = { "mp4v", "FMP4", "XVID", "DIVX", "DX50", "MP4V" }, matroska = { "V_MPEG4/ISO/SP", "V_MPEG4/ISO/ASP", "V_MPEG4/ISO/AP" } },
|
||||
{ id = "h264", name = "H.264 / AVC", fourcc = { "avc1", "avc3", "H264", "h264", "X264", "x264" }, matroska = { "V_MPEG4/ISO/AVC" } },
|
||||
{ id = "h264", name = "H.264 / AVC", fourcc = { "avc1", "avc3", "H264", "h264", "X264", "x264", "AVC1", "DAVC", "VSSH" }, matroska = { "V_MPEG4/ISO/AVC" }, new = h264Decoder },
|
||||
{ id = "hevc", name = "H.265 / HEVC", fourcc = { "hvc1", "hev1", "HEVC", "H265" }, matroska = { "V_MPEGH/ISO/HEVC" } },
|
||||
{ id = "vp9", name = "VP9", fourcc = { "VP90", "vp09" }, matroska = { "V_VP9" } },
|
||||
{ id = "av1", name = "AV1", fourcc = { "AV01", "av01" }, matroska = { "V_AV1" } },
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
--!strict
|
||||
-- video/h264: raw H.264 / AVC elementary streams (ITU-T H.264 Annex B byte stream: .h264 / .264 files, x264 / ffmpeg
|
||||
-- `-f h264` output, the JVT conformance bitstreams). New in formats-luau.
|
||||
-- Read: the stream cut into access units (codecs/H264.accessUnits) as a one-track Demuxer; open() returns a
|
||||
-- VideoDecoder decoding through codecs/H264 (yuv420p frames in display order, numbered in output order since a raw
|
||||
-- stream has no timestamps; the frame rate comes from the SPS VUI timing, else opts.frameRate, else 25).
|
||||
-- Write: H.264 tracks copied from any video (MP4 / MKV samples are converted from length-prefixed NAL units to Annex B,
|
||||
-- the avcC parameter sets put in front of every keyframe). Not supported: re-encoding other codecs to H.264 (there is
|
||||
-- no H.264 encoder), and whatever codecs/H264 does not decode (interlaced, 4:2:2 / 4:4:4, > 8 bits: UNSUPPORTED).
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Types = require("@formats/Types")
|
||||
local Demux = require("@formats/containers/Demux")
|
||||
local Video = require("@formats/codecs/Video")
|
||||
local Source = require("@formats/codecs/Video/Source")
|
||||
local H264 = require("@formats/codecs/H264")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Format = {
|
||||
name = "h264",
|
||||
category = "video",
|
||||
extensions = { "h264", "264", "avc", "jsv", "26l", "jvt" },
|
||||
mime = { "video/h264" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "containers/Demux", "codecs/Video", "codecs/Video/Source", "codecs/H264" },
|
||||
caps = { decode = true, encode = true, streaming = true, video = { "h264" }, depths = { 8 } },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type OpenOptions = {
|
||||
rgba: boolean?, -- nextFrame returns rgba8 (default false: yuv420p)
|
||||
maxPixels: number?, -- largest picture (default 2^22 luma samples)
|
||||
frameRate: number?, -- frames per second when the stream has no VUI timing (default 25)
|
||||
deblock: boolean?, -- false skips the deblocking filter (faster, not conformant)
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
-- a start code then an SPS / AUD / SEI / PPS NAL header (forbidden bit 0)
|
||||
function Format.sniff(r: Bytes.Reader): number
|
||||
local s = r:peek(5)
|
||||
if not s or #s < 4 then
|
||||
return 0
|
||||
end
|
||||
local hdr
|
||||
if string.byte(s, 1) == 0 and string.byte(s, 2) == 0 and string.byte(s, 3) == 1 then
|
||||
hdr = string.byte(s, 4)
|
||||
elseif #s >= 5 and string.byte(s, 1) == 0 and string.byte(s, 2) == 0 and string.byte(s, 3) == 0 and string.byte(s, 4) == 1 then
|
||||
hdr = string.byte(s, 5)
|
||||
else
|
||||
return 0
|
||||
end
|
||||
if hdr >= 128 then
|
||||
return 0
|
||||
end
|
||||
local t = hdr % 32
|
||||
if t == 7 then
|
||||
return 0.8
|
||||
elseif t == 9 or t == 6 or t == 8 then
|
||||
return 0.5
|
||||
elseif t == 5 then
|
||||
return 0.4
|
||||
end
|
||||
return 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
-- demux(r, opts?) -> the Demuxer (one video track, one packet per access unit) | nil, Err
|
||||
function Format.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?)
|
||||
local buf, base, limit = r.buf, r.base, r.limit
|
||||
local units = H264.accessUnits(buf, base, limit - base)
|
||||
if #units == 0 then
|
||||
return nil, Err.new(Err.CORRUPT, "no access units (no slices after a start code)", base)
|
||||
end
|
||||
local info = H264.info(buffer.readstring(buf, base, math.min(limit - base, 4096))) or {}
|
||||
if info.interlaced or (info.chromaFormat and info.chromaFormat ~= 1) or (info.bitDepth and info.bitDepth ~= 8) then
|
||||
-- still demuxable (remuxing works); decoding reports UNSUPPORTED
|
||||
info.unsupported = true
|
||||
end
|
||||
local fps = info.frameRate or (opts and opts.frameRate) or 25
|
||||
if fps <= 0 or fps > 1000 then
|
||||
fps = 25
|
||||
end
|
||||
local track: Types.Track = {
|
||||
id = 1,
|
||||
kind = "video",
|
||||
codec = "h264",
|
||||
timescale = fps,
|
||||
width = info.width,
|
||||
height = info.height,
|
||||
frameRate = fps,
|
||||
profile = info.profile,
|
||||
level = info.level,
|
||||
ptsInOutputOrder = true,
|
||||
default = true,
|
||||
}
|
||||
local dmx = Demux.new("h264", { track }, buf, { profile = info.profile, level = info.level })
|
||||
local k = 0
|
||||
for i = 1, #units, 3 do
|
||||
dmx:add(1, k, k, 1, units[i + 2] or k == 0, units[i], units[i + 1])
|
||||
k += 1
|
||||
end
|
||||
track.frames = k
|
||||
dmx:finish()
|
||||
return dmx, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
-- encode(video, opts?) -> an Annex B buffer of the source's H.264 track | nil, Err (UNSUPPORTED for other codecs)
|
||||
function Format.encode(value: any, _opts: any?): (buffer?, Err.Err?)
|
||||
local streams, err = Source.streams(value, { audio = false }, { video = { copy = { h264 = true } } })
|
||||
if not streams then
|
||||
return nil, err
|
||||
end
|
||||
local s = streams[1]
|
||||
if not s or s.codec ~= "h264" then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "only H.264 tracks can be written as a raw H.264 stream")
|
||||
end
|
||||
local parts = {}
|
||||
for i, p in s.packets do
|
||||
local data = p.data
|
||||
if s.config then
|
||||
local key = i == 1 or p.keyframe
|
||||
local out, e = H264.toAnnexB(if key then s.config else nil, data)
|
||||
if not out then
|
||||
return nil, e
|
||||
end
|
||||
data = out
|
||||
end
|
||||
table.insert(parts, buffer.tostring(data))
|
||||
end
|
||||
return buffer.fromstring(table.concat(parts)), nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ open
|
||||
-- open(r, opts?) -> a VideoDecoder | nil, Err
|
||||
function Format.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?)
|
||||
local dmx, err = Format.demux(r, opts)
|
||||
if not dmx then
|
||||
return nil, err
|
||||
end
|
||||
return Video.open(dmx, opts)
|
||||
end
|
||||
|
||||
return Format
|
||||
@@ -264,10 +264,20 @@ function Mp4.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
if s.kind == "audio" and s.track and s.track.codecDelay and s.copied then
|
||||
skip = math.floor(s.track.codecDelay * scale + 0.5)
|
||||
end
|
||||
-- video: the skipped decode delay is a composition shift, every frame still plays (ffmpeg drops the frames an
|
||||
-- edit cuts); audio: the codec delay samples are not played
|
||||
local playDuration = nil
|
||||
if s.kind == "video" and skip > 0 then
|
||||
playDuration = 0
|
||||
for _, d in durations do
|
||||
playDuration += d
|
||||
end
|
||||
end
|
||||
local t: any = {
|
||||
kind = s.kind,
|
||||
timescale = scale,
|
||||
skip = if skip > 0 then skip else nil,
|
||||
playDuration = playDuration,
|
||||
samples = samples,
|
||||
durations = durations,
|
||||
cts = if anyCts then cts else nil,
|
||||
|
||||
@@ -0,0 +1,173 @@
|
||||
-- codecs/H264 tests: libx264 streams at many settings (Baseline / Main / High, CAVLC / CABAC, B frames, references,
|
||||
-- weighted prediction, 8x8 transforms, scaling matrices, slices, odd sizes with cropping, ...) decoded and compared
|
||||
-- per frame with ffmpeg's decoder (CRC-32 of the yuv420p planes, bit-exact); the AVCC (avcC + length-prefixed
|
||||
-- samples) and NAL-at-a-time paths; pts propagation; UNSUPPORTED streams (interlaced, 4:2:2, 4:4:4, 10-bit); error
|
||||
-- codes; and the fuzz no-throw pass. Fixtures: tools/fixtures/h264.py.
|
||||
local T = require("@tests/T")
|
||||
require("@formats/host") -- LuaJIT: the trace limits the api sets (host/init.luau)
|
||||
local H264 = require("@formats/codecs/H264")
|
||||
local Crc32 = require("@formats/core/Crc32")
|
||||
local Err = require("@formats/core/Err")
|
||||
local Cases = require("@tests/gen/h264_cases")
|
||||
local Bad = require("@tests/gen/h264_bad")
|
||||
|
||||
local t = T.suite("h264")
|
||||
|
||||
-- 1. every stream, whole, against ffmpeg
|
||||
local nframes = 0
|
||||
for _, c in Cases do
|
||||
local frames, err = H264.decodeAll(c.data)
|
||||
t:check(frames, c.name .. ": " .. tostring(err))
|
||||
t:eq(#frames, #c.frames, c.name .. ": frame count")
|
||||
local good = 0
|
||||
for i, f in frames do
|
||||
if i == 1 then
|
||||
t:check(f.image.format == "yuv420p" and f.image.width == c.width and f.image.height == c.height, c.name .. ": size")
|
||||
end
|
||||
if Crc32.of(f.image.pixels) == c.frames[i] then
|
||||
good += 1
|
||||
end
|
||||
end
|
||||
t:eq(good, #c.frames, c.name .. ": frames bit-exact with ffmpeg")
|
||||
nframes += good
|
||||
end
|
||||
t:note("%d streams, %d frames bit-exact with ffmpeg", #Cases, nframes)
|
||||
|
||||
-- 2. AVCC samples, NAL-at-a-time input, pts
|
||||
local function splitAnnexB(s: string): { string }
|
||||
local out = {}
|
||||
local i = 1
|
||||
local starts = {}
|
||||
while true do
|
||||
local j = string.find(s, "\0\0\1", i, true)
|
||||
if not j then
|
||||
break
|
||||
end
|
||||
table.insert(starts, j + 3)
|
||||
i = j + 3
|
||||
end
|
||||
for k, st in starts do
|
||||
local e = if starts[k + 1] then starts[k + 1] - 4 else #s
|
||||
local nal = string.sub(s, st, e)
|
||||
while string.byte(nal, #nal) == 0 do
|
||||
nal = string.sub(nal, 1, #nal - 1)
|
||||
end
|
||||
table.insert(out, nal)
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
for _, c in Cases do
|
||||
if c.avcc then
|
||||
local dec = H264.newDecoder({ avcC = buffer.fromstring(c.avcc) })
|
||||
t:check(dec, c.name .. ": avcC")
|
||||
local got = {}
|
||||
for i, s in c.samples do
|
||||
local frames, err = (dec :: any):decode(s, i * 1000)
|
||||
t:check(frames, c.name .. ": sample " .. i .. ": " .. tostring(err))
|
||||
for _, f in frames do
|
||||
table.insert(got, f)
|
||||
end
|
||||
end
|
||||
for _, f in (dec :: any):flush() do
|
||||
table.insert(got, f)
|
||||
end
|
||||
local good = 0
|
||||
local ptsOk = true
|
||||
local last = -1
|
||||
for i, f in got do
|
||||
if Crc32.of(f.image.pixels) == c.frames[i] then
|
||||
good += 1
|
||||
end
|
||||
if f.pts % 1000 ~= 0 then
|
||||
ptsOk = false
|
||||
end
|
||||
if f.poc <= last and not f.keyframe then
|
||||
ptsOk = false
|
||||
end
|
||||
last = f.poc
|
||||
end
|
||||
t:eq(good, #c.frames, c.name .. ": AVCC samples bit-exact")
|
||||
t:check(ptsOk, c.name .. ": pts carried per access unit, output in POC order")
|
||||
-- bare NAL units, one call each
|
||||
local dec2 = H264.newDecoder() :: any
|
||||
local got2 = 0
|
||||
for _, nal in splitAnnexB(c.data) do
|
||||
local frames = dec2:decode(nal)
|
||||
for _, f in frames do
|
||||
got2 += 1
|
||||
t:check(Crc32.of(f.image.pixels) == c.frames[got2], c.name .. ": NAL-at-a-time frame " .. got2)
|
||||
end
|
||||
end
|
||||
for _, f in dec2:flush() do
|
||||
got2 += 1
|
||||
t:check(Crc32.of(f.image.pixels) == c.frames[got2], c.name .. ": NAL-at-a-time frame " .. got2)
|
||||
end
|
||||
t:eq(got2, #c.frames, c.name .. ": NAL-at-a-time frame count")
|
||||
end
|
||||
end
|
||||
|
||||
-- 3. unsupported streams
|
||||
for _, c in Bad do
|
||||
local frames, err = H264.decodeAll(c.data)
|
||||
t:check(frames == nil and err and err.code == c.code, c.name .. ": " .. tostring(err))
|
||||
end
|
||||
|
||||
-- 4. error codes
|
||||
do
|
||||
local _, e1 = H264.decodeAll(123 :: any)
|
||||
t:check(e1 and e1.code == Err.ARG, "decode of a number: ARG")
|
||||
local _, e2 = H264.decodeAll(Cases[1].data, { maxPixels = 1000 })
|
||||
t:check(e2 and e2.code == Err.LIMIT, "maxPixels: LIMIT " .. tostring(e2))
|
||||
local _, e3 = H264.newDecoder({ avcC = buffer.fromstring("\1\2") })
|
||||
t:check(e3 and e3.code == Err.TRUNCATED, "short avcC: TRUNCATED")
|
||||
local _, e4 = H264.parseAvcC("\2\0\0\0\0\0\0")
|
||||
t:check(e4 and e4.code == Err.CORRUPT, "avcC version 2: CORRUPT")
|
||||
local frames = H264.decodeAll("")
|
||||
t:check(frames and #frames == 0, "empty input: no frames")
|
||||
-- a stream cut in half still decodes the first frames (the rest concealed or missing)
|
||||
local c = Cases[3]
|
||||
local half = H264.decodeAll(string.sub(c.data, 1, #c.data // 2))
|
||||
t:check(half and #half > 0 and Crc32.of(half[1].image.pixels) == c.frames[1], "truncated stream: first frame intact")
|
||||
-- lowDelay outputs in decoding order (right for streams without reordering)
|
||||
local ld = H264.decodeAll(c.data, { lowDelay = true })
|
||||
t:check(ld and #ld == #c.frames and Crc32.of(ld[#ld].image.pixels) == c.frames[#c.frames], "lowDelay on a P-only stream")
|
||||
end
|
||||
|
||||
-- 5. fuzz: streams with damaged bytes / truncations must never throw
|
||||
local samples = {}
|
||||
for _, c in Cases do
|
||||
if #c.data < 20000 and #samples < 14 then
|
||||
table.insert(samples, c.data)
|
||||
end
|
||||
end
|
||||
t:fuzz("decodeAll", function(b: buffer)
|
||||
return H264.decodeAll(b, { maxPixels = 2 ^ 18 })
|
||||
end, samples, { mutations = 10, keepHeader = 40 })
|
||||
t:fuzz("decodeAll (headers too)", function(b: buffer)
|
||||
return H264.decodeAll(b, { maxPixels = 2 ^ 18 })
|
||||
end, samples, { mutations = 6, garbage = 100 })
|
||||
-- heavier damage: many bytes changed in the slice data
|
||||
do
|
||||
local rand = T.rng(99)
|
||||
local tries, threw = 0, 0
|
||||
for _, s in samples do
|
||||
for _ = 1, 6 do
|
||||
local b = buffer.fromstring(s)
|
||||
local n = buffer.len(b)
|
||||
for _ = 1, 1 + rand(40) do
|
||||
buffer.writeu8(b, 60 + rand(n - 61), rand(256))
|
||||
end
|
||||
tries += 1
|
||||
local ok, err = pcall(H264.decodeAll, b, { maxPixels = 2 ^ 18 })
|
||||
if not ok then
|
||||
threw += 1
|
||||
print(" THREW (heavy mutation): " .. tostring(err))
|
||||
end
|
||||
end
|
||||
end
|
||||
t:check(threw == 0, "heavy mutations never throw (" .. threw .. " of " .. tries .. ")")
|
||||
t:note("heavy mutations: %d damaged streams, none threw", tries)
|
||||
end
|
||||
|
||||
t:done()
|
||||
@@ -0,0 +1,37 @@
|
||||
-- codecs/H264 conformance: a selection of the ITU-T H.264.1 (JVT) conformance bitstreams (Baseline / Main / Extended
|
||||
-- without SP / High: CAVLC, CABAC, B frames, weighted prediction, multiple slices, MMCO / long-term references,
|
||||
-- frame_num gaps, cropping, PCM, 8x8 transforms, scaling matrices, ...) decoded bit-exact against the reference
|
||||
-- decoder's yuv (JM, shipped in each zip; ffmpeg where there is none), and interlaced / SP / 4:2:2 streams refused
|
||||
-- with UNSUPPORTED. Fixtures: tools/fixtures/h264_jvt.py (downloaded from itu.int; skipped when unreachable).
|
||||
local T = require("@tests/T")
|
||||
require("@formats/host") -- LuaJIT: the trace limits the api sets (host/init.luau)
|
||||
local H264 = require("@formats/codecs/H264")
|
||||
local Crc32 = require("@formats/core/Crc32")
|
||||
local Base64 = require("@formats/core/Base64")
|
||||
local Err = require("@formats/core/Err")
|
||||
local Cases = require("@tests/gen/h264_jvt")
|
||||
|
||||
local t = T.suite("h264 conformance")
|
||||
local streams, nframes, refused = 0, 0, 0
|
||||
for _, c in Cases do
|
||||
local data = Base64.decode(c.data64) :: buffer
|
||||
local frames, err = H264.decodeAll(data)
|
||||
if c.expect == "UNSUPPORTED" then
|
||||
t:check(frames == nil and err and err.code == Err.UNSUPPORTED, c.name .. ": UNSUPPORTED (" .. tostring(err) .. ")")
|
||||
refused += 1
|
||||
else
|
||||
t:check(frames, c.name .. ": " .. tostring(err))
|
||||
t:eq(#frames, #c.frames, c.name .. ": frame count")
|
||||
local good = 0
|
||||
for i, f in frames do
|
||||
if Crc32.of(f.image.pixels) == c.frames[i] then
|
||||
good += 1
|
||||
end
|
||||
end
|
||||
t:eq(good, #c.frames, c.name .. ": bit-exact with the " .. c.ref .. " reference")
|
||||
streams += 1
|
||||
nframes += good
|
||||
end
|
||||
end
|
||||
t:note("%d conformance streams (%d frames) bit-exact, %d refused as UNSUPPORTED%s", streams, nframes, refused, if #Cases == 0 then " (fixtures unavailable: no download)" else "")
|
||||
t:done()
|
||||
@@ -0,0 +1,100 @@
|
||||
-- video/h264 tests: H.264 through F.video.open end to end: raw Annex B (.h264, the video/h264 format), MP4 and MKV
|
||||
-- (avcC + length-prefixed samples) and MPEG-TS / AVI (Annex B packets) written by ffmpeg / libx264, frames bit-exact
|
||||
-- against ffmpeg's decode of each file; display-order timestamps; the raw writer (MP4 -> .h264) read back; sniffing;
|
||||
-- the fuzz no-throw pass on the raw demuxer. Fixtures: tools/fixtures/h264.py (h264_containers).
|
||||
local T = require("@tests/T")
|
||||
local F = require("@formats")
|
||||
local Fmt = require("@formats/video/h264")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Crc32 = require("@formats/core/Crc32")
|
||||
local Cases = require("@tests/gen/h264_containers")
|
||||
|
||||
local t = T.suite("video/h264")
|
||||
t:eq(Fmt.name, "h264", "name")
|
||||
|
||||
local function frames(v: any): ({ any }, any)
|
||||
local out = {}
|
||||
while true do
|
||||
local f, err = v:nextFrame()
|
||||
if not f then
|
||||
return out, err
|
||||
end
|
||||
table.insert(out, f)
|
||||
end
|
||||
end
|
||||
|
||||
local byName = {}
|
||||
for _, c in Cases do
|
||||
byName[c.name] = c
|
||||
local v, err = F.video.open(c.data)
|
||||
t:check(v ~= nil, c.name .. ": F.video.open " .. tostring(err))
|
||||
if v then
|
||||
t:eq(v.codec, "h264", c.name .. ": codec")
|
||||
local got, ferr = frames(v)
|
||||
t:check(ferr == nil, c.name .. ": no decode error " .. tostring(ferr))
|
||||
t:eq(#got, #c.frames, c.name .. ": frame count")
|
||||
local good, mono = 0, true
|
||||
for i, f in got do
|
||||
if Crc32.of(f.image.pixels) == c.frames[i] then
|
||||
good += 1
|
||||
end
|
||||
if i > 1 and f.pts <= got[i - 1].pts then
|
||||
mono = false
|
||||
end
|
||||
end
|
||||
t:eq(good, #c.frames, c.name .. ": frames bit-exact with ffmpeg")
|
||||
t:check(mono, c.name .. ": display-order timestamps increase")
|
||||
t:check(got[1] and got[1].image.meta.yuv and got[1].image.meta.yuv.range == "limited", c.name .. ": meta.yuv")
|
||||
local rgba = got[1] and v:toRGBA(got[1])
|
||||
t:check(rgba and rgba.format == "rgba8" and rgba.width == c.width, c.name .. ": toRGBA")
|
||||
end
|
||||
end
|
||||
|
||||
-- raw format directly: sniff, demux, 25 fps output order
|
||||
do
|
||||
local c = byName["cabac_b.h264"]
|
||||
local r = Bytes.reader(buffer.fromstring(c.data))
|
||||
t:check(Fmt.sniff(r) >= 0.5, "sniff a raw stream")
|
||||
t:check(Fmt.sniff(Bytes.reader(buffer.fromstring(byName["cabac_b.mp4"].data))) == 0, "sniff rejects MP4")
|
||||
local dmx = Fmt.demux(r)
|
||||
t:check(dmx and dmx:count(1) == #c.frames, "one packet per access unit")
|
||||
local v = Fmt.open(Bytes.reader(buffer.fromstring(c.data)))
|
||||
local got = frames(v)
|
||||
t:check(#got == #c.frames and math.abs(got[2].pts - 1 / 25) < 1e-9, "raw: pts in output order at 25 fps")
|
||||
end
|
||||
|
||||
-- writer: the MP4's H.264 track as a raw Annex B stream, decoded again
|
||||
for _, src in { "cabac_b.mp4", "baseline.mkv", "baseline.ts" } do
|
||||
local c = byName[src]
|
||||
local v = F.video.open(c.data)
|
||||
local out, err = F.save(v, nil, { format = "h264" })
|
||||
t:check(out ~= nil, src .. " -> h264: " .. tostring(err))
|
||||
if out then
|
||||
local v2 = F.video.open(out)
|
||||
t:check(v2 ~= nil and v2.format == "h264", src .. " -> h264: reads back as raw H.264")
|
||||
local got = frames(v2)
|
||||
local good = 0
|
||||
for i, f in got do
|
||||
if Crc32.of(f.image.pixels) == c.frames[i] then
|
||||
good += 1
|
||||
end
|
||||
end
|
||||
t:eq(good, #c.frames, src .. " -> h264: frames bit-exact")
|
||||
end
|
||||
end
|
||||
|
||||
-- fuzz: the raw demuxer + decoder
|
||||
local samples = { byName["baseline.h264"].data, byName["cabac_b.h264"].data }
|
||||
t:fuzz("open + frames", function(b: buffer)
|
||||
local v = Fmt.open(Bytes.reader(b), { maxPixels = 2 ^ 18 })
|
||||
if v then
|
||||
for _ = 1, 40 do
|
||||
if not v:nextFrame() then
|
||||
break
|
||||
end
|
||||
end
|
||||
end
|
||||
return v
|
||||
end, samples, { mutations = 8, keepHeader = 30 })
|
||||
|
||||
t:done()
|
||||
@@ -1030,3 +1030,24 @@ do
|
||||
run(" (jit tuned)")
|
||||
end
|
||||
end
|
||||
do
|
||||
-- H.264 (codecs/H264): whole Annex B streams, frames per second (decode + the cropped yuv420p output copies). The
|
||||
-- testsrc2 clips are easy (mostly static); the mandelbrot zooms move everywhere. LuaJIT runs twice: with its default
|
||||
-- trace limits and with the ones host/init.luau sets (maxtrace=8000, maxmcode=65536).
|
||||
local H264 = require("@formats/codecs/H264")
|
||||
local HB = require("@tests/gen/h264_bench")
|
||||
local function run(tag: string)
|
||||
for _, c in HB do
|
||||
local n = c.width * c.height * 3 // 2 * #c.frames
|
||||
local dt = bench(string.format("h264 %s %dx%d%s", c.name, c.width, c.height, tag), 3, n, function()
|
||||
H264.decodeAll(c.data)
|
||||
end)
|
||||
print(string.format("%-8s %-30s %8.1f fps", runtime, " (" .. #c.frames .. " frames)", #c.frames / dt))
|
||||
end
|
||||
end
|
||||
run("")
|
||||
if runtime == "luajit" then
|
||||
require("@formats/host")
|
||||
run(" (jit tuned)")
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,189 @@
|
||||
# H.264 fixtures (tools/fixtures.py). Reference tools: ffmpeg's libx264 encodes synthetic clips (testsrc2 / mandelbrot /
|
||||
# noise) at many settings (profiles, CAVLC / CABAC, B frames, references, weighted prediction, 8x8 transforms, slices,
|
||||
# scaling matrices, odd sizes with cropping, ...); ffmpeg's own H.264 decoder (-f rawvideo -pix_fmt yuv420p) gives the
|
||||
# reference frames, compared per frame by CRC-32 of the cropped yuv420p planes.
|
||||
# tests/gen/h264_cases.luau { name, data (Annex B), width, height, frames = { crc ... }, avcc?, samples? }
|
||||
# tests/gen/h264_bad.luau streams expected to fail: { name, data, code }
|
||||
# tests/gen/h264_bench.luau bigger streams for tools/bench.luau: { name, data, width, height, frames }
|
||||
import os, subprocess, tempfile, zlib
|
||||
|
||||
INPUTS = []
|
||||
|
||||
SRC = {
|
||||
"testsrc2": "testsrc2=s={w}x{h}:r=25",
|
||||
"noise": "testsrc2=s={w}x{h}:r=25,noise=alls=24:allf=t+u",
|
||||
"mandel": "mandelbrot=s={w}x{h}:r=25",
|
||||
"fade": "testsrc2=s={w}x{h}:r=25,fade=in:0:8,hue=H=t*2",
|
||||
}
|
||||
|
||||
# name, source, w, h, frames, x264 params, extra ffmpeg args
|
||||
CASES = [
|
||||
("cavlc_intra", "testsrc2", 176, 144, 3, "keyint=1:cabac=0:8x8dct=0:bframes=0:ref=1", []),
|
||||
("cavlc_intra_noise", "noise", 176, 144, 2, "keyint=1:cabac=0:8x8dct=0:bframes=0:qp=12", []),
|
||||
("cavlc_p", "testsrc2", 176, 144, 12, "cabac=0:8x8dct=0:bframes=0:ref=1:weightp=0", []),
|
||||
("cavlc_p_refs4", "noise", 176, 144, 12, "cabac=0:8x8dct=0:bframes=0:ref=4:weightp=0:mixed-refs=1", []),
|
||||
("cavlc_p_weightp", "fade", 176, 144, 12, "cabac=0:8x8dct=0:bframes=0:ref=3:weightp=2", []),
|
||||
("cavlc_slices", "testsrc2", 176, 144, 6, "cabac=0:8x8dct=0:bframes=0:slices=4", []),
|
||||
("cavlc_high_8x8", "noise", 176, 144, 8, "cabac=0:8x8dct=1:bframes=0:ref=2", []),
|
||||
("cavlc_b3", "testsrc2", 176, 144, 14, "cabac=0:8x8dct=0:bframes=3:b-pyramid=normal:ref=3", []),
|
||||
("cavlc_b_temporal", "noise", 176, 144, 10, "cabac=0:bframes=2:direct=temporal:ref=2:b-pyramid=none", []),
|
||||
("cavlc_constrained", "noise", 176, 144, 8, "cabac=0:bframes=0:constrained-intra=1:ref=2", []),
|
||||
("cabac_intra", "testsrc2", 176, 144, 3, "keyint=1:cabac=1:8x8dct=0:bframes=0", []),
|
||||
("cabac_intra_8x8", "noise", 176, 144, 2, "keyint=1:cabac=1:8x8dct=1:bframes=0:qp=10", []),
|
||||
("cabac_p", "testsrc2", 176, 144, 12, "cabac=1:8x8dct=0:bframes=0:ref=1:weightp=0", []),
|
||||
("cabac_p_refs4", "noise", 176, 144, 12, "cabac=1:bframes=0:ref=4:weightp=1", []),
|
||||
("cabac_weightp", "fade", 176, 144, 12, "cabac=1:bframes=0:ref=3:weightp=2", []),
|
||||
("cabac_b3", "testsrc2", 176, 144, 16, "cabac=1:bframes=3:b-pyramid=normal:ref=4:weightb=1", []),
|
||||
("cabac_b3_noise", "noise", 176, 144, 12, "cabac=1:bframes=3:b-pyramid=strict:ref=3:direct=spatial", []),
|
||||
("cabac_b_temporal", "noise", 176, 144, 10, "cabac=1:bframes=2:direct=temporal:ref=3:weightb=0", []),
|
||||
("cabac_b_weightb", "fade", 176, 144, 12, "cabac=1:bframes=3:weightb=1:weightp=2:ref=3", []),
|
||||
("cabac_slices", "noise", 176, 144, 8, "cabac=1:bframes=2:slices=3:ref=2", []),
|
||||
("high_cqm", "noise", 176, 144, 8, "cabac=1:8x8dct=1:bframes=2:cqm=jvt:ref=2", []),
|
||||
("high_lowqp", "noise", 176, 144, 4, "cabac=1:8x8dct=1:bframes=1:qp=4", []),
|
||||
("cavlc_lowqp", "noise", 176, 144, 4, "cabac=0:8x8dct=1:bframes=1:qp=4", []),
|
||||
("deblock_off", "testsrc2", 176, 144, 6, "cabac=1:bframes=1:no-deblock=1", []),
|
||||
("deblock_offsets", "noise", 176, 144, 6, "cabac=1:bframes=1:deblock=-3,3", []),
|
||||
("qvga_main", "mandel", 320, 240, 6, "cabac=1:bframes=2:ref=2:8x8dct=0", []),
|
||||
("odd_98x62", "noise", 98, 62, 6, "cabac=1:bframes=2:ref=2", []),
|
||||
("odd_34x18", "testsrc2", 34, 18, 5, "cabac=0:bframes=1:ref=1", []),
|
||||
("tiny_16x16", "noise", 16, 16, 4, "cabac=1:bframes=1", []),
|
||||
("wide_200x40", "noise", 200, 40, 6, "cabac=1:bframes=3:ref=3:8x8dct=1", []),
|
||||
("poc2_baseline", "testsrc2", 176, 144, 8, "cabac=0:bframes=0:ref=2", ["-profile:v", "baseline"]),
|
||||
("intra_refresh", "noise", 176, 144, 10, "cabac=0:bframes=0:intra-refresh=1:keyint=6", []),
|
||||
("keyint_short", "testsrc2", 176, 144, 14, "cabac=1:bframes=2:keyint=5:min-keyint=1:open-gop=0", []),
|
||||
("open_gop", "testsrc2", 176, 144, 14, "cabac=1:bframes=2:keyint=6:open-gop=1", []),
|
||||
("partitions_all", "noise", 176, 144, 8, "cabac=1:bframes=2:partitions=all:8x8dct=1:subme=9:me=umh", []),
|
||||
("cavlc_partitions_all", "noise", 176, 144, 8, "cabac=0:bframes=2:partitions=all:8x8dct=1:subme=9", []),
|
||||
]
|
||||
|
||||
BENCH = [
|
||||
("qvga_cabac_b", "testsrc2", 320, 240, 30, "cabac=1:bframes=3:ref=3:crf=23"),
|
||||
("qvga_baseline", "testsrc2", 320, 240, 30, "cabac=0:bframes=0:ref=1:8x8dct=0:crf=23"),
|
||||
("nhd_cabac_b", "testsrc2", 640, 360, 30, "cabac=1:bframes=3:ref=3:crf=23"),
|
||||
("nhd_baseline", "testsrc2", 640, 360, 30, "cabac=0:bframes=0:ref=1:8x8dct=0:crf=23"),
|
||||
("qvga_mandel_high", "mandel", 320, 240, 30, "cabac=1:bframes=3:ref=3:8x8dct=1:crf=23"),
|
||||
("qvga_mandel_base", "mandel", 320, 240, 30, "cabac=0:bframes=0:ref=1:8x8dct=0:crf=23"),
|
||||
("nhd_mandel_high", "mandel", 640, 360, 30, "cabac=1:bframes=3:ref=3:8x8dct=1:crf=23"),
|
||||
("nhd_mandel_base", "mandel", 640, 360, 30, "cabac=0:bframes=0:ref=1:8x8dct=0:crf=23"),
|
||||
]
|
||||
|
||||
|
||||
def ffmpeg(ctx, args):
|
||||
return ctx.nix("ffmpeg", ["ffmpeg", "-hide_banner", "-loglevel", "error", "-y"] + args)
|
||||
|
||||
|
||||
def encode(ctx, tmp, name, src, w, h, n, params, extra):
|
||||
out = os.path.join(tmp, name + ".h264")
|
||||
lav = SRC[src].format(w=w, h=h)
|
||||
ffmpeg(ctx, ["-f", "lavfi", "-i", lav, "-frames:v", str(n), "-pix_fmt", "yuv420p", "-c:v", "libx264",
|
||||
"-x264-params", params + ":threads=1", *extra, "-f", "h264", out])
|
||||
with open(out, "rb") as f:
|
||||
data = f.read()
|
||||
ref = os.path.join(tmp, name + ".yuv")
|
||||
ffmpeg(ctx, ["-threads", "1", "-i", out, "-fps_mode", "passthrough", "-f", "rawvideo", "-pix_fmt", "yuv420p", ref])
|
||||
with open(ref, "rb") as f:
|
||||
raw = f.read()
|
||||
fs = w * h + 2 * ((w + 1) // 2) * ((h + 1) // 2)
|
||||
frames = [zlib.crc32(raw[i:i + fs]) for i in range(0, len(raw), fs)]
|
||||
return data, frames
|
||||
|
||||
|
||||
def to_avcc(data):
|
||||
"""Annex B -> (avcC record, length-prefixed samples split at access unit delimiters / first slices)"""
|
||||
nals = []
|
||||
i = 0
|
||||
starts = []
|
||||
while True:
|
||||
j = data.find(b"\x00\x00\x01", i)
|
||||
if j < 0:
|
||||
break
|
||||
starts.append(j + 3)
|
||||
i = j + 3
|
||||
for k, s in enumerate(starts):
|
||||
e = starts[k + 1] - 3 if k + 1 < len(starts) else len(data)
|
||||
nal = data[s:e]
|
||||
while nal.endswith(b"\x00"):
|
||||
nal = nal[:-1]
|
||||
nals.append(nal)
|
||||
sps = [n for n in nals if n[0] & 31 == 7]
|
||||
pps = [n for n in nals if n[0] & 31 == 8]
|
||||
rec = bytes([1, sps[0][1], sps[0][2], sps[0][3], 0xFF, 0xE0 | len(sps)])
|
||||
for s in sps:
|
||||
rec += len(s).to_bytes(2, "big") + s
|
||||
rec += bytes([len(pps)])
|
||||
for p in pps:
|
||||
rec += len(p).to_bytes(2, "big") + p
|
||||
samples = []
|
||||
cur = b""
|
||||
has_slice = False
|
||||
for n in nals:
|
||||
t = n[0] & 31
|
||||
if t in (7, 8):
|
||||
continue
|
||||
# a new access unit: SEI / AUD after a slice, or a slice with first_mb_in_slice == 0 (first bit 1)
|
||||
if has_slice and (t in (6, 9) or (t in (1, 5) and n[1] & 0x80)):
|
||||
samples.append(cur)
|
||||
cur = b""
|
||||
has_slice = False
|
||||
cur += len(n).to_bytes(4, "big") + n
|
||||
if t in (1, 5):
|
||||
has_slice = True
|
||||
if cur:
|
||||
samples.append(cur)
|
||||
return rec, samples
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
cases = []
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
for name, src, w, h, n, params, extra in CASES:
|
||||
data, frames = encode(ctx, tmp, name, src, w, h, n, params, extra)
|
||||
c = {"name": name, "data": data, "width": w, "height": h, "frames": frames}
|
||||
if name in ("cabac_b3", "cavlc_p"):
|
||||
rec, samples = to_avcc(data)
|
||||
c["avcc"] = rec
|
||||
c["samples"] = samples
|
||||
cases.append(c)
|
||||
ctx.emit("h264_cases", cases)
|
||||
bad = []
|
||||
lav = SRC["testsrc2"].format(w=64, h=64)
|
||||
out = os.path.join(tmp, "interlaced.h264")
|
||||
ffmpeg(ctx, ["-f", "lavfi", "-i", lav, "-frames:v", "4", "-pix_fmt", "yuv420p", "-c:v", "libx264",
|
||||
"-x264-params", "interlaced=1:threads=1", "-f", "h264", out])
|
||||
bad.append({"name": "interlaced", "data": open(out, "rb").read(), "code": "UNSUPPORTED"})
|
||||
out = os.path.join(tmp, "yuv444.h264")
|
||||
ffmpeg(ctx, ["-f", "lavfi", "-i", lav, "-frames:v", "2", "-pix_fmt", "yuv444p", "-c:v", "libx264",
|
||||
"-x264-params", "threads=1", "-f", "h264", out])
|
||||
bad.append({"name": "yuv444", "data": open(out, "rb").read(), "code": "UNSUPPORTED"})
|
||||
out = os.path.join(tmp, "yuv422.h264")
|
||||
ffmpeg(ctx, ["-f", "lavfi", "-i", lav, "-frames:v", "2", "-pix_fmt", "yuv422p", "-c:v", "libx264",
|
||||
"-x264-params", "threads=1", "-f", "h264", out])
|
||||
bad.append({"name": "yuv422", "data": open(out, "rb").read(), "code": "UNSUPPORTED"})
|
||||
out = os.path.join(tmp, "10bit.h264")
|
||||
ffmpeg(ctx, ["-f", "lavfi", "-i", lav, "-frames:v", "2", "-pix_fmt", "yuv420p10le", "-c:v", "libx264",
|
||||
"-x264-params", "threads=1", "-f", "h264", out])
|
||||
bad.append({"name": "10bit", "data": open(out, "rb").read(), "code": "UNSUPPORTED"})
|
||||
ctx.emit("h264_bad", bad)
|
||||
# containers: the same encodes written by ffmpeg into MP4 / MKV (avcC) and TS / AVI (Annex B), referenced by ffmpeg's decode of each file
|
||||
cont = []
|
||||
for name, params, n in (("cabac_b", "cabac=1:bframes=3:ref=3:8x8dct=1", 20), ("baseline", "cabac=0:bframes=0:ref=2", 12)):
|
||||
raw = os.path.join(tmp, "c_" + name + ".h264")
|
||||
ffmpeg(ctx, ["-f", "lavfi", "-i", SRC["noise"].format(w=176, h=144), "-frames:v", str(n), "-pix_fmt", "yuv420p",
|
||||
"-c:v", "libx264", "-x264-params", params + ":threads=1", "-f", "h264", raw])
|
||||
for ext in ("h264", "mp4", "mkv", "ts", "avi"):
|
||||
path = raw if ext == "h264" else os.path.join(tmp, "c_%s.%s" % (name, ext))
|
||||
if ext != "h264":
|
||||
ffmpeg(ctx, ["-f", "lavfi", "-i", SRC["noise"].format(w=176, h=144), "-frames:v", str(n), "-pix_fmt", "yuv420p",
|
||||
"-c:v", "libx264", "-x264-params", params + ":threads=1", path])
|
||||
yuv = path + ".yuv"
|
||||
ffmpeg(ctx, ["-threads", "1", "-i", path, "-fps_mode", "passthrough", "-f", "rawvideo", "-pix_fmt", "yuv420p", yuv])
|
||||
rawyuv = open(yuv, "rb").read()
|
||||
fs = 176 * 144 * 3 // 2
|
||||
cont.append({"name": name + "." + ext, "ext": ext, "data": open(path, "rb").read(), "width": 176, "height": 144,
|
||||
"frames": [zlib.crc32(rawyuv[i:i + fs]) for i in range(0, len(rawyuv), fs)]})
|
||||
ctx.emit("h264_containers", cont)
|
||||
bench = []
|
||||
for name, src, w, h, n, params in BENCH:
|
||||
data, frames = encode(ctx, tmp, name, src, w, h, n, params, [])
|
||||
bench.append({"name": name, "data": data, "width": w, "height": h, "frames": frames})
|
||||
ctx.emit("h264_bench", bench)
|
||||
@@ -0,0 +1,82 @@
|
||||
# H.264 conformance fixtures (tools/fixtures.py): a selection of the ITU-T H.264.1 / JVT conformance bitstreams
|
||||
# (freely downloadable from https://www.itu.int/wftp3/av-arch/jvt-site/draft_conformance/), downloaded once into
|
||||
# tests/gen/jvt_cache/. Reference frames: the decoded .yuv shipped in each zip (the JM reference decoder's output) when
|
||||
# it has the expected size, else ffmpeg's decode (-fps_mode passthrough). Per-frame CRC-32 of yuv420p.
|
||||
# tests/gen/h264_jvt.luau { name, data64 (the bitstream, base64), width, height, frames = { crc ... }, ref = "jm" | "ffmpeg", expect = "ok" |
|
||||
# "UNSUPPORTED" } (empty when the site cannot be reached)
|
||||
import base64, json, os, subprocess, urllib.request, zipfile, zlib
|
||||
|
||||
INPUTS = []
|
||||
|
||||
BASE = "https://www.itu.int/wftp3/av-arch/jvt-site/draft_conformance/"
|
||||
OK = [
|
||||
"AVCv1/BA1_Sony_D", "AVCv1/BA2_Sony_F", "AVCv1/BA3_SVA_C", "AVCv1/BA_MW_D", "AVCv1/BANM_MW_D", "AVCv1/BAMQ2_JVC_C",
|
||||
"AVCv1/BASQP1_Sony_C", "AVCv1/CABA1_SVA_B", "AVCv1/CABA2_Sony_E", "AVCv1/CABA3_SVA_B", "AVCv1/CABA3_TOSHIBA_E",
|
||||
"AVCv1/CABACI3_Sony_B", "AVCv1/CABAST3_Sony_E", "AVCv1/CACQP3_Sony_D", "AVCv1/CANL2_Sony_E", "AVCv1/CANL3_SVA_B",
|
||||
"AVCv1/CANL4_SVA_B", "AVCv1/CAQP1_Sony_B", "AVCv1/CI_MW_D", "AVCv1/CVBS3_Sony_C", "AVCv1/CVFC1_Sony_C",
|
||||
"AVCv1/CVSE2_Sony_B", "AVCv1/CVSEFDFT3_Sony_E", "AVCv1/CVWP3_TOSHIBA_E", "AVCv1/MIDR_MW_D", "AVCv1/MPS_MW_A",
|
||||
"AVCv1/MR1_BT_A", "AVCv1/MR1_MW_A", "AVCv1/MR2_TANDBERG_E", "AVCv1/MR4_TANDBERG_C", "AVCv1/NL2_Sony_H",
|
||||
"AVCv1/NLMQ2_JVC_C", "AVCv1/NRF_MW_E", "AVCv1/SL1_SVA_B", "AVCv1/SVA_BA2_D", "AVCv1/SVA_CL1_E", "AVCv1/SVA_FM1_E",
|
||||
"AVCv1/SVA_NL2_E", "AVCv1/cavlc_mot_frm0_full_B", "AVCv1/cabac_mot_frm0_full", "FRExt/FRExt1_Panasonic_D",
|
||||
"FRExt/FRExt3_Panasonic_E", "FRExt/HCAFR1_HHI_C", "FRExt/HCAFR2_HHI_A", "FRExt/HCBP2_HHI_A", "FRExt/HCMP1_HHI_A",
|
||||
"FRExt/brcm_freh3", "FRExt/freh12_b",
|
||||
]
|
||||
UNSUPPORTED = ["FRExt/HCAFF1_HHI_B", "FRExt/HCAMFF1_HHI_B", "AVCv1/SP1_BT_A", "FRExt/Hi422FR1_SONY_A"]
|
||||
EXT = (".jsv", ".264", ".h264", ".avc", ".26l", ".jvt")
|
||||
|
||||
|
||||
def fetch(ctx, item):
|
||||
cache = os.path.join(ctx.gen, "jvt_cache")
|
||||
os.makedirs(cache, exist_ok=True)
|
||||
path = os.path.join(cache, item.split("/")[1] + ".zip")
|
||||
if not os.path.exists(path):
|
||||
try:
|
||||
with urllib.request.urlopen(BASE + item + ".zip", timeout=120) as r:
|
||||
data = r.read()
|
||||
except Exception as e:
|
||||
print("h264_jvt: cannot download %s: %s" % (item, e))
|
||||
return None
|
||||
with open(path, "wb") as f:
|
||||
f.write(data)
|
||||
return path
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
ff = ctx.nix("ffmpeg", ["sh", "-c", "command -v ffmpeg"]).decode().strip()
|
||||
fp = os.path.join(os.path.dirname(ff), "ffprobe")
|
||||
out = []
|
||||
for item in OK + UNSUPPORTED:
|
||||
z = fetch(ctx, item)
|
||||
if not z:
|
||||
continue
|
||||
zf = zipfile.ZipFile(z)
|
||||
names = zf.namelist()
|
||||
bs = [n for n in names if n.lower().endswith(EXT)]
|
||||
if not bs:
|
||||
continue
|
||||
data = zf.read(bs[0])
|
||||
name = item.split("/")[1]
|
||||
tmp = os.path.join(ctx.gen, "jvt_cache", name + ".bit")
|
||||
with open(tmp, "wb") as f:
|
||||
f.write(data)
|
||||
if item in UNSUPPORTED:
|
||||
out.append({"name": name, "data64": base64.b64encode(data).decode(), "width": 0, "height": 0, "frames": [], "ref": "none", "expect": "UNSUPPORTED"})
|
||||
continue
|
||||
st = json.loads(subprocess.run([fp, "-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height",
|
||||
"-of", "json", tmp], capture_output=True, text=True).stdout)["streams"][0]
|
||||
w, h = st["width"], st["height"]
|
||||
fs = w * h * 3 // 2
|
||||
raw = subprocess.run([ff, "-v", "error", "-threads", "1", "-i", tmp, "-fps_mode", "passthrough", "-f", "rawvideo",
|
||||
"-pix_fmt", "yuv420p", "-"], capture_output=True).stdout
|
||||
frames = [zlib.crc32(raw[i:i + fs]) for i in range(0, len(raw), fs)]
|
||||
ref = "ffmpeg"
|
||||
yuvs = [n for n in names if n.lower().endswith(".yuv")]
|
||||
if yuvs:
|
||||
jm = zf.read(yuvs[0])
|
||||
if len(jm) == len(frames) * fs:
|
||||
jmf = [zlib.crc32(jm[i:i + fs]) for i in range(0, len(jm), fs)]
|
||||
if jmf != frames:
|
||||
print("h264_jvt: %s: JM and ffmpeg references differ, using JM" % name)
|
||||
frames, ref = jmf, "jm"
|
||||
out.append({"name": name, "data64": base64.b64encode(data).decode(), "width": w, "height": h, "frames": frames, "ref": ref, "expect": "ok"})
|
||||
ctx.emit("h264_jvt", out)
|
||||
Reference in new issue
Block a user