306 lines
9.9 KiB
Luau
306 lines
9.9 KiB
Luau
--!strict
|
|
-- codecs/Video/Source: what a video writer (Matroska / WebM, AVI, Y4M, MP4) gets to write, from whatever it was given:
|
|
-- a VideoDecoder (F.load / F.video.open of any video or animated image) or a Demuxer. Each output stream is either
|
|
-- copied (the source track's packets, when the target container takes that codec: remuxing, e.g. VP8 into WebM,
|
|
-- since VP8 is decode-only) or produced (decoded frames encoded with a registered encoder such as MJPEG, raw
|
|
-- yuv420p frames, PCM audio from the audio Decoder). New in formats-luau.
|
|
--
|
|
-- local streams, err = Source.streams(value, opts, {
|
|
-- video = { copy = { vp8 = true }, encode = "mjpeg" }, -- copy: codec ids the container takes ("*" = any)
|
|
-- audio = { copy = { opus = true, vorbis = true }, pcm = true },
|
|
-- })
|
|
-- -- streams[i] = { kind, codec, copied, width, height, frameRate, sampleRate, channels, bitsPerSample, config,
|
|
-- -- track, packets = { { pts, duration (seconds), keyframe, data } } }
|
|
local Err = require("@formats/core/Err")
|
|
local Types = require("@formats/Types")
|
|
local Yuv = require("@formats/codecs/Yuv")
|
|
|
|
local Source = {}
|
|
|
|
export type OutPacket = { pts: number, dts: number?, duration: number, keyframe: boolean, data: buffer }
|
|
export type Stream = {
|
|
kind: "video" | "audio",
|
|
codec: string,
|
|
copied: boolean,
|
|
width: number?,
|
|
height: number?,
|
|
frameRate: number?,
|
|
sampleRate: number?,
|
|
channels: number?,
|
|
bitsPerSample: number?,
|
|
config: buffer?,
|
|
track: Types.Track?,
|
|
packets: { OutPacket },
|
|
}
|
|
export type Want = {
|
|
video: { copy: { [string]: boolean }?, encode: string? }?,
|
|
audio: { copy: { [string]: boolean }?, pcm: boolean? }?,
|
|
}
|
|
|
|
local function allows(set: { [string]: boolean }?, codec: string): boolean
|
|
return set ~= nil and (set[codec] == true or set["*"] == true)
|
|
end
|
|
|
|
-- the packets of a source track, times in seconds
|
|
local function copyPackets(dmx: any, track: Types.Track): { OutPacket }
|
|
local out = {}
|
|
local scale = if track.timescale and track.timescale > 0 then track.timescale else 1
|
|
local n = dmx:count(track.id)
|
|
for k = 1, n do
|
|
local p = dmx:get(track.id, k)
|
|
if p then
|
|
table.insert(out, { pts = p.pts / scale, dts = (p.dts or p.pts) / scale, duration = (p.duration or 0) / scale, keyframe = p.keyframe, data = p.data })
|
|
end
|
|
end
|
|
return out
|
|
end
|
|
|
|
local function trackStream(track: Types.Track, packets: { OutPacket }): Stream
|
|
return {
|
|
kind = track.kind :: any,
|
|
codec = track.codec,
|
|
copied = true,
|
|
width = track.width,
|
|
height = track.height,
|
|
frameRate = track.frameRate,
|
|
sampleRate = track.sampleRate,
|
|
channels = track.channels,
|
|
bitsPerSample = track.bitsPerSample,
|
|
config = track.config,
|
|
track = track,
|
|
packets = packets,
|
|
}
|
|
end
|
|
|
|
-- encodeFrames(video, codec, opts) -> the video's frames encoded with the registry's encoder for codec ("rawvideo":
|
|
-- yuv420p planes)
|
|
local function encodeFrames(v: any, codec: string, opts: any): (Stream?, Err.Err?)
|
|
local encode: ((img: Types.Image, opts: any) -> (buffer?, Err.Err?))? = nil
|
|
if codec ~= "rawvideo" then
|
|
local Video = require("@formats/codecs/Video")
|
|
local e = Video.entry(codec)
|
|
encode = e and e.encode
|
|
if not encode then
|
|
return nil, Err.new(Err.UNSUPPORTED, "no " .. codec .. " encoder")
|
|
end
|
|
end
|
|
if type(v.reset) == "function" then
|
|
v:reset()
|
|
end
|
|
local packets: { OutPacket } = {}
|
|
local w, h = v.width, v.height
|
|
local maxFrames = opts.maxFrames or math.huge
|
|
while #packets < maxFrames do
|
|
local f, err = v:nextFrame()
|
|
if not f then
|
|
if err then
|
|
return nil, err
|
|
end
|
|
break
|
|
end
|
|
local img: Types.Image = f.image
|
|
if (w == 0 or h == 0) and #packets == 0 then
|
|
w, h = img.width, img.height
|
|
end
|
|
if img.width ~= w or img.height ~= h then
|
|
return nil, Err.new(Err.UNSUPPORTED, "frame size changes mid-stream (" .. img.width .. "x" .. img.height .. ")")
|
|
end
|
|
local data: buffer?
|
|
if codec == "rawvideo" then
|
|
local y = if img.format == "yuv420p" then img else Yuv.imageFromRgba(img, "limited", "bt601")
|
|
if not y then
|
|
return nil, Err.new(Err.UNSUPPORTED, "frame format " .. img.format)
|
|
end
|
|
data = y.pixels
|
|
else
|
|
local e2
|
|
data, e2 = (encode :: any)(img, opts)
|
|
if not data then
|
|
return nil, e2 or Err.new(Err.ARG, "frame " .. f.index .. " failed to encode")
|
|
end
|
|
end
|
|
table.insert(packets, { pts = f.pts, duration = f.duration, keyframe = true, data = data :: buffer })
|
|
end
|
|
if #packets == 0 then
|
|
return nil, Err.new(Err.ARG, "no frames to write")
|
|
end
|
|
local fr = v.frameRate
|
|
if not fr or fr <= 0 then
|
|
local d = packets[1].duration
|
|
fr = if d > 0 then 1 / d else 25
|
|
end
|
|
return {
|
|
kind = "video",
|
|
codec = codec,
|
|
copied = false,
|
|
width = w,
|
|
height = h,
|
|
frameRate = fr,
|
|
packets = packets,
|
|
} :: Stream, nil
|
|
end
|
|
|
|
-- pcmFrom(decoder, opts) -> an s16le stream from an audio Decoder (chunks of opts.audioChunk frames, default 4096)
|
|
local function pcmFrom(dec: any, opts: any): (Stream?, Err.Err?)
|
|
local ch, rate = dec.channels, dec.sampleRate
|
|
if type(ch) ~= "number" or ch < 1 or type(rate) ~= "number" or rate <= 0 then
|
|
return nil, Err.new(Err.ARG, "audio decoder without channels / sample rate")
|
|
end
|
|
pcall(dec.seek, dec, 0)
|
|
local chunk = opts.audioChunk or 4096
|
|
local packets: { OutPacket } = {}
|
|
local pos = 0
|
|
local tmp: buffer? = nil
|
|
while true do
|
|
local ok, out, n = pcall(dec.read, dec, chunk, tmp)
|
|
if not ok or not out or not n or n <= 0 then
|
|
break
|
|
end
|
|
tmp = out
|
|
local data = buffer.create(n * ch * 2)
|
|
for i = 0, n * ch - 1 do
|
|
local s = buffer.readf32(out, i * 4)
|
|
local v = math.floor(s * 32768 + 0.5)
|
|
if v > 32767 then
|
|
v = 32767
|
|
elseif v < -32768 then
|
|
v = -32768
|
|
elseif v ~= v then
|
|
v = 0
|
|
end
|
|
buffer.writei16(data, i * 2, v)
|
|
end
|
|
table.insert(packets, { pts = pos / rate, duration = n / rate, keyframe = true, data = data })
|
|
pos += n
|
|
end
|
|
return {
|
|
kind = "audio",
|
|
codec = "pcm_s16le",
|
|
copied = false,
|
|
sampleRate = rate,
|
|
channels = ch,
|
|
bitsPerSample = 16,
|
|
packets = packets,
|
|
} :: Stream, nil
|
|
end
|
|
|
|
-- streams(value, opts, want) -> { Stream } | nil, Err
|
|
function Source.streams(value: any, opts: any?, want: Want): ({ Stream }?, Err.Err?)
|
|
local o = opts or {}
|
|
if type(value) ~= "table" or (value.kind ~= "video" and value.kind ~= "demuxer") then
|
|
return nil, Err.new(Err.ARG, "expected a video (VideoDecoder) or a Demuxer")
|
|
end
|
|
local dmx = if value.kind == "demuxer" then value else value.demuxer
|
|
local out: { Stream } = {}
|
|
-- video
|
|
local vt: Types.Track? = if value.kind == "video" then value.track else (dmx and dmx:track("video"))
|
|
local wv = want.video
|
|
if wv and o.video ~= false then
|
|
if vt and dmx and allows(wv.copy, vt.codec) and not o.reencode then
|
|
table.insert(out, trackStream(vt, copyPackets(dmx, vt)))
|
|
elseif value.kind == "video" and wv.encode then
|
|
local s, err = encodeFrames(value, wv.encode, o)
|
|
if not s then
|
|
return nil, err
|
|
end
|
|
table.insert(out, s)
|
|
elseif vt then
|
|
return nil, Err.new(Err.UNSUPPORTED, "cannot write " .. vt.codec .. " video" .. (if wv.encode then "" else " (this container cannot take it and it cannot be re-encoded)"))
|
|
end
|
|
end
|
|
-- audio
|
|
local wa = want.audio
|
|
if wa and o.audio ~= false then
|
|
local at: Types.Track? = dmx and dmx:track("audio")
|
|
if at and dmx and allows(wa.copy, at.codec) and not o.reencodeAudio then
|
|
table.insert(out, trackStream(at, copyPackets(dmx, at)))
|
|
elseif wa.pcm and value.kind == "video" and value.audio then
|
|
local s, err = pcmFrom(value.audio, o)
|
|
if not s then
|
|
return nil, err
|
|
end
|
|
if #s.packets > 0 then
|
|
table.insert(out, s)
|
|
end
|
|
elseif at and o.audio == true then
|
|
return nil, Err.new(Err.UNSUPPORTED, "cannot write " .. at.codec .. " audio to this container")
|
|
end
|
|
end
|
|
if #out == 0 then
|
|
return nil, Err.new(Err.ARG, "nothing to write (no video or audio stream)")
|
|
end
|
|
return out, nil
|
|
end
|
|
|
|
-- rational(fps) -> num, den: integer rates as n / 1, NTSC rates as n * 1000 / 1001, else to a millisecond
|
|
function Source.rational(fps: number): (number, number)
|
|
if fps ~= fps or fps <= 0 then
|
|
return 25, 1
|
|
end
|
|
if math.abs(fps - math.floor(fps + 0.5)) < 1e-6 then
|
|
return math.floor(fps + 0.5), 1
|
|
end
|
|
local ntsc = fps * 1001 / 1000
|
|
if math.abs(ntsc - math.floor(ntsc + 0.5)) < 1e-4 then
|
|
return math.floor(ntsc + 0.5) * 1000, 1001
|
|
end
|
|
return math.floor(fps * 1000 + 0.5), 1000
|
|
end
|
|
|
|
-- constantRate(stream, maxFps?) -> num, den, { OutPacket }: a video stream at a constant frame rate for the
|
|
-- containers that have one (AVI, Y4M): the rate of the shortest frame (at most maxFps, default 100), each packet
|
|
-- repeated to fill its duration (a GIF's 100 / 50 / 200 ms frames become 2, 1 and 4 frames at 20 fps)
|
|
function Source.constantRate(s: Stream, maxFps: number?): (number, number, { OutPacket })
|
|
local fd = math.huge
|
|
for _, p in s.packets do
|
|
if p.duration and p.duration > 0 and p.duration < fd then
|
|
fd = p.duration
|
|
end
|
|
end
|
|
if fd == math.huge then
|
|
fd = if s.frameRate and s.frameRate > 0 then 1 / s.frameRate else 0.04
|
|
end
|
|
fd = math.max(fd, 1 / (maxFps or 100))
|
|
local num, den = Source.rational(1 / fd)
|
|
local step = den / num
|
|
local out: { OutPacket } = {}
|
|
local slots = 0
|
|
local t0 = if s.packets[1] then s.packets[1].pts else 0
|
|
for _, p in s.packets do
|
|
local stop = p.pts - t0 + (if p.duration and p.duration > 0 then p.duration else step)
|
|
local n = math.max(1, math.floor(stop / step + 0.5) - slots)
|
|
for _ = 1, n do
|
|
table.insert(out, { pts = t0 + slots * step, duration = step, keyframe = p.keyframe, data = p.data })
|
|
slots += 1
|
|
end
|
|
end
|
|
return num, den, out
|
|
end
|
|
|
|
-- interleave(streams) -> { { stream index, packet } } merged by decode time (dts, else pts); each stream keeps its
|
|
-- own order
|
|
function Source.interleave(streams: { Stream }): { { any } }
|
|
local order = {}
|
|
local pos = table.create(#streams, 1)
|
|
while true do
|
|
local best, bt = 0, math.huge
|
|
for si, s in streams do
|
|
local p = s.packets[pos[si]]
|
|
if p then
|
|
local t = p.dts or p.pts
|
|
if best == 0 or t < bt then
|
|
best, bt = si, t
|
|
end
|
|
end
|
|
end
|
|
if best == 0 then
|
|
break
|
|
end
|
|
table.insert(order, { best, streams[best].packets[pos[best]] })
|
|
pos[best] += 1
|
|
end
|
|
return order
|
|
end
|
|
|
|
return Source
|