ws-video2-flv: video/flv (FLV demux: tags, onMetaData AMF0, Sorenson / H.264 (avcC, composition times) / VP6 / screen video / enhanced FourCC tracks, MP3 / AAC / PCM / G.711 / ADPCM / Nellymoser / Speex audio, keyframe seek; FLV mux: H.264 / Sorenson / VP6 / screen copied, AAC (ADTS re-framed) / MP3 / PCM audio, onMetaData)

Outside the folder: codecs/video/Video BUILTIN gains known (decoder-less) entries vp6f, vp6a, flashsv, flashsv2.
This commit is contained in:
4DBug committed 2026-10-31 15:09:20 -05:00
1 parent 2a5da31c80
commit efc0812746
9 files changed
+1230

No files matched your search

+1
View File
@@ -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 | flv | .flv .f4v | yes | yes | streaming: true, remux: true, video: "flv1", "h264", audio: true, metadata: true | `tests/video/flv.luau` |
| video | h264 | .h264 .264 .avc .jsv .26l .jvt | yes | yes | streaming: true, video: "h264", depths: 8 | `tests/video/h264.luau` |
| video | mkv | .mkv .webm .mka .mk3d | yes | yes | streaming: true, remux: true, video: "vp8", "mjpeg", "mpeg1", "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` |
+12
View File
@@ -290,6 +290,18 @@ local list: { Entry } = {
return require("@formats/video/avi")
end,
},
{
name = "flv",
category = "video",
path = "video/flv",
extensions = { "flv", "f4v" },
mime = { "video/x-flv", "video/flv" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Demux", "codecs/video/Video", "codecs/video/Video/Source", "codecs/video/H263", "codecs/video/H264", "codecs/audio/Aac" },
caps = { decode = true, encode = true, streaming = true, remux = true, video = { "flv1", "h264" }, audio = true, metadata = true },
load = function()
return require("@formats/video/flv")
end,
},
{
name = "h264",
category = "video",
+4
View File
@@ -280,6 +280,10 @@ local BUILTIN: { Entry } = {
{ id = "theora", name = "Theora", matroska = { "V_THEORA" } },
{ id = "h263", name = "H.263", fourcc = { "H263", "h263", "s263", "U263" }, new = h263Decoder },
{ id = "flv1", name = "Sorenson Spark (FLV1)", fourcc = { "FLV1" }, new = h263Decoder },
{ id = "vp6f", name = "On2 VP6 (Flash)", fourcc = { "VP6F", "FLV4" } },
{ id = "vp6a", name = "On2 VP6 with alpha (Flash)", fourcc = { "VP6A" } },
{ id = "flashsv", name = "Flash Screen Video", fourcc = { "FSV1" } },
{ id = "flashsv2", name = "Flash Screen Video 2" },
{ id = "png", name = "PNG", fourcc = { "png ", "MPNG" }, matroska = { "V_PNG" } },
}
+166
View File
@@ -0,0 +1,166 @@
--!strict
-- video/flv/Amf: AMF0 values (Adobe's Action Message Format 0, as FLV script data tags use it). Written from the AMF0
-- specification and the FLV specification v10. Read: number, boolean, string, object, null, undefined, reference
-- (the referenced object), ECMA array, strict array, date (milliseconds), long string; anything else stops the
-- value. Write: numbers, booleans, strings, strict arrays and ECMA arrays (ordered key / value lists). Never throws.
--
-- local name, value = Amf.script(reader) -- a script tag body: "onMetaData", { duration = 12.3, ... }
-- Amf.writeValue(w, v); Amf.writeEcma(w, { { "duration", 12.3 }, ... })
local Bytes = require("@formats/core/Bytes")
local Amf = {}
-- null / undefined inside arrays (dropped from objects)
Amf.NULL = table.freeze({})
local MAX_DEPTH = 32
local function str(r: Bytes.Reader, long: boolean): string
local n = if long then r:u32be() else r:u16be()
return r:string(n)
end
local readValue: (r: Bytes.Reader, depth: number, refs: { any }) -> any
-- object properties up to the end marker (00 00 09) or the end of the data
local function props(r: Bytes.Reader, depth: number, refs: { any }, into: { [string]: any }): boolean
while not r.err and r:remaining() >= 3 do
local key = str(r, false)
if key == "" and r:peekU8() == 9 then
r:skip(1)
return true
end
local v = readValue(r, depth + 1, refs)
if r.err or v == nil then
return false
end
if v ~= Amf.NULL then
into[key] = v
end
end
return false
end
readValue = function(r: Bytes.Reader, depth: number, refs: { any }): any
if depth > MAX_DEPTH or r:remaining() < 1 then
return nil
end
local t = r:u8()
if t == 0 then
return r:f64be()
elseif t == 1 then
return r:u8() ~= 0
elseif t == 2 then
return str(r, false)
elseif t == 12 then
return str(r, true)
elseif t == 3 or t == 8 then
if t == 8 then
r:u32be() -- the count (approximate in practice: the end marker ends it)
end
local o: { [string]: any } = {}
table.insert(refs, o)
props(r, depth, refs, o)
return o
elseif t == 10 then
local n = r:u32be()
local a: { any } = {}
table.insert(refs, a)
for i = 1, n do
if r.err or r:remaining() < 1 then
break
end
local v = readValue(r, depth + 1, refs)
if v == nil then
break
end
a[i] = v
end
return a
elseif t == 5 or t == 6 then
return Amf.NULL
elseif t == 7 then
local i = r:u16be()
return refs[i + 1] or Amf.NULL
elseif t == 11 then
local ms = r:f64be()
r:i16be()
return ms
end
return nil
end
-- value(reader) -> the next AMF0 value | nil (unknown type, truncated, nested too deep)
function Amf.value(r: Bytes.Reader): any
local ok, v = pcall(readValue, r, 0, {})
return if ok and not r.err then v else nil
end
-- script(reader) -> name, value: a script data tag body (an AMF0 string, then its value) | nil
function Amf.script(r: Bytes.Reader): (string?, any)
local name = Amf.value(r)
if type(name) ~= "string" then
return nil, nil
end
return name, Amf.value(r)
end
-- ------------------------------------------------------------------------------------------------ write
local function writeString(w: Bytes.Writer, s: string)
if #s > 65535 then
w:u8(12)
w:u32be(#s)
else
w:u8(2)
w:u16be(#s)
end
w:string(s)
end
-- writeValue(w, v): a number, boolean, string, array (strict array) or Amf.NULL; other values are written as null
function Amf.writeValue(w: Bytes.Writer, v: any)
local t = type(v)
if t == "number" then
w:u8(0)
w:f64be(v)
elseif t == "boolean" then
w:u8(1)
w:u8(if v then 1 else 0)
elseif t == "string" then
writeString(w, v)
elseif t == "table" and v ~= Amf.NULL and #v > 0 then
w:u8(10)
w:u32be(#v)
for _, x in v do
Amf.writeValue(w, x)
end
else
w:u8(5)
end
end
-- writeEcma(w, list): an ECMA array of { key, value } pairs (values: as writeValue; a list nested as
-- { key, { pairs = { ... } } } becomes an object)
function Amf.writeEcma(w: Bytes.Writer, list: { { any } }, object: boolean?)
if object then
w:u8(3)
else
w:u8(8)
w:u32be(#list)
end
for _, kv in list do
local k: string = kv[1]
w:u16be(#k)
w:string(k)
local v = kv[2]
if type(v) == "table" and v.pairs then
Amf.writeEcma(w, v.pairs, true)
else
Amf.writeValue(w, v)
end
end
w:u16be(0)
w:u8(9)
end
return Amf
+288
View File
@@ -0,0 +1,288 @@
--!strict
-- video/flv/Mux: the FLV writer (Adobe's Video File Format Specification v10): the header, an onMetaData script tag
-- (duration, width, height, data rates, frame rate, codec ids, audio format, encoder, file size), the H.264
-- AVCDecoderConfigurationRecord / AAC AudioSpecificConfig sequence headers, the packets of codecs/video/Video/Source
-- streams as tags interleaved by decode time (milliseconds, shifted so none is negative; H.264 composition times),
-- and H.264's end-of-sequence tag. AAC from ADTS sources (MPEG-TS) is split into raw frames with a configuration made
-- from the first ADTS header. Interpreted; never throws (returns nil, Err).
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Amf = require("@formats/video/flv/Amf")
local Mux = {}
-- the codecs FLV holds (copied from the source)
local VIDEO_COPY: { [string]: boolean } = { h264 = true, flv1 = true, vp6f = true, vp6a = true, flashsv = true, flashsv2 = true }
local AUDIO_COPY: { [string]: boolean } = { aac = true, mp3 = true, pcm_s16le = true, pcm_u8 = true, pcm_alaw = true, pcm_mulaw = true, adpcm_swf = true, nellymoser = true, speex = true }
Mux.VIDEO_COPY = VIDEO_COPY
Mux.AUDIO_COPY = AUDIO_COPY
local VIDEO_IDS: { [string]: number } = { flv1 = 2, flashsv = 3, vp6f = 4, vp6a = 5, flashsv2 = 6, h264 = 7 }
local AUDIO_FORMATS: { [string]: number } = { pcm_s16le = 3, pcm_u8 = 3, adpcm_swf = 1, mp3 = 2, nellymoser = 6, pcm_alaw = 7, pcm_mulaw = 8, aac = 10, speex = 11 }
local RATE_CODES: { [number]: number } = { [5512] = 0, [5513] = 0, [11025] = 1, [22050] = 2, [44100] = 3 }
local AAC_RATES = { 96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350 }
local function isAdts(s: any): boolean
if s.track and s.track.adts then
return true
end
local p = s.packets[1]
return s.config == nil and p ~= nil and buffer.len(p.data) >= 7 and buffer.readu8(p.data, 0) == 0xFF and buffer.readu8(p.data, 1) >= 0xF0
end
-- audioProblem(stream) -> why FLV cannot hold this audio stream | nil
function Mux.audioProblem(s: any): string?
local fmt = AUDIO_FORMATS[s.codec]
if not fmt then
return "FLV has no audio codec " .. tostring(s.codec)
end
if (s.channels or 1) > 2 then
return "FLV audio has at most 2 channels"
end
local rate = math.floor((s.sampleRate or 0) + 0.5)
if s.codec == "aac" then
if not s.config and not isAdts(s) then
return "AAC without its AudioSpecificConfig"
end
elseif (s.codec == "pcm_alaw" or s.codec == "pcm_mulaw") and rate ~= 8000 then
return "FLV G.711 audio is 8000 Hz (not " .. rate .. ")"
elseif s.codec ~= "mp3" and s.codec ~= "speex" and s.codec ~= "nellymoser" and s.codec ~= "pcm_alaw" and s.codec ~= "pcm_mulaw" and RATE_CODES[rate] == nil then
return "FLV " .. s.codec .. " audio is 5512, 11025, 22050 or 44100 Hz (not " .. rate .. ")"
end
return nil
end
local function audioFlags(s: any): number
local fmt = AUDIO_FORMATS[s.codec]
local rate = math.floor((s.sampleRate or 44100) + 0.5)
local rc = RATE_CODES[rate] or 3
local size = if s.codec == "pcm_u8" then 0 else 1
local stereo = if (s.channels or 1) > 1 then 1 else 0
if s.codec == "aac" then
rc, stereo = 3, 1
elseif s.codec == "mp3" and rate == 8000 then
fmt = 14
elseif s.codec == "speex" then
rc, stereo = 0, 0
elseif s.codec == "pcm_alaw" or s.codec == "pcm_mulaw" then
rc = 0
elseif s.codec == "nellymoser" then
if rate == 16000 then
fmt = 4
elseif rate == 8000 then
fmt = 5
end
stereo = 0
end
return fmt * 16 + rc * 4 + size * 2 + stereo
end
-- ADTS frames -> raw AAC frames (1024 samples each) and the AudioSpecificConfig of the first header
local function fromAdts(s: any): ({ any }?, buffer?)
local out = {}
local cfg: buffer? = nil
local rate = s.sampleRate or 44100
for _, p in s.packets do
local d: buffer = p.data
local n = buffer.len(d)
local o = 0
local t = p.pts
while o + 7 <= n do
local b1, b2, b3 = buffer.readu8(d, o + 1), buffer.readu8(d, o + 2), buffer.readu8(d, o + 3)
if buffer.readu8(d, o) ~= 0xFF or b1 < 0xF0 then
return nil, nil
end
local len = (b3 % 4) * 2048 + buffer.readu8(d, o + 4) * 8 + buffer.readu8(d, o + 5) // 32
local hl = if b1 % 2 == 1 then 7 else 9
if len < hl or o + len > n then
return nil, nil
end
if not cfg then
local aot = b2 // 64 + 1
local sfi = (b2 // 4) % 16
local ch = (b2 % 2) * 4 + b3 // 64
cfg = buffer.create(2)
buffer.writeu8(cfg, 0, aot * 8 + sfi // 2)
buffer.writeu8(cfg, 1, (sfi % 2) * 128 + ch * 8)
rate = AAC_RATES[sfi + 1] or rate
end
local f = buffer.create(len - hl)
buffer.copy(f, 0, d, o + hl, len - hl)
table.insert(out, { pts = t, dts = t, duration = 1024 / rate, keyframe = true, data = f })
t += 1024 / rate
o += len
end
end
return out, cfg
end
local function f64At(b: buffer, at: number, v: number)
local t = buffer.create(8)
buffer.writef64(t, 0, v)
for i = 0, 7 do
buffer.writeu8(b, at + i, buffer.readu8(t, 7 - i))
end
end
-- mux(streams) -> buffer | nil, Err
function Mux.mux(streams: { any }): (buffer?, Err.Err?)
local video, audio = nil :: any, nil :: any
for _, s in streams do
if s.kind == "video" and not video then
if not VIDEO_IDS[s.codec] then
return nil, Err.new(Err.UNSUPPORTED, "FLV has no video codec " .. tostring(s.codec))
end
if s.codec == "h264" and (s.config == nil or buffer.len(s.config) < 7 or buffer.readu8(s.config, 0) ~= 1) then
return nil, Err.new(Err.UNSUPPORTED, "H.264 without an avcC (an Annex B source) cannot be written to FLV")
end
video = s
elseif s.kind == "audio" and not audio then
audio = s
end
end
if not video and not audio then
return nil, Err.new(Err.ARG, "no video or audio stream")
end
local aConfig: buffer? = audio and audio.config
local aPackets: { any } = audio and audio.packets or {}
if audio and audio.codec == "aac" and isAdts(audio) then
local pk, cfg = fromAdts(audio)
if not pk or not cfg then
return nil, Err.new(Err.CORRUPT, "bad ADTS AAC audio")
end
aPackets, aConfig = pk, cfg
end
local order: { { any } } = {} -- { kind, packet }
do
local vi, ai = 1, 1
local vp: { any } = if video then video.packets else {}
while vi <= #vp or ai <= #aPackets do
local a, v = aPackets[ai], vp[vi]
if v and (not a or (v.dts or v.pts) <= (a.dts or a.pts)) then
table.insert(order, { "video", v })
vi += 1
else
table.insert(order, { "audio", a })
ai += 1
end
end
end
-- times: milliseconds, shifted so the earliest decode time is 0 when any is negative
local shift = 0
local duration = 0
local vBytes, aBytes = 0, 0
for _, e in order do
local p = e[2]
local t = p.dts or p.pts
if t < -shift then
shift = -t
end
duration = math.max(duration, p.pts + (p.duration or 0))
if e[1] == "video" then
vBytes += buffer.len(p.data)
else
aBytes += buffer.len(p.data)
end
end
local function ms(t: number): number
return math.floor((t + shift) * 1000 + 0.5)
end
local w = Bytes.writer(65536 + vBytes + aBytes + #order * 20)
w:string("FLV")
w:u8(1)
w:u8((if audio then 4 else 0) + (if video then 1 else 0))
w:u32be(9)
w:u32be(0)
local function tag(kind: number, ts: number, head: { number }, data: buffer?)
local n = #head + (if data then buffer.len(data) else 0)
w:u8(kind)
w:u24be(n)
local t = ts % 0x100000000
w:u24be(t % 0x1000000)
w:u8(t // 0x1000000)
w:u24be(0)
for _, x in head do
w:u8(x)
end
if data then
w:bytes(data)
end
w:u32be(11 + n)
end
-- onMetaData
local props: { { any } } = { { "duration", duration } }
if video then
table.insert(props, { "width", video.width or 0 })
table.insert(props, { "height", video.height or 0 })
table.insert(props, { "videodatarate", if duration > 0 then vBytes * 8 / duration / 1000 else 0 })
table.insert(props, { "framerate", video.frameRate or 0 })
table.insert(props, { "videocodecid", VIDEO_IDS[video.codec] })
end
if audio then
local flags = audioFlags(audio)
table.insert(props, { "audiodatarate", if duration > 0 then aBytes * 8 / duration / 1000 else 0 })
table.insert(props, { "audiosamplerate", math.floor((audio.sampleRate or 44100) + 0.5) })
table.insert(props, { "audiosamplesize", if audio.codec == "pcm_u8" then 8 else 16 })
table.insert(props, { "stereo", (audio.channels or 1) > 1 })
table.insert(props, { "audiocodecid", flags // 16 })
end
table.insert(props, { "encoder", "formats-luau" })
table.insert(props, { "filesize", 0 })
local mw = Bytes.writer(512)
Amf.writeValue(mw, "onMetaData")
Amf.writeEcma(mw, props)
local metaBody = mw:finish()
local metaAt = w:tell() + 11
tag(18, 0, {}, metaBody)
local fileSizeAt = metaAt + buffer.len(metaBody) - 3 - 8 -- the last value (filesize) before the end marker
-- sequence headers
local vid = if video then VIDEO_IDS[video.codec] else 0
if video and video.codec == "h264" then
tag(9, 0, { 0x10 + vid, 0, 0, 0, 0 }, video.config)
end
local aflags = if audio then audioFlags(audio) else 0
if audio and audio.codec == "aac" then
tag(8, 0, { aflags, 0 }, aConfig)
end
local vp6 = if video and (video.codec == "vp6f" or video.codec == "vp6a") then video.config else nil
local vp6Byte = if vp6 and buffer.len(vp6) > 0 then buffer.readu8(vp6, 0) else 0
if video and (video.codec == "vp6f" or video.codec == "vp6a") and not vp6 then
local wd, ht = video.width or 0, video.height or 0
vp6Byte = ((16 - wd % 16) % 16) * 16 + (16 - ht % 16) % 16
end
local lastVideo = 0
for _, e in order do
local p = e[2]
local dts = ms(p.dts or p.pts)
if e[1] == "video" then
local ft = (if p.keyframe then 1 else 2) * 16 + vid
if video.codec == "h264" then
local cts = ms(p.pts) - dts
if cts < 0 then
cts += 0x1000000
end
tag(9, dts, { ft, 1, cts // 65536 % 256, cts // 256 % 256, cts % 256 }, p.data)
elseif vp6 or video.codec == "vp6f" or video.codec == "vp6a" then
tag(9, dts, { ft, vp6Byte }, p.data)
else
tag(9, dts, { ft }, p.data)
end
lastVideo = math.max(lastVideo, dts)
elseif audio.codec == "aac" then
tag(8, dts, { aflags, 1 }, p.data)
else
tag(8, dts, { aflags }, p.data)
end
end
if video and video.codec == "h264" then
tag(9, lastVideo, { 0x10 + vid, 2, 0, 0, 0 }, nil)
end
local out = w:finish()
f64At(out, fileSizeAt, buffer.len(out))
return out, nil
end
return Mux
+402
View File
@@ -0,0 +1,402 @@
--!strict
-- video/flv: Flash Video (FLV, Adobe's Video File Format Specification v10, and the Enhanced RTMP / FLV extension's
-- FourCC video tags). New in formats-luau.
-- Read: the header, the tag stream and onMetaData (AMF0: duration, width, height, framerate, codec ids, keyframes, ...
-- into meta.metadata) into a Demuxer (times in milliseconds; keyframe flags from the video tags; seeking by
-- keyframes) and open() returns a VideoDecoder: video through the codecs/video/Video registry (Sorenson Spark / FLV1
-- and H.264 decode; VP6 / VP6 alpha, screen video 1 / 2 and enhanced FourCC codecs (HEVC, AV1, VP9) are known tracks
-- whose decoding is UNSUPPORTED); H.264's AVCDecoderConfigurationRecord in track.config, composition time offsets
-- in the pts. Audio through the api's opts.openAudio hook: MP3 (also 8 kHz), AAC (AudioSpecificConfig in track.config),
-- linear PCM (platform-endian read as little-endian), A-law / mu-law; Flash ADPCM, Nellymoser and Speex are known
-- tracks without an audio decoder (UNSUPPORTED). Flv.demux(r) gives the Demuxer.
-- Write: H.264 / Sorenson Spark / VP6 / screen video copied from the source (FLV has no codec we encode), AAC / MP3 /
-- PCM / A-law / mu-law / ADPCM / Nellymoser / Speex audio copied (AAC from ADTS sources re-framed), else PCM s16 at
-- the FLV sample rates (5512 / 11025 / 22050 / 44100 Hz), with onMetaData (duration, sizes, frame rate, data
-- rates, codec ids, file size).
-- Not supported: encrypted tags (the track's packets are dropped, track.unsupported says so), multitrack and ModEx
-- enhanced packets (skipped), writing H.264 from Annex B sources (no avcC).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Demux = require("@formats/containers/Demux")
local Video = require("@formats/codecs/video/Video")
local Source = require("@formats/codecs/video/Video/Source")
local H263 = require("@formats/codecs/video/H263")
local H264 = require("@formats/codecs/video/H264")
local Aac = require("@formats/codecs/audio/Aac")
local Amf = require("@formats/video/flv/Amf")
local Mux = require("@formats/video/flv/Mux")
-- ------------------------------------------------------------------------------------------------ contract
local Flv = {
name = "flv",
category = "video",
extensions = { "flv", "f4v" },
mime = { "video/x-flv", "video/flv" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Demux", "codecs/video/Video", "codecs/video/Video/Source", "codecs/video/H263", "codecs/video/H264", "codecs/audio/Aac" },
caps = { decode = true, encode = true, streaming = true, remux = true, video = { "flv1", "h264" }, audio = true, metadata = true },
}
-- ------------------------------------------------------------------------------------------------ types
export type OpenOptions = {
rgba: boolean?, -- nextFrame returns rgba8 images (default false: yuv420p from the codec)
track: number?, -- the video track id (1 video, 2 audio)
audio: boolean?, -- false: do not open the audio track
maxPackets: number?, -- refuse files with more tags (default 2^24)
maxPixels: number?,
openAudio: any?, -- set by the api: (demuxer, track) -> audio Decoder
}
export type EncodeOptions = {
video: boolean?, -- false: no video
audio: boolean?, -- false: no audio; true: fail when the audio cannot be written (default: dropped)
reencodeAudio: boolean?, -- PCM s16 even when the audio could be copied
}
-- ------------------------------------------------------------------------------------------------ constants
Flv.VIDEO_ID = 1
Flv.AUDIO_ID = 2
-- SoundFormat -> codec id
local AUDIO_CODECS: { [number]: string } = {
[0] = "pcm", -- platform-endian (little-endian in practice)
[1] = "adpcm_swf",
[2] = "mp3",
[3] = "pcm",
[4] = "nellymoser",
[5] = "nellymoser",
[6] = "nellymoser",
[7] = "pcm_alaw",
[8] = "pcm_mulaw",
[10] = "aac",
[11] = "speex",
[14] = "mp3",
[15] = "device_specific",
}
local AUDIO_RATES = { [0] = 5512, 11025, 22050, 44100 }
-- the formats with a fixed rate (G.711: 8 kHz as ffmpeg reads them) / always mono
local FIXED_RATE: { [number]: number } = { [4] = 16000, [5] = 8000, [7] = 8000, [8] = 8000, [11] = 16000, [14] = 8000 }
local MONO: { [number]: boolean } = { [4] = true, [5] = true, [11] = true }
-- CodecID -> codec id
local VIDEO_CODECS: { [number]: string } = {
[2] = "flv1",
[3] = "flashsv",
[4] = "vp6f",
[5] = "vp6a",
[6] = "flashsv2",
[7] = "h264",
}
-- Enhanced FLV audio FourCCs
local AUDIO_FOURCC: { [string]: string } = { Opus = "opus", fLaC = "flac", mp4a = "aac", [".mp3"] = "mp3", ["ac-3"] = "ac3", ["ec-3"] = "eac3" }
-- ------------------------------------------------------------------------------------------------ sniff
function Flv.sniff(r: Bytes.Reader): number
if r:remaining() >= 9 and r:peek(3) == "FLV" then
return if r:peekU8(3) == 1 then 1 else 0.6
end
return 0
end
-- ------------------------------------------------------------------------------------------------ decode
local readu8 = buffer.readu8
local function u24(b: buffer, p: number): number
return readu8(b, p) * 65536 + readu8(b, p + 1) * 256 + readu8(b, p + 2)
end
local function s24(b: buffer, p: number): number
local v = u24(b, p)
return if v >= 0x800000 then v - 0x1000000 else v
end
local function copy(b: buffer, p: number, n: number): buffer
local c = buffer.create(n)
buffer.copy(c, 0, b, p, n)
return c
end
-- the picture size of a codec's first keyframe (Sorenson, VP6, screen video) | nil
local function frameSize(codec: string, b: buffer, p: number, n: number): (number?, number?)
if codec == "flv1" then
local h = H263.header(b, p, n, true)
if h then
return h.width, h.height
end
elseif (codec == "vp6f" or codec == "vp6a") and n >= 8 then
-- VP6 key frame header: type / quant / marker, version / profile / interlace, [16-bit offset], MB rows, MB
-- cols, display rows, display cols; the FLV adjustment byte (p - 1, before the frame) crops width / height
local adj = readu8(b, p - 1)
local q = p + (if codec == "vp6a" then 3 else 0)
if q + 6 > p + n or readu8(b, q) >= 128 then
return nil, nil
end
local b1 = readu8(b, q + 1)
local o = q + 2
if readu8(b, q) % 2 == 1 or (b1 // 2) % 4 == 0 then
o += 2
end
if o + 4 > p + n then
return nil, nil
end
local w = readu8(b, o + 3) * 16 - adj // 16
local h = readu8(b, o + 2) * 16 - adj % 16
if w > 0 and h > 0 then
return w, h
end
elseif (codec == "flashsv" or codec == "flashsv2") and n >= 4 then
return (readu8(b, p) % 16) * 256 + readu8(b, p + 1), (readu8(b, p + 2) % 16) * 256 + readu8(b, p + 3)
end
return nil, nil
end
-- demux(r, opts?) -> the Demuxer (containers/Demux) | nil, Err
function Flv.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?)
local o: OpenOptions = opts or {}
local b, base, limit = r.buf, r.base, r.limit
if limit - base < 9 or buffer.readstring(b, base, 3) ~= "FLV" then
return nil, Err.new(Err.CORRUPT, "not an FLV file (no FLV signature)", base)
end
local flags = readu8(b, base + 4)
local dataOffset = buffer.readu32(b, base + 5)
dataOffset = bit32.byteswap(dataOffset)
if dataOffset < 9 or base + dataOffset > limit then
return nil, Err.new(Err.CORRUPT, "bad header size " .. dataOffset, base + 5)
end
local meta: { [string]: any } = { version = readu8(b, base + 3), hasAudio = bit32.band(flags, 4) ~= 0, hasVideo = bit32.band(flags, 1) ~= 0 }
local tracks: { Types.Track } = {}
local dmx = Demux.new("flv", tracks, b, meta)
local vt: any, at: any = nil, nil
local keyOff, keyLen = -1, 0 -- the first video keyframe
local maxPackets = o.maxPackets or 2 ^ 24
local count = 0
local p = base + dataOffset + 4 -- after PreviousTagSize0
while p + 11 <= limit do
local tagType = bit32.band(readu8(b, p), 0x1F)
local filtered = bit32.band(readu8(b, p), 0x20) ~= 0
local size = u24(b, p + 1)
local ts = u24(b, p + 4) + readu8(b, p + 7) * 0x1000000
if ts >= 0x80000000 then
ts -= 0x100000000
end
local d = p + 11
if d + size > limit then
meta.truncated = true
break
end
count += 1
if count > maxPackets then
return nil, Err.new(Err.LIMIT, "more than " .. maxPackets .. " tags")
end
if tagType == 8 and size >= 1 then
local a = readu8(b, d)
local fmt = a // 16
if not at then
at = { id = Flv.AUDIO_ID, kind = "audio", codec = "unknown", codecTag = "flv audio " .. fmt, timescale = 1000, default = true }
table.insert(tracks, at)
local bits = if (a // 2) % 2 == 1 then 16 else 8
local codec = AUDIO_CODECS[fmt] or ("flv_audio_" .. fmt)
if codec == "pcm" then
codec = if bits == 16 then "pcm_s16le" else "pcm_u8"
end
at.codec = codec
at.soundFormat = fmt
at.sampleRate = FIXED_RATE[fmt] or AUDIO_RATES[(a // 4) % 4]
at.channels = if MONO[fmt] then 1 else a % 2 + 1
at.bitsPerSample = if codec == "pcm_alaw" or codec == "pcm_mulaw" then 8 else bits
end
if filtered then
at.unsupported = "encrypted audio tags"
elseif fmt == 10 and at.soundFormat == 10 then
if size >= 2 then
if readu8(b, d + 1) == 0 then
local c = copy(b, d + 2, size - 2)
at.config = c
local cfg = Aac.config(c)
if cfg then
at.sampleRate = cfg.extensionRate or cfg.sampleRate
at.channels = cfg.channels
end
elseif size > 2 then
dmx:add(at.id, ts, nil, nil, true, d + 2, size - 2)
end
end
elseif fmt == 9 and at.soundFormat == 9 then
-- Enhanced FLV: packet type, FourCC
if size >= 5 then
local pt = a % 16
local fcc = buffer.readstring(b, d + 1, 4)
at.codec = AUDIO_FOURCC[fcc] or fcc
at.codecTag = fcc
if pt == 0 then
at.config = copy(b, d + 5, size - 5)
elseif pt == 1 and size > 5 then
dmx:add(at.id, ts, nil, nil, true, d + 5, size - 5)
end
end
elseif fmt == at.soundFormat and size > 1 then
dmx:add(at.id, ts, nil, nil, true, d + 1, size - 1)
end
elseif tagType == 9 and size >= 1 then
local v = readu8(b, d)
local enhanced = v >= 128
local frameType = if enhanced then (v // 16) % 8 else v // 16
if frameType ~= 5 then -- not a video info / command frame
local codec: string?, codecTag: string? = nil, nil
local pt, cts, q, n = 0, 0, 0, 0
if enhanced then
if size < 5 then
codec = nil
else
local fcc = buffer.readstring(b, d + 1, 4)
codec, codecTag = Video.fromFourcc(fcc) or fcc, fcc
pt = v % 16
q, n, cts = d + 5, size - 5, 0
if pt == 1 and (fcc == "avc1" or fcc == "hvc1") then
if n >= 3 then
cts = s24(b, q)
end
q, n = q + 3, n - 3
elseif pt == 3 then
pt = 1 -- coded frames without a composition time
end
end
else
local id = v % 16
codec = VIDEO_CODECS[id] or ("flv_video_" .. id)
codecTag = "flv video " .. id
pt, q, n, cts = 1, d + 1, size - 1, 0
if codec == "h264" then
if size >= 5 then
pt = readu8(b, d + 1)
cts = s24(b, d + 2)
else
pt = 2
end
q, n = d + 5, size - 5
elseif codec == "vp6f" or codec == "vp6a" then
q, n = d + 2, size - 2 -- after the adjustment byte (the track's config, as ffmpeg's extradata)
end
end
if codec then
if not vt then
vt = { id = Flv.VIDEO_ID, kind = "video", codec = codec, codecTag = codecTag, timescale = 1000, default = true }
table.insert(tracks, vt)
end
if (codec == "vp6f" or codec == "vp6a") and not vt.config and size >= 2 then
vt.config = copy(b, d + 1, 1) -- the crop (adjustment) byte
end
if filtered then
vt.unsupported = "encrypted video tags"
elseif codec == vt.codec then
if pt == 0 then
if n > 0 then
vt.config = copy(b, q, n)
end
elseif pt == 1 and n > 0 then
local key = frameType == 1
dmx:add(vt.id, ts + cts, ts, nil, key, q, n)
if key and keyOff < 0 then
keyOff, keyLen = q, n
end
end
end
end
end
elseif tagType == 18 and size > 0 then
local name, value = Amf.script(Bytes.reader(b, d, size))
if name == "onMetaData" and type(value) == "table" and meta.metadata == nil then
meta.metadata = value
elseif name then
meta.scripts = meta.scripts or {}
table.insert(meta.scripts, { name = name, time = ts / 1000, value = value })
end
end
p = d + size + 4
end
-- the track facts onMetaData and the codec headers give
local md: { [string]: any } = meta.metadata or {}
if type(md.duration) == "number" and md.duration > 0 then
meta.duration = md.duration
end
if vt then
if vt.codec == "h264" and vt.config then
local ok, info = pcall(H264.info, vt.config)
if ok and info then
vt.width, vt.height = info.width, info.height
end
elseif keyOff >= 0 then
local w, h = frameSize(vt.codec, b, keyOff, keyLen)
vt.width, vt.height = w, h
end
if not vt.width and type(md.width) == "number" and type(md.height) == "number" then
vt.width, vt.height = math.floor(md.width), math.floor(md.height)
end
local fr = md.framerate or md.videoframerate
if type(fr) == "number" and fr > 0 and fr < 1000 then
vt.frameRate = fr
else
-- from the timestamps: the frames over the time they span
local n = dmx:count(vt.id)
local t0 = if n > 0 then dmx:info(vt.id, 1) else nil
local t1 = if n > 1 then dmx:info(vt.id, n) else nil
if t0 and t1 and t1 > t0 then
vt.frameRate = math.floor((n - 1) / ((t1 - t0) / 1000) * 1000 + 0.5) / 1000
end
end
end
if at and at.codec == "aac" and not at.config then
at.unsupported = "AAC without its AudioSpecificConfig"
end
dmx:finish()
return dmx, nil
end
-- ------------------------------------------------------------------------------------------------ encode
-- encode(video, opts?) -> buffer | nil, Err: a VideoDecoder (F.load / F.video.open) or a Demuxer
function Flv.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
local o: any = opts or {}
local streams, err = Source.streams(value, o, {
video = { copy = Mux.VIDEO_COPY },
audio = { copy = Mux.AUDIO_COPY, pcm = true },
})
if not streams then
return nil, err
end
-- audio FLV cannot hold (PCM at other rates): dropped, or an error with opts.audio = true
for i = #streams, 1, -1 do
local s = streams[i]
local why = s.kind == "audio" and Mux.audioProblem(s)
if why then
if o.audio == true then
return nil, Err.new(Err.UNSUPPORTED, why)
end
table.remove(streams, i)
end
end
if #streams == 0 then
return nil, Err.new(Err.UNSUPPORTED, "nothing FLV can hold")
end
local ok, buf, merr = pcall(Mux.mux, streams)
if not ok then
return nil, Err.new(Err.ARG, "internal error: " .. tostring(buf))
end
return buf, merr
end
-- ------------------------------------------------------------------------------------------------ open
-- open(r, opts?) -> a VideoDecoder (kind "video": nextFrame / seek / audio / demuxer) | nil, Err
function Flv.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?)
local ok, dmx, err = pcall(Flv.demux, r, opts)
if not ok then
return nil, Err.new(Err.CORRUPT, "internal error: " .. tostring(dmx))
end
if not dmx then
return nil, err
end
return Video.open(dmx, opts :: Video.OpenOptions?)
end
return Flv
+229
View File
@@ -0,0 +1,229 @@
-- video/flv tests: FLV files from ffmpeg (Sorenson Spark + MP3 / PCM s16 / PCM u8 / ADPCM / Nellymoser / Speex /
-- A-law, H.264 with B-frames + AAC, Flash screen video, audio only): tracks and every packet against ffprobe
-- (composition times in the pts, keyframes), onMetaData, frames against ffmpeg (Sorenson bit-exact, H.264 PSNR), audio
-- through the api hook (PCM exact; ADPCM / Nellymoser / Speex known but UNSUPPORTED), seeking; crafted VP6 /
-- enhanced FourCC / encrypted / truncated files; our writer (FLV, MP4, Matroska sources) read back by ffprobe and
-- ffmpeg (tools/fixtures/flv.py) and by our demuxer with the source's packets; fuzz. Fixtures: tools/fixtures/flv.py.
local T = require("@tests/T")
local C = require("@tests/video/_common")
local F = require("@formats")
local Flv = require("@formats/video/flv")
local Video = require("@formats/codecs/video/Video")
local Bytes = require("@formats/core/Bytes")
local Crc32 = require("@formats/core/Crc32")
local Fx = require("@tests/gen/flv_cases")
local Mx = require("@tests/gen/flv_mux")
local Src = require("@tests/gen/flv_src")
local t = T.suite("flv")
t:eq(Flv.name, "flv", "name")
t:eq(Flv.category, "video", "category")
local EXACT_AUDIO = { pcm_s16le = true, pcm_u8 = true, pcm_alaw = true }
local NO_AUDIO_FORMAT = { adpcm_swf = true, nellymoser = true, speex = true }
local byName = {}
for _, c in Fx do
byName[c.name] = c
end
-- every frame's CRC against ffmpeg's (codecs we decode bit-exactly), else PSNR
local function frames(v: any, c: any, label: string)
if v.codec == "flv1" then
v:reset()
local n, bad = 0, 0
while true do
local f, err = v:nextFrame()
if not f then
t:check(err == nil, label .. ": decode error " .. tostring(err))
break
end
n += 1
if Crc32.of(f.image.pixels) ~= c.frames[n] then
bad += 1
end
end
t:eq(n, #c.frames, label .. ": frame count")
t:eq(bad, 0, label .. ": Sorenson frames bit-exact with ffmpeg")
else
C.frames(t, v, c, label, 38)
end
end
for _, c in Fx do
local label = c.name
t:check(Flv.sniff(Bytes.reader(buffer.fromstring(c.data))) == 1, label .. ": sniff")
local v, err = C.open(c.data)
t:check(v ~= nil, label .. ": open " .. tostring(err))
if v then
local dmx = v.demuxer
t:eq(#dmx.tracks, #c.streams, label .. ": track count")
C.packets(t, dmx, c, label)
for i, s in c.streams do
local tr = dmx.tracks[i]
if s.kind == "video" then
t:check(tr.width == s.width and tr.height == s.height, label .. ": video size " .. tostring(tr.width) .. "x" .. tostring(tr.height))
t:check(tr.codec == s.codec, label .. ": video codec " .. tr.codec .. " (" .. s.codec .. ")")
elseif s.rate then
t:check(tr.sampleRate == s.rate and tr.channels == s.channels, label .. ": audio " .. tostring(tr.sampleRate) .. " Hz x " .. tostring(tr.channels))
end
end
local md = dmx.meta.metadata
t:check(md ~= nil and type(md.duration) == "number" and md.duration > 0, label .. ": onMetaData duration")
if c.frames then
frames(v, c, label)
C.seek(t, v, c, label, 0.5)
elseif dmx:track("video") then
local _, e = v:nextFrame()
t:check(e ~= nil and e.code == F.Err.UNSUPPORTED and not Video.canDecode(v.codec), label .. ": " .. v.codec .. " is known, decoding UNSUPPORTED")
end
local at = dmx:track("audio")
if at then
if NO_AUDIO_FORMAT[at.codec] then
t:check(v.audio == nil and v.audioError and v.audioError.code == F.Err.UNSUPPORTED, label .. ": " .. at.codec .. " audio UNSUPPORTED (" .. tostring(v.audioError) .. ")")
else
C.audio(t, v, c, label, EXACT_AUDIO[at.codec], 30)
end
end
end
end
-- details: H.264 config and composition times, metadata, screen video size
do
local v = assert(C.open(byName["h264_aac.flv"].data))
local vt, at = v.demuxer:track("video"), v.demuxer:track("audio")
t:check(vt.config ~= nil and buffer.readu8(vt.config, 0) == 1, "h264: avcC in track.config")
t:check(at.config ~= nil and buffer.len(at.config) >= 2, "h264: AudioSpecificConfig in track.config")
local reordered = false
for k = 1, v.demuxer:count(vt.id) do
local p = v.demuxer:get(vt.id, k)
if p and p.pts ~= p.dts then
reordered = true
end
end
t:check(reordered, "h264: B-frame composition times in the pts")
t:eq(v.frameRate, 12, "h264: frame rate from onMetaData")
local md = v.demuxer.meta.metadata
t:check(md.width == 160 and md.height == 120 and md.videocodecid == 7 and md.audiocodecid == 10, "onMetaData: width, height, codec ids")
t:check(type(md.encoder) == "string", "onMetaData: encoder string")
local s = assert(C.open(byName["screen.flv"].data))
t:check(s.codec == "flashsv" and s.width == 64 and s.height == 48, "screen video: known codec, size from its first packet")
end
-- crafted files: VP6 (known, UNSUPPORTED, size from its key frame header), an enhanced FourCC tag, encrypted tags,
-- truncation, not FLV
local function flv(tags: { { any } }): buffer
local w = Bytes.writer(256)
w:string("FLV")
w:u8(1)
w:u8(1)
w:u32be(9)
w:u32be(0)
for _, tg in tags do
local body: string = tg[3]
w:u8(tg[1])
w:u24be(#body)
w:u24be(tg[2])
w:u8(0)
w:u24be(0)
w:string(body)
w:u32be(11 + #body)
end
return w:finish()
end
do
-- VP6: frame type 1 / codec 4, adjustment 0x00, key frame header (marker 0, profile 3: no offset), 2 x 3 MBs
local key = "\20\0" .. "\0\6" .. "\2\3\2\3" .. string.rep("\0", 8)
local inter = "\36\0" .. "\128" .. string.rep("\0", 8)
local b = flv({ { 9, 0, key }, { 9, 40, inter }, { 9, 80, key } })
local v = assert(F.video.open(b))
t:check(v.codec == "vp6f" and v.width == 48 and v.height == 32, "vp6: codec vp6f, " .. v.width .. "x" .. v.height .. " from its header")
t:check(v.track.config ~= nil and buffer.len(v.track.config) == 1, "vp6: the adjustment byte as config")
t:eq(v.demuxer:count(1), 3, "vp6: packets")
local p = assert(v.demuxer:get(1, 1))
t:check(buffer.len(p.data) == #key - 2 and p.keyframe, "vp6: packet after the adjustment byte, keyframe")
t:check(not assert(v.demuxer:get(1, 2)).keyframe, "vp6: inter frame")
local _, e = v:nextFrame()
t:check(e ~= nil and e.code == F.Err.UNSUPPORTED, "vp6: decoding UNSUPPORTED")
v.demuxer:seek(0.06)
t:eq(assert(v.demuxer:read(1)).pts, 0, "vp6: seek to the keyframe before")
-- remux of a copied VP6 track keeps the adjustment byte
local out = assert(F.save(v.demuxer, nil, { format = "flv" }))
local v2 = assert(F.video.open(out))
t:check(v2.codec == "vp6f" and v2.demuxer:count(1) == 3 and buffer.tostring(assert(v2.demuxer:get(1, 1)).data) == buffer.tostring(p.data), "vp6: remuxed")
-- enhanced FLV: an hvc1 sequence start and coded frames (with composition time)
local hv = flv({ { 9, 0, "\144hvc1" .. "\1\2\3" }, { 9, 0, "\145hvc1" .. "\0\0\40" .. "\9\9" }, { 9, 40, "\163hvc1" .. "\7\7\7" } })
local h = assert(Flv.demux(Bytes.reader(hv)))
local vt = assert(h:track("video"))
t:check(vt.codec == "hevc" and vt.config ~= nil and buffer.len(vt.config) == 3, "enhanced: hvc1 -> hevc, sequence start as config")
local p1, p2 = assert(h:get(1, 1)), assert(h:get(1, 2))
t:check(p1.pts == 40 and p1.dts == 0 and buffer.len(p1.data) == 2 and p1.keyframe, "enhanced: coded frames with composition time")
t:check(p2.pts == 40 and buffer.len(p2.data) == 3 and not p2.keyframe, "enhanced: coded frames X")
-- encrypted audio tags: the track says why
local enc = flv({ { 8 + 32, 0, "\47\1\2\3" } })
local d = assert(Flv.demux(Bytes.reader(enc)))
t:check(d:track("audio").unsupported ~= nil and d:count(2) == 0, "encrypted tags: dropped, track.unsupported")
-- truncated: the tags before the cut
local full = buffer.fromstring(byName["sorenson_mp3.flv"].data)
local cut = buffer.create(buffer.len(full) // 2)
buffer.copy(cut, 0, full, 0, buffer.len(cut))
local tr = assert(Flv.demux(Bytes.reader(cut)))
t:check(tr.meta.truncated == true and tr:count(1) > 0, "truncated file: meta.truncated, packets before the cut")
local _, e2 = Flv.demux(Bytes.reader(buffer.fromstring("RIFF0000AVI LIST")))
t:check(e2 ~= nil and e2.code == F.Err.CORRUPT, "not FLV: CORRUPT")
end
-- our writer: read back by ffprobe / ffmpeg (fixtures) and by our demuxer, packets equal to the source's
local SOURCES = { mp4 = Src.mp4, mkv = Src.mkv, ts = Src.ts }
for _, c in Mx do
local label = "write " .. c.name
if c.err then
t:check(c.source == "ts" and string.find(c.err, "UNSUPPORTED", 1, true) ~= nil, label .. ": " .. c.err)
else
local v = assert(C.open(c.data))
t:eq(#v.demuxer.tracks, #c.streams, label .. ": ffprobe sees the same tracks")
C.packets(t, v.demuxer, c, label)
if c.frames then
frames(v, c, label)
end
local at = v.demuxer:track("audio")
if at then
C.audio(t, v, c, label, EXACT_AUDIO[at.codec], 30)
end
-- the source's packets, byte for byte
local src = assert(C.open(SOURCES[c.source] or byName[c.source].data))
local a, b = src.demuxer, v.demuxer
local same = true
for _, kind in { "video", "audio" } do
local ta, tb = a:track(kind), b:track(kind)
if (ta == nil) ~= (tb == nil) then
same = false
elseif ta and tb then
if a:count(ta.id) ~= b:count(tb.id) then
same = false
else
for k = 1, a:count(ta.id) do
local p, q = assert(a:get(ta.id, k)), assert(b:get(tb.id, k))
if buffer.tostring(p.data) ~= buffer.tostring(q.data) or p.keyframe ~= q.keyframe then
same = false
end
end
end
end
end
t:check(same, label .. ": the source's packets (" .. c.source .. ")")
local md = b.meta.metadata
t:check(md and md.encoder == "formats-luau" and md.filesize == #c.data, label .. ": onMetaData encoder and file size")
end
end
-- fuzz
local samples = {}
for _, n in { "sorenson_mp3.flv", "h264_aac.flv", "sorenson_pcm.flv", "screen.flv" } do
local d = byName[n].data
table.insert(samples, string.sub(d, 1, math.min(#d, 30000)))
end
t:fuzz("open", C.fuzzOpen(Flv), samples, { mutations = 6, garbage = 100 })
t:done()
+42
View File
@@ -0,0 +1,42 @@
-- tools/fixtures/_flv_encode: run by tools/fixtures/flv.py (luau, from the repo root) so ffprobe / ffmpeg can check our
-- FLV writer: remuxes FLV fixtures (tests/gen/flv_cases) and the MP4 / Matroska / MPEG-TS sources (tests/gen/flv_src)
-- and prints "<name> <source> <hex>" lines (or "<name> <source> ERR <message>").
local F = require("@formats")
local Cases = require("@tests/gen/flv_cases")
local Src = require("@tests/gen/flv_src")
local function hex(b: buffer): string
local t = table.create(buffer.len(b))
for i = 0, buffer.len(b) - 1 do
t[i + 1] = string.format("%02x", buffer.readu8(b, i))
end
return table.concat(t)
end
local function find(name: string): string
for _, c in Cases do
if c.name == name then
return c.data
end
end
error("no fixture " .. name)
end
local JOBS = {
{ "remux_h264_aac.flv", "h264_aac.flv", find("h264_aac.flv") },
{ "remux_sorenson_mp3.flv", "sorenson_mp3.flv", find("sorenson_mp3.flv") },
{ "remux_pcm.flv", "sorenson_pcm.flv", find("sorenson_pcm.flv") },
{ "remux_screen.flv", "screen.flv", find("screen.flv") },
{ "mp4_h264_aac.flv", "mp4", Src.mp4 },
{ "mkv_h264_mp3.flv", "mkv", Src.mkv },
{ "ts_h264_aac.flv", "ts", Src.ts },
}
for _, j in JOBS do
local name, source, data = j[1], j[2], j[3]
local out, err = F.convert(buffer.fromstring(data), "flv")
if out then
print(name .. " " .. source .. " " .. hex(out))
else
print(name .. " " .. source .. " ERR " .. tostring(err))
end
end
+86
View File
@@ -0,0 +1,86 @@
# FLV fixtures (tools/fixtures.py): files made by ffmpeg (Sorenson Spark + MP3 / PCM s16 / PCM u8 / Flash ADPCM /
# Nellymoser / Speex / A-law, H.264 with B-frames + AAC, Flash screen video), with ffprobe's streams and packets,
# ffmpeg's frames (CRC-32 of `-flags +bitexact -idct int` decoding; the first two raw) and audio (f32); then our FLV
# writer (tools/fixtures/_flv_encode.luau) remuxes FLV, MP4, Matroska and MPEG-TS sources and each output is probed,
# decoded and emitted the same way, so the test can read our files with our demuxer and compare them with ffmpeg's view.
# tests/gen/flv_cases.luau { { name, data, streams, packets, frames, yuv, pcm, pcmBytes } }
# tests/gen/flv_src.luau { mp4 = H.264 + AAC MP4, mkv = H.264 + MP3 Matroska, ts = H.264 + AAC MPEG-TS }
# tests/gen/flv_mux.luau { { name, source, data, streams, packets, frames, pcm, pcmBytes } | { name, err } }
import importlib.util, os, shutil, subprocess, tempfile
_spec = importlib.util.spec_from_file_location("_video_helpers", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_video.py"))
V = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(V)
INPUTS = ["tools/fixtures/_video.py", "tools/fixtures/_flv_encode.luau", "src/Formats/video/flv", "src/Formats/codecs/video/Video"]
SRC = ["-f", "lavfi", "-i", "testsrc2=size=160x120:rate=12"]
def aud(rate, ch=1, freq=550):
return ["-f", "lavfi", "-i", "sine=frequency=%d:sample_rate=%d" % (freq, rate), "-ac", str(ch)]
def case(tmp, name, decode_audio=True):
path = os.path.join(tmp, name)
c = {"name": name, "data": open(path, "rb").read(), "streams": V.streams(path), "packets": V.packets(path)}
vs = [s for s in c["streams"] if s["kind"] == "video"]
if vs and vs[0]["codec"] in ("flv1", "h264"):
w, h = vs[0]["width"], vs[0]["height"]
raw = V.ffmpeg(["-flags", "+bitexact", "-idct", "int", "-i", path, "-map", "0:v:0", "-fps_mode", "passthrough", "-f",
"rawvideo", "-pix_fmt", "yuv420p", "-"])
n = w * h + 2 * ((w + 1) // 2) * ((h + 1) // 2)
frames = [raw[i:i + n] for i in range(0, len(raw) - n + 1, n)]
c["frames"] = [V.crc(f) for f in frames]
c["yuv"] = frames[:2]
if decode_audio and any(s["kind"] == "audio" for s in c["streams"]):
pcm = V.pcm_f32(path)
c["pcm"] = pcm[:8192 * 4]
c["pcmBytes"] = len(pcm)
return c
def generate(ctx):
tmp = tempfile.mkdtemp(prefix="flvfx_")
ff = lambda *a: V.ffmpeg(list(a), cwd=tmp)
ff(*SRC, *aud(44100), "-t", "1", "-c:v", "flv", "-b:v", "300k", "-g", "6", "-c:a", "libmp3lame", "-b:a", "64k", "sorenson_mp3.flv")
ff(*SRC, *aud(44100), "-t", "1", "-c:v", "libx264", "-preset", "veryfast", "-bf", "2", "-g", "6", "-c:a", "aac", "-b:a", "96k",
"h264_aac.flv")
ff(*SRC, *aud(22050, 2), "-t", "1", "-c:v", "flv", "-g", "12", "-c:a", "pcm_s16le", "sorenson_pcm.flv")
ff(*SRC, *aud(11025), "-t", "1", "-c:v", "flv", "-g", "12", "-c:a", "pcm_u8", "sorenson_pcm8.flv")
ff(*SRC, *aud(22050), "-t", "0.5", "-c:v", "flv", "-c:a", "adpcm_swf", "sorenson_adpcm.flv")
ff(*SRC, *aud(22050), "-t", "0.5", "-c:v", "flv", "-c:a", "nellymoser", "sorenson_nelly.flv")
ff(*SRC, *aud(16000), "-t", "0.5", "-c:v", "flv", "-c:a", "libspeex", "sorenson_speex.flv")
ff(*SRC, *aud(8000), "-t", "0.5", "-c:v", "flv", "-c:a", "pcm_alaw", "sorenson_alaw.flv")
ff("-f", "lavfi", "-i", "testsrc2=size=64x48:rate=10", "-t", "0.5", "-c:v", "flashsv", "screen.flv")
ff(*aud(44100, 2), "-t", "0.5", "-c:a", "libmp3lame", "audio_only.flv")
names = ["sorenson_mp3.flv", "h264_aac.flv", "sorenson_pcm.flv", "sorenson_pcm8.flv", "sorenson_adpcm.flv",
"sorenson_nelly.flv", "sorenson_speex.flv", "sorenson_alaw.flv", "screen.flv", "audio_only.flv"]
cases = [case(tmp, n) for n in names]
ctx.emit("flv_cases", cases)
# sources for the writer
ff(*SRC, *aud(44100), "-t", "1", "-c:v", "libx264", "-preset", "veryfast", "-bf", "2", "-g", "6", "-c:a", "aac", "src.mp4")
ff(*SRC, *aud(44100, 2), "-t", "1", "-c:v", "libx264", "-preset", "veryfast", "-bf", "0", "-g", "12", "-c:a", "libmp3lame",
"src.mkv")
ff(*SRC, *aud(44100), "-t", "1", "-c:v", "libx264", "-preset", "veryfast", "-c:a", "aac", "src.ts")
srcs = {k: open(os.path.join(tmp, "src." + k), "rb").read() for k in ("mp4", "mkv", "ts")}
ctx.emit("flv_src", srcs)
luau = os.environ.get("LUAU") or shutil.which("luau")
cmd = [luau, "tools/fixtures/_flv_encode.luau"] if luau else ["nix", "shell", "nixpkgs#luau", "-c", "luau", "tools/fixtures/_flv_encode.luau"]
out = subprocess.run(cmd, capture_output=True, check=True, cwd=ctx.root).stdout.decode()
mux = []
for line in out.split("\n"):
if not line.strip():
continue
name, source, rest = line.split(" ", 2)
if rest.startswith("ERR "):
mux.append({"name": name, "source": source, "err": rest[4:]})
continue
open(os.path.join(tmp, name), "wb").write(bytes.fromhex(rest))
c = case(tmp, name)
c["source"] = source
c.pop("yuv", None)
mux.append(c)
ctx.emit("flv_mux", mux)