ws-apifix: music is audio (F.save / F.convert of a Module or Midi to an audio format renders it, render options from opts; F.audio.open / load render music bytes), F.music builder (ops/MusicOps: new, addPattern, setCell / getCell, addSample, addInstrument, note; also F.ops.music), MIDI writer writes track.name as a 0x03 event
api (init.luau): detectFor() falls back from audio to rendering music formats; encoderFor finds audio formats for music values; renderMusic() through codecs/audio/Tracker or music/midi render. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
1 parent
90c5886f61
commit
4fb5c3a155
7 files changed
+692
-16
No files matched your search
+2
-2
@@ -250,5 +250,5 @@ visualisers.
|
||||
number.
|
||||
- `F.save(decoder)` without `opts.format` or a destination fails with `Err.ARG`, because a Decoder has no source
|
||||
format.
|
||||
- `F.audio.load` does not take music files (MOD, MIDI). Use `F.music.open(src)` for their audio
|
||||
([music.md](music.md)).
|
||||
- Music files (MOD, S3M, XM, IT, MIDI) are audio too: `F.audio.open` / `F.audio.load` render them, with the
|
||||
render options in `opts` ([music.md](music.md)).
|
||||
+72
-10
@@ -142,8 +142,8 @@ end
|
||||
| `F.music.load(src, opts?)` / `F.load` | a Module, a Midi or a SoundFont |
|
||||
| `F.music.open(src, opts?)` / `F.open` | the rendered audio Decoder (decode and render options together) |
|
||||
|
||||
`F.audio.open` and `F.audio.load` do not take music files; use `F.music.open`, or `F.open`, which detects any
|
||||
category.
|
||||
Every music file that renders is also audio: `F.audio.open(src)` gives the same rendered Decoder as `F.music.open`,
|
||||
and `F.audio.load(src)` the whole render as an Audio. Decode and render options go in the same `opts`.
|
||||
|
||||
| Option | Formats | Meaning |
|
||||
|---|---|---|
|
||||
@@ -157,6 +157,8 @@ assert(dec.sampleRate == 22050 and dec.channels == 2)
|
||||
assert(math.abs(dec.duration - 3) < 0.01) -- 2 s of notes + the 1 s release tail
|
||||
local d2 = assert(F.open(modBytes)) -- any category: a Decoder for a module
|
||||
assert(d2.channels == 2)
|
||||
local d3 = assert(F.audio.open(midiBytes, { sampleRate = 22050 })) -- music is audio too
|
||||
assert(d3.sampleRate == 22050)
|
||||
```
|
||||
|
||||
## Rendering
|
||||
@@ -199,20 +201,20 @@ assert(first.frames == 22050)
|
||||
|
||||
A Midi is plain data: build one with `F.Types.Midi.new(division?)` and save it as `.mid`. Events need absolute
|
||||
ticks; the writer sorts nothing, so keep each track's events in tick order. A track's `name` is read from its
|
||||
track-name meta event (0x03); the writer writes events only, so put the name in an event.
|
||||
track-name meta event (0x03); the writer writes `track.name` as one at tick 0 when the track has no 0x03 event of
|
||||
its own.
|
||||
|
||||
```luau
|
||||
local m = F.Types.Midi.new(480) -- 480 ticks per quarter note, SMF type 1
|
||||
local events = {
|
||||
{ tick = 0, type = "meta", meta = 0x51, data = { 0x07, 0xA1, 0x20 } }, -- tempo: 500000 us per quarter
|
||||
{ tick = 0, type = "meta", meta = 0x03, data = { string.byte("Arpeggio", 1, -1) } }, -- the track name
|
||||
{ tick = 0, type = "program", channel = 0, data = { 0 } },
|
||||
}
|
||||
for i, note in { 60, 64, 67, 72 } do
|
||||
table.insert(events, { tick = (i - 1) * 240, type = "noteOn", channel = 0, data = { note, 100 } })
|
||||
table.insert(events, { tick = i * 240, type = "noteOff", channel = 0, data = { note, 0 } })
|
||||
end
|
||||
table.insert(m.tracks, { events = events })
|
||||
table.insert(m.tracks, { name = "Arpeggio", events = events }) -- written as a 0x03 event
|
||||
local bytes = assert(F.save(m, nil, { format = "midi" }))
|
||||
local back = assert(F.music.load(bytes))
|
||||
assert(back.tracks[1].name == "Arpeggio" and back.meta.length == 1) -- 4 eighth notes at 120 BPM
|
||||
@@ -232,6 +234,69 @@ local _, err = F.save(song, nil, { format = "it" })
|
||||
assert(err.code == F.Err.UNSUPPORTED) -- read only
|
||||
```
|
||||
|
||||
Saving a Module or a Midi to an **audio** format renders it first, with the render options (see
|
||||
[Rendering](#rendering)) taken from the same `opts`; `F.convert` does the same from music bytes:
|
||||
|
||||
```luau
|
||||
local song = assert(F.music.load(modBytes))
|
||||
local wav = assert(F.save(song, nil, { format = "wav", sampleRate = 22050 }))
|
||||
assert((assert(F.audio.load(wav))).sampleRate == 22050)
|
||||
local flac = assert(F.convert(midiBytes, "flac", { soundfont = sf2Bytes, tail = 0.5 }))
|
||||
assert(F.detect(flac) == "flac")
|
||||
```
|
||||
|
||||
### Building a module
|
||||
|
||||
`F.music` has a small builder for tracker modules, so you never touch the pattern buffers or the sample tuning
|
||||
fields yourself. Pattern numbers are 0-based (as the order list names them), rows 0-based, channels 1-based, and
|
||||
sample and instrument numbers 1-based (0 = none in a cell). Every call returns `nil, Err.ARG` for bad arguments.
|
||||
|
||||
| Call | Returns |
|
||||
|---|---|
|
||||
| `F.music.new({ format?, channels?, title?, speed?, tempo? })` | an empty Module: `format` `"mod"` (default), `"xm"`, `"s3m"` or `"it"`; 4 channels by default |
|
||||
| `F.music.addPattern(m, rows?, { order? }?)` | the new pattern's number; `rows` default 64 (MOD needs 64); appended to `m.order` unless `order = false` |
|
||||
| `F.music.setCell(m, pattern, row, channel, cell)` | `true`; `cell = { note, instrument, volume, effect, param }`, missing fields 0 |
|
||||
| `F.music.getCell(m, pattern, row, channel)` | the cell, with `note` as a number |
|
||||
| `F.music.addSample(m, spec)` | the new sample's number |
|
||||
| `F.music.addInstrument(m, spec)` | the new instrument's number (XM / IT only; MOD and S3M cells name samples) |
|
||||
| `F.music.note(name)` | the note number: `"C-4"` = 49, `"C#4"` / `"Db4"` = 50, `"off"` 255, `"cut"` 254, `"fade"` 253 |
|
||||
|
||||
`addSample` takes `audio` (a mono or stereo Audio) or `data` (f32 frames) with `length` and `channels`; `rate`
|
||||
(the Hz the sample plays at on C-4 for MOD / XM, C-5 for S3M / IT; default the Audio's rate, else 8363), `loop`
|
||||
(`"none"`, `"forward"`, `"pingpong"`), `loopStart` / `loopEnd` (frames), `volume` 0..64, `pan` 0..256 and `bits`
|
||||
(8 or 16, what a writer stores). MOD files keep only a finetune of -1..+7/8 semitone, so give MOD samples a rate
|
||||
near 8363 Hz. `addInstrument` takes `name`, `sample` (every note) or `samples` (a `{ [note] = sample }` keymap),
|
||||
`fadeout`, and a volume `envelope = { points = { { tick, 0..64 }, ... }, sustain?, loopStart?, loopEnd? }`.
|
||||
|
||||
```luau
|
||||
local tone = F.Types.Audio.new(8363, 1, 8363) -- 1 s of a 440 Hz sine at MOD's C-4 rate
|
||||
for i = 0, 8362 do
|
||||
buffer.writef32(tone.samples, i * 4, 0.5 * math.sin(i / 8363 * 2 * math.pi * 440))
|
||||
end
|
||||
local song = assert(F.music.new({ format = "mod", channels = 4, title = "beeps" }))
|
||||
local s = assert(F.music.addSample(song, { name = "sine", audio = tone, loop = "forward" }))
|
||||
local p = assert(F.music.addPattern(song)) -- pattern 0, 64 rows, in the order list
|
||||
for row = 0, 63, 8 do
|
||||
assert(F.music.setCell(song, p, row, 1, { note = if row % 16 == 0 then "C-4" else "G-4", instrument = s }))
|
||||
end
|
||||
assert(F.music.setCell(song, p, 63, 2, { effect = 0xC, param = 0 })) -- effect C00: volume 0
|
||||
assert(F.music.getCell(song, p, 8, 1).note == F.music.note("G-4"))
|
||||
local mod = assert(F.save(song)) -- a .mod (the module's format)
|
||||
local wav = assert(F.save(song, nil, { format = "wav" })) -- or rendered
|
||||
assert(F.detect(mod) == "mod" and F.detect(wav) == "wav")
|
||||
|
||||
local xm = assert(F.music.new({ format = "xm", channels = 2 }))
|
||||
local smp = assert(F.music.addSample(xm, { audio = tone }))
|
||||
local lead = assert(F.music.addInstrument(xm, {
|
||||
name = "lead", sample = smp, fadeout = 512,
|
||||
envelope = { points = { { 0, 64 }, { 10, 40 }, { 40, 0 } }, sustain = 2 },
|
||||
}))
|
||||
local p2 = assert(F.music.addPattern(xm, 32))
|
||||
assert(F.music.setCell(xm, p2, 0, 1, { note = "C-4", instrument = lead }))
|
||||
assert(F.music.setCell(xm, p2, 16, 1, { note = "off" }))
|
||||
assert(F.music.load(assert(F.save(xm))).instruments[1].name == "lead")
|
||||
```
|
||||
|
||||
| Format | Encoder options |
|
||||
|---|---|
|
||||
| midi | `runningStatus` (default true: the bytes python's mido writes) |
|
||||
@@ -252,11 +317,8 @@ See [FORMATS.md](../FORMATS.md) for each format's capabilities.
|
||||
|
||||
## Gotchas
|
||||
|
||||
- **Saving music as audio needs a render.** `F.save(song, nil, { format = "wav" })` and `F.convert(modBytes, "wav")`
|
||||
fail with `UNKNOWN_FORMAT` ("no format named wav for music"). Render first:
|
||||
`F.save(song:render(), nil, { format = "wav" })`.
|
||||
- `F.audio.open(midiBytes)` fails with `UNKNOWN_FORMAT`; use `F.music.open` or `F.open`.
|
||||
- `track.name` is not written: add a meta 0x03 event to name a track.
|
||||
- Saving music to an audio format renders it with the options in `opts`: `F.save(song, nil, { format = "wav",
|
||||
loop = true })` would render up to `maxDuration` (an hour by default), so leave `loop` off when saving.
|
||||
- A Midi you build yourself has no `render` method; `F.format("midi").render(midi, opts)` renders it.
|
||||
- MIDI event ticks are absolute, not the deltas stored in the file. Pitch bend `data` is `{ lsb, msb }`, not a
|
||||
signed value: `(msb * 128 + lsb) - 8192`.
|
||||
|
||||
+62
-3
@@ -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
|
||||
@@ -314,7 +328,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 +342,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 +376,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 +412,29 @@ end
|
||||
|
||||
local encodeTextures: (scene: any) -> Err.Err?
|
||||
|
||||
-- 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 +452,9 @@ 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 == "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
|
||||
@@ -476,6 +516,13 @@ function F.save(value: any, dest: string?, opts: Options?): (any, Err.Err?)
|
||||
end
|
||||
value = v
|
||||
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
|
||||
@@ -616,6 +663,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 +742,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 +757,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,365 @@
|
||||
--!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 = 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, value = type(pt) == "table" and pt[1], type(pt) == "table" and pt[2]
|
||||
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
|
||||
@@ -169,6 +169,23 @@ do
|
||||
t:check(nope == nil and nerr.code == Err.ARG, "encode refuses nil")
|
||||
end
|
||||
|
||||
-- track.name is written as a 0x03 meta event at tick 0 when the track has none; an existing one wins
|
||||
do
|
||||
local m = Types.Midi.new(96)
|
||||
local notes = { { tick = 0, type = "noteOn", channel = 0, data = { 60, 100 } }, { tick = 96, type = "noteOff", channel = 0, data = { 60, 0 } } }
|
||||
m.tracks[1] = { name = "Lead", events = notes }
|
||||
m.tracks[2] = { name = "Ignored", events = { { tick = 0, type = "meta", meta = 0x03, data = { string.byte("Bass", 1, -1) } } } }
|
||||
m.tracks[3] = { name = "", events = {} }
|
||||
local back = decode(Midi.encode(m) :: buffer)
|
||||
t:eq(back.tracks[1].name, "Lead", "track.name written")
|
||||
local first = back.tracks[1].events[1]
|
||||
t:check(first.type == "meta" and first.meta == 0x03 and first.tick == 0, "as a 0x03 event at tick 0")
|
||||
t:eq(#back.tracks[1].events, 4, "name + 2 notes + end of track")
|
||||
t:eq(back.tracks[2].name, "Bass", "the track's own 0x03 event wins")
|
||||
t:eq(back.tracks[3].name, nil, "empty name: nothing written")
|
||||
t:eq(#m.tracks[1].events, 2, "the caller's events are not changed")
|
||||
end
|
||||
|
||||
-- crafted bad files
|
||||
for _, c in Bad do
|
||||
local ok, m, err = pcall(decode, c.data)
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
-- ops/MusicOps tests (F.music.new / addPattern / setCell / getCell / addSample / addInstrument / note) and the
|
||||
-- music-as-audio bridges of the api: F.save / F.convert of a Module or a Midi to an audio format (rendered, render
|
||||
-- options through opts), F.audio.open / F.audio.load of music bytes. Everything is built here (no fixtures).
|
||||
local T = require("@tests/T")
|
||||
local F = require("@formats")
|
||||
local Err = require("@formats/core/Err")
|
||||
|
||||
local t = T.suite("musicops")
|
||||
|
||||
-- a 1 s 440 Hz sine at 8363 Hz (MOD's C-4 rate)
|
||||
local function sine(rate: number, frames: number): any
|
||||
local a = F.Types.Audio.new(rate, 1, frames)
|
||||
for i = 0, frames - 1 do
|
||||
buffer.writef32(a.samples, i * 4, math.sin(i / rate * 2 * math.pi * 440) * 0.5)
|
||||
end
|
||||
return a
|
||||
end
|
||||
|
||||
-- note names
|
||||
do
|
||||
t:eq(F.music.note("C-0"), 1, "C-0")
|
||||
t:eq(F.music.note("C-4"), 49, "C-4")
|
||||
t:eq(F.music.note("c#4"), 50, "C#4")
|
||||
t:eq(F.music.note("Db4"), 50, "Db4")
|
||||
t:eq(F.music.note("B-9"), 120, "B-9")
|
||||
t:eq(F.music.note("off"), 255, "key off")
|
||||
t:eq(F.music.note("cut"), 254, "note cut")
|
||||
t:eq(F.music.note(61), 61, "a number")
|
||||
for _, badNote in { "H-4", "C-", 121, "Cb0", {}, -1 } do
|
||||
local n, e = F.music.note(badNote)
|
||||
t:check(n == nil and e and e.code == Err.ARG, "bad note " .. tostring(badNote))
|
||||
end
|
||||
end
|
||||
|
||||
-- a MOD built from scratch: saved, reloaded, rendered
|
||||
local a = sine(8363, 8363)
|
||||
local song = assert(F.music.new({ format = "mod", channels = 4, title = "demo", speed = 3 }))
|
||||
do
|
||||
t:eq(song.kind, "music", "kind")
|
||||
t:eq(song.meta.source.format, "mod", "source format")
|
||||
local s = assert(F.music.addSample(song, { name = "sine", audio = a, loop = "forward", volume = 48 }))
|
||||
t:eq(s, 1, "sample number")
|
||||
local p = assert(F.music.addPattern(song))
|
||||
t:eq(p, 0, "pattern number")
|
||||
t:eq(#song.order, 1, "appended to the order")
|
||||
t:check(F.music.setCell(song, p, 0, 1, { note = "C-4", instrument = s }), "setCell")
|
||||
t:check(F.music.setCell(song, p, 32, 2, { note = "E-4", instrument = s, effect = 0xC, param = 32 }), "setCell 2")
|
||||
local c = assert(F.music.getCell(song, p, 32, 2))
|
||||
t:check(c.note == 53 and c.instrument == 1 and c.effect == 0xC and c.param == 32 and c.volume == 0, "getCell")
|
||||
-- bad arguments
|
||||
local _, e1 = F.music.setCell(song, p, 64, 1, {})
|
||||
t:check(e1 and e1.code == Err.ARG, "row out of range")
|
||||
local _, e2 = F.music.setCell(song, p, 0, 5, {})
|
||||
t:check(e2 and e2.code == Err.ARG, "channel out of range")
|
||||
local _, e3 = F.music.setCell(song, 7, 0, 1, {})
|
||||
t:check(e3 and e3.code == Err.ARG, "no such pattern")
|
||||
local _, e4 = F.music.setCell(song, p, 0, 1, { param = 300 })
|
||||
t:check(e4 and e4.code == Err.ARG, "param out of range")
|
||||
local _, e5 = F.music.addInstrument(song, { sample = 1 })
|
||||
t:check(e5 and e5.code == Err.ARG, "MOD has no instruments")
|
||||
local _, e6 = F.music.new({ format = "mid" })
|
||||
t:check(e6 and e6.code == Err.ARG, "unknown tracker format")
|
||||
local _, e7 = F.music.addSample(song, { audio = F.Types.Audio.new(8000, 3, 4) })
|
||||
t:check(e7 and e7.code == Err.ARG, "3-channel sample")
|
||||
local _, e8 = F.music.addPattern({} :: any)
|
||||
t:check(e8 and e8.code == Err.ARG, "not a module")
|
||||
|
||||
local mod = assert(F.save(song)) -- the source format
|
||||
t:eq(F.detect(mod), "mod", "saved as MOD")
|
||||
local back = assert(F.music.load(mod))
|
||||
t:eq(back.title, "demo", "title round trip")
|
||||
t:check(back.samples[1].loopType == 1 and back.samples[1].volume == 48, "sample loop / volume round trip")
|
||||
local c2 = assert(F.music.getCell(back, 0, 32, 2))
|
||||
t:check(c2.note == 53 and c2.instrument == 1 and c2.effect == 0xC and c2.param == 32, "cells round trip")
|
||||
local dec = assert(song:render({ sampleRate = 22050 }))
|
||||
local au = assert(F.ops.audio.toAudio(dec))
|
||||
t:check(au.frames > 22050 and F.ops.audio.peak(au) > 0.05, "renders sound")
|
||||
end
|
||||
|
||||
-- an XM with an instrument and a volume envelope
|
||||
do
|
||||
local xm = assert(F.music.new({ format = "xm", channels = 2 }))
|
||||
local s = assert(F.music.addSample(xm, { audio = a, rate = 16726 })) -- an octave up: relativeNote 12
|
||||
t:eq(xm.samples[s].relativeNote, 12, "rate -> relativeNote")
|
||||
t:eq(xm.samples[s].finetune, 0, "rate -> finetune")
|
||||
local i = assert(F.music.addInstrument(xm, { name = "lead", sample = s, fadeout = 512, envelope = { points = { { 0, 64 }, { 10, 32 }, { 40, 0 } }, sustain = 2 } }))
|
||||
local p = assert(F.music.addPattern(xm, 32))
|
||||
assert(F.music.setCell(xm, p, 0, 1, { note = "C-4", instrument = i }))
|
||||
assert(F.music.setCell(xm, p, 16, 1, { note = "off" }))
|
||||
local back = assert(F.music.load(assert(F.save(xm))))
|
||||
t:check(back.format == "xm" and #back.instruments == 1 and back.instruments[1].name == "lead", "XM instrument round trip")
|
||||
t:check(back.instruments[1].volEnv and back.instruments[1].volEnv.enabled and #back.instruments[1].volEnv.ticks == 3, "XM envelope round trip")
|
||||
local _, ebad = F.music.addInstrument(xm, { sample = 9 })
|
||||
t:check(ebad and ebad.code == Err.ARG, "instrument on a missing sample")
|
||||
local _, eenv = F.music.addInstrument(xm, { envelope = { points = { { 5, 10 }, { 5, 20 } } } })
|
||||
t:check(eenv and eenv.code == Err.ARG, "envelope ticks must increase")
|
||||
end
|
||||
|
||||
-- music saved and converted as audio: rendered, with the render options from opts
|
||||
do
|
||||
local wav = assert(F.save(song, nil, { format = "wav", sampleRate = 22050 }))
|
||||
local au = assert(F.audio.load(wav))
|
||||
t:check(au.sampleRate == 22050 and au.channels == 2 and au.frames > 0, "F.save(module, wav) renders")
|
||||
local mod = assert(F.save(song))
|
||||
local w2 = assert(F.convert(mod, "wav", { sampleRate = 11025 }))
|
||||
t:eq(F.detect(w2), "wav", "F.convert(mod, wav)")
|
||||
t:eq((assert(F.audio.load(w2))).sampleRate, 11025, "convert passes sampleRate to the render")
|
||||
t:check(F.audio.save(song, nil, { format = "flac" }) ~= nil, "F.audio.save(module)")
|
||||
|
||||
local m = F.Types.Midi.new(480)
|
||||
table.insert(m.tracks, { events = {
|
||||
{ tick = 0, type = "noteOn", channel = 0, data = { 60, 100 } },
|
||||
{ tick = 480, type = "noteOff", channel = 0, data = { 60, 0 } },
|
||||
} })
|
||||
local mw = assert(F.save(m, nil, { format = "wav", tail = 0.5 })) -- a hand-built Midi (no render method)
|
||||
local ma = assert(F.audio.load(mw))
|
||||
t:eq(ma.frames, math.floor(1.0 * 44100 + 0.5), "Midi rendered: 0.5 s of notes + 0.5 s tail")
|
||||
local mid = assert(F.save(m, nil, { format = "midi" }))
|
||||
t:eq(F.detect(assert(F.convert(mid, "wav"))), "wav", "F.convert(midi, wav)")
|
||||
|
||||
-- F.audio.open / load of music bytes: the rendered Decoder
|
||||
local d1 = assert(F.audio.open(mid, { tail = 0 }))
|
||||
t:check(d1.channels == 2 and d1.sampleRate == 44100 and d1.frames == 22050, "F.audio.open(midi)")
|
||||
local d2 = assert(F.audio.open(mod))
|
||||
t:check(d2.channels == 2 and d2.frames > 0, "F.audio.open(mod)")
|
||||
local a2 = assert(F.audio.load(mod, { sampleRate = 8000 }))
|
||||
t:check(a2.kind == "audio" and a2.sampleRate == 8000, "F.audio.load(mod)")
|
||||
local d3 = assert(F.audio.open(mod, { format = "mod" }))
|
||||
t:check(d3.frames > 0, "F.audio.open with format = mod")
|
||||
-- still an error for data no format reads
|
||||
local _, e = F.audio.open(buffer.fromstring("not audio at all"))
|
||||
t:check(e and e.code == Err.UNKNOWN_FORMAT, "unknown data")
|
||||
-- and a soundfont is not audio
|
||||
local _, e2 = F.audio.save(m, nil, { format = "png" })
|
||||
t:check(e2 ~= nil, "music to a non-audio format fails")
|
||||
end
|
||||
|
||||
-- no throws on random cell / sample arguments
|
||||
do
|
||||
local rng = T.rng(7)
|
||||
local ok = true
|
||||
for _ = 1, 300 do
|
||||
local vals = { rng(300) - 20, "C-4", nil, {}, -1, 0.5, 1e9 }
|
||||
local pick = function(): any
|
||||
return vals[rng(#vals) + 1]
|
||||
end
|
||||
local pok = pcall(function()
|
||||
F.music.setCell(song, pick(), pick(), pick(), { note = pick(), instrument = pick(), param = pick() })
|
||||
F.music.getCell(song, pick(), pick(), pick())
|
||||
F.music.addSample(song, { data = buffer.create(rng(16)), length = pick(), loop = "forward", loopStart = pick(), loopEnd = pick() })
|
||||
end)
|
||||
ok = ok and pok
|
||||
end
|
||||
t:check(ok, "random arguments never throw")
|
||||
end
|
||||
|
||||
t:done()
|
||||
Reference in new issue
Block a user