--!strict -- codecs/audio/Hively: the AHX / HivelyTracker engine behind music/ahx and music/hvl: the loader for both file formats -- (Load), the replayer with its waveform generator (Tables: triangle / sawtooth / square / noise and the 31 + 31 -- filtered copies) and integer mixer (Player), and the render glue to a Types.Decoder (stereo f32). A port of -- HivelyTracker's hvl2wav replay.c 1.9 (BSD-3-Clause, (c) 2006-2018 Pete Gordon; licenses/hivelytracker-LICENSE.txt): -- at hvl2wav's settings the output equals hvl2wav's 16-bit samples / 32768, sample for sample. -- -- local Hively = require("@rosetta/codecs/audio/Hively") -- local tune, err = Hively.parse(buf, 0, buffer.len(buf)) -- the replayer's Tune -- local song = Hively.module(tune) -- a Types.Module-shaped value with render() -- local dec = Hively.decoder(tune, { sampleRate = 44100 }) -- a Types.Decoder -- -- Not supported: hvl2wav's -a auto gain; a speed multiplier of 4 at 44.1 kHz renders 880 samples per 50 Hz frame -- (hvl2wav pads each frame to 882 with stale samples). local Err = require("@rosetta/core/Err") local Types = require("@rosetta/Types") local Load = require("@rosetta/codecs/audio/Hively/Load") local Player = require("@rosetta/codecs/audio/Hively/Player") local Pcm = require("@rosetta/codecs/audio/Pcm") local Hively = {} export type Tune = Load.Tune export type RenderOptions = { sampleRate: number?, -- default 44100 (the replayer runs at any rate: 8000..192000) subsong: number?, -- 0 = the main song (default), 1..n the subsongs stereo: number?, -- AHX stereo separation 0..4 (0 mono, 4 = 100 % Amiga L R R L); default 0 as hvl2wav. HVL: the file's loop: boolean?, -- keep playing past the song end (frames / duration still give one pass) maxDuration: number?, -- seconds, default 600 (hvl2wav's 10 minute limit) } -- parse(b, base?, limit?) -> Tune | nil, Err function Hively.parse(b: buffer, base: number?, limit: number?): (Tune?, Err.Err?) local tune, msg, kind = Load.parse(b, base or 0, limit or buffer.len(b)) if not tune then return nil, Err.from(msg or "corrupt", nil, kind) end return tune, nil end local function settings(tune: Tune, opts: RenderOptions?): (number?, number, number, Err.Err?) local o: RenderOptions = opts or {} local rate = o.sampleRate or 44100 if type(rate) ~= "number" or rate < 8000 or rate > 192000 or rate % 1 ~= 0 then return nil, 0, 0, Err.new(Err.ARG, "render: sampleRate must be an integer 8000..192000") end local sub = o.subsong or 0 if type(sub) ~= "number" or sub < 0 or sub > #tune.subsongs or sub % 1 ~= 0 then return nil, 0, 0, Err.new(Err.ARG, string.format("render: subsong must be 0..%d", #tune.subsongs)) end return rate, sub, tonumber(o.stereo) or 0, nil end -- frameCount(tune, opts?) -> 50 Hz frames until the song end (as hvl2wav stops), capped by maxDuration function Hively.frameCount(tune: Tune, opts: RenderOptions?): number local rate, sub, stereo = settings(tune, opts) local st = rate and Player.new(tune, rate :: number, stereo, sub) if not st then return 0 end local maxFrames = math.floor(((opts and opts.maxDuration) or 600) * 50) local n = 0 while n < maxFrames and not st.songEndReached do for _ = 1, tune.speedMultiplier do Player.irq(st, false) end n += 1 end return n end -- decoder(tune, opts?) -> Types.Decoder | nil, Err function Hively.decoder(tune: Tune, opts: RenderOptions?): (Types.Decoder?, Err.Err?) local rate, sub, stereo, err = settings(tune, opts) if not rate then return nil, err end local sr = rate :: number local mult = tune.speedMultiplier local perIrq = sr // 50 // mult local perFrame = perIrq * mult local nframes = Hively.frameCount(tune, opts) local frames = nframes * perFrame local loop = opts ~= nil and opts.loop == true local st = Player.new(tune, sr, stereo, sub) :: Player.State local fbuf = buffer.create(perFrame * 8) local fpos, ffill = 0, 0 -- read position / filled frames inside fbuf local pos = 0 local function nextFrame() for k = 0, mult - 1 do Player.irq(st, true) Player.mix(st, fbuf, k * perIrq, perIrq) end fpos, ffill = 0, perFrame end local dec = { sampleRate = sr, channels = 2, frames = frames, duration = frames / sr, bitrate = 0, tags = { title = if tune.title ~= "" then tune.title else nil } :: Types.Tags, } local function read(_self: any, n: number, out: buffer?): (buffer, number) n = math.max(0, math.floor(n)) if not loop then n = math.min(n, frames - pos) end local b = out if not b or buffer.len(b) < n * 8 then b = buffer.create(math.max(n, 1) * 8) end local ob = b :: buffer local done = 0 while done < n do if fpos >= ffill then nextFrame() end local k = math.min(n - done, ffill - fpos) buffer.copy(ob, done * 8, fbuf, fpos * 8, k * 8) fpos += k done += k end pos += n return ob, n end dec.read = read :: any local scratch = buffer.create(4096 * 8) dec.seek = function(_self: any, seconds: number) local target = math.max(0, math.floor((tonumber(seconds) or 0) * sr)) if not loop then target = math.min(target, frames) end if target < pos then st = Player.new(tune, sr, stereo, sub) :: Player.State pos, fpos, ffill = 0, 0, 0 end while pos < target do read(nil, math.min(4096, target - pos), scratch) end end :: any dec.position = function(_self: any): number return pos / sr end :: any return (dec :: any) :: Types.Decoder, nil end -- module(tune) -> a Types.Module-shaped value (kind "music"): tracks as patterns (rows * 6 bytes: note, instrument, -- fx, param, fxb, paramb), positions, instruments with their play lists, and render(opts) -> Decoder function Hively.module(tune: Tune): Types.Module local patterns = {} for t = 0, tune.trackNr do local data = buffer.create(tune.trackLength * 6) buffer.copy(data, 0, tune.tracks, t * 64 * 6, tune.trackLength * 6) patterns[t + 1] = { rows = tune.trackLength, data = data } end local order, positions = {}, {} for i = 0, tune.positionNr - 1 do order[i + 1] = i local tr, tp = {}, {} for c = 0, tune.channels - 1 do tr[c + 1] = buffer.readu8(tune.positions, (i * 16 + c) * 2) tp[c + 1] = buffer.readi8(tune.positions, (i * 16 + c) * 2 + 1) end positions[i + 1] = { tracks = tr, transpose = tp } end local m: any = { kind = "music", format = tune.format, title = tune.title, channels = tune.channels, speed = 6, tempo = 125 * tune.speedMultiplier, -- 50 Hz player calls per speed multiplier (a tick lasts 2.5 / tempo s) patterns = patterns, order = order, positions = positions, restart = tune.restart, subsongs = table.clone(tune.subsongs), instruments = tune.instruments, samples = {}, meta = { source = { format = tune.format, version = tune.version, speedMultiplier = tune.speedMultiplier, trackLength = tune.trackLength, tracks = tune.trackNr + 1, mixgain = if tune.format == "hvl" then tune.mixgain else nil, stereo = if tune.format == "hvl" then tune.stereo else nil, }, }, tune = tune, } m.render = function(self: any, opts: RenderOptions?): Types.Decoder local dec, derr = Hively.decoder(self.tune, opts) if dec then return dec end -- the Types contract returns a Decoder: a failed render is an empty one carrying the Err local empty: any = Pcm.audioDecoder(Types.Audio.new(44100, 2, 0)) empty.err = derr return empty end return m :: Types.Module end return Hively