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:
1 parent
2a5da31c80
commit
efc0812746
9 files changed
+1230
No files matched your search
@@ -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",
|
||||
|
||||
@@ -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" } },
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
Reference in new issue
Block a user