--!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" }, 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