rename: src/Formats -> src/Rosetta, @formats -> @rosetta requires, build/luajit/rosetta + rosetta._compat, build/roblox/Rosetta, ROSETTA_* env/globals, writer vendor strings
This commit is contained in:
1 parent
2956576d7f
commit
22ddcd78fa
941 files changed
+3364
-3364
No files matched your search
@@ -0,0 +1,482 @@
|
||||
--!strict
|
||||
-- ops/AudioOps: editing on the standard Audio (layer 5.5: core, Types and codecs only): a Decoder collected into an
|
||||
-- Audio, gain (linear or dB), normalize, mix, channel remixing (downmix / upmix with the usual WAVE-layout matrices),
|
||||
-- resampling (codecs/audio/Resample), trim, concat, fades, peak / RMS. New code.
|
||||
--
|
||||
-- local AudioOps = require("@rosetta/ops/AudioOps") -- F.ops.audio in the api
|
||||
-- local a = AudioOps.toAudio(F.audio.open(src)) -- an Audio from an Audio or a streaming Decoder
|
||||
-- local louder = AudioOps.gainDb(a, 6) -- every call returns a new Audio | nil, Err (never throws)
|
||||
-- local mono = AudioOps.downmix(a) -- or AudioOps.remix(a, 1); upmix(a, 6)
|
||||
-- local a48 = AudioOps.resample(a, 48000, { quality = "high" })
|
||||
-- local mixed = AudioOps.mix({ a, b }, { 0.5, 0.5 }) -- other rates / channel counts are converted to a's
|
||||
-- local clip = AudioOps.trim(a, 1.5, 4) -- seconds [1.5, 4)
|
||||
-- local both = AudioOps.concat({ a, b })
|
||||
-- local peak, perChannel = AudioOps.peak(a) -- max |sample|; AudioOps.rms(a) the same shape
|
||||
--
|
||||
-- Conventions: samples are the Audio's interleaved f32 (no clipping is applied: values past +-1 are kept, encoders
|
||||
-- clip). Channels are in WAVE order (FL FR C LFE BL BR SL SR, as every decoder returns them). Downmixes follow the
|
||||
-- ITU-R BS.775 coefficients (centre and surrounds at -3 dB, LFE dropped), scaled so a full-scale input cannot
|
||||
-- exceed full scale; upmixes copy mono to FL / FR and stereo to FL / FR (other channels silent). Tags and meta are
|
||||
-- copied from the (first) input.
|
||||
local Err = require("@rosetta/core/Err")
|
||||
local Types = require("@rosetta/Types")
|
||||
local Pcm = require("@rosetta/codecs/audio/Pcm")
|
||||
local Resample = require("@rosetta/codecs/audio/Resample")
|
||||
|
||||
local AudioOps = {}
|
||||
|
||||
local readf32, writef32 = buffer.readf32, buffer.writef32
|
||||
local floor, max, min, abs, sqrt = math.floor, math.max, math.min, math.abs, math.sqrt
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ validation
|
||||
local function isAudio(a: any): boolean
|
||||
return type(a) == "table"
|
||||
and a.kind == "audio"
|
||||
and type(a.samples) == "buffer"
|
||||
and type(a.frames) == "number"
|
||||
and type(a.channels) == "number"
|
||||
and a.channels >= 1
|
||||
and type(a.sampleRate) == "number"
|
||||
and a.sampleRate > 0
|
||||
and buffer.len(a.samples) >= a.frames * a.channels * 4
|
||||
end
|
||||
|
||||
local function bad(what: string): (nil, Err.Err)
|
||||
return nil, Err.new(Err.ARG, what)
|
||||
end
|
||||
|
||||
-- a new Audio with a's rate / tags / meta and the given layout
|
||||
local function like(a: Types.Audio, channels: number, frames: number, rate: number?): Types.Audio
|
||||
local out = Types.Audio.new(rate or a.sampleRate, channels, frames)
|
||||
out.tags = table.clone(a.tags or {})
|
||||
out.meta = table.clone(a.meta or {})
|
||||
return out
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ conversion
|
||||
-- toAudio(audioOrDecoder, opts?) -> Audio: an Audio as it is, a Decoder read to its end (opts.maxFrames: Err.LIMIT
|
||||
-- past it; default 2^31)
|
||||
function AudioOps.toAudio(v: any, opts: { maxFrames: number? }?): (Types.Audio?, Err.Err?)
|
||||
if isAudio(v) then
|
||||
return v, nil
|
||||
end
|
||||
local src, err = Pcm.source(v)
|
||||
if not src then
|
||||
return nil, err
|
||||
end
|
||||
return Pcm.collect(src, opts and opts.maxFrames)
|
||||
end
|
||||
AudioOps.fromDecoder = AudioOps.toAudio
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ levels
|
||||
-- gain(a, factor) -> Audio with every sample times factor
|
||||
function AudioOps.gain(a: Types.Audio, factor: number): (Types.Audio?, Err.Err?)
|
||||
if not isAudio(a) then
|
||||
return bad("gain: expected an Audio")
|
||||
end
|
||||
if type(factor) ~= "number" or factor ~= factor then
|
||||
return bad("gain: factor must be a number")
|
||||
end
|
||||
local n = a.frames * a.channels
|
||||
local out = like(a, a.channels, a.frames)
|
||||
local s, d = a.samples, out.samples
|
||||
for i = 0, n - 1 do
|
||||
writef32(d, i * 4, readf32(s, i * 4) * factor)
|
||||
end
|
||||
return out, nil
|
||||
end
|
||||
|
||||
-- gainDb(a, dB) -> Audio scaled by 10^(dB / 20)
|
||||
function AudioOps.gainDb(a: Types.Audio, db: number): (Types.Audio?, Err.Err?)
|
||||
if type(db) ~= "number" or db ~= db then
|
||||
return bad("gainDb: dB must be a number")
|
||||
end
|
||||
return AudioOps.gain(a, 10 ^ (db / 20))
|
||||
end
|
||||
|
||||
-- peak(a) -> the largest |sample|, { per channel }
|
||||
function AudioOps.peak(a: Types.Audio): (number?, { number } | Err.Err)
|
||||
if not isAudio(a) then
|
||||
return nil, Err.new(Err.ARG, "peak: expected an Audio")
|
||||
end
|
||||
local ch = a.channels
|
||||
local per = table.create(ch, 0)
|
||||
local s = a.samples
|
||||
for f = 0, a.frames - 1 do
|
||||
local p = f * ch * 4
|
||||
for c = 1, ch do
|
||||
local v = abs(readf32(s, p + (c - 1) * 4))
|
||||
if v > per[c] then
|
||||
per[c] = v
|
||||
end
|
||||
end
|
||||
end
|
||||
local m = 0
|
||||
for c = 1, ch do
|
||||
m = max(m, per[c])
|
||||
end
|
||||
return m, per
|
||||
end
|
||||
|
||||
-- rms(a) -> the root mean square over every sample, { per channel } (0 for no frames)
|
||||
function AudioOps.rms(a: Types.Audio): (number?, { number } | Err.Err)
|
||||
if not isAudio(a) then
|
||||
return nil, Err.new(Err.ARG, "rms: expected an Audio")
|
||||
end
|
||||
local ch = a.channels
|
||||
local per = table.create(ch, 0)
|
||||
local s = a.samples
|
||||
for f = 0, a.frames - 1 do
|
||||
local p = f * ch * 4
|
||||
for c = 1, ch do
|
||||
local v = readf32(s, p + (c - 1) * 4)
|
||||
per[c] += v * v
|
||||
end
|
||||
end
|
||||
local total = 0
|
||||
local n = max(1, a.frames)
|
||||
for c = 1, ch do
|
||||
total += per[c]
|
||||
per[c] = sqrt(per[c] / n)
|
||||
end
|
||||
return sqrt(total / (n * ch)), per
|
||||
end
|
||||
|
||||
-- normalize(a, target?) -> Audio scaled so its peak is target (default 1; silence is returned unchanged)
|
||||
function AudioOps.normalize(a: Types.Audio, target: number?): (Types.Audio?, Err.Err?)
|
||||
local p, perr = AudioOps.peak(a)
|
||||
if not p then
|
||||
return nil, perr :: Err.Err
|
||||
end
|
||||
local t = target or 1
|
||||
if type(t) ~= "number" or t ~= t or t < 0 then
|
||||
return bad("normalize: target must be a number >= 0")
|
||||
end
|
||||
return AudioOps.gain(a, if p > 0 then t / p else 1)
|
||||
end
|
||||
|
||||
-- fade(a, inSeconds?, outSeconds?) -> Audio with linear fade-in / fade-out ramps
|
||||
function AudioOps.fade(a: Types.Audio, inSec: number?, outSec: number?): (Types.Audio?, Err.Err?)
|
||||
if not isAudio(a) then
|
||||
return bad("fade: expected an Audio")
|
||||
end
|
||||
local fi = floor(max(0, (inSec or 0) * a.sampleRate) + 0.5)
|
||||
local fo = floor(max(0, (outSec or 0) * a.sampleRate) + 0.5)
|
||||
if fi ~= fi or fo ~= fo then
|
||||
return bad("fade: bad duration")
|
||||
end
|
||||
local out = like(a, a.channels, a.frames)
|
||||
buffer.copy(out.samples, 0, a.samples, 0, a.frames * a.channels * 4)
|
||||
local ch, d, n = a.channels, out.samples, a.frames
|
||||
for f = 0, min(fi, n) - 1 do
|
||||
local g = f / fi
|
||||
for c = 0, ch - 1 do
|
||||
local p = (f * ch + c) * 4
|
||||
writef32(d, p, readf32(d, p) * g)
|
||||
end
|
||||
end
|
||||
for k = 0, min(fo, n) - 1 do
|
||||
local f = n - 1 - k
|
||||
local g = k / fo
|
||||
for c = 0, ch - 1 do
|
||||
local p = (f * ch + c) * 4
|
||||
writef32(d, p, readf32(d, p) * g)
|
||||
end
|
||||
end
|
||||
return out, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ channels
|
||||
-- the WAVE-order speakers of 1 .. 8 channel layouts (as FFmpeg's default layouts)
|
||||
local LAYOUT: { { string } } = {
|
||||
{ "C" },
|
||||
{ "FL", "FR" },
|
||||
{ "FL", "FR", "C" },
|
||||
{ "FL", "FR", "BL", "BR" },
|
||||
{ "FL", "FR", "C", "BL", "BR" },
|
||||
{ "FL", "FR", "C", "LFE", "BL", "BR" },
|
||||
{ "FL", "FR", "C", "LFE", "BC", "SL", "SR" },
|
||||
{ "FL", "FR", "C", "LFE", "BL", "BR", "SL", "SR" },
|
||||
}
|
||||
local H = sqrt(0.5) -- -3 dB
|
||||
-- speaker -> its contribution to (left, right) in a stereo downmix
|
||||
local TO_STEREO: { [string]: { number } } = {
|
||||
FL = { 1, 0 }, FR = { 0, 1 }, C = { H, H }, LFE = { 0, 0 }, BL = { H, 0 }, BR = { 0, H }, SL = { H, 0 },
|
||||
SR = { 0, H }, BC = { 0.5, 0.5 },
|
||||
}
|
||||
|
||||
-- matrix(from, to) -> m[o][i]: output channel o = sum m[o][i] * input i
|
||||
local function matrix(from: number, to: number): { { number } }
|
||||
local m: { { number } } = table.create(to) :: any
|
||||
for o = 1, to do
|
||||
m[o] = table.create(from, 0)
|
||||
end
|
||||
if from == to then
|
||||
for c = 1, to do
|
||||
m[c][c] = 1
|
||||
end
|
||||
return m
|
||||
end
|
||||
local inL, outL = LAYOUT[from], LAYOUT[to]
|
||||
if to < from and inL and outL and to <= 2 then
|
||||
-- down to stereo (then mono = the average of the two)
|
||||
local l: { number }, r: { number } = table.create(from, 0), table.create(from, 0)
|
||||
local sl, sr = 0, 0
|
||||
for i, sp in inL do
|
||||
local w = TO_STEREO[sp] or { 0, 0 }
|
||||
l[i], r[i] = w[1], w[2]
|
||||
sl += w[1]
|
||||
sr += w[2]
|
||||
end
|
||||
local norm = 1 / max(sl, sr, 1)
|
||||
for i = 1, from do
|
||||
if to == 2 then
|
||||
m[1][i], m[2][i] = l[i] * norm, r[i] * norm
|
||||
else
|
||||
m[1][i] = (l[i] + r[i]) * norm * 0.5
|
||||
end
|
||||
end
|
||||
return m
|
||||
end
|
||||
if from == 1 then
|
||||
-- mono up: FL and FR (or the only channel)
|
||||
if outL then
|
||||
local placed = false
|
||||
for o, sp in outL do
|
||||
if sp == "FL" or sp == "FR" then
|
||||
m[o][1] = 1
|
||||
placed = true
|
||||
end
|
||||
end
|
||||
if not placed then
|
||||
m[1][1] = 1
|
||||
end
|
||||
else
|
||||
m[1][1] = 1
|
||||
end
|
||||
return m
|
||||
end
|
||||
if inL and outL then
|
||||
-- same-named speakers carry over; down: missing speakers fold into the stereo pair at their weights
|
||||
local outIdx: { [string]: number } = {}
|
||||
for o, sp in outL do
|
||||
outIdx[sp] = o
|
||||
end
|
||||
for i, sp in inL do
|
||||
local o = outIdx[sp]
|
||||
if o then
|
||||
m[o][i] = 1
|
||||
elseif to < from and outIdx.FL ~= nil and outIdx.FR ~= nil then
|
||||
local w = TO_STEREO[sp] or { 0, 0 }
|
||||
local fl, fr = outIdx.FL :: number, outIdx.FR :: number
|
||||
m[fl][i] += w[1]
|
||||
m[fr][i] += w[2]
|
||||
end
|
||||
end
|
||||
if to < from then
|
||||
for o = 1, to do
|
||||
local s = 0
|
||||
for i = 1, from do
|
||||
s += m[o][i]
|
||||
end
|
||||
if s > 1 then
|
||||
for i = 1, from do
|
||||
m[o][i] /= s
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
return m
|
||||
end
|
||||
-- unknown layouts: channel i -> i, extra outputs silent, extra inputs dropped
|
||||
for c = 1, min(from, to) do
|
||||
m[c][c] = 1
|
||||
end
|
||||
return m
|
||||
end
|
||||
AudioOps.matrix = matrix
|
||||
|
||||
-- remix(a, channels, m?) -> Audio with that many channels (m: an explicit m[out][in] matrix; default matrix(...))
|
||||
function AudioOps.remix(a: Types.Audio, channels: number, m: { { number } }?): (Types.Audio?, Err.Err?)
|
||||
if not isAudio(a) then
|
||||
return bad("remix: expected an Audio")
|
||||
end
|
||||
if type(channels) ~= "number" or channels < 1 or channels > 256 or channels % 1 ~= 0 then
|
||||
return bad("remix: channels must be 1 .. 256")
|
||||
end
|
||||
local from = a.channels
|
||||
local mm = m or matrix(from, channels)
|
||||
if type(mm) ~= "table" or #mm ~= channels then
|
||||
return bad("remix: the matrix needs one row per output channel")
|
||||
end
|
||||
for o = 1, channels do
|
||||
if type(mm[o]) ~= "table" then
|
||||
return bad("remix: matrix row " .. o .. " is not a table")
|
||||
end
|
||||
end
|
||||
local out = like(a, channels, a.frames)
|
||||
local s, d = a.samples, out.samples
|
||||
local x = table.create(from, 0)
|
||||
for f = 0, a.frames - 1 do
|
||||
local p = f * from * 4
|
||||
for i = 1, from do
|
||||
x[i] = readf32(s, p + (i - 1) * 4)
|
||||
end
|
||||
local q = f * channels * 4
|
||||
for o = 1, channels do
|
||||
local row = mm[o]
|
||||
local v = 0
|
||||
for i = 1, from do
|
||||
local w = row[i]
|
||||
if w and w ~= 0 then
|
||||
v += w * x[i]
|
||||
end
|
||||
end
|
||||
writef32(d, q + (o - 1) * 4, v)
|
||||
end
|
||||
end
|
||||
return out, nil
|
||||
end
|
||||
|
||||
-- downmix(a, channels?) -> Audio with fewer channels (default 2; mono input stays mono)
|
||||
function AudioOps.downmix(a: Types.Audio, channels: number?): (Types.Audio?, Err.Err?)
|
||||
if not isAudio(a) then
|
||||
return bad("downmix: expected an Audio")
|
||||
end
|
||||
local n = channels or min(2, a.channels)
|
||||
if n > a.channels then
|
||||
return bad("downmix: more output channels than input")
|
||||
end
|
||||
return AudioOps.remix(a, n)
|
||||
end
|
||||
|
||||
-- upmix(a, channels) -> Audio with more channels
|
||||
function AudioOps.upmix(a: Types.Audio, channels: number): (Types.Audio?, Err.Err?)
|
||||
if not isAudio(a) then
|
||||
return bad("upmix: expected an Audio")
|
||||
end
|
||||
if type(channels) ~= "number" or channels < a.channels then
|
||||
return bad("upmix: fewer output channels than input")
|
||||
end
|
||||
return AudioOps.remix(a, channels)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ time
|
||||
-- resample(a, rate, opts?) -> Audio at the new rate (codecs/audio/Resample: opts.quality "low" | "medium" | "high")
|
||||
function AudioOps.resample(a: Types.Audio, rate: number, opts: Resample.Options?): (Types.Audio?, Err.Err?)
|
||||
if not isAudio(a) then
|
||||
return bad("resample: expected an Audio")
|
||||
end
|
||||
local samples, frames = Resample.buffer(a.samples, a.frames, a.channels, a.sampleRate, rate, opts)
|
||||
if not samples then
|
||||
return bad("resample: " .. tostring(frames))
|
||||
end
|
||||
local out = like(a, a.channels, 0, rate)
|
||||
out.samples = samples
|
||||
out.frames = frames :: number
|
||||
return out, nil
|
||||
end
|
||||
|
||||
-- trim(a, start, stop?) -> Audio of the seconds [start, stop) (clamped to the audio; stop default the end)
|
||||
function AudioOps.trim(a: Types.Audio, start: number, stop: number?): (Types.Audio?, Err.Err?)
|
||||
if not isAudio(a) then
|
||||
return bad("trim: expected an Audio")
|
||||
end
|
||||
if type(start) ~= "number" or start ~= start or (stop ~= nil and (type(stop) ~= "number" or stop ~= stop)) then
|
||||
return bad("trim: start / stop must be numbers (seconds)")
|
||||
end
|
||||
local f0 = math.clamp(floor(start * a.sampleRate + 0.5), 0, a.frames)
|
||||
local f1 = if stop then math.clamp(floor(stop * a.sampleRate + 0.5), f0, a.frames) else a.frames
|
||||
local ch = a.channels
|
||||
local out = like(a, ch, f1 - f0)
|
||||
buffer.copy(out.samples, 0, a.samples, f0 * ch * 4, (f1 - f0) * ch * 4)
|
||||
return out, nil
|
||||
end
|
||||
|
||||
-- conform(list, what) -> the audios converted to the first one's rate and channel count | nil, Err
|
||||
local function conform(list: { Types.Audio }, what: string): ({ Types.Audio }?, Err.Err?)
|
||||
if type(list) ~= "table" or #list == 0 then
|
||||
return nil, Err.new(Err.ARG, what .. ": expected a non-empty list of Audio")
|
||||
end
|
||||
local first = list[1]
|
||||
if not isAudio(first) then
|
||||
return nil, Err.new(Err.ARG, what .. ": item 1 is not an Audio")
|
||||
end
|
||||
local out = { first }
|
||||
for i = 2, #list do
|
||||
local a = list[i]
|
||||
if not isAudio(a) then
|
||||
return nil, Err.new(Err.ARG, what .. ": item " .. i .. " is not an Audio")
|
||||
end
|
||||
if a.sampleRate ~= first.sampleRate then
|
||||
local r, err = AudioOps.resample(a, first.sampleRate)
|
||||
if not r then
|
||||
return nil, err
|
||||
end
|
||||
a = r
|
||||
end
|
||||
if a.channels ~= first.channels then
|
||||
local r, err = AudioOps.remix(a, first.channels)
|
||||
if not r then
|
||||
return nil, err
|
||||
end
|
||||
a = r
|
||||
end
|
||||
out[i] = a
|
||||
end
|
||||
return out, nil
|
||||
end
|
||||
|
||||
-- concat(list) -> Audio: the audios one after the other (at the first one's rate and channel count)
|
||||
function AudioOps.concat(list: { Types.Audio }): (Types.Audio?, Err.Err?)
|
||||
local items, err = conform(list, "concat")
|
||||
if not items then
|
||||
return nil, err
|
||||
end
|
||||
local first = items[1]
|
||||
local ch = first.channels
|
||||
local total = 0
|
||||
for _, a in items do
|
||||
total += a.frames
|
||||
end
|
||||
local out = like(first, ch, total)
|
||||
local at = 0
|
||||
for _, a in items do
|
||||
buffer.copy(out.samples, at * ch * 4, a.samples, 0, a.frames * ch * 4)
|
||||
at += a.frames
|
||||
end
|
||||
return out, nil
|
||||
end
|
||||
|
||||
-- mix(list, weights?) -> Audio: the sum of the audios (times weights[i], default 1 each), as long as the longest, at
|
||||
-- the first one's rate and channel count
|
||||
function AudioOps.mix(list: { Types.Audio }, weights: { number }?): (Types.Audio?, Err.Err?)
|
||||
local items, err = conform(list, "mix")
|
||||
if not items then
|
||||
return nil, err
|
||||
end
|
||||
if weights ~= nil and type(weights) ~= "table" then
|
||||
return bad("mix: weights must be a list of numbers")
|
||||
end
|
||||
local first = items[1]
|
||||
local ch = first.channels
|
||||
local frames = 0
|
||||
for _, a in items do
|
||||
frames = max(frames, a.frames)
|
||||
end
|
||||
local out = like(first, ch, frames)
|
||||
local d = out.samples
|
||||
for i, a in items do
|
||||
local w = if weights then weights[i] or 1 else 1
|
||||
if type(w) ~= "number" then
|
||||
return bad("mix: weight " .. i .. " is not a number")
|
||||
end
|
||||
local s = a.samples
|
||||
for k = 0, a.frames * ch - 1 do
|
||||
writef32(d, k * 4, readf32(d, k * 4) + readf32(s, k * 4) * w)
|
||||
end
|
||||
end
|
||||
return out, nil
|
||||
end
|
||||
|
||||
return AudioOps
|
||||
@@ -0,0 +1,520 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- ops/ImageOps/Kernels: the hot loops behind ops/ImageOps (native; never throws). Every function trusts its caller
|
||||
-- (ops/ImageOps validates sizes, formats and buffer lengths first), so all buffer indexes are in range by
|
||||
-- construction. Samples are addressed by kind: 1 = u8, 2 = u16, 4 = f32 (little endian, as Types.Image buffers).
|
||||
-- The resampling follows Pillow's Resample.c (separable convolution, horizontal pass first, filter support scaled by
|
||||
-- the downscale ratio, 22-bit fixed-point coefficients for 8-bit samples) and Geometry.c (affine transforms through
|
||||
-- pixel centres, bilinear with clamped neighbours); the alpha compositing is Pillow's AlphaComposite.c.
|
||||
local readu8, writeu8, readu16, writeu16, readf32, writef32 = buffer.readu8, buffer.writeu8, buffer.readu16, buffer.writeu16, buffer.readf32, buffer.writef32
|
||||
local floor, clamp = math.floor, math.clamp
|
||||
|
||||
local K = {}
|
||||
|
||||
-- format ids: rgba8 1, rgba16 2, rgbaf32 3, rgb8 4, gray8 5, gray16 6, graya8 7, alpha8 8
|
||||
K.ID = { rgba8 = 1, rgba16 = 2, rgbaf32 = 3, rgb8 = 4, gray8 = 5, gray16 = 6, graya8 = 7, alpha8 = 8 } :: { [string]: number }
|
||||
K.KIND = { rgba8 = 1, rgba16 = 2, rgbaf32 = 4, rgb8 = 1, gray8 = 1, gray16 = 2, graya8 = 1, alpha8 = 1 } :: { [string]: number }
|
||||
K.CHANNELS = { rgba8 = 4, rgba16 = 4, rgbaf32 = 4, rgb8 = 3, gray8 = 1, gray16 = 1, graya8 = 2, alpha8 = 1 } :: { [string]: number }
|
||||
|
||||
local function rd(b: buffer, o: number, kind: number): number
|
||||
if kind == 1 then
|
||||
return readu8(b, o)
|
||||
elseif kind == 2 then
|
||||
return readu16(b, o)
|
||||
end
|
||||
return readf32(b, o)
|
||||
end
|
||||
|
||||
local function wr(b: buffer, o: number, kind: number, v: number)
|
||||
if kind == 1 then
|
||||
writeu8(b, o, clamp(floor(v + 0.5), 0, 255))
|
||||
elseif kind == 2 then
|
||||
writeu16(b, o, clamp(floor(v + 0.5), 0, 65535))
|
||||
else
|
||||
writef32(b, o, v)
|
||||
end
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ convert
|
||||
-- depth: 8 -> 0..255, 16 -> 0..65535, 0 -> float 0..1
|
||||
local DEPTH = { 8, 16, 0, 8, 8, 16, 8, 8 }
|
||||
|
||||
local function depthConv(v: number, from: number, to: number): number
|
||||
if from == to then
|
||||
return v
|
||||
end
|
||||
if from == 8 then
|
||||
if to == 16 then
|
||||
return v * 257
|
||||
end
|
||||
return v / 255
|
||||
elseif from == 16 then
|
||||
if to == 8 then
|
||||
return (v * 255 + 32767) // 65535
|
||||
end
|
||||
return v / 65535
|
||||
end
|
||||
-- float
|
||||
if v ~= v then
|
||||
v = 0
|
||||
end
|
||||
if to == 8 then
|
||||
return clamp(floor(v * 255 + 0.5), 0, 255)
|
||||
end
|
||||
return clamp(floor(v * 65535 + 0.5), 0, 65535)
|
||||
end
|
||||
|
||||
-- Pillow's L24 luma (19595 R + 38470 G + 7471 B + 0x8000) >> 16, in the source depth
|
||||
local function luma(r: number, g: number, b: number, depth: number): number
|
||||
if depth == 0 then
|
||||
return (r * 19595 + g * 38470 + b * 7471) / 65536
|
||||
end
|
||||
return (r * 19595 + g * 38470 + b * 7471 + 32768) // 65536
|
||||
end
|
||||
|
||||
function K.convert(src: buffer, sf: number, dst: buffer, df: number, n: number)
|
||||
local sd, dd = DEPTH[sf] :: number, DEPTH[df] :: number
|
||||
local smax = if sd == 8 then 255 elseif sd == 16 then 65535 else 1
|
||||
local toGray = df == 5 or df == 6 or df == 7
|
||||
for i = 0, n - 1 do
|
||||
local r: number, g: number, b: number, a: number
|
||||
if sf == 1 then
|
||||
local o = i * 4
|
||||
r, g, b, a = readu8(src, o), readu8(src, o + 1), readu8(src, o + 2), readu8(src, o + 3) :: number
|
||||
elseif sf == 2 then
|
||||
local o = i * 8
|
||||
r, g, b, a = readu16(src, o), readu16(src, o + 2), readu16(src, o + 4), readu16(src, o + 6) :: number
|
||||
elseif sf == 3 then
|
||||
local o = i * 16
|
||||
r, g, b, a = readf32(src, o), readf32(src, o + 4), readf32(src, o + 8), readf32(src, o + 12) :: number
|
||||
elseif sf == 4 then
|
||||
local o = i * 3
|
||||
r, g, b, a = readu8(src, o), readu8(src, o + 1), readu8(src, o + 2), 255
|
||||
elseif sf == 5 then
|
||||
local v = readu8(src, i)
|
||||
r, g, b, a = v, v, v, 255
|
||||
elseif sf == 6 then
|
||||
local v = readu16(src, i * 2)
|
||||
r, g, b, a = v, v, v, 65535
|
||||
elseif sf == 7 then
|
||||
local v = readu8(src, i * 2)
|
||||
r, g, b, a = v, v, v, readu8(src, i * 2 + 1) :: number
|
||||
else
|
||||
r, g, b, a = 255, 255, 255, readu8(src, i)
|
||||
end
|
||||
if toGray then
|
||||
local isGray = sf == 5 or sf == 6 or sf == 7
|
||||
local l = if isGray then r else luma(r, g, b, sd)
|
||||
l = depthConv(l, sd, dd)
|
||||
if df == 5 then
|
||||
writeu8(dst, i, l)
|
||||
elseif df == 6 then
|
||||
writeu16(dst, i * 2, l)
|
||||
else
|
||||
writeu8(dst, i * 2, l)
|
||||
writeu8(dst, i * 2 + 1, depthConv(a, sd, dd))
|
||||
end
|
||||
elseif df == 8 then
|
||||
writeu8(dst, i, depthConv(a, sd, 8))
|
||||
else
|
||||
r, g, b = depthConv(r, sd, dd), depthConv(g, sd, dd), depthConv(b, sd, dd) :: number
|
||||
if df == 1 then
|
||||
local o = i * 4
|
||||
writeu8(dst, o, r)
|
||||
writeu8(dst, o + 1, g)
|
||||
writeu8(dst, o + 2, b)
|
||||
writeu8(dst, o + 3, depthConv(a, sd, dd))
|
||||
elseif df == 2 then
|
||||
local o = i * 8
|
||||
writeu16(dst, o, r)
|
||||
writeu16(dst, o + 2, g)
|
||||
writeu16(dst, o + 4, b)
|
||||
writeu16(dst, o + 6, depthConv(a, sd, dd))
|
||||
elseif df == 3 then
|
||||
local o = i * 16
|
||||
writef32(dst, o, r)
|
||||
writef32(dst, o + 4, g)
|
||||
writef32(dst, o + 8, b)
|
||||
writef32(dst, o + 12, if a == smax and sd ~= 0 then 1 else depthConv(a, sd, dd))
|
||||
else -- rgb8
|
||||
local o = i * 3
|
||||
writeu8(dst, o, r)
|
||||
writeu8(dst, o + 1, g)
|
||||
writeu8(dst, o + 2, b)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- JPEG-style BT.601 full range
|
||||
function K.rgbaToYuv(src: buffer, w: number, h: number, dst: buffer)
|
||||
local cw, ch = (w + 1) // 2, (h + 1) // 2
|
||||
local uo, vo = w * h, w * h + cw * ch
|
||||
for i = 0, w * h - 1 do
|
||||
local o = i * 4
|
||||
local r, g, b = readu8(src, o), readu8(src, o + 1), readu8(src, o + 2)
|
||||
writeu8(dst, i, clamp(floor(0.299 * r + 0.587 * g + 0.114 * b + 0.5), 0, 255))
|
||||
end
|
||||
for cy = 0, ch - 1 do
|
||||
for cx = 0, cw - 1 do
|
||||
local sr, sg, sb, n = 0, 0, 0, 0
|
||||
for dy = 0, 1 do
|
||||
local y = cy * 2 + dy
|
||||
if y < h then
|
||||
for dx = 0, 1 do
|
||||
local x = cx * 2 + dx
|
||||
if x < w then
|
||||
local o = (y * w + x) * 4
|
||||
sr += readu8(src, o)
|
||||
sg += readu8(src, o + 1)
|
||||
sb += readu8(src, o + 2)
|
||||
n += 1
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
sr, sg, sb = sr / n, sg / n, sb / n
|
||||
local i = cy * cw + cx
|
||||
writeu8(dst, uo + i, clamp(floor(128 - 0.168736 * sr - 0.331264 * sg + 0.5 * sb + 0.5), 0, 255))
|
||||
writeu8(dst, vo + i, clamp(floor(128 + 0.5 * sr - 0.418688 * sg - 0.081312 * sb + 0.5), 0, 255))
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function K.yuvToRgba(src: buffer, w: number, h: number, dst: buffer)
|
||||
local cw, ch = (w + 1) // 2, (h + 1) // 2
|
||||
local uo, vo = w * h, w * h + cw * ch
|
||||
for y = 0, h - 1 do
|
||||
local crow = (y // 2) * cw
|
||||
for x = 0, w - 1 do
|
||||
local yy = readu8(src, y * w + x)
|
||||
local ci = crow + x // 2
|
||||
local u, v = readu8(src, uo + ci) - 128, readu8(src, vo + ci) - 128
|
||||
local o = (y * w + x) * 4
|
||||
writeu8(dst, o, clamp(floor(yy + 1.402 * v + 0.5), 0, 255))
|
||||
writeu8(dst, o + 1, clamp(floor(yy - 0.344136 * u - 0.714136 * v + 0.5), 0, 255))
|
||||
writeu8(dst, o + 2, clamp(floor(yy + 1.772 * u + 0.5), 0, 255))
|
||||
writeu8(dst, o + 3, 255)
|
||||
end
|
||||
end
|
||||
local _ = ch
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ geometry
|
||||
-- flip(src, dst, w, h, bpp, horizontal)
|
||||
function K.flip(src: buffer, dst: buffer, w: number, h: number, bpp: number, horizontal: boolean)
|
||||
local stride = w * bpp
|
||||
if not horizontal then
|
||||
for y = 0, h - 1 do
|
||||
buffer.copy(dst, (h - 1 - y) * stride, src, y * stride, stride)
|
||||
end
|
||||
return
|
||||
end
|
||||
for y = 0, h - 1 do
|
||||
local row = y * stride
|
||||
for x = 0, w - 1 do
|
||||
buffer.copy(dst, row + (w - 1 - x) * bpp, src, row + x * bpp, bpp)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- rotate90(src, dst, w, h, bpp, turns): counter-clockwise quarter turns 1..3
|
||||
function K.rotate90(src: buffer, dst: buffer, w: number, h: number, bpp: number, turns: number)
|
||||
for y = 0, h - 1 do
|
||||
for x = 0, w - 1 do
|
||||
local ox, oy, ow
|
||||
if turns == 1 then
|
||||
ox, oy, ow = y, w - 1 - x, h
|
||||
elseif turns == 2 then
|
||||
ox, oy, ow = w - 1 - x, h - 1 - y, w
|
||||
else
|
||||
ox, oy, ow = h - 1 - y, x, h
|
||||
end
|
||||
local so, d = (y * w + x) * bpp, (oy * ow + ox) * bpp
|
||||
if bpp == 4 then
|
||||
buffer.writeu32(dst, d, buffer.readu32(src, so))
|
||||
else
|
||||
buffer.copy(dst, d, src, so, bpp)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ resample
|
||||
local function bilinearF(x: number): number
|
||||
if x < 0 then
|
||||
x = -x
|
||||
end
|
||||
if x < 1 then
|
||||
return 1 - x
|
||||
end
|
||||
return 0
|
||||
end
|
||||
|
||||
local function sinc(x: number): number
|
||||
if x == 0 then
|
||||
return 1
|
||||
end
|
||||
x *= math.pi
|
||||
return math.sin(x) / x
|
||||
end
|
||||
|
||||
local function lanczosF(x: number): number
|
||||
if x > -3 and x < 3 then
|
||||
return sinc(x) * sinc(x / 3)
|
||||
end
|
||||
return 0
|
||||
end
|
||||
|
||||
local function trunc(x: number): number
|
||||
return if x < 0 then math.ceil(x) else floor(x)
|
||||
end
|
||||
|
||||
-- Pillow precompute_coeffs: per output index its first input index, tap count and weights (normalised)
|
||||
export type Coeffs = { start: { number }, count: { number }, weights: { { number } } }
|
||||
|
||||
function K.coeffs(inSize: number, outSize: number, filter: string): Coeffs
|
||||
local support0 = if filter == "lanczos" then 3 else 1
|
||||
local f = if filter == "lanczos" then lanczosF else bilinearF
|
||||
local scale = inSize / outSize
|
||||
local filterscale = math.max(scale, 1)
|
||||
local support = support0 * filterscale
|
||||
local ss = 1 / filterscale
|
||||
local start, count, weights = table.create(outSize, 0), table.create(outSize, 0), table.create(outSize) :: { { number } }
|
||||
for xx = 0, outSize - 1 do
|
||||
local center = (xx + 0.5) * scale
|
||||
local xmin = math.max(0, trunc(center - support + 0.5))
|
||||
local xmax = math.min(inSize, trunc(center + support + 0.5)) - xmin
|
||||
local w = table.create(math.max(xmax, 0), 0)
|
||||
local ww = 0
|
||||
for x = 0, xmax - 1 do
|
||||
local v = f((x + xmin - center + 0.5) * ss)
|
||||
w[x + 1] = v
|
||||
ww += v
|
||||
end
|
||||
if ww ~= 0 then
|
||||
for x = 1, xmax do
|
||||
w[x] /= ww
|
||||
end
|
||||
end
|
||||
start[xx + 1], count[xx + 1], weights[xx + 1] = xmin, math.max(xmax, 0), w
|
||||
end
|
||||
return { start = start, count = count, weights = weights }
|
||||
end
|
||||
|
||||
-- one separable pass. horizontal: src w x h -> dst outN x h; vertical: src w x h -> dst w x outN. ch channels of kind.
|
||||
function K.resamplePass(src: buffer, w: number, h: number, ch: number, kind: number, dst: buffer, outN: number, c: Coeffs, horizontal: boolean)
|
||||
local start, count, weights = c.start, c.count, c.weights
|
||||
local size = kind
|
||||
local fixed = kind == 1
|
||||
-- 8-bit: Pillow's 22-bit fixed-point coefficients
|
||||
local iw: { { number } } = weights
|
||||
if fixed then
|
||||
iw = table.create(outN) :: { { number } }
|
||||
for i = 1, outN do
|
||||
local src0 = weights[i]
|
||||
local t = table.create(#src0, 0)
|
||||
for k = 1, #src0 do
|
||||
local v = src0[k] * 4194304
|
||||
t[k] = if v < 0 then math.ceil(v - 0.5) else floor(v + 0.5)
|
||||
end
|
||||
iw[i] = t
|
||||
end
|
||||
end
|
||||
if horizontal then
|
||||
for y = 0, h - 1 do
|
||||
local row = y * w
|
||||
for xx = 0, outN - 1 do
|
||||
local s0, n, wt = start[xx + 1], count[xx + 1], iw[xx + 1]
|
||||
local o = ((y * outN) + xx) * ch * size
|
||||
for cc = 0, ch - 1 do
|
||||
if fixed then
|
||||
local acc = 2097152
|
||||
for k = 0, n - 1 do
|
||||
acc += readu8(src, (row + s0 + k) * ch + cc) * wt[k + 1]
|
||||
end
|
||||
writeu8(dst, o + cc, clamp(acc // 4194304, 0, 255))
|
||||
else
|
||||
local acc = 0
|
||||
for k = 0, n - 1 do
|
||||
acc += rd(src, ((row + s0 + k) * ch + cc) * size, kind) * wt[k + 1]
|
||||
end
|
||||
wr(dst, o + cc * size, kind, acc)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
else
|
||||
for yy = 0, outN - 1 do
|
||||
local s0, n, wt = start[yy + 1], count[yy + 1], iw[yy + 1]
|
||||
for x = 0, w - 1 do
|
||||
local o = (yy * w + x) * ch * size
|
||||
for cc = 0, ch - 1 do
|
||||
if fixed then
|
||||
local acc = 2097152
|
||||
for k = 0, n - 1 do
|
||||
acc += readu8(src, ((s0 + k) * w + x) * ch + cc) * wt[k + 1]
|
||||
end
|
||||
writeu8(dst, o + cc, clamp(acc // 4194304, 0, 255))
|
||||
else
|
||||
local acc = 0
|
||||
for k = 0, n - 1 do
|
||||
acc += rd(src, (((s0 + k) * w + x) * ch + cc) * size, kind) * wt[k + 1]
|
||||
end
|
||||
wr(dst, o + cc * size, kind, acc)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
local _ = h
|
||||
end
|
||||
|
||||
-- nearest: dst pixel (x, y) = src pixel (floor((x + 0.5) * w / ow), ...)
|
||||
function K.nearest(src: buffer, w: number, h: number, bpp: number, dst: buffer, ow: number, oh: number)
|
||||
local sx, sy = w / ow, h / oh
|
||||
for y = 0, oh - 1 do
|
||||
local iy = math.min(floor((y + 0.5) * sy), h - 1)
|
||||
for x = 0, ow - 1 do
|
||||
local ix = math.min(floor((x + 0.5) * sx), w - 1)
|
||||
buffer.copy(dst, (y * ow + x) * bpp, src, (iy * w + ix) * bpp, bpp)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- affine(src, w, h, ch, kind, dst, ow, oh, m): dst pixel centres mapped through m = { a, b, c, d, e, f } to src
|
||||
-- coordinates (xin = a x + b y + c), bilinear with clamped neighbours; centres outside the source -> zeros (Pillow)
|
||||
function K.affine(src: buffer, w: number, h: number, ch: number, kind: number, dst: buffer, ow: number, oh: number, m: { number })
|
||||
local a, b, c, d, e, f = m[1], m[2], m[3], m[4], m[5], m[6]
|
||||
local size = kind
|
||||
for y = 0, oh - 1 do
|
||||
local py = y + 0.5
|
||||
for x = 0, ow - 1 do
|
||||
local px = x + 0.5
|
||||
local xin = a * px + b * py + c - 0.5
|
||||
local yin = d * px + e * py + f - 0.5
|
||||
local o = (y * ow + x) * ch * size
|
||||
local x0 = floor(xin)
|
||||
local y0 = floor(yin)
|
||||
if xin < -0.5 or xin >= w - 0.5 or yin < -0.5 or yin >= h - 0.5 then
|
||||
continue -- dst starts zeroed
|
||||
end
|
||||
local dx, dy = xin - x0, yin - y0
|
||||
local xa, xb = clamp(x0, 0, w - 1), clamp(x0 + 1, 0, w - 1)
|
||||
local ya, yb = clamp(y0, 0, h - 1), clamp(y0 + 1, 0, h - 1)
|
||||
for cc = 0, ch - 1 do
|
||||
local p00 = rd(src, ((ya * w + xa) * ch + cc) * size, kind)
|
||||
local p01 = rd(src, ((ya * w + xb) * ch + cc) * size, kind)
|
||||
local p10 = rd(src, ((yb * w + xa) * ch + cc) * size, kind)
|
||||
local p11 = rd(src, ((yb * w + xb) * ch + cc) * size, kind)
|
||||
local top = p00 + (p01 - p00) * dx
|
||||
local bot = p10 + (p11 - p10) * dx
|
||||
local v = top + (bot - top) * dy
|
||||
if kind == 1 then
|
||||
writeu8(dst, o + cc, clamp(floor(v), 0, 255)) -- Pillow truncates
|
||||
else
|
||||
wr(dst, o + cc * size, kind, v)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ compositing
|
||||
-- overRgba8(dst, dw, src, sw, sx, sy, dx, dy, w, h, opacity255): Pillow's alpha_composite of src onto dst, in place
|
||||
function K.overRgba8(dst: buffer, dw: number, src: buffer, sw: number, sx: number, sy: number, dx: number, dy: number, w: number, h: number, opacity: number)
|
||||
for y = 0, h - 1 do
|
||||
for x = 0, w - 1 do
|
||||
local so = ((sy + y) * sw + sx + x) * 4
|
||||
local doff = ((dy + y) * dw + dx + x) * 4
|
||||
local sa = readu8(src, so + 3)
|
||||
if opacity < 255 then
|
||||
sa = (sa * opacity + 127) // 255
|
||||
end
|
||||
if sa == 0 then
|
||||
continue
|
||||
end
|
||||
local da = readu8(dst, doff + 3)
|
||||
local blend = da * (255 - sa)
|
||||
local outa255 = sa * 255 + blend
|
||||
local coef1 = (sa * 255 * 255 * 128) // outa255
|
||||
local coef2 = 255 * 128 - coef1
|
||||
for cc = 0, 2 do
|
||||
local t = readu8(src, so + cc) * coef1 + readu8(dst, doff + cc) * coef2 + 0x80 * 128
|
||||
t = ((t // 256) + t) // 256
|
||||
writeu8(dst, doff + cc, t // 128)
|
||||
end
|
||||
local t = outa255 + 0x80
|
||||
writeu8(dst, doff + 3, ((t // 256) + t) // 256)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- overFloat: straight-alpha "over" for rgba16 (kind 2) / rgbaf32 (kind 4); max = 65535 or 1
|
||||
function K.overFloat(dst: buffer, dw: number, src: buffer, sw: number, sx: number, sy: number, dx: number, dy: number, w: number, h: number, opacity: number, kind: number)
|
||||
local max = if kind == 2 then 65535 else 1
|
||||
local px = 4 * kind
|
||||
for y = 0, h - 1 do
|
||||
for x = 0, w - 1 do
|
||||
local so = ((sy + y) * sw + sx + x) * px
|
||||
local doff = ((dy + y) * dw + dx + x) * px
|
||||
local sa = rd(src, so + 3 * kind, kind) / max * opacity
|
||||
if sa <= 0 then
|
||||
continue
|
||||
end
|
||||
local da = rd(dst, doff + 3 * kind, kind) / max
|
||||
local oa = sa + da * (1 - sa)
|
||||
for cc = 0, 2 do
|
||||
local s = rd(src, so + cc * kind, kind)
|
||||
local d = rd(dst, doff + cc * kind, kind)
|
||||
wr(dst, doff + cc * kind, kind, if oa > 0 then (s * sa + d * da * (1 - sa)) / oa else 0)
|
||||
end
|
||||
wr(dst, doff + 3 * kind, kind, oa * max)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- copyRect: rows of a rectangle (bpp bytes per pixel)
|
||||
function K.copyRect(dst: buffer, dw: number, src: buffer, sw: number, sx: number, sy: number, dx: number, dy: number, w: number, h: number, bpp: number)
|
||||
for y = 0, h - 1 do
|
||||
buffer.copy(dst, ((dy + y) * dw + dx) * bpp, src, ((sy + y) * sw + sx) * bpp, w * bpp)
|
||||
end
|
||||
end
|
||||
|
||||
-- premultiply / unpremultiply in place: ch channels, alpha last, kind
|
||||
function K.premultiply(b: buffer, n: number, ch: number, kind: number, un: boolean)
|
||||
local max = if kind == 1 then 255 elseif kind == 2 then 65535 else 1
|
||||
local px = ch * kind
|
||||
for i = 0, n - 1 do
|
||||
local o = i * px
|
||||
local a = rd(b, o + (ch - 1) * kind, kind)
|
||||
for cc = 0, ch - 2 do
|
||||
local v = rd(b, o + cc * kind, kind)
|
||||
local r
|
||||
if un then
|
||||
if a <= 0 then
|
||||
r = 0
|
||||
elseif kind == 4 then
|
||||
r = v / a
|
||||
elseif kind == 1 then
|
||||
r = math.min(255, (v * 255) // a) -- Pillow's rgbA2rgba
|
||||
else
|
||||
r = math.min(max, (v * max + a // 2) // a)
|
||||
end
|
||||
else
|
||||
if kind == 4 then
|
||||
r = v * a
|
||||
elseif kind == 1 then
|
||||
local t = v * a + 128 -- Pillow's MULDIV255
|
||||
r = ((t // 256) + t) // 256
|
||||
else
|
||||
r = (v * a + max // 2) // max
|
||||
end
|
||||
end
|
||||
wr(b, o + cc * kind, kind, r)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
return K
|
||||
@@ -0,0 +1,689 @@
|
||||
--!strict
|
||||
-- ops/ImageOps: editing on the standard Image (layer 5.5: core, Types and codecs only). Pixel format conversion,
|
||||
-- crop, resize (nearest / bilinear / Lanczos-3, as Pillow), flips, quarter turns and arbitrary rotation (bilinear, as
|
||||
-- Pillow's rotate), alpha compositing (Pillow's alpha_composite for rgba8), premultiplication, pixel access, and
|
||||
-- helpers for animations (Image.frames). New code; the resampling and compositing follow Pillow's C sources.
|
||||
--
|
||||
-- local Ops = require("@rosetta/ops/ImageOps")
|
||||
-- local small = Ops.resize(img, 320, 240, "lanczos") -- every call returns a new Image | nil, Err (never throws)
|
||||
-- local grey = Ops.convert(img, "gray8")
|
||||
-- Ops.blit(canvas, sprite, 10, 20) -- in place on canvas, straight-alpha "over"
|
||||
-- for i, frame in Ops.coalesce(gif) do ... end -- full-canvas frames of an animation
|
||||
--
|
||||
-- Conventions: angles are degrees counter-clockwise and rotate90 turns are counter-clockwise quarter turns (as
|
||||
-- Pillow). Resizing and rotating filter premultiplied alpha (as Pillow does for RGBA / LA). Grey is Pillow's
|
||||
-- L = (19595 R + 38470 G + 7471 B + 32768) >> 16. 8 <-> 16 bit is * 257 and
|
||||
-- (v * 255 + 32767) // 65535; float <-> integer clamps to 0..1 and rounds (no gamma). alpha8 converts to white with
|
||||
-- that alpha. yuv420p is JPEG-style BT.601 full range (2x2 box chroma); geometric ops on yuv420p go through rgba8.
|
||||
local Err = require("@rosetta/core/Err")
|
||||
local Types = require("@rosetta/Types")
|
||||
local K = require("@rosetta/ops/ImageOps/Kernels")
|
||||
|
||||
local ImageOps = {}
|
||||
|
||||
local MAX_PIXELS = 2 ^ 26
|
||||
|
||||
type Image = Types.Image
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ validation
|
||||
local function arg(msg: string): (nil, Err.Err)
|
||||
return nil, Err.new(Err.ARG, msg)
|
||||
end
|
||||
|
||||
local function isInt(v: any): boolean
|
||||
return type(v) == "number" and v == v and v % 1 == 0 and v > -2 ^ 31 and v < 2 ^ 31
|
||||
end
|
||||
|
||||
local function bytesOf(fmt: string, w: number, h: number): number?
|
||||
if fmt == "yuv420p" then
|
||||
return w * h + 2 * ((w + 1) // 2) * ((h + 1) // 2)
|
||||
end
|
||||
local bpp = Types.BPP[fmt]
|
||||
return if bpp then w * h * bpp else nil
|
||||
end
|
||||
|
||||
-- check(img) -> true | nil, Err: a well-formed Image (known format, sizes, buffer long enough)
|
||||
local function check(img: any): (boolean?, Err.Err?)
|
||||
if type(img) ~= "table" or type(img.pixels) ~= "buffer" then
|
||||
return arg("expected an Image")
|
||||
end
|
||||
if not isInt(img.width) or not isInt(img.height) or img.width < 1 or img.height < 1 then
|
||||
return arg("bad image size")
|
||||
end
|
||||
local need = bytesOf(img.format, img.width, img.height)
|
||||
if not need then
|
||||
return arg("unknown pixel format " .. tostring(img.format))
|
||||
end
|
||||
if buffer.len(img.pixels) < need then
|
||||
return arg("pixel buffer too small for " .. img.width .. " x " .. img.height .. " " .. img.format)
|
||||
end
|
||||
return true, nil
|
||||
end
|
||||
ImageOps.check = check
|
||||
|
||||
local function limit(w: number, h: number, opts: any): (boolean?, Err.Err?)
|
||||
local max: number = (type(opts) == "table" and opts.maxPixels) or MAX_PIXELS
|
||||
if w * h > max then
|
||||
return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, max))
|
||||
end
|
||||
return true, nil
|
||||
end
|
||||
|
||||
-- a new Image of the same kind with a copy of meta's plain fields (source, palette...) but no frames
|
||||
local function like(img: Image, w: number, h: number, fmt: string?): Image
|
||||
local out = Types.Image.new(w, h, (fmt or img.format) :: any)
|
||||
for k, v in img.meta do
|
||||
out.meta[k] = v
|
||||
end
|
||||
out.loops = img.loops
|
||||
return out
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ basics
|
||||
-- new(w, h, format?) -> a zero-filled Image | nil, Err
|
||||
function ImageOps.new(w: number, h: number, format: string?): (Image?, Err.Err?)
|
||||
local fmt = format or "rgba8"
|
||||
if not isInt(w) or not isInt(h) or w < 1 or h < 1 then
|
||||
return arg("bad image size")
|
||||
end
|
||||
if not bytesOf(fmt, 1, 1) then
|
||||
return arg("unknown pixel format " .. tostring(fmt))
|
||||
end
|
||||
local ok, e = limit(w, h, nil)
|
||||
if not ok then
|
||||
return nil, e
|
||||
end
|
||||
return Types.Image.new(w, h, fmt :: any), nil
|
||||
end
|
||||
|
||||
-- copy(img) -> a deep copy of the pixels (frames are shared)
|
||||
function ImageOps.copy(img: Image): (Image?, Err.Err?)
|
||||
local ok, e = check(img)
|
||||
if not ok then
|
||||
return nil, e
|
||||
end
|
||||
local out = like(img, img.width, img.height)
|
||||
buffer.copy(out.pixels, 0, img.pixels, 0, buffer.len(out.pixels))
|
||||
out.frames = img.frames
|
||||
return out, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ convert
|
||||
-- convert(img, format) -> a new Image in format (a copy when it is already)
|
||||
function ImageOps.convert(img: Image, format: string): (Image?, Err.Err?)
|
||||
local ok, e = check(img)
|
||||
if not ok then
|
||||
return nil, e
|
||||
end
|
||||
if not bytesOf(format, 1, 1) then
|
||||
return arg("unknown pixel format " .. tostring(format))
|
||||
end
|
||||
local w, h = img.width, img.height
|
||||
if img.format == format then
|
||||
return ImageOps.copy(img)
|
||||
end
|
||||
local src = img
|
||||
if img.format == "yuv420p" then
|
||||
local rgba = like(img, w, h, "rgba8")
|
||||
K.yuvToRgba(img.pixels, w, h, rgba.pixels)
|
||||
if format == "rgba8" then
|
||||
return rgba, nil
|
||||
end
|
||||
src = rgba
|
||||
end
|
||||
local out = like(img, w, h, format)
|
||||
if format == "yuv420p" then
|
||||
local rgba = src
|
||||
if src.format ~= "rgba8" then
|
||||
rgba = like(img, w, h, "rgba8")
|
||||
K.convert(src.pixels, K.ID[src.format], rgba.pixels, K.ID.rgba8, w * h)
|
||||
end
|
||||
K.rgbaToYuv(rgba.pixels, w, h, out.pixels)
|
||||
return out, nil
|
||||
end
|
||||
K.convert(src.pixels, K.ID[src.format], out.pixels, K.ID[format], w * h)
|
||||
return out, nil
|
||||
end
|
||||
|
||||
-- ops on yuv420p run on rgba8 and convert back
|
||||
local function viaRgba(img: Image, f: (Image) -> (Image?, Err.Err?)): (Image?, Err.Err?)
|
||||
if img.format ~= "yuv420p" then
|
||||
return f(img)
|
||||
end
|
||||
local rgba = ImageOps.convert(img, "rgba8") :: Image
|
||||
local res, e = f(rgba)
|
||||
if not res then
|
||||
return nil, e
|
||||
end
|
||||
return ImageOps.convert(res, "yuv420p")
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ geometry
|
||||
local ALPHA_CH: { [string]: number } = { rgba8 = 4, rgba16 = 4, rgbaf32 = 4, graya8 = 2 }
|
||||
|
||||
-- crop(img, x, y, w, h) -> the rectangle clipped to the image | nil, Err (empty)
|
||||
function ImageOps.crop(img: Image, x: number, y: number, w: number, h: number): (Image?, Err.Err?)
|
||||
local ok, e = check(img)
|
||||
if not ok then
|
||||
return nil, e
|
||||
end
|
||||
if not (isInt(x) and isInt(y) and isInt(w) and isInt(h)) then
|
||||
return arg("crop: integer x, y, w, h")
|
||||
end
|
||||
local x0, y0 = math.max(0, x), math.max(0, y)
|
||||
local x1, y1 = math.min(img.width, x + w), math.min(img.height, y + h)
|
||||
if x1 <= x0 or y1 <= y0 then
|
||||
return arg("crop: the rectangle is outside the image or empty")
|
||||
end
|
||||
return viaRgba(img, function(im: Image): (Image?, Err.Err?)
|
||||
local bpp = Types.BPP[im.format] :: number
|
||||
local out = like(im, x1 - x0, y1 - y0)
|
||||
K.copyRect(out.pixels, out.width, im.pixels, im.width, x0, y0, 0, 0, out.width, out.height, bpp)
|
||||
return out, nil
|
||||
end)
|
||||
end
|
||||
|
||||
-- flip(img, "h" | "v") -> mirrored horizontally (left-right) or vertically (top-bottom)
|
||||
function ImageOps.flip(img: Image, axis: string): (Image?, Err.Err?)
|
||||
local ok, e = check(img)
|
||||
if not ok then
|
||||
return nil, e
|
||||
end
|
||||
if axis ~= "h" and axis ~= "v" then
|
||||
return arg("flip: axis must be \"h\" or \"v\"")
|
||||
end
|
||||
return viaRgba(img, function(im: Image): (Image?, Err.Err?)
|
||||
local out = like(im, im.width, im.height)
|
||||
K.flip(im.pixels, out.pixels, im.width, im.height, Types.BPP[im.format] :: number, axis == "h")
|
||||
return out, nil
|
||||
end)
|
||||
end
|
||||
|
||||
-- rotate90(img, turns) -> turned by turns counter-clockwise quarter turns (any integer; negative = clockwise)
|
||||
function ImageOps.rotate90(img: Image, turns: number): (Image?, Err.Err?)
|
||||
local ok, e = check(img)
|
||||
if not ok then
|
||||
return nil, e
|
||||
end
|
||||
if not isInt(turns) then
|
||||
return arg("rotate90: integer turns")
|
||||
end
|
||||
local t = turns % 4
|
||||
if t == 0 then
|
||||
return ImageOps.copy(img)
|
||||
end
|
||||
return viaRgba(img, function(im: Image): (Image?, Err.Err?)
|
||||
local swap = t ~= 2
|
||||
local out = like(im, if swap then im.height else im.width, if swap then im.width else im.height)
|
||||
K.rotate90(im.pixels, out.pixels, im.width, im.height, Types.BPP[im.format] :: number, t)
|
||||
return out, nil
|
||||
end)
|
||||
end
|
||||
|
||||
export type ResizeFilter = "nearest" | "bilinear" | "lanczos"
|
||||
|
||||
-- resize(img, w, h, filter?, opts?) -> w x h (filter default "bilinear"; opts.maxPixels)
|
||||
function ImageOps.resize(img: Image, w: number, h: number, filter: string?, opts: any?): (Image?, Err.Err?)
|
||||
local ok, e = check(img)
|
||||
if not ok then
|
||||
return nil, e
|
||||
end
|
||||
if not isInt(w) or not isInt(h) or w < 1 or h < 1 then
|
||||
return arg("resize: bad target size")
|
||||
end
|
||||
local f = filter or "bilinear"
|
||||
if f ~= "nearest" and f ~= "bilinear" and f ~= "lanczos" then
|
||||
return arg("resize: filter must be nearest, bilinear or lanczos")
|
||||
end
|
||||
local lok, le = limit(w, h, opts)
|
||||
if not lok then
|
||||
return nil, le
|
||||
end
|
||||
return viaRgba(img, function(im: Image): (Image?, Err.Err?)
|
||||
local fmt = im.format
|
||||
local bpp = Types.BPP[fmt] :: number
|
||||
local out = like(im, w, h)
|
||||
if f == "nearest" then
|
||||
K.nearest(im.pixels, im.width, im.height, bpp, out.pixels, w, h)
|
||||
return out, nil
|
||||
end
|
||||
local kind, ch = K.KIND[fmt], K.CHANNELS[fmt]
|
||||
local src, sw, sh = im.pixels, im.width, im.height
|
||||
local alpha = ALPHA_CH[fmt]
|
||||
if alpha then
|
||||
src = buffer.create(buffer.len(im.pixels))
|
||||
buffer.copy(src, 0, im.pixels)
|
||||
K.premultiply(src, sw * sh, alpha, kind, false)
|
||||
end
|
||||
if w ~= sw then
|
||||
local tmp = buffer.create(w * sh * bpp)
|
||||
K.resamplePass(src, sw, sh, ch, kind, tmp, w, K.coeffs(sw, w, f), true)
|
||||
src, sw = tmp, w
|
||||
end
|
||||
if h ~= sh then
|
||||
K.resamplePass(src, sw, sh, ch, kind, out.pixels, h, K.coeffs(sh, h, f), false)
|
||||
elseif src == im.pixels or (w == im.width and alpha) then
|
||||
buffer.copy(out.pixels, 0, im.pixels, 0, w * h * bpp)
|
||||
return out, nil
|
||||
else
|
||||
out.pixels = src
|
||||
end
|
||||
if alpha then
|
||||
K.premultiply(out.pixels, w * h, alpha, kind, true)
|
||||
end
|
||||
return out, nil
|
||||
end)
|
||||
end
|
||||
|
||||
-- rotate(img, degrees, opts?) -> rotated counter-clockwise about the centre with bilinear sampling (as Pillow's
|
||||
-- rotate(angle, BILINEAR, expand)): opts.expand (default true) grows the canvas to hold the whole image; uncovered
|
||||
-- pixels are zero (transparent). opts.maxPixels.
|
||||
function ImageOps.rotate(img: Image, degrees: number, opts: { expand: boolean?, maxPixels: number? }?): (Image?, Err.Err?)
|
||||
local ok, e = check(img)
|
||||
if not ok then
|
||||
return nil, e
|
||||
end
|
||||
if type(degrees) ~= "number" or degrees ~= degrees or degrees == math.huge or degrees == -math.huge then
|
||||
return arg("rotate: degrees must be a finite number")
|
||||
end
|
||||
local expand = not (opts and opts.expand == false)
|
||||
if degrees % 90 == 0 and (expand or degrees % 180 == 0 or img.width == img.height) then
|
||||
return ImageOps.rotate90(img, (degrees // 90) % 4)
|
||||
end
|
||||
local w, h = img.width, img.height
|
||||
local ang = -math.rad(degrees)
|
||||
local function r15(v: number): number
|
||||
return math.floor(v * 1e15 + 0.5) / 1e15
|
||||
end
|
||||
local m = { r15(math.cos(ang)), r15(math.sin(ang)), 0, r15(-math.sin(ang)), r15(math.cos(ang)), 0 }
|
||||
local function tr(x: number, y: number): (number, number)
|
||||
return m[1] * x + m[2] * y + m[3], m[4] * x + m[5] * y + m[6]
|
||||
end
|
||||
local cx, cy = w / 2, h / 2
|
||||
m[3], m[6] = tr(-cx, -cy)
|
||||
m[3] += cx
|
||||
m[6] += cy
|
||||
local nw, nh = w, h
|
||||
if expand then
|
||||
local xs, ys = {}, {}
|
||||
for _, p in { { 0, 0 }, { w, 0 }, { w, h }, { 0, h } } do
|
||||
local x, y = tr(p[1], p[2])
|
||||
table.insert(xs, x)
|
||||
table.insert(ys, y)
|
||||
end
|
||||
nw = math.ceil(math.max(xs[1], xs[2], xs[3], xs[4])) - math.floor(math.min(xs[1], xs[2], xs[3], xs[4]))
|
||||
nh = math.ceil(math.max(ys[1], ys[2], ys[3], ys[4])) - math.floor(math.min(ys[1], ys[2], ys[3], ys[4]))
|
||||
m[3], m[6] = tr(-(nw - w) / 2, -(nh - h) / 2)
|
||||
end
|
||||
local lok, le = limit(nw, nh, opts)
|
||||
if not lok then
|
||||
return nil, le
|
||||
end
|
||||
return viaRgba(img, function(im: Image): (Image?, Err.Err?)
|
||||
local out = like(im, nw, nh)
|
||||
local kind = K.KIND[im.format]
|
||||
local alpha = ALPHA_CH[im.format]
|
||||
local src = im.pixels
|
||||
if alpha then
|
||||
src = buffer.create(buffer.len(im.pixels))
|
||||
buffer.copy(src, 0, im.pixels)
|
||||
K.premultiply(src, w * h, alpha, kind, false)
|
||||
end
|
||||
K.affine(src, w, h, K.CHANNELS[im.format], kind, out.pixels, nw, nh, m)
|
||||
if alpha then
|
||||
K.premultiply(out.pixels, nw * nh, alpha, kind, true)
|
||||
end
|
||||
return out, nil
|
||||
end)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ compositing
|
||||
local RGBA: { [string]: boolean } = { rgba8 = true, rgba16 = true, rgbaf32 = true }
|
||||
|
||||
export type BlitOptions = { blend: ("over" | "source")?, opacity: number? }
|
||||
|
||||
-- blit(dst, src, x, y, opts?) -> dst (modified in place) | nil, Err. src is clipped to dst; it is converted to dst's
|
||||
-- format first when they differ. blend "over" (default: Porter-Duff over, straight alpha; Pillow's alpha_composite
|
||||
-- for rgba8) or "source" (copy); opts.opacity 0..1 scales src alpha ("over" only).
|
||||
function ImageOps.blit(dst: Image, src: Image, x: number, y: number, opts: BlitOptions?): (Image?, Err.Err?)
|
||||
local ok, e = check(dst)
|
||||
if not ok then
|
||||
return nil, e
|
||||
end
|
||||
local ok2, e2 = check(src)
|
||||
if not ok2 then
|
||||
return nil, e2
|
||||
end
|
||||
if not isInt(x) or not isInt(y) then
|
||||
return arg("blit: integer x, y")
|
||||
end
|
||||
local blend = (opts and opts.blend) or "over"
|
||||
if blend ~= "over" and blend ~= "source" then
|
||||
return arg("blit: blend must be \"over\" or \"source\"")
|
||||
end
|
||||
local opacity = (opts and opts.opacity) or 1
|
||||
if type(opacity) ~= "number" or not (opacity >= 0 and opacity <= 1) then
|
||||
return arg("blit: opacity must be 0..1")
|
||||
end
|
||||
-- clip
|
||||
local sx, sy = math.max(0, -x), math.max(0, -y)
|
||||
local dx, dy = math.max(0, x), math.max(0, y)
|
||||
local w = math.min(src.width - sx, dst.width - dx)
|
||||
local h = math.min(src.height - sy, dst.height - dy)
|
||||
if w <= 0 or h <= 0 then
|
||||
return dst, nil
|
||||
end
|
||||
if dst.format == "yuv420p" or (blend == "over" and not RGBA[dst.format]) then
|
||||
-- work on an rgba copy of the region, then write it back in dst's format
|
||||
local region = ImageOps.crop(dst, dx, dy, w, h) :: Image
|
||||
local work = if region.format == "rgba8" then region else ImageOps.convert(region, "rgba8") :: Image
|
||||
ImageOps.blit(work, src, x - dx, y - dy, opts)
|
||||
if dst.format == "yuv420p" then
|
||||
local full = ImageOps.convert(dst, "rgba8") :: Image
|
||||
ImageOps.blit(full, work, dx, dy, { blend = "source" })
|
||||
local back = ImageOps.convert(full, "yuv420p") :: Image
|
||||
buffer.copy(dst.pixels, 0, back.pixels, 0, buffer.len(back.pixels))
|
||||
else
|
||||
local back = ImageOps.convert(work, dst.format) :: Image
|
||||
K.copyRect(dst.pixels, dst.width, back.pixels, back.width, 0, 0, dx, dy, w, h, Types.BPP[dst.format] :: number)
|
||||
end
|
||||
return dst, nil
|
||||
end
|
||||
local s = src
|
||||
if src.format ~= dst.format then
|
||||
s = ImageOps.convert(src, dst.format) :: Image
|
||||
end
|
||||
if blend == "source" then
|
||||
K.copyRect(dst.pixels, dst.width, s.pixels, s.width, sx, sy, dx, dy, w, h, Types.BPP[dst.format] :: number)
|
||||
elseif dst.format == "rgba8" then
|
||||
K.overRgba8(dst.pixels, dst.width, s.pixels, s.width, sx, sy, dx, dy, w, h, math.floor(opacity * 255 + 0.5))
|
||||
else
|
||||
K.overFloat(dst.pixels, dst.width, s.pixels, s.width, sx, sy, dx, dy, w, h, opacity, K.KIND[dst.format])
|
||||
end
|
||||
return dst, nil
|
||||
end
|
||||
|
||||
-- composite(dst, src, x?, y?, opts?) -> a new Image: a copy of dst with src blitted onto it
|
||||
function ImageOps.composite(dst: Image, src: Image, x: number?, y: number?, opts: BlitOptions?): (Image?, Err.Err?)
|
||||
local out, e = ImageOps.copy(dst)
|
||||
if not out then
|
||||
return nil, e
|
||||
end
|
||||
out.frames = nil
|
||||
return ImageOps.blit(out, src, x or 0, y or 0, opts)
|
||||
end
|
||||
|
||||
local function premul(img: Image, un: boolean): (Image?, Err.Err?)
|
||||
local out, e = ImageOps.copy(img)
|
||||
if not out then
|
||||
return nil, e
|
||||
end
|
||||
out.frames = nil
|
||||
local ch = ALPHA_CH[img.format]
|
||||
if ch then
|
||||
K.premultiply(out.pixels, img.width * img.height, ch, K.KIND[img.format], un)
|
||||
end
|
||||
return out, nil
|
||||
end
|
||||
|
||||
-- premultiply(img) / unpremultiply(img) -> a new Image (formats without alpha are copied unchanged)
|
||||
function ImageOps.premultiply(img: Image): (Image?, Err.Err?)
|
||||
return premul(img, false)
|
||||
end
|
||||
function ImageOps.unpremultiply(img: Image): (Image?, Err.Err?)
|
||||
return premul(img, true)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ pixels
|
||||
local MAXV: { [string]: number } = { rgba8 = 255, rgba16 = 65535, rgbaf32 = 1, rgb8 = 255, gray8 = 255, gray16 = 65535, graya8 = 255, alpha8 = 255, yuv420p = 255 }
|
||||
|
||||
-- getPixel(img, x, y) -> r, g, b, a in the format's scale (0..255, 0..65535 or float); grey gives r = g = b;
|
||||
-- alpha8 gives white; yuv420p converts to RGB. nil, Err out of range.
|
||||
function ImageOps.getPixel(img: Image, x: number, y: number): (any, any, number?, number?)
|
||||
local ok, e = check(img)
|
||||
if not ok then
|
||||
return nil, e
|
||||
end
|
||||
if not isInt(x) or not isInt(y) or x < 0 or y < 0 or x >= img.width or y >= img.height then
|
||||
return arg("getPixel: coordinates out of range")
|
||||
end
|
||||
local b, f, i = img.pixels, img.format, y * img.width + x
|
||||
local ru8, ru16, rf = buffer.readu8, buffer.readu16, buffer.readf32
|
||||
if f == "rgba8" then
|
||||
return ru8(b, i * 4), ru8(b, i * 4 + 1), ru8(b, i * 4 + 2), ru8(b, i * 4 + 3)
|
||||
elseif f == "rgba16" then
|
||||
return ru16(b, i * 8), ru16(b, i * 8 + 2), ru16(b, i * 8 + 4), ru16(b, i * 8 + 6)
|
||||
elseif f == "rgbaf32" then
|
||||
return rf(b, i * 16), rf(b, i * 16 + 4), rf(b, i * 16 + 8), rf(b, i * 16 + 12)
|
||||
elseif f == "rgb8" then
|
||||
return ru8(b, i * 3), ru8(b, i * 3 + 1), ru8(b, i * 3 + 2), 255
|
||||
elseif f == "gray8" then
|
||||
local v = ru8(b, i)
|
||||
return v, v, v, 255
|
||||
elseif f == "gray16" then
|
||||
local v = ru16(b, i * 2)
|
||||
return v, v, v, 65535
|
||||
elseif f == "graya8" then
|
||||
local v = ru8(b, i * 2)
|
||||
return v, v, v, ru8(b, i * 2 + 1)
|
||||
elseif f == "alpha8" then
|
||||
return 255, 255, 255, ru8(b, i)
|
||||
end
|
||||
local one = ImageOps.crop(img, x - x % 2, y - y % 2, 2, 2) :: Image
|
||||
local rgba = ImageOps.convert(one, "rgba8") :: Image
|
||||
local j = ((y % 2) * rgba.width + (x % 2)) * 4
|
||||
if j + 4 > buffer.len(rgba.pixels) then
|
||||
j = 0
|
||||
end
|
||||
return ru8(rgba.pixels, j), ru8(rgba.pixels, j + 1), ru8(rgba.pixels, j + 2), 255
|
||||
end
|
||||
|
||||
-- setPixel(img, x, y, r, g, b, a?) -> true (in place) | nil, Err. Values in the format's scale (clamped and
|
||||
-- rounded for integer formats); grey formats take Pillow's luma of r, g, b; a defaults to opaque. Not for yuv420p.
|
||||
function ImageOps.setPixel(img: Image, x: number, y: number, r: number, g: number, b: number, a: number?): (boolean?, Err.Err?)
|
||||
local ok, e = check(img)
|
||||
if not ok then
|
||||
return nil, e
|
||||
end
|
||||
if not isInt(x) or not isInt(y) or x < 0 or y < 0 or x >= img.width or y >= img.height then
|
||||
return arg("setPixel: coordinates out of range")
|
||||
end
|
||||
if type(r) ~= "number" or type(g) ~= "number" or type(b) ~= "number" or (a ~= nil and type(a) ~= "number") then
|
||||
return arg("setPixel: numeric channels")
|
||||
end
|
||||
local f = img.format
|
||||
if f == "yuv420p" then
|
||||
return arg("setPixel: not supported on yuv420p (convert to rgba8 first)")
|
||||
end
|
||||
local max = MAXV[f]
|
||||
local al = if a == nil then max else a
|
||||
local function q(v: number): number
|
||||
if max == 1 then
|
||||
return v
|
||||
end
|
||||
if v ~= v then
|
||||
return 0
|
||||
end
|
||||
return math.clamp(math.floor(v + 0.5), 0, max)
|
||||
end
|
||||
local px, i = img.pixels, y * img.width + x
|
||||
local wu8, wu16, wf = buffer.writeu8, buffer.writeu16, buffer.writef32
|
||||
local function grey(): number
|
||||
if max == 1 then
|
||||
return (r * 19595 + g * 38470 + b * 7471) / 65536
|
||||
end
|
||||
return (q(r) * 19595 + q(g) * 38470 + q(b) * 7471 + 32768) // 65536
|
||||
end
|
||||
if f == "rgba8" then
|
||||
wu8(px, i * 4, q(r))
|
||||
wu8(px, i * 4 + 1, q(g))
|
||||
wu8(px, i * 4 + 2, q(b))
|
||||
wu8(px, i * 4 + 3, q(al))
|
||||
elseif f == "rgba16" then
|
||||
wu16(px, i * 8, q(r))
|
||||
wu16(px, i * 8 + 2, q(g))
|
||||
wu16(px, i * 8 + 4, q(b))
|
||||
wu16(px, i * 8 + 6, q(al))
|
||||
elseif f == "rgbaf32" then
|
||||
wf(px, i * 16, r)
|
||||
wf(px, i * 16 + 4, g)
|
||||
wf(px, i * 16 + 8, b)
|
||||
wf(px, i * 16 + 12, al)
|
||||
elseif f == "rgb8" then
|
||||
wu8(px, i * 3, q(r))
|
||||
wu8(px, i * 3 + 1, q(g))
|
||||
wu8(px, i * 3 + 2, q(b))
|
||||
elseif f == "gray8" then
|
||||
wu8(px, i, grey())
|
||||
elseif f == "gray16" then
|
||||
wu16(px, i * 2, grey())
|
||||
elseif f == "graya8" then
|
||||
wu8(px, i * 2, grey())
|
||||
wu8(px, i * 2 + 1, q(al))
|
||||
else
|
||||
wu8(px, i, q(al))
|
||||
end
|
||||
return true, nil
|
||||
end
|
||||
|
||||
-- fill(img, r, g, b, a?) -> img (in place) with every pixel set (values as setPixel)
|
||||
function ImageOps.fill(img: Image, r: number, g: number, b: number, a: number?): (Image?, Err.Err?)
|
||||
local ok, e = check(img)
|
||||
if not ok then
|
||||
return nil, e
|
||||
end
|
||||
if img.format == "yuv420p" then
|
||||
return arg("fill: not supported on yuv420p")
|
||||
end
|
||||
local sok, se = ImageOps.setPixel(img, 0, 0, r, g, b, a)
|
||||
if not sok then
|
||||
return nil, se
|
||||
end
|
||||
local bpp = Types.BPP[img.format] :: number
|
||||
local n = img.width * img.height * bpp
|
||||
local filled = bpp
|
||||
while filled < n do
|
||||
local c = math.min(filled, n - filled)
|
||||
buffer.copy(img.pixels, filled, img.pixels, 0, c)
|
||||
filled += c
|
||||
end
|
||||
return img, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ animation
|
||||
-- frameCount(img) -> the number of frames (1 for a still image)
|
||||
function ImageOps.frameCount(img: Image): number
|
||||
if type(img) == "table" and type(img.frames) == "table" and #img.frames > 0 then
|
||||
return #img.frames
|
||||
end
|
||||
return 1
|
||||
end
|
||||
|
||||
-- durations(img) -> { seconds } per frame ({ 0 } for a still image)
|
||||
function ImageOps.durations(img: Image): { number }
|
||||
local out = {}
|
||||
if type(img) == "table" and type(img.frames) == "table" and #img.frames > 0 then
|
||||
for i, f in img.frames do
|
||||
out[i] = if type(f.delay) == "number" then f.delay else 0
|
||||
end
|
||||
return out
|
||||
end
|
||||
return { 0 }
|
||||
end
|
||||
|
||||
-- coalesce(img) -> { Image } | nil, Err: every frame composited onto a width x height canvas (rgba8, or rgba16 /
|
||||
-- rgbaf32 when the image is), honouring each frame's x, y, blend ("over" / "source") and the previous frame's
|
||||
-- dispose ("none" keeps the canvas, "background" clears the frame's rectangle to transparent, "previous" restores
|
||||
-- the canvas from before the frame). A still image gives { img }.
|
||||
function ImageOps.coalesce(img: Image): ({ Image }?, Err.Err?)
|
||||
local ok, e = check(img)
|
||||
if not ok then
|
||||
return nil, e
|
||||
end
|
||||
local frames = img.frames
|
||||
if type(frames) ~= "table" or #frames == 0 then
|
||||
return { img }, nil
|
||||
end
|
||||
local fmt = if RGBA[img.format] then img.format else "rgba8"
|
||||
local canvas = Types.Image.new(img.width, img.height, fmt :: any)
|
||||
local bpp = Types.BPP[fmt] :: number
|
||||
local out = {}
|
||||
for i, f in frames do
|
||||
if type(f) ~= "table" then
|
||||
return arg("coalesce: frame " .. i .. " is not a Frame")
|
||||
end
|
||||
local fi = f.image
|
||||
local fok, fe = check(fi)
|
||||
if not fok then
|
||||
return nil, Err.new(Err.ARG, "coalesce: frame " .. i .. ": " .. (fe :: Err.Err).message)
|
||||
end
|
||||
local fx, fy = if isInt(f.x) then f.x else 0, if isInt(f.y) then f.y else 0
|
||||
local saved: buffer? = nil
|
||||
if f.dispose == "previous" then
|
||||
local sb = buffer.create(buffer.len(canvas.pixels))
|
||||
buffer.copy(sb, 0, canvas.pixels)
|
||||
saved = sb
|
||||
end
|
||||
local bok, be = ImageOps.blit(canvas, fi, fx, fy, { blend = if f.blend == "source" then "source" else "over" })
|
||||
if not bok then
|
||||
return nil, be
|
||||
end
|
||||
local snap = Types.Image.new(img.width, img.height, fmt :: any)
|
||||
buffer.copy(snap.pixels, 0, canvas.pixels)
|
||||
for k, v in img.meta do
|
||||
snap.meta[k] = v
|
||||
end
|
||||
snap.meta.delay = f.delay
|
||||
out[i] = snap
|
||||
if f.dispose == "background" then
|
||||
local x0, y0 = math.max(0, fx), math.max(0, fy)
|
||||
local x1, y1 = math.min(img.width, fx + fi.width), math.min(img.height, fy + fi.height)
|
||||
for y = y0, y1 - 1 do
|
||||
if x1 > x0 then
|
||||
buffer.fill(canvas.pixels, (y * img.width + x0) * bpp, 0, (x1 - x0) * bpp)
|
||||
end
|
||||
end
|
||||
elseif saved then
|
||||
canvas.pixels = saved
|
||||
end
|
||||
end
|
||||
return out, nil
|
||||
end
|
||||
|
||||
-- fromFrames(images, delays?) -> an animated Image: img.frames = the images as full-canvas frames (x = y = 0,
|
||||
-- dispose "none", blend "source"), img.pixels = a copy of frame 1. delays: a number (every frame) or { seconds }
|
||||
-- (default 0.1). All images need the same size and format.
|
||||
function ImageOps.fromFrames(images: { Image }, delays: (number | { number })?): (Image?, Err.Err?)
|
||||
if type(images) ~= "table" or #images == 0 then
|
||||
return arg("fromFrames: a non-empty list of Images")
|
||||
end
|
||||
local first = images[1]
|
||||
local ok, e = check(first)
|
||||
if not ok then
|
||||
return nil, e
|
||||
end
|
||||
local frames = {}
|
||||
for i, im in images do
|
||||
local iok, ie = check(im)
|
||||
if not iok then
|
||||
return nil, ie
|
||||
end
|
||||
if im.width ~= first.width or im.height ~= first.height or im.format ~= first.format then
|
||||
return arg("fromFrames: frame " .. i .. " differs in size or format from frame 1")
|
||||
end
|
||||
local d = 0.1
|
||||
if type(delays) == "number" then
|
||||
d = delays
|
||||
elseif type(delays) == "table" and type(delays[i]) == "number" then
|
||||
d = delays[i]
|
||||
end
|
||||
frames[i] = { image = im, delay = d, x = 0, y = 0, dispose = "none", blend = "source" }
|
||||
end
|
||||
local out = like(first, first.width, first.height)
|
||||
buffer.copy(out.pixels, 0, first.pixels, 0, buffer.len(out.pixels))
|
||||
out.frames = frames :: any
|
||||
out.loops = 0
|
||||
return out, nil
|
||||
end
|
||||
|
||||
return ImageOps
|
||||
@@ -0,0 +1,101 @@
|
||||
--!strict
|
||||
-- ops/LayerOps: editing on the Layered type (PSD, Aseprite): flatten a layer tree (or one animation frame) to an
|
||||
-- rgba8 Image with the blend modes of codecs/image/Blend, opacity, groups (isolated, or pass-through), clipping layers and
|
||||
-- grey layer masks; every frame as an animated Image; walking the leaves.
|
||||
--
|
||||
-- local LayerOps = require("@rosetta/ops/LayerOps")
|
||||
-- local img = LayerOps.flatten(layered) -- frame 1 / the layers
|
||||
-- local img3 = LayerOps.flatten(layered, { frame = 3 })
|
||||
-- local anim = LayerOps.flattenFrames(layered) -- an Image with frames (delays from the Layered frames)
|
||||
-- for layer, depth in LayerOps.leaves(layered.layers) do ... end
|
||||
--
|
||||
-- Never throws: bad values return nil, Err.ARG.
|
||||
local Err = require("@rosetta/core/Err")
|
||||
local Types = require("@rosetta/Types")
|
||||
local Blend = require("@rosetta/codecs/image/Blend")
|
||||
|
||||
local LayerOps = {}
|
||||
|
||||
export type FlattenOptions = {
|
||||
frame: number?, -- 1-based animation frame (default: layered.layers, which is frame 1)
|
||||
hidden: boolean?, -- include hidden layers (default false)
|
||||
background: { number }?, -- r, g, b, a 0..255 under everything (default transparent)
|
||||
}
|
||||
|
||||
-- flatten(layered, opts?) -> rgba8 Image (layered.width x layered.height) | nil, Err
|
||||
function LayerOps.flatten(layered: Types.Layered, opts: FlattenOptions?): (Types.Image?, Err.Err?)
|
||||
if type(layered) ~= "table" or type(layered.width) ~= "number" or type(layered.height) ~= "number" or type(layered.layers) ~= "table" then
|
||||
return nil, Err.new(Err.ARG, "flatten: needs a Layered value")
|
||||
end
|
||||
local o: FlattenOptions = opts or {}
|
||||
local w, h = math.floor(layered.width), math.floor(layered.height)
|
||||
if w < 0 or h < 0 or w * h > 2 ^ 28 then
|
||||
return nil, Err.new(Err.ARG, "flatten: bad size")
|
||||
end
|
||||
local layers = layered.layers
|
||||
if o.frame then
|
||||
local f = if type(layered.frames) == "table" then layered.frames[o.frame] else nil
|
||||
if f == nil and o.frame ~= 1 then
|
||||
return nil, Err.new(Err.ARG, "flatten: no frame " .. tostring(o.frame))
|
||||
end
|
||||
if f then
|
||||
layers = f.layers
|
||||
end
|
||||
end
|
||||
local img = Types.Image.new(w, h)
|
||||
local bg = o.background
|
||||
if type(bg) == "table" then
|
||||
local v = (bg[1] or 0) + (bg[2] or 0) * 256 + (bg[3] or 0) * 65536 + (bg[4] or 255) * 16777216
|
||||
for i = 0, w * h - 1 do
|
||||
buffer.writeu32(img.pixels, i * 4, v)
|
||||
end
|
||||
end
|
||||
Blend.flatten(layers, img.pixels, w, h, o.hidden == true)
|
||||
return img, nil
|
||||
end
|
||||
|
||||
-- flattenFrames(layered, opts?) -> an rgba8 Image whose frames are every flattened frame (frame 1 is the image)
|
||||
function LayerOps.flattenFrames(layered: Types.Layered, opts: FlattenOptions?): (Types.Image?, Err.Err?)
|
||||
local first, err = LayerOps.flatten(layered, opts)
|
||||
if not first then
|
||||
return nil, err
|
||||
end
|
||||
local frames = if type(layered.frames) == "table" then layered.frames else {}
|
||||
if #frames == 0 then
|
||||
return first, nil
|
||||
end
|
||||
local list: { Types.Frame } = {}
|
||||
for i, f in frames do
|
||||
local o: FlattenOptions = table.clone(opts or {}) :: any
|
||||
o.frame = i
|
||||
local img = if i == 1 then first else LayerOps.flatten(layered, o)
|
||||
if not img then
|
||||
return nil, Err.new(Err.ARG, "flatten: frame " .. i)
|
||||
end
|
||||
list[i] = { image = img, delay = tonumber(f.delay) or 0.1, x = 0, y = 0, dispose = "none", blend = "source" }
|
||||
end
|
||||
first.frames = list
|
||||
return first, nil
|
||||
end
|
||||
|
||||
-- leaves(layers) -> iterator of (layer, depth) over the non-group layers of a tree, bottom to top
|
||||
function LayerOps.leaves(layers: { Types.Layer }): () -> (Types.Layer?, number?)
|
||||
local stack: { { any } } = { { layers, 0, 0 } }
|
||||
return function(): (Types.Layer?, number?)
|
||||
while #stack > 0 do
|
||||
local top = stack[#stack]
|
||||
top[2] += 1
|
||||
local l = top[1][top[2]]
|
||||
if l == nil then
|
||||
table.remove(stack)
|
||||
elseif type(l.children) == "table" then
|
||||
table.insert(stack, { l.children, 0, top[3] + 1 })
|
||||
else
|
||||
return l, top[3]
|
||||
end
|
||||
end
|
||||
return nil, nil
|
||||
end
|
||||
end
|
||||
|
||||
return LayerOps
|
||||
@@ -0,0 +1,167 @@
|
||||
--!strict
|
||||
--!native
|
||||
-- ops/MeshOps/Greedy: greedy meshing of a dense voxel grid (one byte per cell, 0 = empty): for each axis and each
|
||||
-- slice between two layers of cells, the exposed faces are masked by palette index, and runs of equal faces are merged
|
||||
-- into maximal rectangles (Mikola Lysenko's "Meshing in a Minecraft game", 2012). Faces between two filled cells are
|
||||
-- hidden whatever their indices. Output: 4 vertices and 2 triangles per rectangle, counter-clockwise seen from the
|
||||
-- outside. Never throws; the caller checks buffer.len(data) >= sx * sy * sz.
|
||||
local Greedy = {}
|
||||
|
||||
local readu8, readi32, writei32 = buffer.readu8, buffer.readi32, buffer.writei32
|
||||
local writef32, writeu8, writeu32 = buffer.writef32, buffer.writeu8, buffer.writeu32
|
||||
|
||||
export type Out = {
|
||||
positions: buffer, -- f32 x3 per vertex
|
||||
normals: buffer, -- f32 x3 per vertex
|
||||
index: buffer, -- u8 palette index per vertex
|
||||
indices: buffer, -- u32, 6 per quad
|
||||
vertices: number,
|
||||
quads: number,
|
||||
}
|
||||
|
||||
-- run(data, sx, sy, sz, ox, oy, oz, scale) -> Out: vertex position = (cell corner + (ox, oy, oz)) * scale
|
||||
function Greedy.run(data: buffer, sx: number, sy: number, sz: number, ox: number, oy: number, oz: number, scale: number): Out
|
||||
local cap = 1024
|
||||
local pos = buffer.create(cap * 48)
|
||||
local nrm = buffer.create(cap * 48)
|
||||
local idx = buffer.create(cap * 4)
|
||||
local tri = buffer.create(cap * 24)
|
||||
local quads = 0
|
||||
local maxFace = math.max(sx * sy, sy * sz, sz * sx)
|
||||
local mask = buffer.create(maxFace * 4)
|
||||
local corner = { 0, 0, 0 }
|
||||
for d = 0, 2 do
|
||||
-- u, v: the two other axes, cyclic so that e_u x e_v = e_d
|
||||
local u, v = (d + 1) % 3, (d + 2) % 3
|
||||
local nd = if d == 0 then sx elseif d == 1 then sy else sz
|
||||
local nu = if u == 0 then sx elseif u == 1 then sy else sz
|
||||
local nv = if v == 0 then sx elseif v == 1 then sy else sz
|
||||
local std = if d == 0 then 1 elseif d == 1 then sx else sx * sy
|
||||
local stu = if u == 0 then 1 elseif u == 1 then sx else sx * sy
|
||||
local stv = if v == 0 then 1 elseif v == 1 then sx else sx * sy
|
||||
for slice = -1, nd - 1 do
|
||||
-- the mask of faces between layer slice and slice + 1: +index (faces +d, owned by slice), -index (faces -d)
|
||||
local any = false
|
||||
for j = 0, nv - 1 do
|
||||
for i = 0, nu - 1 do
|
||||
local base = i * stu + j * stv
|
||||
local a = if slice >= 0 then readu8(data, base + slice * std) else 0
|
||||
local b = if slice + 1 < nd then readu8(data, base + (slice + 1) * std) else 0
|
||||
local m = 0
|
||||
if a ~= 0 and b == 0 then
|
||||
m = a
|
||||
elseif a == 0 and b ~= 0 then
|
||||
m = -b
|
||||
end
|
||||
if m ~= 0 then
|
||||
any = true
|
||||
end
|
||||
writei32(mask, (i + j * nu) * 4, m)
|
||||
end
|
||||
end
|
||||
if any then
|
||||
for j = 0, nv - 1 do
|
||||
local i = 0
|
||||
while i < nu do
|
||||
local m = readi32(mask, (i + j * nu) * 4)
|
||||
if m == 0 then
|
||||
i += 1
|
||||
else
|
||||
local w = 1
|
||||
while i + w < nu and readi32(mask, (i + w + j * nu) * 4) == m do
|
||||
w += 1
|
||||
end
|
||||
local h = 1
|
||||
local grow = true
|
||||
while j + h < nv and grow do
|
||||
for k = 0, w - 1 do
|
||||
if readi32(mask, (i + k + (j + h) * nu) * 4) ~= m then
|
||||
grow = false
|
||||
break
|
||||
end
|
||||
end
|
||||
if grow then
|
||||
h += 1
|
||||
end
|
||||
end
|
||||
for jj = j, j + h - 1 do
|
||||
for k = 0, w - 1 do
|
||||
writei32(mask, (i + k + jj * nu) * 4, 0)
|
||||
end
|
||||
end
|
||||
-- emit the rectangle
|
||||
if quads == cap then
|
||||
local ncap = cap * 2
|
||||
local function grow2(b: buffer, per: number): buffer
|
||||
local nb = buffer.create(ncap * per)
|
||||
buffer.copy(nb, 0, b, 0, cap * per)
|
||||
return nb
|
||||
end
|
||||
pos, nrm, idx, tri = grow2(pos, 48), grow2(nrm, 48), grow2(idx, 4), grow2(tri, 24) :: buffer
|
||||
cap = ncap
|
||||
end
|
||||
corner[d + 1] = slice + 1
|
||||
corner[u + 1] = i
|
||||
corner[v + 1] = j
|
||||
local cx, cy, cz = corner[1], corner[2], corner[3]
|
||||
-- the u and v edge vectors
|
||||
local ux = if u == 0 then w else 0
|
||||
local uy = if u == 1 then w else 0
|
||||
local uz = if u == 2 then w else 0
|
||||
local vx = if v == 0 then h else 0
|
||||
local vy = if v == 1 then h else 0
|
||||
local vz = if v == 2 then h else 0
|
||||
local nsign = if m > 0 then 1 else -1
|
||||
local nx = if d == 0 then nsign else 0
|
||||
local ny = if d == 1 then nsign else 0
|
||||
local nz = if d == 2 then nsign else 0
|
||||
local col = if m > 0 then m else -m
|
||||
local vb = quads * 48
|
||||
local px0, py0, pz0 = (cx + ox) * scale, (cy + oy) * scale, (cz + oz) * scale
|
||||
writef32(pos, vb, px0)
|
||||
writef32(pos, vb + 4, py0)
|
||||
writef32(pos, vb + 8, pz0)
|
||||
writef32(pos, vb + 12, px0 + ux * scale)
|
||||
writef32(pos, vb + 16, py0 + uy * scale)
|
||||
writef32(pos, vb + 20, pz0 + uz * scale)
|
||||
writef32(pos, vb + 24, px0 + (ux + vx) * scale)
|
||||
writef32(pos, vb + 28, py0 + (uy + vy) * scale)
|
||||
writef32(pos, vb + 32, pz0 + (uz + vz) * scale)
|
||||
writef32(pos, vb + 36, px0 + vx * scale)
|
||||
writef32(pos, vb + 40, py0 + vy * scale)
|
||||
writef32(pos, vb + 44, pz0 + vz * scale)
|
||||
for k = 0, 3 do
|
||||
writef32(nrm, vb + k * 12, nx)
|
||||
writef32(nrm, vb + k * 12 + 4, ny)
|
||||
writef32(nrm, vb + k * 12 + 8, nz)
|
||||
writeu8(idx, quads * 4 + k, col)
|
||||
end
|
||||
local v0 = quads * 4
|
||||
local ib = quads * 24
|
||||
if m > 0 then
|
||||
writeu32(tri, ib, v0)
|
||||
writeu32(tri, ib + 4, v0 + 1)
|
||||
writeu32(tri, ib + 8, v0 + 2)
|
||||
writeu32(tri, ib + 12, v0)
|
||||
writeu32(tri, ib + 16, v0 + 2)
|
||||
writeu32(tri, ib + 20, v0 + 3)
|
||||
else
|
||||
writeu32(tri, ib, v0)
|
||||
writeu32(tri, ib + 4, v0 + 2)
|
||||
writeu32(tri, ib + 8, v0 + 1)
|
||||
writeu32(tri, ib + 12, v0)
|
||||
writeu32(tri, ib + 16, v0 + 3)
|
||||
writeu32(tri, ib + 20, v0 + 2)
|
||||
end
|
||||
quads += 1
|
||||
i += w
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
return { positions = pos, normals = nrm, index = idx, indices = tri, vertices = quads * 4, quads = quads }
|
||||
end
|
||||
|
||||
return Greedy
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,369 @@
|
||||
--!strict
|
||||
-- ops/MusicOps: building and editing tracker Modules (layer 5.5, over codecs/audio/Tracker) without touching the
|
||||
-- engine's internal layout (5-byte cells, f32 sample buffers, tuning fields): a new module, patterns, cells by name,
|
||||
-- samples from an Audio, instruments. New code. F.music.new / addPattern / setCell / getCell / addSample /
|
||||
-- addInstrument / note in the api (also F.ops.music).
|
||||
--
|
||||
-- local M = require("@rosetta/ops/MusicOps")
|
||||
-- local song = M.new({ format = "mod", channels = 4, title = "demo" })
|
||||
-- local s = M.addSample(song, { name = "beep", audio = someAudio, loop = "forward" }) -- sample 1
|
||||
-- local p = M.addPattern(song) -- pattern 0 (64 rows), appended to the order list
|
||||
-- M.setCell(song, p, 0, 1, { note = "C-4", instrument = s, effect = 0xC, param = 40 })
|
||||
-- local wav = F.save(song, nil, { format = "wav" }) -- rendered; or F.save(song) for the .mod
|
||||
--
|
||||
-- Conventions: pattern numbers are 0-based (as the order list names them), rows 0-based, channels 1-based, sample
|
||||
-- and instrument numbers 1-based (0 = none in a cell). Notes are numbers (1 = C-0, 49 = C-4, 61 = C-5; 254 cut, 255
|
||||
-- key off, 253 fade) or names: "C-4", "C#4", "Db4", "off", "cut", "fade". Effects keep the format's own numbering
|
||||
-- (MOD / XM 0..35, S3M / IT 1..26 = A..Z). Never throws: bad arguments return nil, Err.ARG.
|
||||
local Err = require("@rosetta/core/Err")
|
||||
local Tracker = require("@rosetta/codecs/audio/Tracker")
|
||||
|
||||
local MusicOps = {}
|
||||
|
||||
local FORMATS = { mod = true, xm = true, s3m = true, it = true }
|
||||
|
||||
local function bad(what: string): (nil, Err.Err)
|
||||
return nil, Err.new(Err.ARG, what)
|
||||
end
|
||||
|
||||
local function isModule(m: any): boolean
|
||||
-- (the engine family: modules of the other tracker formats, music/mtm etc., play as one of the four)
|
||||
return type(m) == "table" and m.kind == "music" and FORMATS[Tracker.family(m) or ""] == true and type(m.patterns) == "table"
|
||||
end
|
||||
|
||||
local function int(v: any, lo: number, hi: number): boolean
|
||||
return type(v) == "number" and v == v and v % 1 == 0 and v >= lo and v <= hi
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ module
|
||||
export type NewOptions = {
|
||||
format: string?, -- "mod" (default), "xm", "s3m", "it": the effect family (mod and xm can be saved)
|
||||
channels: number?, -- 1..32 for mod, else 1..64 (default 4)
|
||||
title: string?,
|
||||
speed: number?, -- ticks per row (default 6)
|
||||
tempo: number?, -- BPM (default 125)
|
||||
}
|
||||
|
||||
-- new(opts?) -> an empty Module (kind "music") with a render method; meta.source.format = the format
|
||||
function MusicOps.new(opts: NewOptions?): (any, Err.Err?)
|
||||
local o: NewOptions = opts or {}
|
||||
local format = o.format or "mod"
|
||||
if not FORMATS[format] then
|
||||
return bad("new: format must be mod, xm, s3m or it")
|
||||
end
|
||||
local channels = o.channels or 4
|
||||
if not int(channels, 1, if format == "mod" then 32 else 64) then
|
||||
return bad("new: bad channel count")
|
||||
end
|
||||
local m = Tracker.newModule(format, channels)
|
||||
m.title = if type(o.title) == "string" then o.title else ""
|
||||
if o.speed ~= nil then
|
||||
if not int(o.speed, 1, 255) then
|
||||
return bad("new: speed must be 1..255")
|
||||
end
|
||||
m.speed = o.speed
|
||||
end
|
||||
if o.tempo ~= nil then
|
||||
if type(o.tempo) ~= "number" or o.tempo < 32 or o.tempo > 1000 then
|
||||
return bad("new: tempo must be 32..1000")
|
||||
end
|
||||
m.tempo = o.tempo
|
||||
end
|
||||
m.meta = { source = { format = format } }
|
||||
return m, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ patterns
|
||||
-- addPattern(module, rows?, opts?) -> the new pattern's number (0-based) | nil, Err. rows default 64 (MOD needs 64).
|
||||
-- The pattern is appended to the order list unless opts.order == false.
|
||||
function MusicOps.addPattern(m: any, rows: number?, opts: { order: boolean? }?): (number?, Err.Err?)
|
||||
if not isModule(m) then
|
||||
return bad("addPattern: needs a tracker Module")
|
||||
end
|
||||
local n = rows or 64
|
||||
if not int(n, 1, 1024) then
|
||||
return bad("addPattern: rows must be 1..1024")
|
||||
end
|
||||
table.insert(m.patterns, Tracker.newPattern(n, m.channels))
|
||||
local index = #m.patterns - 1
|
||||
if not (opts and opts.order == false) then
|
||||
table.insert(m.order, index)
|
||||
end
|
||||
return index, nil
|
||||
end
|
||||
|
||||
local NAMES: { [string]: number } = { c = 0, d = 2, e = 4, f = 5, g = 7, a = 9, b = 11 }
|
||||
local SPECIAL: { [string]: number } = { off = 255, ["==="] = 255, cut = 254, ["^^^"] = 254, fade = 253, ["~~~"] = 253 }
|
||||
|
||||
-- note(nameOrNumber) -> the note number (1 = C-0 .. 120 = B-9, 253 / 254 / 255) | nil, Err: "C-4" = 49, "C#4" = 50,
|
||||
-- "Db4" = 50, "off", "cut", "fade"
|
||||
function MusicOps.note(v: any): (number?, Err.Err?)
|
||||
if type(v) == "number" then
|
||||
if int(v, 0, 120) or v == 253 or v == 254 or v == 255 then
|
||||
return v, nil
|
||||
end
|
||||
return bad("note: number must be 0..120 or 253..255")
|
||||
end
|
||||
if type(v) ~= "string" then
|
||||
return bad("note: expected a number or a name")
|
||||
end
|
||||
local s = string.lower(v)
|
||||
if SPECIAL[s] then
|
||||
return SPECIAL[s], nil
|
||||
end
|
||||
local letter, acc, oct = string.match(s, "^([a-g])([#b%-]?)(%d)$")
|
||||
if not letter then
|
||||
return bad("note: bad name " .. v)
|
||||
end
|
||||
local n = NAMES[letter :: string] + (if acc == "#" then 1 elseif acc == "b" then -1 else 0)
|
||||
local num = 1 + (tonumber(oct) :: number) * 12 + n
|
||||
if num < 1 or num > 120 then
|
||||
return bad("note: out of range " .. v)
|
||||
end
|
||||
return num, nil
|
||||
end
|
||||
|
||||
export type Cell = {
|
||||
note: (number | string)?, -- 0 / nil = none
|
||||
instrument: number?, -- 1-based sample (MOD / S3M) or instrument (XM / IT); 0 = none
|
||||
volume: number?, -- the volume column as the format stores it (0 = none)
|
||||
effect: number?, -- the format's effect number (MOD / XM 0..35; S3M / IT 1..26)
|
||||
param: number?, -- 0..255
|
||||
}
|
||||
|
||||
local function patternAt(m: any, pattern: any, row: any, channel: any): (any, Err.Err?)
|
||||
if not isModule(m) then
|
||||
return bad("needs a tracker Module")
|
||||
end
|
||||
local p: any = if int(pattern, 0, 1e6) then m.patterns[pattern + 1] else nil
|
||||
if p == nil then
|
||||
return bad("no pattern " .. tostring(pattern))
|
||||
end
|
||||
if not int(row, 0, p.rows - 1) then
|
||||
return bad("row " .. tostring(row) .. " outside 0.." .. (p.rows - 1))
|
||||
end
|
||||
if not int(channel, 1, m.channels) then
|
||||
return bad("channel " .. tostring(channel) .. " outside 1.." .. m.channels)
|
||||
end
|
||||
return p, nil
|
||||
end
|
||||
|
||||
-- setCell(module, pattern, row, channel, cell) -> true | nil, Err: writes one cell (missing fields = 0)
|
||||
function MusicOps.setCell(m: any, pattern: number, row: number, channel: number, cell: Cell): (boolean?, Err.Err?)
|
||||
local p, err = patternAt(m, pattern, row, channel)
|
||||
if not p then
|
||||
return nil, err
|
||||
end
|
||||
if type(cell) ~= "table" then
|
||||
return bad("setCell: cell must be a table")
|
||||
end
|
||||
local note = 0
|
||||
if cell.note ~= nil then
|
||||
local n, nerr = MusicOps.note(cell.note)
|
||||
if not n then
|
||||
return nil, nerr
|
||||
end
|
||||
note = n
|
||||
end
|
||||
for _, k in { "instrument", "volume", "effect", "param" } do
|
||||
local v = (cell :: any)[k]
|
||||
if v ~= nil and not int(v, 0, 255) then
|
||||
return bad("setCell: " .. k .. " must be 0..255")
|
||||
end
|
||||
end
|
||||
Tracker.setCell(m, pattern, row, channel, note, cell.instrument or 0, cell.volume or 0, cell.effect or 0, cell.param or 0)
|
||||
return true, nil
|
||||
end
|
||||
|
||||
-- getCell(module, pattern, row, channel) -> { note, instrument, volume, effect, param } (numbers) | nil, Err
|
||||
function MusicOps.getCell(m: any, pattern: number, row: number, channel: number): (Cell?, Err.Err?)
|
||||
local p, err = patternAt(m, pattern, row, channel)
|
||||
if not p then
|
||||
return nil, err
|
||||
end
|
||||
local note, ins, vol, fx, param = Tracker.cell(m, pattern, row, channel)
|
||||
return { note = note, instrument = ins, volume = vol, effect = fx, param = param }, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ samples
|
||||
export type SampleSpec = {
|
||||
name: string?,
|
||||
audio: any?, -- an Audio (1 or 2 channels): the sample data and, unless rate is given, its rate
|
||||
data: buffer?, -- or raw f32 frames (interleaved when channels = 2) ...
|
||||
length: number?, -- ... with their frame count (default: the whole buffer)
|
||||
channels: number?, -- 1 (default) or 2, for data
|
||||
rate: number?, -- Hz the sample plays at on C-4 (MOD / XM) or C-5 (S3M / IT); default the Audio's, else 8363
|
||||
loop: string?, -- "none" (default), "forward", "pingpong"
|
||||
loopStart: number?, -- frames (default 0)
|
||||
loopEnd: number?, -- frames, exclusive (default the length)
|
||||
volume: number?, -- 0..64 (default 64)
|
||||
pan: number?, -- 0..256 (XM / IT; nil = the channel's)
|
||||
bits: number?, -- 8 or 16: what writers store (default 8 for MOD, else 16)
|
||||
}
|
||||
|
||||
local LOOPS: { [string]: number } = { none = 0, forward = 1, pingpong = 2 }
|
||||
|
||||
-- addSample(module, spec) -> the new sample's number (1-based) | nil, Err. The rate sets the tuning: c5speed for
|
||||
-- S3M / IT, relativeNote + finetune (1/128 semitones from 8363 Hz) for MOD / XM (MOD files store only the finetune,
|
||||
-- -1..+7/8 semitone: use rates near 8363 Hz when saving a MOD).
|
||||
function MusicOps.addSample(m: any, spec: SampleSpec): (number?, Err.Err?)
|
||||
if not isModule(m) then
|
||||
return bad("addSample: needs a tracker Module")
|
||||
end
|
||||
if type(spec) ~= "table" then
|
||||
return bad("addSample: spec must be a table")
|
||||
end
|
||||
local data: buffer, length: number, channels: number
|
||||
local rate = spec.rate
|
||||
local a = spec.audio
|
||||
if a ~= nil then
|
||||
if type(a) ~= "table" or a.kind ~= "audio" or type(a.samples) ~= "buffer" or not int(a.frames, 0, 2 ^ 31) or (a.channels ~= 1 and a.channels ~= 2) or buffer.len(a.samples) < a.frames * a.channels * 4 then
|
||||
return bad("addSample: audio must be a mono or stereo Audio")
|
||||
end
|
||||
data, length, channels = a.samples, a.frames, a.channels
|
||||
rate = rate or a.sampleRate
|
||||
elseif type(spec.data) == "buffer" then
|
||||
channels = spec.channels or 1
|
||||
if channels ~= 1 and channels ~= 2 then
|
||||
return bad("addSample: channels must be 1 or 2")
|
||||
end
|
||||
local d: buffer = spec.data
|
||||
length = spec.length or buffer.len(d) // (4 * channels)
|
||||
if not int(length, 0, 2 ^ 31) or buffer.len(d) < length * channels * 4 then
|
||||
return bad("addSample: data shorter than length")
|
||||
end
|
||||
data = d
|
||||
else
|
||||
return bad("addSample: needs audio or data")
|
||||
end
|
||||
rate = rate or 8363
|
||||
if type(rate) ~= "number" or rate < 1 or rate > 1e7 then
|
||||
return bad("addSample: bad rate")
|
||||
end
|
||||
local s = Tracker.newSample(spec.name)
|
||||
local copy = buffer.create(length * channels * 4)
|
||||
buffer.copy(copy, 0, data, 0, length * channels * 4)
|
||||
s.data, s.length, s.channels = copy, length, channels
|
||||
s.bits = spec.bits or (if Tracker.family(m) == "mod" then 8 else 16)
|
||||
if s.bits ~= 8 and s.bits ~= 16 then
|
||||
return bad("addSample: bits must be 8 or 16")
|
||||
end
|
||||
s.c5speed = rate
|
||||
local semis = 12 * math.log(rate / 8363) / math.log(2)
|
||||
local rn = math.floor(semis + 0.5)
|
||||
if rn < -96 or rn > 95 then
|
||||
return bad("addSample: rate out of range")
|
||||
end
|
||||
s.relativeNote = rn
|
||||
s.finetune = math.clamp(math.floor((semis - rn) * 128 + 0.5), -128, 127)
|
||||
local lt = LOOPS[spec.loop or "none"]
|
||||
if lt == nil then
|
||||
return bad("addSample: loop must be none, forward or pingpong")
|
||||
end
|
||||
if lt > 0 then
|
||||
local ls, le = spec.loopStart or 0, spec.loopEnd or length
|
||||
if not int(ls, 0, length) or not int(le, 0, length) or le - ls < 1 then
|
||||
return bad("addSample: bad loop")
|
||||
end
|
||||
s.loopStart, s.loopEnd, s.loopType = ls, le, lt
|
||||
end
|
||||
if spec.volume ~= nil then
|
||||
if type(spec.volume) ~= "number" or spec.volume < 0 or spec.volume > 64 then
|
||||
return bad("addSample: volume must be 0..64")
|
||||
end
|
||||
s.volume = spec.volume
|
||||
end
|
||||
if spec.pan ~= nil then
|
||||
if type(spec.pan) ~= "number" or spec.pan < 0 or spec.pan > 256 then
|
||||
return bad("addSample: pan must be 0..256")
|
||||
end
|
||||
s.pan = spec.pan
|
||||
end
|
||||
table.insert(m.samples, s)
|
||||
return #m.samples, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ instruments
|
||||
export type InstrumentSpec = {
|
||||
name: string?,
|
||||
sample: number?, -- the sample every note plays (1-based)
|
||||
samples: { [number]: number }?, -- or a keymap: note number -> sample number (other notes: none)
|
||||
fadeout: number?, -- volume fade per tick after key off, as the format stores it (XM 0..4095, IT 0..1024)
|
||||
envelope: { points: { { number } }, sustain: number?, loopStart: number?, loopEnd: number? }?, -- volume
|
||||
-- envelope: points { tick, 0..64 } with ticks increasing; sustain / loop points are 1-based point indexes
|
||||
}
|
||||
|
||||
-- addInstrument(module, spec) -> the new instrument's number (1-based) | nil, Err. XM and IT modules only (MOD /
|
||||
-- S3M cells name samples directly).
|
||||
function MusicOps.addInstrument(m: any, spec: InstrumentSpec): (number?, Err.Err?)
|
||||
if not isModule(m) then
|
||||
return bad("addInstrument: needs a tracker Module")
|
||||
end
|
||||
if Tracker.family(m) ~= "xm" and Tracker.family(m) ~= "it" then
|
||||
return bad("addInstrument: only xm and it modules have instruments (mod / s3m cells name samples)")
|
||||
end
|
||||
if type(spec) ~= "table" then
|
||||
return bad("addInstrument: spec must be a table")
|
||||
end
|
||||
local ins = Tracker.newInstrument(spec.name)
|
||||
if spec.sample ~= nil then
|
||||
if not int(spec.sample, 1, #m.samples) then
|
||||
return bad("addInstrument: no sample " .. tostring(spec.sample))
|
||||
end
|
||||
for n = 1, 120 do
|
||||
ins.sampleMap[n] = spec.sample
|
||||
end
|
||||
elseif type(spec.samples) == "table" then
|
||||
for note, smp in spec.samples do
|
||||
if not int(note, 1, 120) or not int(smp, 0, #m.samples) then
|
||||
return bad("addInstrument: bad keymap entry")
|
||||
end
|
||||
ins.sampleMap[note] = smp
|
||||
end
|
||||
end
|
||||
if spec.fadeout ~= nil then
|
||||
if not int(spec.fadeout, 0, 65535) then
|
||||
return bad("addInstrument: bad fadeout")
|
||||
end
|
||||
ins.fadeout = spec.fadeout
|
||||
end
|
||||
local e = spec.envelope
|
||||
if e ~= nil then
|
||||
if type(e) ~= "table" or type(e.points) ~= "table" or #e.points == 0 then
|
||||
return bad("addInstrument: envelope needs points")
|
||||
end
|
||||
local env = Tracker.newEnvelope()
|
||||
local last = -1
|
||||
for i, pt in e.points do
|
||||
local tick: any, value: any = nil, nil
|
||||
if type(pt) == "table" then
|
||||
tick, value = pt[1], pt[2]
|
||||
end
|
||||
if not int(tick, 0, 65535) or type(value) ~= "number" or value < 0 or value > 64 or (tick :: number) <= last then
|
||||
return bad("addInstrument: envelope point " .. i .. " must be { tick, 0..64 } with increasing ticks")
|
||||
end
|
||||
last = tick :: number
|
||||
env.ticks[i], env.values[i] = tick, value
|
||||
end
|
||||
env.enabled = true
|
||||
local n = #e.points
|
||||
if e.sustain ~= nil then
|
||||
if not int(e.sustain, 1, n) then
|
||||
return bad("addInstrument: bad sustain point")
|
||||
end
|
||||
env.sustain, env.susStart, env.susEnd = true, e.sustain, e.sustain
|
||||
end
|
||||
if e.loopStart ~= nil or e.loopEnd ~= nil then
|
||||
local ls, le = e.loopStart or 1, e.loopEnd or n
|
||||
if not int(ls, 1, n) or not int(le, ls, n) then
|
||||
return bad("addInstrument: bad envelope loop")
|
||||
end
|
||||
env.loop, env.loopStart, env.loopEnd = true, ls, le
|
||||
end
|
||||
ins.volEnv = env
|
||||
end
|
||||
table.insert(m.instruments, ins)
|
||||
return #m.instruments, nil
|
||||
end
|
||||
|
||||
return MusicOps
|
||||
Reference in new issue
Block a user