882 lines
32 KiB
Luau
882 lines
32 KiB
Luau
--!strict
|
|
-- Formats: read, write and convert file formats in pure Luau, on Roblox and on LuaJIT / LÖVE (through tools/build.py).
|
|
-- Every format of a category maps onto one standard type (src/Formats/Types.luau): a PNG and a WebP both load as an
|
|
-- Image. Formats are found through the generated Registry: by content (each format's sniff), then by extension.
|
|
--
|
|
-- local F = require(Formats) -- Roblox: the ModuleScript; LuaJIT: require("formats"); luau: "@formats"
|
|
-- local img, err = F.load(src, opts?) -- src: buffer | string | path (hosts with files); err: core/Err
|
|
-- local img = F.image.load(src) -- the same, restricted to one category (F.audio, F.model, ...)
|
|
-- local dec = F.audio.open(src) -- streaming decoders (audio / video)
|
|
-- local buf = F.save(img, nil, { format = "png" }) -- a buffer; without format: the source format
|
|
-- F.save(img, "out.png") -- a file (the format from the extension), on hosts with files
|
|
-- local s = F.saveString(img, { format = "png" })
|
|
-- local buf = F.convert(src, "png", opts?) -- load + save
|
|
-- F.formats() -- the capability list (also docs/FORMATS.md)
|
|
-- F.ops.image.resize(img, 64, 64) -- editing: F.ops.image / mesh / layers / audio / vector.rasterize
|
|
--
|
|
-- Never throws on bad data or bad arguments: every function returns nil, Err (Err.code, Err.message, tostring(err)).
|
|
local Err = require("@formats/core/Err")
|
|
local Bytes = require("@formats/core/Bytes")
|
|
local Input = require("@formats/core/Input")
|
|
local Types = require("@formats/Types")
|
|
local Registry = require("@formats/Registry")
|
|
local Video = require("@formats/codecs/video/Video")
|
|
local AudioWrap = require("@formats/containers/AudioWrap")
|
|
local ImageOps = require("@formats/ops/ImageOps")
|
|
local host = require("@formats/host")
|
|
|
|
local F = {}
|
|
|
|
F.version = "0.1.0"
|
|
F.Err = Err
|
|
F.Types = Types
|
|
F.Bytes = Bytes
|
|
F.null = Types.null
|
|
F.host = host
|
|
F.plugins = {} :: { [string]: any } -- injected optional dependencies (plugins.brep for cad/step)
|
|
|
|
-- value.kind -> category
|
|
local KIND_CATEGORY: { [string]: string } = {
|
|
image = "image",
|
|
audio = "audio",
|
|
video = "video",
|
|
scene = "model",
|
|
cad = "cad",
|
|
font = "font",
|
|
archive = "archive",
|
|
vector = "vector",
|
|
tilemap = "vector",
|
|
layered = "layered",
|
|
subtitles = "subtitle",
|
|
music = "music",
|
|
midi = "music",
|
|
playlist = "playlist",
|
|
}
|
|
|
|
-- ------------------------------------------------------------------------------------------------ registry access
|
|
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
|
|
|
|
-- find(nameOrExt, category?) -> the entry whose name, then whose extension, matches
|
|
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
|
|
|
|
-- detect(buf, name?, category?, format?) -> entry | nil, Err: opts.format, else the best sniff, else the extension
|
|
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 = 0
|
|
for _, e in Registry do
|
|
if inCategory(e, category) and (e.caps.decode or e.caps.open) 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 ext and table.find(e.extensions, ext) then
|
|
score += 0.01 -- ties go to the extension
|
|
end
|
|
if score > bestScore then
|
|
best, bestScore = e, score
|
|
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
|
|
|
|
-- detectFor(buf, name, o) -> entry | nil, Err, rendered: detect with o.category / o.format; every music file that
|
|
-- renders (MOD, S3M, XM, IT, MIDI) is also audio, so an audio lookup that finds nothing falls back to them (rendered =
|
|
-- true: open the format, which renders it, instead of decoding it)
|
|
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
|
|
|
|
-- full decode through a streaming decoder (audio formats with open but no decode)
|
|
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(path) -> resolve(uri): reads files relative to path's directory (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
|
|
|
|
-- ------------------------------------------------------------------------------------------------ API
|
|
export type Options = { [string]: any } -- format (name or extension), category, path, data, name, + format options
|
|
|
|
local load: (src: any, opts: Options?) -> (any, Err.Err?)
|
|
|
|
-- bitmap fonts (font/bmfont) name their page images: attach a lazy loader, opts.loadPage(file, page) -> Image | buffer
|
|
-- | string, else the files next to the descriptor on hosts with a file system
|
|
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 -- already an Image
|
|
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
|
|
|
|
-- single-stream archives (gzip / zst / xz / bz2 / br: meta.stream) whose one entry sniffs as another archive (a
|
|
-- .tar.gz) load as that inner archive, with meta.compression = the outer format. opts.unwrap = false keeps the outer
|
|
-- one; an explicit opts.format also does.
|
|
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" or not value.meta.stream then
|
|
return value
|
|
end
|
|
local ok, list = pcall(value.list, value)
|
|
if not ok or type(list) ~= "table" or #list ~= 1 then
|
|
return value
|
|
end
|
|
local rok, inner = pcall(value.read, value, list[1].name)
|
|
if not rok or type(inner) ~= "buffer" then
|
|
return value
|
|
end
|
|
local e = detect(inner, nil, "archive", nil)
|
|
if not e then
|
|
return value
|
|
end
|
|
local io = table.clone(o)
|
|
io.category = "archive"
|
|
io.name = list[1].name
|
|
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
|
|
v.meta.compression = formatName
|
|
return v
|
|
end
|
|
|
|
-- Embedded images (PNG inside ICO, JPEG inside TIFF, thumbnails, textures): a format never requires another format,
|
|
-- so the api hands decoders opts.decodeImage(buf) -> Image | nil, Err and encoders opts.encodeImage(img, format) ->
|
|
-- buffer | nil, Err (unless the caller passed its own). Formats work without them (returning Err.UNSUPPORTED for
|
|
-- the embedded parts) when called directly.
|
|
-- They also see the injected plug-ins as opts.plugins (F.plugins: the B-rep kernel for cad/step) unless given their own.
|
|
--
|
|
-- Audio tracks of video containers: opts.openAudio(demuxer, track) -> audio Decoder | nil, Err. The track's packets
|
|
-- become a stream an audio format reads (containers/AudioWrap: PCM -> WAV, Opus / Vorbis -> Ogg, AAC -> ADTS, MP3 /
|
|
-- FLAC as they are), opened through F.open with that format.
|
|
local function openAudio(demuxer: any, track: any): (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" })
|
|
-- 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)
|
|
if dec and fmt ~= "opus" and fmt ~= "vorbis" and type(track.codecDelay) == "number" and track.codecDelay > 0 then
|
|
dec = AudioWrap.trim(dec, math.floor(track.codecDelay * dec.sampleRate + 0.5))
|
|
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 then
|
|
return o
|
|
end
|
|
local c = table.clone(o)
|
|
if c.plugins == nil then
|
|
c.plugins = F.plugins
|
|
end
|
|
if c.openAudio == nil then
|
|
c.openAudio = openAudio
|
|
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
|
|
return c
|
|
end
|
|
|
|
-- load(src, opts?) -> value | nil, Err
|
|
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
|
|
-- files next to the one loaded (OBJ .mtl, glTF .bin / images): opts.resolve(uri) for the decoder
|
|
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
|
|
|
|
-- open(src, opts?) -> a streaming decoder (audio Decoder / VideoDecoder / Demuxer) | nil, Err
|
|
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?
|
|
|
|
-- videoToImage(v, opts) -> an animated rgba8 Image of the video's frames (for the GIF / APNG / WebP writers) | nil,
|
|
-- Err. opts.frames: how many frames to keep (default all, up to the cap); opts.fps: the output frame rate (frames are
|
|
-- picked at 1 / fps steps, each held as long as it covers; default the source's own timing); opts.maxFrames: the cap
|
|
-- (default 300); opts.maxPixels: a cap on frames * width * height (default 2^25). Reads the decoder from where it is.
|
|
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
|
|
|
|
-- renderMusic(value, opts) -> the audio Decoder of a Module (codecs/audio/Tracker) or a Midi (music/midi render) |
|
|
-- nil, Err. opts are the render options: sampleRate, soundfont, gain, tail, interpolation, stereoSeparation, ...
|
|
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)
|
|
else
|
|
local Tracker: any = require("@formats/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
|
|
|
|
-- the writable format for a value: opts.format, the destination's extension, or the source format
|
|
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
|
|
|
|
-- save(value, dest?, opts?) -> buffer (no dest) | true (written to dest) | nil, Err. Formats that write extra files
|
|
-- (caps.extraFiles: bmfont pages) return them without a dest as a third value { [file name] = bytes } (or fill the
|
|
-- caller's opts.files); with a dest they are written next to it.
|
|
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
|
|
-- the encoder sees the format key it was picked by ("glb" vs "gltf"), the destination's name, and (writing a file)
|
|
-- an opts.files table for the extra files it writes (OBJ .mtl, glTF .bin)
|
|
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 = {} -- returned as the third value: F.save(ttf, nil, { format = "bmfont" }) -> fnt, nil, pages
|
|
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) -- the render options (sampleRate, soundfont, loop, ...) come from opts
|
|
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
|
|
|
|
-- saveString(value, opts?) -> string | nil, Err
|
|
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
|
|
|
|
-- convert(src, format, opts?) -> buffer (or true with opts.out = a path) | nil, Err. opts go to both load and save.
|
|
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
|
|
|
|
-- detect(src, opts?) -> format name | nil, Err
|
|
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 } }
|
|
|
|
-- formats(category?) -> { FormatInfo } (no format module is loaded)
|
|
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
|
|
|
|
-- format(name) -> the format module itself (its contract table: sniff / decode / encode / extras such as png.info)
|
|
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
|
|
|
|
-- ------------------------------------------------------------------------------------------------ category facades
|
|
-- F.image.load / save / open / formats, F.audio..., F.model... : the same calls restricted to one category
|
|
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
|
|
|
|
-- F.cad.toBodies(cad, opts?) -> bodies, result | nil, Err; F.cad.fromBodies(bodies, opts?) -> Cad | nil, Err;
|
|
-- F.cad.tessellate(cad | bodies, opts?) -> Scene | nil, Err: cad/step's B-rep calls with the injected kernel
|
|
-- (F.plugins.brep, unless opts.brep / opts.plugins is given). Without a plug-in they return Err.UNSUPPORTED.
|
|
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
|
|
-- F.music.new / addPattern / setCell / getCell / addSample / addInstrument / note: building and editing tracker
|
|
-- Modules (ops/MusicOps, loaded on first use): F.music.new({ format = "mod", channels = 4 }) -> Module
|
|
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(img, opts?) -> a frames-backed VideoDecoder: an animated GIF / APNG / WebP (img.frames, composited
|
|
-- onto full canvases by ImageOps.coalesce) or a still image (one frame). opts.rgba is accepted (frames are rgba8).
|
|
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(images, delays?, opts?) -> a VideoDecoder over a list of same-size images (an image sequence:
|
|
-- F.save(F.video.fromFrames(list, 1 / 25), "out.avi")); delays in seconds (a number = every frame, default 0.1)
|
|
F.video.fromFrames = function(images: any, delays: any?, opts: Options?): (any, Err.Err?)
|
|
return Video.fromFrames(images, delays, opts)
|
|
end
|
|
-- F.video.codecs: the video codec registry (codecs/video/Video: register / entry / fromFourcc / fromMatroska / decoder)
|
|
F.video.codecs = Video
|
|
|
|
-- F.model.loadTextures(scene, opts?) -> scene, { [index]: Err }: decodes each texture's encoded bytes (texture.data, or
|
|
-- texture.uri through opts.resolve) into texture.image with F.image.load. Model formats never decode images
|
|
-- themselves (a format does not require another format); this is the lazy step at the api layer. Textures whose
|
|
-- image format is missing or broken keep image = nil and report an Err.
|
|
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
|
|
|
|
-- ------------------------------------------------------------------------------------------------ ops
|
|
-- F.ops: editing on the standard types, loaded on first use.
|
|
-- F.ops.image ops/ImageOps convert, crop, resize, flip, rotate, blit / composite, coalesce, ...
|
|
-- F.ops.mesh ops/MeshOps triangulate, transform, computeNormals / Tangents, weld, merge, meshVoxels, ...
|
|
-- F.ops.layers ops/LayerOps flatten / flattenFrames a Layered (PSD, Aseprite), leaves
|
|
-- F.ops.audio ops/AudioOps toAudio, gain / gainDb / normalize, mix, remix / downmix / upmix, resample, trim,
|
|
-- concat, fade, peak, rms
|
|
-- F.ops.music ops/MusicOps new, addPattern, setCell / getCell, addSample, addInstrument, note (also on F.music)
|
|
-- F.ops.vector.rasterize(vector, w?, h?, opts?) -> rgba8 Image: the SVG renderer (vector/svg) for any Vector
|
|
local OPS: { [string]: () -> any } = {
|
|
image = function()
|
|
return ImageOps
|
|
end,
|
|
mesh = function()
|
|
return require("@formats/ops/MeshOps")
|
|
end,
|
|
layers = function()
|
|
return require("@formats/ops/LayerOps")
|
|
end,
|
|
audio = function()
|
|
return require("@formats/ops/AudioOps")
|
|
end,
|
|
music = function()
|
|
return require("@formats/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
|