New shared modules under codecs/audio/Aac: Sbr (bitstream, band tables, delta decoding), SbrBits, SbrQmf (32-band analysis / 64-band synthesis QMF through DCT-IV), SbrHf (HF generation and adjustment), Ps (baseline PS), SbrTables (ISO tables, from syom 0.8.1, MIT). Explicit signalling enables SBR at construction; implicit SBR / PS is found by Decoder:probe / Aac.probeFrames. audio/aac and audio/m4a report the output rate and take opts.sbr = false for the core only; m4a scales iTunSMPB by the media tick. Outside the folder: containers/AudioWrap writes an AAC-LC ADTS header for HE-AAC AudioSpecificConfigs (the decoder finds SBR in the stream); the api's default openAudio hook forwards opts.sbr.
883 lines
27 KiB
Luau
883 lines
27 KiB
Luau
--!strict
|
|
-- Rosetta: read, write and convert file formats in pure Luau, on Roblox and on LuaJIT / LÖVE (through tools/build.py).
|
|
-- Formats are found through the generated Registry: by content (each format's sniff), then by extension. Never throws
|
|
-- on bad data or bad arguments: every function returns nil, Err.
|
|
local Err = require("@rosetta/core/Err")
|
|
local Bytes = require("@rosetta/core/Bytes")
|
|
local Input = require("@rosetta/core/Input")
|
|
local Types = require("@rosetta/Types")
|
|
local Registry = require("@rosetta/Registry")
|
|
local Video = require("@rosetta/codecs/video/Video")
|
|
local AudioWrap = require("@rosetta/containers/AudioWrap")
|
|
local Rbx = require("@rosetta/codecs/model/Rbx")
|
|
local ImageOps = require("@rosetta/ops/ImageOps")
|
|
local host = require("@rosetta/host")
|
|
|
|
local F = {}
|
|
|
|
F.version = "0.1.0"
|
|
F.Err = Err
|
|
F.Types = Types
|
|
F.Bytes = Bytes
|
|
F.Rbx = Rbx
|
|
F.null = Types.null
|
|
F.host = host
|
|
F.plugins = {} :: { [string]: any } -- injected optional dependencies (plugins.brep for cad/step)
|
|
|
|
local KIND_CATEGORY: { [string]: string } = {
|
|
image = "image",
|
|
audio = "audio",
|
|
video = "video",
|
|
scene = "model",
|
|
rbxtree = "model", -- codecs/model/Rbx trees (model/rbxm, model/rbxmx)
|
|
cad = "cad",
|
|
font = "font",
|
|
archive = "archive",
|
|
vector = "vector",
|
|
tilemap = "vector",
|
|
layered = "layered",
|
|
subtitles = "subtitle",
|
|
music = "music",
|
|
midi = "music",
|
|
playlist = "playlist",
|
|
}
|
|
|
|
local loaded: { [string]: any } = {}
|
|
|
|
local function module(entry: Registry.Entry): (any, Err.Err?)
|
|
local m = loaded[entry.path]
|
|
if m then
|
|
return m
|
|
end
|
|
local ok, res = pcall(entry.load)
|
|
if not ok then
|
|
return nil, Err.new(Err.UNSUPPORTED, "format " .. entry.name .. " failed to load: " .. tostring(res))
|
|
end
|
|
loaded[entry.path] = res
|
|
return res
|
|
end
|
|
|
|
local function inCategory(entry: Registry.Entry, category: string?): boolean
|
|
return category == nil or entry.category == category
|
|
end
|
|
|
|
local function find(key: string, category: string?): Registry.Entry?
|
|
local k = string.lower(key)
|
|
for _, e in Registry do
|
|
if e.name == k and inCategory(e, category) then
|
|
return e
|
|
end
|
|
end
|
|
for _, e in Registry do
|
|
if inCategory(e, category) and table.find(e.extensions, k) then
|
|
return e
|
|
end
|
|
end
|
|
return nil
|
|
end
|
|
|
|
local LATE: { [string]: number } = { br = 0.3 } -- archive/br: a trial decode of up to 256 KB
|
|
|
|
local function detect(buf: buffer, name: string?, category: string?, format: string?): (Registry.Entry?, Err.Err?)
|
|
if format then
|
|
local e = find(format, category)
|
|
if not e then
|
|
return nil, Err.new(Err.UNKNOWN_FORMAT, "no format named " .. format .. (if category then " in " .. category else ""))
|
|
end
|
|
return e, nil
|
|
end
|
|
local ext = Input.extension(name)
|
|
local best: Registry.Entry? = nil
|
|
local bestScore, bestIdx = 0, 0
|
|
-- sniffs score 0..1 (core/Sniff); the extension's format scoring 1 cannot be beaten. Formats with a costly sniff
|
|
-- (LATE: the most they score) run last, and only when they could still win; ties go to registry order.
|
|
local late: { number }? = nil
|
|
for idx, e in Registry do
|
|
if inCategory(e, category) and (e.caps.decode or e.caps.open) then
|
|
local cap = LATE[e.name]
|
|
if cap then
|
|
late = late or {}
|
|
table.insert(late :: { number }, idx)
|
|
continue
|
|
end
|
|
local m = module(e)
|
|
if m and m.sniff then
|
|
local ok, score = pcall(m.sniff, Bytes.reader(buf))
|
|
if ok and type(score) == "number" and score > 0 then
|
|
local extHit = ext and table.find(e.extensions, ext)
|
|
if extHit then
|
|
score += 0.01 -- ties go to the extension
|
|
end
|
|
if score > bestScore then
|
|
best, bestScore, bestIdx = e, score, idx
|
|
if extHit and score >= 1.01 then
|
|
return e, nil
|
|
end
|
|
end
|
|
end
|
|
end
|
|
end
|
|
end
|
|
if late then
|
|
for _, idx in late do
|
|
local e = Registry[idx]
|
|
local extHit = ext and table.find(e.extensions, ext)
|
|
local cap = LATE[e.name] + (if extHit then 0.01 else 0)
|
|
if cap > bestScore or (cap == bestScore and idx < bestIdx) then
|
|
local m = module(e)
|
|
if m and m.sniff then
|
|
local ok, score = pcall(m.sniff, Bytes.reader(buf))
|
|
if ok and type(score) == "number" and score > 0 then
|
|
if extHit then
|
|
score += 0.01
|
|
end
|
|
if score > bestScore or (score == bestScore and idx < bestIdx) then
|
|
best, bestScore, bestIdx = e, score, idx
|
|
end
|
|
end
|
|
end
|
|
end
|
|
end
|
|
end
|
|
if best then
|
|
return best, nil
|
|
end
|
|
if ext then
|
|
local e = find(ext, category)
|
|
if e then
|
|
return e, nil
|
|
end
|
|
end
|
|
return nil, Err.new(Err.UNKNOWN_FORMAT, "unrecognised data" .. (if name then " (" .. name .. ")" else "") .. (if category then " for " .. category else ""))
|
|
end
|
|
|
|
-- music that renders (MOD, S3M, XM, IT, MIDI) is also audio: an audio lookup falls back to it (rendered = true)
|
|
local function detectFor(buf: buffer, name: string?, o: { [string]: any }): (Registry.Entry?, Err.Err?, boolean)
|
|
local entry, err = detect(buf, name, o.category, o.format)
|
|
if not entry and o.category == "audio" then
|
|
local e = detect(buf, name, "music", o.format)
|
|
if e and e.caps.render then
|
|
return e, nil, true
|
|
end
|
|
end
|
|
return entry, err, false
|
|
end
|
|
|
|
local function tag(value: any, formatName: string)
|
|
if type(value) == "table" then
|
|
local meta = value.meta
|
|
if type(meta) == "table" then
|
|
if meta.source == nil then
|
|
meta.source = { format = formatName }
|
|
elseif type(meta.source) == "table" and meta.source.format == nil then
|
|
meta.source.format = formatName
|
|
end
|
|
end
|
|
end
|
|
end
|
|
|
|
local function drain(dec: any): any
|
|
local channels = dec.channels
|
|
local parts, total = {}, 0
|
|
while true do
|
|
local out, n = dec:read(65536)
|
|
if not out or n == 0 then
|
|
break
|
|
end
|
|
local copy = buffer.create(n * channels * 4)
|
|
buffer.copy(copy, 0, out, 0, n * channels * 4)
|
|
table.insert(parts, copy)
|
|
total += n
|
|
end
|
|
local a = Types.Audio.new(dec.sampleRate, channels, total)
|
|
local o = 0
|
|
for _, p in parts do
|
|
buffer.copy(a.samples, o, p)
|
|
o += buffer.len(p)
|
|
end
|
|
a.tags = dec.tags or {}
|
|
return a
|
|
end
|
|
|
|
-- siblings resolve relative to path's directory only (no absolute paths, no "..", no URLs)
|
|
local function siblings(path: string): (uri: string) -> buffer?
|
|
local dir = string.match(path, "^(.*[/\\])") or ""
|
|
return function(uri: string): buffer?
|
|
if type(uri) ~= "string" or uri == "" or string.find(uri, "^%a[%w+.-]*:") or string.sub(uri, 1, 1) == "/" then
|
|
return nil
|
|
end
|
|
local u = string.gsub(uri, "%%(%x%x)", function(h: string): string
|
|
return string.char(tonumber(h, 16) :: number)
|
|
end)
|
|
for part in string.gmatch(u, "[^/\\]+") do
|
|
if part == ".." then
|
|
return nil
|
|
end
|
|
end
|
|
local b = host.readFile(dir .. u)
|
|
return b
|
|
end
|
|
end
|
|
|
|
export type Options = { [string]: any } -- format (name or extension), category, path, data, name, + format options
|
|
|
|
local load: (src: any, opts: Options?) -> (any, Err.Err?)
|
|
|
|
local function pageLoader(value: any, name: string?, o: Options)
|
|
if type(value) ~= "table" or value.kind ~= "font" or type(value.meta) ~= "table" or type(value.meta.pageFiles) ~= "table" then
|
|
return
|
|
end
|
|
local user: any = o.loadPage
|
|
if value.pages or (value.meta.pageLoader and type(user) ~= "function") then
|
|
return
|
|
end
|
|
local dir = if name then string.match(name, "^(.*[/\\])") or "" else nil
|
|
if type(user) ~= "function" and not (dir and host.hasFiles) then
|
|
return
|
|
end
|
|
value.meta.pageLoader = function(file: string, page: number): (any, Err.Err?)
|
|
local src: any
|
|
if type(user) == "function" then
|
|
src = (user :: any)(file, page)
|
|
else
|
|
src = (dir :: string) .. file
|
|
end
|
|
if type(src) == "table" then
|
|
return src
|
|
end
|
|
if src == nil then
|
|
return nil, Err.new(Err.IO, "no data for page " .. file)
|
|
end
|
|
return load(src, { category = "image", name = file, path = type(user) ~= "function" })
|
|
end
|
|
end
|
|
|
|
-- a single-stream archive (meta.stream) holding another archive or a .pcf / .psf(u) / .bdf font loads as that, with
|
|
-- meta.compression = the outer format; package archives load as meta.payload (meta.container / meta.outer)
|
|
local function unwrap(value: any, formatName: string, o: Options): any
|
|
if o.unwrap == false or o.format ~= nil or (o._depth or 0) >= 3 then
|
|
return value
|
|
end
|
|
if type(value) ~= "table" or value.kind ~= "archive" or type(value.meta) ~= "table" then
|
|
return value
|
|
end
|
|
local payload = value.meta.payload
|
|
if not value.meta.stream and type(payload) ~= "string" then
|
|
return value
|
|
end
|
|
local ok, list = pcall(value.list, value)
|
|
if not ok or type(list) ~= "table" or (#list ~= 1 and type(payload) ~= "string") or #list == 0 then
|
|
return value
|
|
end
|
|
local entryName = if type(payload) == "string" then payload else list[1].name
|
|
local rok, inner = pcall(value.read, value, entryName)
|
|
if not rok or type(inner) ~= "buffer" then
|
|
return value
|
|
end
|
|
local category = "archive"
|
|
local e = detect(inner, nil, "archive", nil)
|
|
local innerExt = Input.extension(entryName) or ""
|
|
if not e and value.meta.stream and (innerExt == "pcf" or innerExt == "psf" or innerExt == "psfu" or innerExt == "bdf") then
|
|
-- compressed bitmap fonts (.pcf.gz, .psf.gz, .bdf.gz: X11 and console font directories) load as the font
|
|
e = detect(inner, entryName, "font", nil)
|
|
category = "font"
|
|
end
|
|
if not e then
|
|
return value
|
|
end
|
|
local io = table.clone(o)
|
|
io.category = category
|
|
io.name = entryName
|
|
io._depth = (o._depth or 0) + 1
|
|
local v = load(inner, io)
|
|
if type(v) ~= "table" or type(v.meta) ~= "table" then
|
|
return value
|
|
end
|
|
if type(payload) == "string" then
|
|
v.meta.container = formatName
|
|
v.meta.outer = value
|
|
else
|
|
v.meta.compression = formatName
|
|
end
|
|
return v
|
|
end
|
|
|
|
-- api hooks (a format never requires another format): opts.decodeImage / encodeImage, opts.plugins, opts.decodeModule,
|
|
-- opts.openAudio (containers/AudioWrap: PCM -> WAV, Opus / Vorbis -> Ogg, AAC -> ADTS, MP3 / FLAC / AC-3 as they are)
|
|
local function openAudio(demuxer: any, track: any, sbr: boolean?): (any, Err.Err?)
|
|
local buf, fmt, err = AudioWrap.wrap(demuxer, track)
|
|
if not buf then
|
|
return nil, err
|
|
end
|
|
local dec, oerr = F.open(buf, { format = fmt, category = "audio", sbr = sbr })
|
|
-- Matroska CodecDelay: ffmpeg drops it for MPEG audio / AAC; Opus has its own pre-skip and Vorbis's delay is
|
|
-- already the decoder's own (its first packet returns nothing)
|
|
-- MP4 edit lists add the play length (the encoder's end padding is cut, as ffmpeg does)
|
|
if dec and fmt ~= "opus" and fmt ~= "vorbis" then
|
|
local skip = if type(track.codecDelay) == "number" and track.codecDelay > 0 then math.floor(track.codecDelay * dec.sampleRate + 0.5) else 0
|
|
local length = if type(track.playDuration) == "number" and track.playDuration > 0 then math.floor(track.playDuration * dec.sampleRate + 0.5) else nil
|
|
if skip > 0 or length then
|
|
dec = AudioWrap.trim(dec, skip, length)
|
|
end
|
|
end
|
|
return dec, oerr
|
|
end
|
|
|
|
local function withHooks(o: Options): Options
|
|
if o.decodeImage ~= nil and o.encodeImage ~= nil and o.plugins ~= nil and o.openAudio ~= nil and o.decodeModule ~= nil then
|
|
return o
|
|
end
|
|
local c = table.clone(o)
|
|
if c.plugins == nil then
|
|
c.plugins = F.plugins
|
|
end
|
|
if c.openAudio == nil then
|
|
-- opts.sbr reaches the AAC decoder of a video's audio track
|
|
local sbr = o.sbr
|
|
c.openAudio = function(demuxer: any, track: any): (any, Err.Err?)
|
|
return openAudio(demuxer, track, sbr)
|
|
end
|
|
end
|
|
if c.decodeImage == nil then
|
|
c.decodeImage = function(b: buffer): (any, Err.Err?)
|
|
return F.load(b, { category = "image" })
|
|
end
|
|
end
|
|
if c.encodeImage == nil then
|
|
c.encodeImage = function(img: any, format: string): (any, Err.Err?)
|
|
return F.save(img, nil, { format = format, category = "image" })
|
|
end
|
|
end
|
|
if c.decodeModule == nil then
|
|
c.decodeModule = function(b: buffer, format: string?): (any, Err.Err?)
|
|
return F.load(b, { category = "music", format = format })
|
|
end
|
|
end
|
|
return c
|
|
end
|
|
|
|
function F.load(src: any, opts: Options?): (any, Err.Err?)
|
|
local o: Options = opts or {}
|
|
local buf, ierr, name = Input.resolve(src, o, host)
|
|
if not buf then
|
|
return nil, ierr
|
|
end
|
|
if name and o.name == nil then
|
|
o = table.clone(o)
|
|
o.name = name -- formats may use the file name (single-stream archives name their entry after it)
|
|
end
|
|
local entry, derr, rendered = detectFor(buf, name, o)
|
|
if not entry then
|
|
return nil, derr
|
|
end
|
|
local m, merr = module(entry)
|
|
if not m then
|
|
return nil, merr
|
|
end
|
|
if o.resolve == nil and name and name == (type(src) == "string" and src or nil) and host.hasFiles then
|
|
o = table.clone(o)
|
|
o.resolve = siblings(name)
|
|
end
|
|
local value, err
|
|
if m.decode and not rendered then
|
|
local ok, v, e = pcall(m.decode, Bytes.reader(buf), withHooks(o))
|
|
if not ok then
|
|
return nil, Err.wrap(Err.new(Err.CORRUPT, "decoder threw: " .. tostring(v)), entry.name)
|
|
end
|
|
value, err = v, e
|
|
elseif m.open then
|
|
local ok, dec, e = pcall(m.open, Bytes.reader(buf), withHooks(o))
|
|
if not ok then
|
|
return nil, Err.wrap(Err.new(Err.CORRUPT, "decoder threw: " .. tostring(dec)), entry.name)
|
|
end
|
|
if dec then
|
|
value = if type(dec) == "table" and dec.kind == "video" then dec else drain(dec)
|
|
end
|
|
err = e
|
|
else
|
|
return nil, Err.wrap(Err.new(Err.UNSUPPORTED, "no decoder"), entry.name)
|
|
end
|
|
if value == nil then
|
|
return nil, Err.wrap(err or Err.new(Err.CORRUPT, "decode failed"), entry.name)
|
|
end
|
|
tag(value, entry.name)
|
|
pageLoader(value, name, o)
|
|
return unwrap(value, entry.name, o)
|
|
end
|
|
load = F.load
|
|
|
|
function F.open(src: any, opts: Options?): (any, Err.Err?)
|
|
local o: Options = opts or {}
|
|
local buf, ierr, name = Input.resolve(src, o, host)
|
|
if not buf then
|
|
return nil, ierr
|
|
end
|
|
local entry, derr = detectFor(buf, name, o)
|
|
if not entry and o.category == "video" and o.format == nil then
|
|
entry = detect(buf, name, "image", nil) -- animated images open as frames-backed videos
|
|
end
|
|
if not entry then
|
|
return nil, derr
|
|
end
|
|
local m, merr = module(entry)
|
|
if not m then
|
|
return nil, merr
|
|
end
|
|
if not m.open and entry.category == "image" and o.category == "video" then
|
|
local io = table.clone(o)
|
|
io.category = "image"
|
|
io.format = entry.name
|
|
local img, lerr = F.load(buf, io)
|
|
if not img then
|
|
return nil, lerr
|
|
end
|
|
return F.video.fromImage(img, o)
|
|
end
|
|
if not m.open then
|
|
return nil, Err.wrap(Err.new(Err.UNSUPPORTED, "no streaming decoder (use load)"), entry.name)
|
|
end
|
|
local ok, dec, e = pcall(m.open, Bytes.reader(buf), withHooks(o))
|
|
if not ok then
|
|
return nil, Err.wrap(Err.new(Err.CORRUPT, "decoder threw: " .. tostring(dec)), entry.name)
|
|
end
|
|
if dec == nil then
|
|
return nil, Err.wrap(e or Err.new(Err.CORRUPT, "open failed"), entry.name)
|
|
end
|
|
return dec
|
|
end
|
|
|
|
local encodeTextures: (scene: any) -> Err.Err?
|
|
|
|
local function videoToImage(v: any, o: Options): (any, Err.Err?)
|
|
if type(v.nextFrame) ~= "function" or type(v.toRGBA) ~= "function" then
|
|
return nil, Err.new(Err.ARG, "save: not a VideoDecoder")
|
|
end
|
|
local cap = o.maxFrames or 300
|
|
local want = o.frames
|
|
local fps = o.fps
|
|
if type(cap) ~= "number" or cap < 1 or (want ~= nil and (type(want) ~= "number" or want < 1)) or (fps ~= nil and (type(fps) ~= "number" or fps <= 0 or fps > 1000)) then
|
|
return nil, Err.new(Err.ARG, "save: frames / maxFrames must be >= 1 and fps 0..1000")
|
|
end
|
|
local limit = math.floor(if want then math.min(want, cap) else cap)
|
|
local w, h = math.max(1, tonumber(v.width) or 1), math.max(1, tonumber(v.height) or 1)
|
|
limit = math.max(1, math.min(limit, math.floor((o.maxPixels or 2 ^ 25) / (w * h))))
|
|
local defaultDur = if type(v.frameRate) == "number" and v.frameRate > 0 then 1 / v.frameRate else 0.1
|
|
local images: { any }, delays: { number } = {}, {}
|
|
local t0: number? = nil
|
|
local taken = 0 -- output slots used (fps mode)
|
|
while #images < limit do
|
|
local ok, f, ferr = pcall(v.nextFrame, v)
|
|
if not ok then
|
|
return nil, Err.new(Err.CORRUPT, "video decoder threw: " .. tostring(f))
|
|
end
|
|
if f == nil then
|
|
if ferr then
|
|
return nil, ferr
|
|
end
|
|
break
|
|
end
|
|
local dur = if type(f.duration) == "number" and f.duration > 0 then f.duration else defaultDur
|
|
local delay = dur
|
|
if fps then
|
|
local start: number = t0 or f.pts
|
|
t0 = start
|
|
local slots = math.ceil((f.pts - start + dur) * fps - 1e-6) - taken
|
|
delay = slots / fps
|
|
taken += math.max(0, slots)
|
|
end
|
|
if delay > 0 then
|
|
local rok, img = pcall(v.toRGBA, v, f)
|
|
if not rok or type(img) ~= "table" then
|
|
return nil, Err.new(Err.CORRUPT, "frame " .. tostring(f.index) .. " did not convert to rgba8")
|
|
end
|
|
table.insert(images, img)
|
|
table.insert(delays, delay)
|
|
end
|
|
end
|
|
if #images == 0 then
|
|
return nil, Err.new(Err.ARG, "save: the video has no frames")
|
|
end
|
|
local img, ierr = ImageOps.fromFrames(images, delays)
|
|
if not img then
|
|
return nil, ierr
|
|
end
|
|
img.loops = if type(v.loops) == "number" then v.loops else 0
|
|
img.meta.source = { format = v.format }
|
|
return img, nil
|
|
end
|
|
|
|
local TRACKER_FAMILY = { mod = true, s3m = true, xm = true, it = true }
|
|
local function renderMusic(value: any, o: Options): (any, Err.Err?)
|
|
local ok, dec, err
|
|
if value.kind == "midi" then
|
|
local m, merr = F.format("midi")
|
|
if not m then
|
|
return nil, merr
|
|
end
|
|
ok, dec, err = pcall(m.render, value, o)
|
|
elseif TRACKER_FAMILY[value.engine or value.format] == nil and type(value.render) == "function" then
|
|
-- AHX / HVL render through the Module's own method (a failed render is an empty Decoder carrying .err)
|
|
ok, dec = pcall(value.render, value, o)
|
|
if ok and type(dec) == "table" and dec.err then
|
|
return nil, dec.err
|
|
end
|
|
else
|
|
local Tracker: any = require("@rosetta/codecs/audio/Tracker")
|
|
ok, dec, err = pcall(Tracker.render, value, o)
|
|
end
|
|
if not ok then
|
|
return nil, Err.new(Err.ARG, "render threw: " .. tostring(dec))
|
|
end
|
|
if dec == nil then
|
|
return nil, err or Err.new(Err.ARG, "render failed")
|
|
end
|
|
return dec, nil
|
|
end
|
|
|
|
local function encoderFor(value: any, dest: string?, o: Options): (Registry.Entry?, any, Err.Err?, string?)
|
|
local category = o.category
|
|
if category == nil and type(value) == "table" and type(value.kind) == "string" then
|
|
category = KIND_CATEGORY[value.kind]
|
|
end
|
|
local key = o.format or Input.extension(dest)
|
|
if key == nil and type(value) == "table" and type(value.meta) == "table" and type(value.meta.source) == "table" then
|
|
key = value.meta.source.format
|
|
end
|
|
if key == nil then
|
|
return nil, nil, Err.new(Err.ARG, "save: no format (pass opts.format or a destination with an extension)")
|
|
end
|
|
local entry = find(key, category)
|
|
if not entry and category == "image" and type(value) == "table" and value.kind == "image" then
|
|
entry = find(key, "video") -- an (animated) image written as a video: F.convert(gif, "avi")
|
|
end
|
|
if not entry and category == "video" and type(value) == "table" and value.kind == "video" then
|
|
entry = find(key, "image") -- a video written as an animated image (F.save): F.convert(avi, "gif")
|
|
end
|
|
if not entry and category == "music" and type(value) == "table" and (value.kind == "music" or value.kind == "midi") then
|
|
entry = find(key, "audio") -- a Module / Midi saved as audio is rendered first (F.save): F.convert(mod, "wav")
|
|
end
|
|
if not entry then
|
|
return nil, nil, Err.new(Err.UNKNOWN_FORMAT, "no format named " .. key .. (if category then " for " .. category else ""))
|
|
end
|
|
local m, merr = module(entry)
|
|
if not m then
|
|
return nil, nil, merr
|
|
end
|
|
if not m.encode then
|
|
local alt = nil
|
|
for _, e in Registry do
|
|
if e.category == entry.category and e.caps.encode then
|
|
alt = e.name
|
|
break
|
|
end
|
|
end
|
|
return nil, nil, Err.wrap(Err.new(Err.UNSUPPORTED, "read-only format" .. (if alt then "; try " .. alt else "")), entry.name)
|
|
end
|
|
return entry, m, nil, key
|
|
end
|
|
|
|
-- scene textures with only a decoded image get PNG bytes before a model writer sees them (writers never encode images)
|
|
function encodeTextures(scene: any): Err.Err?
|
|
if type(scene.textures) ~= "table" then
|
|
return nil
|
|
end
|
|
for _, tex in scene.textures do
|
|
if type(tex) == "table" and tex.data == nil and type(tex.image) == "table" and tex.uri == nil then
|
|
local png, err = F.save(tex.image, nil, { format = "png" })
|
|
if not png then
|
|
return err
|
|
end
|
|
tex.data, tex.mime = png, "image/png"
|
|
end
|
|
end
|
|
return nil
|
|
end
|
|
|
|
function F.save(value: any, dest: string?, opts: Options?): (any, Err.Err?, { [string]: any }?)
|
|
local o: Options = opts or {}
|
|
local entry, m, err, key = encoderFor(value, dest, o)
|
|
if not entry then
|
|
return nil, err
|
|
end
|
|
o = table.clone(o)
|
|
o.format = o.format or key
|
|
if dest then
|
|
o.name = o.name or string.match(dest, "([^/\\]+)$")
|
|
if o.files == nil then
|
|
o.files = {}
|
|
end
|
|
elseif o.files == nil and entry.caps.extraFiles then
|
|
o.files = {}
|
|
end
|
|
if entry.category == "video" and type(value) == "table" and value.kind == "image" then
|
|
local v, verr = F.video.fromImage(value)
|
|
if not v then
|
|
return nil, verr
|
|
end
|
|
value = v
|
|
end
|
|
if entry.category == "image" and type(value) == "table" and value.kind == "video" then
|
|
local img, ierr = videoToImage(value, o)
|
|
if not img then
|
|
return nil, ierr
|
|
end
|
|
value = img
|
|
end
|
|
if entry.category == "audio" and type(value) == "table" and (value.kind == "music" or value.kind == "midi") then
|
|
local dec, rerr = renderMusic(value, o)
|
|
if not dec then
|
|
return nil, rerr
|
|
end
|
|
value = dec
|
|
end
|
|
if type(value) == "table" and value.kind == "scene" then
|
|
local terr = encodeTextures(value)
|
|
if terr then
|
|
return nil, terr
|
|
end
|
|
end
|
|
local ok, buf, e = pcall(m.encode, value, withHooks(o))
|
|
if not ok then
|
|
return nil, Err.wrap(Err.new(Err.ARG, "encoder threw: " .. tostring(buf)), entry.name)
|
|
end
|
|
if buf == nil then
|
|
return nil, Err.wrap(e or Err.new(Err.ARG, "encode failed"), entry.name)
|
|
end
|
|
if dest then
|
|
local wok, werr = host.writeFile(dest, buf)
|
|
if not wok then
|
|
return nil, werr
|
|
end
|
|
if type(o.files) == "table" and o.files ~= (opts and opts.files) then
|
|
local dir = string.match(dest, "^(.*[/\\])") or ""
|
|
for fname, data in o.files do
|
|
local fok, ferr = host.writeFile(dir .. fname, if type(data) == "string" then buffer.fromstring(data) else data)
|
|
if not fok then
|
|
return nil, ferr
|
|
end
|
|
end
|
|
end
|
|
return true
|
|
end
|
|
if type(o.files) == "table" and o.files ~= (opts and opts.files) and next(o.files) ~= nil then
|
|
return buf, nil, o.files
|
|
end
|
|
return buf
|
|
end
|
|
|
|
function F.saveString(value: any, opts: Options?): (string?, Err.Err?)
|
|
local buf, err = F.save(value, nil, opts)
|
|
if not buf then
|
|
return nil, err
|
|
end
|
|
return buffer.tostring(buf), nil
|
|
end
|
|
|
|
function F.convert(src: any, format: string, opts: Options?): (any, Err.Err?, { [string]: any }?)
|
|
local o: Options = opts or {}
|
|
local value, err = F.load(src, o)
|
|
if value == nil then
|
|
return nil, err
|
|
end
|
|
local so = table.clone(o)
|
|
so.format = format
|
|
so.category = nil
|
|
return F.save(value, o.out, so)
|
|
end
|
|
|
|
function F.detect(src: any, opts: Options?): (string?, Err.Err?)
|
|
local o: Options = opts or {}
|
|
local buf, ierr, name = Input.resolve(src, o, host)
|
|
if not buf then
|
|
return nil, ierr
|
|
end
|
|
local entry, err = detect(buf, name, o.category, o.format)
|
|
if not entry then
|
|
return nil, err
|
|
end
|
|
-- a format may name the file's flavour more precisely (video/mkv: "webm" for DocType webm)
|
|
local m = module(entry)
|
|
if m and type(m.variant) == "function" then
|
|
local ok, v = pcall(m.variant, Bytes.reader(buf))
|
|
if ok and type(v) == "string" then
|
|
return v, nil
|
|
end
|
|
end
|
|
return entry.name, nil
|
|
end
|
|
|
|
export type FormatInfo = { name: string, category: string, extensions: { string }, mime: { string }, caps: { [string]: any } }
|
|
|
|
function F.formats(category: string?): { FormatInfo }
|
|
local out = {}
|
|
for _, e in Registry do
|
|
if inCategory(e, category) then
|
|
table.insert(out, { name = e.name, category = e.category, extensions = e.extensions, mime = e.mime, caps = e.caps })
|
|
end
|
|
end
|
|
return out
|
|
end
|
|
|
|
function F.format(name: string): (any, Err.Err?)
|
|
local e = find(name)
|
|
if not e then
|
|
return nil, Err.new(Err.UNKNOWN_FORMAT, "no format named " .. name)
|
|
end
|
|
return module(e)
|
|
end
|
|
|
|
local function with(opts: Options?, category: string): Options
|
|
local o: Options = if opts then table.clone(opts) else {}
|
|
o.category = category
|
|
return o
|
|
end
|
|
for category in Types.CATEGORIES do
|
|
local cat: string = category
|
|
F[cat] = {
|
|
load = function(src: any, opts: Options?): (any, Err.Err?)
|
|
return F.load(src, with(opts, cat))
|
|
end,
|
|
open = function(src: any, opts: Options?): (any, Err.Err?)
|
|
return F.open(src, with(opts, cat))
|
|
end,
|
|
save = function(value: any, dest: string?, opts: Options?): (any, Err.Err?)
|
|
return F.save(value, dest, with(opts, cat))
|
|
end,
|
|
formats = function(): { FormatInfo }
|
|
return F.formats(cat)
|
|
end,
|
|
}
|
|
end
|
|
F.data.null = Types.null
|
|
|
|
for _, fn in { "toBodies", "fromBodies", "tessellate" } do
|
|
local name: string = fn
|
|
F.cad[name] = function(value: any, opts: Options?): (any, any)
|
|
local o: Options = if opts then table.clone(opts) else {}
|
|
if o.plugins == nil then
|
|
o.plugins = F.plugins
|
|
end
|
|
local m, err = F.format("step")
|
|
if not m then
|
|
return nil, err
|
|
end
|
|
local ok, a, b = pcall(m[name], value, o)
|
|
if not ok then
|
|
return nil, Err.wrap(Err.new(Err.CORRUPT, name .. " threw: " .. tostring(a)), "step")
|
|
end
|
|
if a == nil and type(b) == "table" and b.code then
|
|
return nil, Err.wrap(b, "step")
|
|
end
|
|
return a, b
|
|
end
|
|
end
|
|
for _, fn in { "new", "addPattern", "setCell", "getCell", "addSample", "addInstrument", "note" } do
|
|
local name: string = fn
|
|
F.music[name] = function(...: any): (any, Err.Err?)
|
|
return (F.ops.music :: any)[name](...)
|
|
end
|
|
end
|
|
F.video.fromImage = function(img: any, opts: Options?): (any, Err.Err?)
|
|
if type(img) ~= "table" or img.kind ~= "image" then
|
|
return nil, Err.new(Err.ARG, "fromImage: expected an Image")
|
|
end
|
|
local frames, delays = { img }, { 0.1 }
|
|
if type(img.frames) == "table" and #img.frames > 0 then
|
|
local list, cerr = ImageOps.coalesce(img)
|
|
if not list then
|
|
return nil, cerr
|
|
end
|
|
frames = list
|
|
delays = {}
|
|
for i, f in img.frames do
|
|
delays[i] = if type(f.delay) == "number" and f.delay > 0 then f.delay else 0.1
|
|
end
|
|
elseif img.format ~= "rgba8" and img.format ~= "yuv420p" then
|
|
local c, cerr = ImageOps.convert(img, "rgba8")
|
|
if not c then
|
|
return nil, cerr
|
|
end
|
|
frames = { c }
|
|
end
|
|
local src = type(img.meta) == "table" and img.meta.source
|
|
return Video.fromFrames(frames, delays, { format = type(src) == "table" and src.format or "image", loops = img.loops, meta = img.meta })
|
|
end
|
|
F.video.fromFrames = function(images: any, delays: any?, opts: Options?): (any, Err.Err?)
|
|
return Video.fromFrames(images, delays, opts)
|
|
end
|
|
F.video.codecs = Video
|
|
|
|
F.model.loadTextures = function(scene: any, opts: Options?): (any, { [number]: Err.Err })
|
|
local errs: { [number]: Err.Err } = {}
|
|
if type(scene) ~= "table" or type(scene.textures) ~= "table" then
|
|
return scene, errs
|
|
end
|
|
local resolve: ((any) -> any)? = opts and opts.resolve
|
|
for i, tex in scene.textures do
|
|
if type(tex) == "table" and tex.image == nil then
|
|
local data = tex.data
|
|
if data == nil and tex.uri and resolve then
|
|
data = resolve(tex.uri)
|
|
end
|
|
if data ~= nil then
|
|
local img, err = F.load(data, { category = "image", name = tex.uri, data = true })
|
|
if img then
|
|
tex.image = img
|
|
elseif err then
|
|
errs[i] = err
|
|
end
|
|
end
|
|
end
|
|
end
|
|
return scene, errs
|
|
end
|
|
|
|
local OPS: { [string]: () -> any } = {
|
|
image = function()
|
|
return ImageOps
|
|
end,
|
|
mesh = function()
|
|
return require("@rosetta/ops/MeshOps")
|
|
end,
|
|
layers = function()
|
|
return require("@rosetta/ops/LayerOps")
|
|
end,
|
|
audio = function()
|
|
return require("@rosetta/ops/AudioOps")
|
|
end,
|
|
music = function()
|
|
return require("@rosetta/ops/MusicOps")
|
|
end,
|
|
vector = function()
|
|
return {
|
|
rasterize = function(v: any, w: number?, h: number?, opts: any?): (any, Err.Err?)
|
|
local svg, err = F.format("svg")
|
|
if not svg then
|
|
return nil, err
|
|
end
|
|
local ok, img, rerr = pcall(svg.rasterize, v, w, h, opts)
|
|
if not ok then
|
|
return nil, Err.wrap(Err.new(Err.CORRUPT, "rasterize threw: " .. tostring(img)), "svg")
|
|
end
|
|
if img == nil and rerr then
|
|
return nil, Err.wrap(rerr, "svg")
|
|
end
|
|
return img, rerr
|
|
end,
|
|
}
|
|
end,
|
|
}
|
|
F.ops = setmetatable({}, {
|
|
__index = function(t: any, k: string): any
|
|
local make = OPS[k]
|
|
if not make then
|
|
return nil
|
|
end
|
|
local m = make()
|
|
rawset(t, k, m)
|
|
return m
|
|
end,
|
|
}) :: any
|
|
|
|
return F
|