merge master
This commit is contained in:
commit
b5964d4afc
39 files changed
+1158
-73
No files matched your search
@@ -501,7 +501,7 @@ local list: { Entry } = {
|
||||
extensions = { "fnt" },
|
||||
mime = { "application/x-bmfont" },
|
||||
deps = { "core/Err", "core/Bytes", "Types" },
|
||||
caps = { decode = true, encode = true, bitmap = true, variants = { "text", "xml", "binary" } },
|
||||
caps = { decode = true, encode = true, bitmap = true, variants = { "text", "xml", "binary" }, extraFiles = true },
|
||||
load = function()
|
||||
return require("@formats/font/bmfont")
|
||||
end,
|
||||
|
||||
@@ -190,6 +190,9 @@ export type Track = {
|
||||
sampleRate: number?,
|
||||
channels: number?,
|
||||
bitsPerSample: number?,
|
||||
codecDelay: number?, -- seconds of decoder output to drop at the start (encoder priming: Matroska CodecDelay, the
|
||||
-- first edit's media time of an MP4 audio track)
|
||||
playDuration: number?, -- seconds to play after the codec delay (an MP4 edit list's length: the end padding cut)
|
||||
config: buffer?, -- codec configuration (CodecPrivate, avcC, OpusHead, Vorbis headers, AVI strf extra, ...)
|
||||
[string]: any,
|
||||
}
|
||||
|
||||
@@ -68,7 +68,7 @@ function Stream.new(b: buffer, idx: any, tags: { [string]: string }, id3: any):
|
||||
channels = nch,
|
||||
frames = total,
|
||||
duration = total / hz,
|
||||
bitrate = if idx.n > 0 then floor(idx.bytes * 8 * hz / (idx.n * spf) / 1000 + 0.5) else 0,
|
||||
bitrate = if idx.n > 0 then floor(idx.bytes * 8 * hz / (idx.n * spf) + 0.5) else 0, -- bit/s
|
||||
tags = tags,
|
||||
id3 = id3,
|
||||
layer = idx.layer,
|
||||
|
||||
@@ -44,7 +44,8 @@ export type OpenOptions = {
|
||||
export type Decoder = Stream.Decoder
|
||||
export type EncodeOptions = {
|
||||
layer: number?, -- 3 (MP3, default) or 2 (MP2)
|
||||
bitrate: number?, -- kbps, constant (default 128 for layer III, 192 for layer II; MPEG-2 / 2.5 rates: 64 / 96)
|
||||
bitrate: number?, -- bits per second, constant: one of the layer's rates (default 128000 for layer III, 192000 for
|
||||
-- layer II; MPEG-2 / 2.5 rates: 64000 / 96000); values below 1000 are kbit/s (128 = 128000, the old unit)
|
||||
mode: ("stereo" | "joint" | "mono")?, -- default "joint" (mid / side) for stereo layer III, "stereo" for layer II,
|
||||
-- "mono" for mono input; layer II has no joint stereo (intensity) and writes "joint" as "stereo"
|
||||
id3: boolean?, -- write an ID3v2.4 tag from the tags (default true when there are tags)
|
||||
@@ -208,9 +209,13 @@ function Mp3.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
if layer == 2 and mode == "joint" then
|
||||
mode = "stereo"
|
||||
end
|
||||
-- bitrate: bit/s, or kbit/s below 1000; the encoder works in kbit/s
|
||||
local bitrate = o.bitrate or (if mpeg1 then (if layer == 3 then 128 else 192) else (if layer == 3 then 64 else 96))
|
||||
if type(bitrate) == "number" and bitrate >= 1000 then
|
||||
bitrate /= 1000
|
||||
end
|
||||
if not table.find(Enc.BITRATES[if mpeg1 then 1 else 2], bitrate) then
|
||||
return nil, Err.new(Err.ARG, string.format("%s kbps is not a layer %d bit rate at %d Hz", tostring(bitrate), layer, rate))
|
||||
return nil, Err.new(Err.ARG, string.format("%s bit/s is not a layer %d bit rate at %d Hz", tostring(if type(o.bitrate) == "number" and o.bitrate < 1000 then o.bitrate * 1000 else o.bitrate), layer, rate))
|
||||
end
|
||||
if layer == 2 and mpeg1 then
|
||||
-- the standard's allowed bit rate / mode combinations
|
||||
|
||||
@@ -15,7 +15,8 @@ local CeltEncoder = require("@formats/codecs/audio/Opus/CeltEncoder")
|
||||
local Encode = {}
|
||||
|
||||
export type Options = {
|
||||
bitrate: number?, -- bits per second (default 64000 per channel; 6000 .. 510000, constant)
|
||||
bitrate: number?, -- bits per second (default 64000 per channel; 6000 .. 510000, constant); values below 1000
|
||||
-- are kbit/s (96 = 96000), as for every encoder's bitrate option
|
||||
tags: { [string]: string }?, -- default: the audio's tags
|
||||
vendor: string?, -- OpusTags vendor (default "formats-luau")
|
||||
serial: number?, -- Ogg stream serial (default 0x4f707573)
|
||||
@@ -39,6 +40,9 @@ function Encode.encode(value: any, opts: Options?): (buffer?, Err.Err?)
|
||||
return nil, Err.new(Err.ARG, "bad sample rate " .. tostring(rate))
|
||||
end
|
||||
local bitrate = o.bitrate or 64000 * ch
|
||||
if type(bitrate) == "number" and bitrate > 0 and bitrate < 1000 then
|
||||
bitrate *= 1000 -- kbit/s
|
||||
end
|
||||
if type(bitrate) ~= "number" or bitrate < 6000 or bitrate > 510000 then
|
||||
return nil, Err.new(Err.ARG, "bitrate 6000 .. 510000")
|
||||
end
|
||||
|
||||
@@ -273,14 +273,40 @@ local function composite(dst: buffer, dw: number, dh: number, src: buffer, sw: n
|
||||
end
|
||||
end
|
||||
|
||||
-- lerp(dst, from, t, n): dst = from + (dst - from) * t per byte over n pixels (pass-through group opacity)
|
||||
local function lerp(dst: buffer, from: buffer, t: number, n: number)
|
||||
-- lerp(dst, from, t, n, w?, mask?): dst = from + (dst - from) * t per byte over n pixels (pass-through group opacity);
|
||||
-- with a mask ({ pixels, width, height, x, y, default } as for composite, in the coordinates of a w-wide canvas) t is
|
||||
-- also scaled by the mask value of each pixel
|
||||
local function lerp(dst: buffer, from: buffer, t: number, n: number, w: number?, mask: any?)
|
||||
if blen(dst) < n * 4 or blen(from) < n * 4 then
|
||||
return
|
||||
end
|
||||
for i = 0, n * 4 - 1 do
|
||||
local a = readu8(from, i)
|
||||
writeu8(dst, i, floor(a + (readu8(dst, i) - a) * t + 0.5))
|
||||
if mask == nil or w == nil or w <= 0 then
|
||||
for i = 0, n * 4 - 1 do
|
||||
local a = readu8(from, i)
|
||||
writeu8(dst, i, floor(a + (readu8(dst, i) - a) * t + 0.5))
|
||||
end
|
||||
return
|
||||
end
|
||||
local mbuf: buffer? = mask.pixels
|
||||
local mw, mh = floor(tonumber(mask.width) or 0), floor(tonumber(mask.height) or 0)
|
||||
local mx0, my0 = floor(tonumber(mask.x) or 0), floor(tonumber(mask.y) or 0)
|
||||
local mdef = (tonumber(mask.default) or 255) / 255
|
||||
if type(mbuf) ~= "buffer" or mw <= 0 or mh <= 0 or blen(mbuf) < mw * mh then
|
||||
mbuf = nil
|
||||
end
|
||||
for p = 0, n - 1 do
|
||||
local px, py = p % w, p // w
|
||||
local mv = mdef
|
||||
local mxx, myy = px - mx0, py - my0
|
||||
if mbuf ~= nil and mxx >= 0 and myy >= 0 and mxx < mw and myy < mh then
|
||||
mv = readu8(mbuf, myy * mw + mxx) / 255
|
||||
end
|
||||
local tt = t * mv
|
||||
local o = p * 4
|
||||
for k = o, o + 3 do
|
||||
local a = readu8(from, k)
|
||||
writeu8(dst, k, floor(a + (readu8(dst, k) - a) * tt + 0.5))
|
||||
end
|
||||
end
|
||||
end
|
||||
Blend.composite = composite
|
||||
@@ -330,8 +356,10 @@ local function compose(layers: { any }, canvas: buffer, w: number, h: number, hi
|
||||
local before = buffer.create(w * h * 4)
|
||||
buffer.copy(before, 0, canvas, 0, w * h * 4)
|
||||
compose(l.children, canvas, w, h, hidden)
|
||||
if opacity < 1 then
|
||||
lerp(canvas, before, opacity, w * h)
|
||||
-- the group's opacity and mask limit how much of its effect reaches the canvas (as in Photoshop)
|
||||
local gm = maskOf(l)
|
||||
if opacity < 1 or gm ~= nil then
|
||||
lerp(canvas, before, opacity, w * h, w, gm)
|
||||
end
|
||||
continue
|
||||
end
|
||||
@@ -360,7 +388,7 @@ end
|
||||
|
||||
-- flatten(layers, canvas, w, h, hidden): composites a Types.Layer tree (bottom to top) onto the w x h rgba8 canvas:
|
||||
-- blend modes, opacity x fillOpacity, groups (isolated, or "passThrough": blended straight onto the canvas, the group
|
||||
-- opacity then mixing before / after), clipping layers (clip = true: source-atop onto the layer below), grey masks.
|
||||
-- opacity and mask then mixing before / after), clipping layers (clip = true: source-atop onto the layer below), grey masks.
|
||||
-- hidden = true includes invisible layers.
|
||||
function Blend.flatten(layers: { any }, canvas: buffer, w: number, h: number, hidden: boolean)
|
||||
if blen(canvas) >= w * h * 4 then
|
||||
|
||||
@@ -466,6 +466,11 @@ function Video.open(demuxer: Types.Demuxer, opts: OpenOptions?): (Types.VideoDec
|
||||
if img then
|
||||
local t = (pts or 0) / scale - start
|
||||
if t + 1e-9 >= skipUntil then
|
||||
if index < 0 then
|
||||
-- the first frame after a seek: its position in the stream (constant-rate: round(pts * fps);
|
||||
-- without a frame rate, counted from the seek)
|
||||
index = if v.frameRate > 0 then math.max(0, math.floor(t * v.frameRate + 0.5)) else 0
|
||||
end
|
||||
index += 1
|
||||
local d = defaultDur
|
||||
if lastPts and t > (lastPts :: number) and defaultDur == 0 then
|
||||
@@ -502,6 +507,7 @@ function Video.open(demuxer: Types.Demuxer, opts: OpenOptions?): (Types.VideoDec
|
||||
flushed = false
|
||||
skipUntil = seconds
|
||||
lastPts = nil
|
||||
index = -1 -- recomputed from the first frame's time
|
||||
if self.audio then
|
||||
pcall(self.audio.seek, self.audio, seconds)
|
||||
end
|
||||
|
||||
@@ -325,16 +325,23 @@ local function adts(track: Types.Track, packets: { Types.Packet }): (buffer?, Er
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ trim
|
||||
-- trim(decoder, frames) -> an audio Decoder that drops the first `frames` sample frames (a container's codec delay:
|
||||
-- Matroska CodecDelay for MP2 / MP3 / AAC, which ffmpeg drops too; Opus handles its pre-skip itself)
|
||||
function AudioWrap.trim(dec: any, skip: number): any
|
||||
if skip <= 0 then
|
||||
-- trim(decoder, frames, length?) -> an audio Decoder that drops the first `frames` sample frames (a container's
|
||||
-- codec delay: Matroska CodecDelay, an MP4 edit's media time for MP2 / MP3 / AAC, which ffmpeg drops too; Opus
|
||||
-- handles its pre-skip itself) and, with length, ends after that many frames (an MP4 edit's length: end padding)
|
||||
function AudioWrap.trim(dec: any, skip: number, length: number?): any
|
||||
if skip <= 0 and length == nil then
|
||||
return dec
|
||||
end
|
||||
skip = math.max(0, skip)
|
||||
local rate = dec.sampleRate
|
||||
local w: any = setmetatable({}, { __index = dec })
|
||||
w.frames = math.max(0, (dec.frames or 0) - skip)
|
||||
w.duration = math.max(0, (dec.duration or 0) - skip / rate)
|
||||
if length then
|
||||
w.frames = if (dec.frames or 0) > 0 then math.min(w.frames, length) else length
|
||||
end
|
||||
w.duration = w.frames / rate
|
||||
local cap = length or math.huge
|
||||
local delivered = 0
|
||||
local function drop()
|
||||
local left = skip
|
||||
while left > 0 do
|
||||
@@ -351,15 +358,23 @@ function AudioWrap.trim(dec: any, skip: number): any
|
||||
started = true
|
||||
drop()
|
||||
end
|
||||
return dec:read(n, out)
|
||||
local want = math.min(n, cap - delivered)
|
||||
if want <= 0 then
|
||||
return out or buffer.create(0), 0
|
||||
end
|
||||
local b, got = dec:read(want, out)
|
||||
delivered += got
|
||||
return b, got
|
||||
end
|
||||
function w.seek(_: any, seconds: number)
|
||||
started = true
|
||||
if seconds <= 0 then
|
||||
dec:seek(0)
|
||||
drop()
|
||||
delivered = 0
|
||||
else
|
||||
dec:seek(seconds + skip / rate)
|
||||
delivered = math.floor(seconds * rate + 0.5)
|
||||
end
|
||||
end
|
||||
function w.position(_: any): number
|
||||
|
||||
@@ -20,7 +20,7 @@ local Bmfont = {
|
||||
extensions = { "fnt" },
|
||||
mime = { "application/x-bmfont" },
|
||||
deps = { "core/Err", "core/Bytes", "Types" },
|
||||
caps = { decode = true, encode = true, bitmap = true, variants = { "text", "xml", "binary" } },
|
||||
caps = { decode = true, encode = true, bitmap = true, variants = { "text", "xml", "binary" }, extraFiles = true },
|
||||
}
|
||||
|
||||
export type DecodeOptions = {
|
||||
@@ -31,6 +31,11 @@ export type EncodeOptions = {
|
||||
variant: ("text" | "xml" | "binary")?, -- default: the variant it was read from, else "text"
|
||||
px: number?, -- fonts without a BMFont description are baked first (see bake)
|
||||
chars: (string | { number })?,
|
||||
file: string?, -- baking: the page file name prefix (default: opts.name without its extension, else "font")
|
||||
name: string?, -- the destination's file name (set by the api)
|
||||
files: { [string]: any }?, -- the page images are written here, encoded by opts.encodeImage (the api passes
|
||||
-- both): files[page file name] = PNG bytes, for the baked pages or a BMFont's loaded pages
|
||||
encodeImage: ((img: any, format: string) -> (buffer?, any))?,
|
||||
}
|
||||
export type BakeOptions = {
|
||||
px: number?, -- pixels per em (default 32)
|
||||
@@ -237,16 +242,42 @@ function Bmfont.encode(font: any, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
return nil, Err.new(Err.ARG, "expected a Font")
|
||||
end
|
||||
local d = type(font.meta) == "table" and font.meta.bmfont or nil
|
||||
local pages = font.pages
|
||||
if d == nil then
|
||||
local baked, err = Bmfont.bake(font, { px = opts and opts.px, chars = opts and opts.chars })
|
||||
-- page names: opts.file, else the destination's base name (the api passes opts.name), else "font"
|
||||
local file = opts and opts.file
|
||||
if file == nil and opts and type(opts.name) == "string" then
|
||||
file = string.match(opts.name, "([^/\\]-)%.[^./\\]*$") or string.match(opts.name, "([^/\\]+)$")
|
||||
if file == "" then
|
||||
file = nil
|
||||
end
|
||||
end
|
||||
local baked, err = Bmfont.bake(font, { px = opts and opts.px, chars = opts and opts.chars, file = file })
|
||||
if not baked then
|
||||
return nil, err
|
||||
end
|
||||
d = baked.meta.bmfont
|
||||
pages = baked.pages
|
||||
end
|
||||
if not validDesc(d) then
|
||||
return nil, Err.new(Err.ARG, "bad BMFont description in font.meta.bmfont")
|
||||
end
|
||||
-- the page images into opts.files, under the names the descriptor gives them
|
||||
local files = opts and opts.files
|
||||
local encodeImage = opts and opts.encodeImage
|
||||
if type(files) == "table" and type(encodeImage) == "function" and type(pages) == "table" then
|
||||
for i, name in d.pages do
|
||||
local img = pages[i]
|
||||
if type(img) == "table" and type(name) == "string" and name ~= "" then
|
||||
local ext = string.lower(string.match(name, "%.([%w]+)$") or "png")
|
||||
local bytes, eerr = encodeImage(img, ext)
|
||||
if not bytes then
|
||||
return nil, Err.new(Err.ARG, "page " .. (i - 1) .. " (" .. name .. "): " .. tostring(eerr and eerr.message or eerr))
|
||||
end
|
||||
files[name] = bytes
|
||||
end
|
||||
end
|
||||
end
|
||||
local variant = (opts and opts.variant) or (font.meta and font.meta.variant) or "text"
|
||||
if variant == "text" then
|
||||
return buffer.fromstring(Parse.writeText(d)), nil
|
||||
|
||||
+160
-9
@@ -12,7 +12,7 @@
|
||||
-- local s = F.saveString(img, { format = "png" })
|
||||
-- local buf = F.convert(src, "png", opts?) -- load + save
|
||||
-- F.formats() -- the capability list (also docs/FORMATS.md)
|
||||
-- F.ops.image.resize(img, 64, 64) -- editing: F.ops.image / mesh / layers / audio / vector.rasterize
|
||||
-- F.ops.image.resize(img, 64, 64) -- editing: F.ops.image / mesh / layers / audio / music / vector
|
||||
--
|
||||
-- Never throws on bad data or bad arguments: every function returns nil, Err (Err.code, Err.message, tostring(err)).
|
||||
local Err = require("@formats/core/Err")
|
||||
@@ -129,6 +129,20 @@ local function detect(buf: buffer, name: string?, category: string?, format: str
|
||||
return nil, Err.new(Err.UNKNOWN_FORMAT, "unrecognised data" .. (if name then " (" .. name .. ")" else "") .. (if category then " for " .. category else ""))
|
||||
end
|
||||
|
||||
-- detectFor(buf, name, o) -> entry | nil, Err, rendered: detect with o.category / o.format; every music file that
|
||||
-- renders (MOD, S3M, XM, IT, MIDI) is also audio, so an audio lookup that finds nothing falls back to them (rendered =
|
||||
-- true: open the format, which renders it, instead of decoding it)
|
||||
local function detectFor(buf: buffer, name: string?, o: { [string]: any }): (Registry.Entry?, Err.Err?, boolean)
|
||||
local entry, err = detect(buf, name, o.category, o.format)
|
||||
if not entry and o.category == "audio" then
|
||||
local e = detect(buf, name, "music", o.format)
|
||||
if e and e.caps.render then
|
||||
return e, nil, true
|
||||
end
|
||||
end
|
||||
return entry, err, false
|
||||
end
|
||||
|
||||
local function tag(value: any, formatName: string)
|
||||
if type(value) == "table" then
|
||||
local meta = value.meta
|
||||
@@ -273,8 +287,13 @@ local function openAudio(demuxer: any, track: any): (any, Err.Err?)
|
||||
local dec, oerr = F.open(buf, { format = fmt, category = "audio" })
|
||||
-- Matroska CodecDelay: ffmpeg drops it for MPEG audio / AAC; Opus has its own pre-skip and Vorbis's delay is
|
||||
-- already the decoder's own (its first packet returns nothing)
|
||||
if dec and fmt ~= "opus" and fmt ~= "vorbis" and type(track.codecDelay) == "number" and track.codecDelay > 0 then
|
||||
dec = AudioWrap.trim(dec, math.floor(track.codecDelay * dec.sampleRate + 0.5))
|
||||
-- MP4 edit lists add the play length (the encoder's end padding is cut, as ffmpeg does)
|
||||
if dec and fmt ~= "opus" and fmt ~= "vorbis" then
|
||||
local skip = if type(track.codecDelay) == "number" and track.codecDelay > 0 then math.floor(track.codecDelay * dec.sampleRate + 0.5) else 0
|
||||
local length = if type(track.playDuration) == "number" and track.playDuration > 0 then math.floor(track.playDuration * dec.sampleRate + 0.5) else nil
|
||||
if skip > 0 or length then
|
||||
dec = AudioWrap.trim(dec, skip, length)
|
||||
end
|
||||
end
|
||||
return dec, oerr
|
||||
end
|
||||
@@ -314,7 +333,7 @@ function F.load(src: any, opts: Options?): (any, Err.Err?)
|
||||
o = table.clone(o)
|
||||
o.name = name -- formats may use the file name (single-stream archives name their entry after it)
|
||||
end
|
||||
local entry, derr = detect(buf, name, o.category, o.format)
|
||||
local entry, derr, rendered = detectFor(buf, name, o)
|
||||
if not entry then
|
||||
return nil, derr
|
||||
end
|
||||
@@ -328,7 +347,7 @@ function F.load(src: any, opts: Options?): (any, Err.Err?)
|
||||
o.resolve = siblings(name)
|
||||
end
|
||||
local value, err
|
||||
if m.decode then
|
||||
if m.decode and not rendered then
|
||||
local ok, v, e = pcall(m.decode, Bytes.reader(buf), withHooks(o))
|
||||
if not ok then
|
||||
return nil, Err.wrap(Err.new(Err.CORRUPT, "decoder threw: " .. tostring(v)), entry.name)
|
||||
@@ -362,7 +381,7 @@ function F.open(src: any, opts: Options?): (any, Err.Err?)
|
||||
if not buf then
|
||||
return nil, ierr
|
||||
end
|
||||
local entry, derr = detect(buf, name, o.category, o.format)
|
||||
local entry, derr = detectFor(buf, name, o)
|
||||
if not entry and o.category == "video" and o.format == nil then
|
||||
entry = detect(buf, name, "image", nil) -- animated images open as frames-backed videos
|
||||
end
|
||||
@@ -398,6 +417,91 @@ end
|
||||
|
||||
local encodeTextures: (scene: any) -> Err.Err?
|
||||
|
||||
-- videoToImage(v, opts) -> an animated rgba8 Image of the video's frames (for the GIF / APNG / WebP writers) | nil,
|
||||
-- Err. opts.frames: how many frames to keep (default all, up to the cap); opts.fps: the output frame rate (frames are
|
||||
-- picked at 1 / fps steps, each held as long as it covers; default the source's own timing); opts.maxFrames: the cap
|
||||
-- (default 300); opts.maxPixels: a cap on frames * width * height (default 2^25). Reads the decoder from where it is.
|
||||
local function videoToImage(v: any, o: Options): (any, Err.Err?)
|
||||
if type(v.nextFrame) ~= "function" or type(v.toRGBA) ~= "function" then
|
||||
return nil, Err.new(Err.ARG, "save: not a VideoDecoder")
|
||||
end
|
||||
local cap = o.maxFrames or 300
|
||||
local want = o.frames
|
||||
local fps = o.fps
|
||||
if type(cap) ~= "number" or cap < 1 or (want ~= nil and (type(want) ~= "number" or want < 1)) or (fps ~= nil and (type(fps) ~= "number" or fps <= 0 or fps > 1000)) then
|
||||
return nil, Err.new(Err.ARG, "save: frames / maxFrames must be >= 1 and fps 0..1000")
|
||||
end
|
||||
local limit = math.floor(if want then math.min(want, cap) else cap)
|
||||
local w, h = math.max(1, tonumber(v.width) or 1), math.max(1, tonumber(v.height) or 1)
|
||||
limit = math.max(1, math.min(limit, math.floor((o.maxPixels or 2 ^ 25) / (w * h))))
|
||||
local defaultDur = if type(v.frameRate) == "number" and v.frameRate > 0 then 1 / v.frameRate else 0.1
|
||||
local images: { any }, delays: { number } = {}, {}
|
||||
local t0: number? = nil
|
||||
local taken = 0 -- output slots used (fps mode)
|
||||
while #images < limit do
|
||||
local ok, f, ferr = pcall(v.nextFrame, v)
|
||||
if not ok then
|
||||
return nil, Err.new(Err.CORRUPT, "video decoder threw: " .. tostring(f))
|
||||
end
|
||||
if f == nil then
|
||||
if ferr then
|
||||
return nil, ferr
|
||||
end
|
||||
break
|
||||
end
|
||||
local dur = if type(f.duration) == "number" and f.duration > 0 then f.duration else defaultDur
|
||||
local delay = dur
|
||||
if fps then
|
||||
local start: number = t0 or f.pts
|
||||
t0 = start
|
||||
local slots = math.ceil((f.pts - start + dur) * fps - 1e-6) - taken
|
||||
delay = slots / fps
|
||||
taken += math.max(0, slots)
|
||||
end
|
||||
if delay > 0 then
|
||||
local rok, img = pcall(v.toRGBA, v, f)
|
||||
if not rok or type(img) ~= "table" then
|
||||
return nil, Err.new(Err.CORRUPT, "frame " .. tostring(f.index) .. " did not convert to rgba8")
|
||||
end
|
||||
table.insert(images, img)
|
||||
table.insert(delays, delay)
|
||||
end
|
||||
end
|
||||
if #images == 0 then
|
||||
return nil, Err.new(Err.ARG, "save: the video has no frames")
|
||||
end
|
||||
local img, ierr = ImageOps.fromFrames(images, delays)
|
||||
if not img then
|
||||
return nil, ierr
|
||||
end
|
||||
img.loops = if type(v.loops) == "number" then v.loops else 0
|
||||
img.meta.source = { format = v.format }
|
||||
return img, nil
|
||||
end
|
||||
|
||||
-- renderMusic(value, opts) -> the audio Decoder of a Module (codecs/audio/Tracker) or a Midi (music/midi render) |
|
||||
-- nil, Err. opts are the render options: sampleRate, soundfont, gain, tail, interpolation, stereoSeparation, ...
|
||||
local function renderMusic(value: any, o: Options): (any, Err.Err?)
|
||||
local ok, dec, err
|
||||
if value.kind == "midi" then
|
||||
local m, merr = F.format("midi")
|
||||
if not m then
|
||||
return nil, merr
|
||||
end
|
||||
ok, dec, err = pcall(m.render, value, o)
|
||||
else
|
||||
local Tracker: any = require("@formats/codecs/audio/Tracker")
|
||||
ok, dec, err = pcall(Tracker.render, value, o)
|
||||
end
|
||||
if not ok then
|
||||
return nil, Err.new(Err.ARG, "render threw: " .. tostring(dec))
|
||||
end
|
||||
if dec == nil then
|
||||
return nil, err or Err.new(Err.ARG, "render failed")
|
||||
end
|
||||
return dec, nil
|
||||
end
|
||||
|
||||
-- the writable format for a value: opts.format, the destination's extension, or the source format
|
||||
local function encoderFor(value: any, dest: string?, o: Options): (Registry.Entry?, any, Err.Err?, string?)
|
||||
local category = o.category
|
||||
@@ -415,6 +519,12 @@ local function encoderFor(value: any, dest: string?, o: Options): (Registry.Entr
|
||||
if not entry and category == "image" and type(value) == "table" and value.kind == "image" then
|
||||
entry = find(key, "video") -- an (animated) image written as a video: F.convert(gif, "avi")
|
||||
end
|
||||
if not entry and category == "video" and type(value) == "table" and value.kind == "video" then
|
||||
entry = find(key, "image") -- a video written as an animated image (F.save): F.convert(avi, "gif")
|
||||
end
|
||||
if not entry and category == "music" and type(value) == "table" and (value.kind == "music" or value.kind == "midi") then
|
||||
entry = find(key, "audio") -- a Module / Midi saved as audio is rendered first (F.save): F.convert(mod, "wav")
|
||||
end
|
||||
if not entry then
|
||||
return nil, nil, Err.new(Err.UNKNOWN_FORMAT, "no format named " .. key .. (if category then " for " .. category else ""))
|
||||
end
|
||||
@@ -452,8 +562,10 @@ function encodeTextures(scene: any): Err.Err?
|
||||
return nil
|
||||
end
|
||||
|
||||
-- save(value, dest?, opts?) -> buffer (no dest) | true (written to dest) | nil, Err
|
||||
function F.save(value: any, dest: string?, opts: Options?): (any, Err.Err?)
|
||||
-- save(value, dest?, opts?) -> buffer (no dest) | true (written to dest) | nil, Err. Formats that write extra files
|
||||
-- (caps.extraFiles: bmfont pages) return them without a dest as a third value { [file name] = bytes } (or fill the
|
||||
-- caller's opts.files); with a dest they are written next to it.
|
||||
function F.save(value: any, dest: string?, opts: Options?): (any, Err.Err?, { [string]: any }?)
|
||||
local o: Options = opts or {}
|
||||
local entry, m, err, key = encoderFor(value, dest, o)
|
||||
if not entry then
|
||||
@@ -468,6 +580,8 @@ function F.save(value: any, dest: string?, opts: Options?): (any, Err.Err?)
|
||||
if o.files == nil then
|
||||
o.files = {}
|
||||
end
|
||||
elseif o.files == nil and entry.caps.extraFiles then
|
||||
o.files = {} -- returned as the third value: F.save(ttf, nil, { format = "bmfont" }) -> fnt, nil, pages
|
||||
end
|
||||
if entry.category == "video" and type(value) == "table" and value.kind == "image" then
|
||||
local v, verr = F.video.fromImage(value)
|
||||
@@ -476,6 +590,20 @@ function F.save(value: any, dest: string?, opts: Options?): (any, Err.Err?)
|
||||
end
|
||||
value = v
|
||||
end
|
||||
if entry.category == "image" and type(value) == "table" and value.kind == "video" then
|
||||
local img, ierr = videoToImage(value, o)
|
||||
if not img then
|
||||
return nil, ierr
|
||||
end
|
||||
value = img
|
||||
end
|
||||
if entry.category == "audio" and type(value) == "table" and (value.kind == "music" or value.kind == "midi") then
|
||||
local dec, rerr = renderMusic(value, o) -- the render options (sampleRate, soundfont, loop, ...) come from opts
|
||||
if not dec then
|
||||
return nil, rerr
|
||||
end
|
||||
value = dec
|
||||
end
|
||||
if type(value) == "table" and value.kind == "scene" then
|
||||
local terr = encodeTextures(value)
|
||||
if terr then
|
||||
@@ -505,6 +633,9 @@ function F.save(value: any, dest: string?, opts: Options?): (any, Err.Err?)
|
||||
end
|
||||
return true
|
||||
end
|
||||
if type(o.files) == "table" and o.files ~= (opts and opts.files) and next(o.files) ~= nil then
|
||||
return buf, nil, o.files
|
||||
end
|
||||
return buf
|
||||
end
|
||||
|
||||
@@ -518,7 +649,7 @@ function F.saveString(value: any, opts: Options?): (string?, Err.Err?)
|
||||
end
|
||||
|
||||
-- convert(src, format, opts?) -> buffer (or true with opts.out = a path) | nil, Err. opts go to both load and save.
|
||||
function F.convert(src: any, format: string, opts: Options?): (any, Err.Err?)
|
||||
function F.convert(src: any, format: string, opts: Options?): (any, Err.Err?, { [string]: any }?)
|
||||
local o: Options = opts or {}
|
||||
local value, err = F.load(src, o)
|
||||
if value == nil then
|
||||
@@ -541,6 +672,14 @@ function F.detect(src: any, opts: Options?): (string?, Err.Err?)
|
||||
if not entry then
|
||||
return nil, err
|
||||
end
|
||||
-- a format may name the file's flavour more precisely (video/mkv: "webm" for DocType webm)
|
||||
local m = module(entry)
|
||||
if m and type(m.variant) == "function" then
|
||||
local ok, v = pcall(m.variant, Bytes.reader(buf))
|
||||
if ok and type(v) == "string" then
|
||||
return v, nil
|
||||
end
|
||||
end
|
||||
return entry.name, nil
|
||||
end
|
||||
|
||||
@@ -616,6 +755,14 @@ for _, fn in { "toBodies", "fromBodies", "tessellate" } do
|
||||
return a, b
|
||||
end
|
||||
end
|
||||
-- F.music.new / addPattern / setCell / getCell / addSample / addInstrument / note: building and editing tracker
|
||||
-- Modules (ops/MusicOps, loaded on first use): F.music.new({ format = "mod", channels = 4 }) -> Module
|
||||
for _, fn in { "new", "addPattern", "setCell", "getCell", "addSample", "addInstrument", "note" } do
|
||||
local name: string = fn
|
||||
F.music[name] = function(...: any): (any, Err.Err?)
|
||||
return (F.ops.music :: any)[name](...)
|
||||
end
|
||||
end
|
||||
-- F.video.fromImage(img, opts?) -> a frames-backed VideoDecoder: an animated GIF / APNG / WebP (img.frames, composited
|
||||
-- onto full canvases by ImageOps.coalesce) or a still image (one frame). opts.rgba is accepted (frames are rgba8).
|
||||
F.video.fromImage = function(img: any, opts: Options?): (any, Err.Err?)
|
||||
@@ -687,6 +834,7 @@ end
|
||||
-- F.ops.layers ops/LayerOps flatten / flattenFrames a Layered (PSD, Aseprite), leaves
|
||||
-- F.ops.audio ops/AudioOps toAudio, gain / gainDb / normalize, mix, remix / downmix / upmix, resample, trim,
|
||||
-- concat, fade, peak, rms
|
||||
-- F.ops.music ops/MusicOps new, addPattern, setCell / getCell, addSample, addInstrument, note (also on F.music)
|
||||
-- F.ops.vector.rasterize(vector, w?, h?, opts?) -> rgba8 Image: the SVG renderer (vector/svg) for any Vector
|
||||
local OPS: { [string]: () -> any } = {
|
||||
image = function()
|
||||
@@ -701,6 +849,9 @@ local OPS: { [string]: () -> any } = {
|
||||
audio = function()
|
||||
return require("@formats/ops/AudioOps")
|
||||
end,
|
||||
music = function()
|
||||
return require("@formats/ops/MusicOps")
|
||||
end,
|
||||
vector = function()
|
||||
return {
|
||||
rasterize = function(v: any, w: number?, h: number?, opts: any?): (any, Err.Err?)
|
||||
|
||||
@@ -3,7 +3,8 @@
|
||||
-- divisions; running status, also across meta / sysex events as most players accept), skips unknown chunks, unwraps
|
||||
-- RIFF RMID. Writes MThd + MTrk with optional running status; with running status on (the default) the bytes are
|
||||
-- those python mido writes for the same events (running status reset after meta / sysex, one end-of-track at the
|
||||
-- end, mid-track end-of-track events dropped). Written from the SMF 1.0 specification (no third-party code).
|
||||
-- end, mid-track end-of-track events dropped); a track's name is written as a 0x03 event at tick 0 when the track
|
||||
-- has none. Written from the SMF 1.0 specification (no third-party code).
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Types = require("@formats/Types")
|
||||
@@ -323,6 +324,21 @@ function Smf.write(midi: Types.Midi, opts: WriteOptions?): (buffer?, Err.Err?)
|
||||
return order[a] < order[c]
|
||||
end)
|
||||
end
|
||||
-- track.name: written as a track-name meta event (0x03) at tick 0 when the track has none of its own
|
||||
if type(track.name) == "string" and track.name ~= "" then
|
||||
local named = false
|
||||
for _, ev in list do
|
||||
if ev.type == "meta" and ev.meta == 0x03 then
|
||||
named = true
|
||||
break
|
||||
end
|
||||
end
|
||||
if not named then
|
||||
local bytes = { string.byte(track.name, 1, math.min(#track.name, 4096)) }
|
||||
list = table.clone(list)
|
||||
table.insert(list, 1, { tick = 0, type = "meta", meta = 0x03, data = bytes })
|
||||
end
|
||||
end
|
||||
w:string("MTrk")
|
||||
local lenAt = w:tell()
|
||||
w:u32be(0)
|
||||
|
||||
@@ -0,0 +1,368 @@
|
||||
--!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("@formats/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("@formats/core/Err")
|
||||
local Tracker = require("@formats/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
|
||||
return type(m) == "table" and m.kind == "music" and FORMATS[m.format] == 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 m.format == "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 m.format ~= "xm" and m.format ~= "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
|
||||
@@ -553,7 +553,9 @@ end
|
||||
export type Options = { maxPackets: number? }
|
||||
|
||||
-- parse(buf, base, limit, opts) -> a Demux | nil, Err
|
||||
function Parse.parse(buf: buffer, base: number, limit: number, opts: Options?): (any, Err.Err?)
|
||||
-- docType(buf, base, limit) -> the EBML header's DocType ("matroska" when it has none), the header's size and data
|
||||
-- offset | nil, Err
|
||||
function Parse.docType(buf: buffer, base: number, limit: number): (string?, any, number?)
|
||||
local id, size, data = Ebml.header(buf, base, limit)
|
||||
if id ~= ID.EBML or not size or not data then
|
||||
return nil, Err.new(Err.CORRUPT, "not an EBML file", base)
|
||||
@@ -567,6 +569,14 @@ function Parse.parse(buf: buffer, base: number, limit: number, opts: Options?):
|
||||
docType = Ebml.string(buf, o, n)
|
||||
end
|
||||
end
|
||||
return docType, size, data
|
||||
end
|
||||
|
||||
function Parse.parse(buf: buffer, base: number, limit: number, opts: Options?): (any, Err.Err?)
|
||||
local docType, size, data = Parse.docType(buf, base, limit)
|
||||
if not docType then
|
||||
return nil, size
|
||||
end
|
||||
if docType ~= "matroska" and docType ~= "webm" then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "EBML document type " .. docType)
|
||||
end
|
||||
|
||||
@@ -67,6 +67,15 @@ function Mkv.sniff(r: Bytes.Reader): number
|
||||
return 0.5
|
||||
end
|
||||
|
||||
-- variant(r) -> "webm" for a WebM file (DocType webm), else nil: the name F.detect reports (never throws)
|
||||
function Mkv.variant(r: Bytes.Reader): string?
|
||||
local ok, docType = pcall(Parse.docType, r.buf, r.pos, r.limit)
|
||||
if ok and docType == "webm" then
|
||||
return "webm"
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
-- encode(video, opts?) -> buffer | nil, Err: a VideoDecoder (F.load / F.video.open of any video or animated image)
|
||||
-- or a Demuxer
|
||||
|
||||
@@ -154,6 +154,9 @@ function Mp4.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?)
|
||||
if it.skip and it.skip > 0 then
|
||||
t.codecDelay = it.skip / it.timescale -- AAC priming: dropped like ffmpeg
|
||||
end
|
||||
if it.playDuration and it.playDuration > 0 and it.timescale > 0 then
|
||||
t.playDuration = it.playDuration / it.timescale -- the edit's length: the end padding is not played
|
||||
end
|
||||
end
|
||||
table.insert(tracks, t)
|
||||
table.insert(src, it)
|
||||
@@ -272,6 +275,8 @@ function Mp4.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
for _, d in durations do
|
||||
playDuration += d
|
||||
end
|
||||
elseif s.kind == "audio" and s.track and s.copied and type(s.track.playDuration) == "number" then
|
||||
playDuration = math.floor(s.track.playDuration * scale + 0.5) -- keep the source's end trim
|
||||
end
|
||||
local t: any = {
|
||||
kind = s.kind,
|
||||
|
||||
Reference in new issue
Block a user