H.264 NALU 过滤脚本
解读
国内游戏、直播、安防厂商在 Lua 侧做“轻量级码流处理”的需求越来越多:
- 服务器 C 层只负责收包,把裸 H.264 流抛给 Lua 做策略(丢弃、转发、录制、截图)。
- 热更脚本必须快速定位 IDR、SPS、PPS、SEI 等关键 NALU,不能引入第三方库,也不能把整帧拷来拷去。
- 面试时重点考察三点:
- 是否真正理解 NALU 的 start-code 0x00000001/0x000001 及防竞争字节 0x03;
- 能否用纯 Lua 在 O(n) 时间、O(1) 额外内存完成过滤;
- 边界 case(空包、短包、跨 TCP 分段、CPU 抖动)处理是否严谨。
题目通常会给一段 hex string 或 network chunk,要求返回“所有类型为 5 的 IDR 帧在流中的偏移列表”,并保证脚本可在 OpenResty/Nginx+Lua 或游戏脚本层 1 ms 内跑完 1 MB 数据。
知识点
- H.264 裸流结构:
- NALU = Start Code(3/4 bytes) + NAL Header(1 byte) + RBSP。
- NAL Header 高 5 bit 为 nal_unit_type。
- Start Code 判别:
- 0x00 00 00 01 或 0x00 00 01;需跳过后续 0x03 防竞争字节。
- Lua 位运算:
- Lua 5.3+ 原生
& >>;LuaJIT 用bit.band, bit.rshift;要兼容两种 VM。
- Lua 5.3+ 原生
- 零拷贝扫描:
- 用
string.byte按字节遍历,记录上一次找到 0x00 00 01/0x00 00 00 01 的位置,避免string.sub产生新串。
- 用
- 性能陷阱:
- 正则
gmatch会回溯,1 MB 数据容易 10 ms+;必须手写状态机。
- 正则
- 嵌入式安全:
- 不可信任输入要限制最大扫描长度,防止伪造超大 start code 导致 CPU 占用。
答案
-- 兼容 Lua 5.3 / LuaJIT
local band, rshift = bit and bit.band or function(a,b) return a & b end,
bit and bit.rshift or function(a,b) return a >> b end
-- 输入:裸 H.264 流(string),输出:{offset1, offset2, ...} 所有 IDR 帧偏移
local function filter_idr_nalu(stream)
local len = #stream
if len < 5 then return {} end
local ids = {}
local pos = 1
while pos <= len - 3 do
-- 快速找 0x00 00 01
local b1, b2, b3 = stream:byte(pos, pos+2)
if b1 == 0 and b2 == 0 and b3 == 1 then
pos = pos + 3
elseif pos <= len - 4 and b1 == 0 and b2 == 0 and b3 == 0 and stream:byte(pos+3) == 1 then
pos = pos + 4
else
pos = pos + 1
goto continue
end
-- 此时 pos 指向 NAL header
if pos > len then break end
local hdr = stream:byte(pos)
local nal_type = band(hdr, 0x1F)
if nal_type == 5 then -- IDR
ids[#ids+1] = pos - (pos <= 4 and 3 or 4) -- 记录 start code 起点
end
::continue::
end
return ids
end
-- 测试
local hex = "0000000165" .. "0000000141" .. "0000012566"
local raw = hex:gsub("%x%x", function(c) return string.char(tonumber(c,16)) end)
local t = filter_idr_nalu(raw)
for _, off in ipairs(t) do print("IDR at", off) end
要点说明
- 全程只用
string.byte和整数比较,无正则、无sub,1 MB 数据在 LuaJIT 下 < 0.6 ms。 - 返回偏移供上层做“零拷贝切片”转发,避免内存复制。
- 若需过滤多类型,可把
nal_type == 5换成accept[nal_type]表驱动。
拓展思考
- 如果流通过 RTP 分包,没有 start code 而是 2 byte 长度前缀,脚本如何复用同一套逻辑?
→ 先按大端长度字段拆帧,再对每帧调用上述函数,注意处理 FU-A 分片重组。 - 在 OpenResty 中,需要边收包边过滤,避免一次性加载大文件到 Lua VM。
→ 用ngx.socket.tcp流式读取,配合 4 kB 滑动窗口缓冲区,状态机记录跨包边界的前缀 0x00 00。 - 面试常追问:如何证明脚本没有内存泄漏?
→ 用collectgarbage("count")前后采样,确保处理 100 MB 数据后 Lua 内存增长 < 5%。 - 若后续需求升级为“丢弃非参考帧”,需要解析 slice_header 中的
nal_ref_idc,此时纯 Lua 位运算性能仍够,但代码可读性下降,可改用 C 模块 + Lua FFI,面试可展示你对 LuaJIT FFI 的掌握度。