From f8f6ef453df4369b728cd31e3d8261f8a029e12b Mon Sep 17 00:00:00 2001 From: SoraKatadzuma Date: Fri, 30 Oct 2026 16:12:42 -0500 Subject: [PATCH] Initial Commit --- .editorconfig | 9 ++ .gitignore | 1 + README.md | 114 +++++++++++++++ audio/audio.sakura | 143 ++++++++++++++++++ audio/elsewhere.sakura | 12 ++ audio/formats.sakura | 85 +++++++++++ audio/mixer.sakura | 264 ++++++++++++++++++++++++++++++++++ audio/mixing.sakura | 212 +++++++++++++++++++++++++++ audio/output.sakura | 158 ++++++++++++++++++++ audio/voices.sakura | 164 +++++++++++++++++++++ audio/vorbis/bits.sakura | 99 +++++++++++++ audio/vorbis/blocks.sakura | 225 +++++++++++++++++++++++++++++ audio/vorbis/codebooks.sakura | 224 +++++++++++++++++++++++++++++ audio/vorbis/floors.sakura | 154 ++++++++++++++++++++ audio/vorbis/mdct.sakura | 134 +++++++++++++++++ audio/vorbis/ogg.sakura | 220 ++++++++++++++++++++++++++++ audio/vorbis/residues.sakura | 183 +++++++++++++++++++++++ audio/vorbis/setup.sakura | 247 +++++++++++++++++++++++++++++++ audio/vorbis/vorbis.sakura | 258 +++++++++++++++++++++++++++++++++ audio/wasapi.sakura | 221 ++++++++++++++++++++++++++++ audio/wav/wav.sakura | 223 ++++++++++++++++++++++++++++ audio/windows/avrt.sakura | 9 ++ audio/windows/kernel32.sakura | 8 ++ audio/windows/ole32.sakura | 23 +++ blossomfile | 56 ++++++++ tests/main.sakura | 10 ++ tests/mixer.sakura | 159 ++++++++++++++++++++ tests/output.sakura | 38 +++++ tests/pages.sakura | 108 ++++++++++++++ tests/sounds.sakura | 58 ++++++++ tests/spec.sakura | 104 ++++++++++++++ tests/streams.sakura | 196 +++++++++++++++++++++++++ tests/support.sakura | 24 ++++ tests/vorbis.sakura | 74 ++++++++++ tests/wav.sakura | 134 +++++++++++++++++ tools/bench.sakura | 80 +++++++++++ 36 files changed, 4431 insertions(+) create mode 100644 .editorconfig create mode 100644 .gitignore create mode 100644 README.md create mode 100644 audio/audio.sakura create mode 100644 audio/elsewhere.sakura create mode 100644 audio/formats.sakura create mode 100644 audio/mixer.sakura create mode 100644 audio/mixing.sakura create mode 100644 audio/output.sakura create mode 100644 audio/voices.sakura create mode 100644 audio/vorbis/bits.sakura create mode 100644 audio/vorbis/blocks.sakura create mode 100644 audio/vorbis/codebooks.sakura create mode 100644 audio/vorbis/floors.sakura create mode 100644 audio/vorbis/mdct.sakura create mode 100644 audio/vorbis/ogg.sakura create mode 100644 audio/vorbis/residues.sakura create mode 100644 audio/vorbis/setup.sakura create mode 100644 audio/vorbis/vorbis.sakura create mode 100644 audio/wasapi.sakura create mode 100644 audio/wav/wav.sakura create mode 100644 audio/windows/avrt.sakura create mode 100644 audio/windows/kernel32.sakura create mode 100644 audio/windows/ole32.sakura create mode 100644 blossomfile create mode 100644 tests/main.sakura create mode 100644 tests/mixer.sakura create mode 100644 tests/output.sakura create mode 100644 tests/pages.sakura create mode 100644 tests/sounds.sakura create mode 100644 tests/spec.sakura create mode 100644 tests/streams.sakura create mode 100644 tests/support.sakura create mode 100644 tests/vorbis.sakura create mode 100644 tests/wav.sakura create mode 100644 tools/bench.sakura diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..c6c8b36 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,9 @@ +root = true + +[*] +indent_style = space +indent_size = 2 +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..cfecb95 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +.blossom diff --git a/README.md b/README.md new file mode 100644 index 0000000..77ec5a4 --- /dev/null +++ b/README.md @@ -0,0 +1,114 @@ +# audio +Sound read from WAV and Ogg Vorbis, mixed, and played: a `mixer` of sounds and the voices playing them, and an `audio_output` playing what it mixes to the system's audio device, on a thread of its own. Long Ogg Vorbis files are streamed, decoded as they play. It's Sakura's, built with [blossom](https://git.malunal.studio/sakura/blossom), reads std's `containers`, `io`, `math`, `thread`, and `time`, and plays through WASAPI on Windows. Its decoders, its mixer, and its output are its own. + +```sakura +import malunal::audio; + +var out := audio_output::open() else (e) { ... }; # the default device, at its rate +var clink := audio::load("sounds/coin.wav") else (e) { ... }; # decoded whole +val coin := out.add(move(clink)); +val file := io::read_file(&music_path) else (e) { ... }; +val music := out.add_streamed(file.view()) else (e) { ... }; # kept as Ogg Vorbis, decoded as it plays + +_ = out.play(coin, playback{ gain = 0.8, pan = -0.3 }); +val playing := out.play(music, playback{ looping = true, bus = 1, fade_in = 2 }); + +{ + var held := out.lock(); # several changes, one lock + held.value().set_bus(1, 0.5); # music at half + held.value().set_pitch(playing, 1.05); +} +out.stop(playing, 1.5); # faded out over 1.5 s +``` +`audio::decode(bytes)` reads bytes already in memory in either format, and `audio::format_of(bytes)` says which, by their first few. `audio::save` writes a WAV file, of 16-bit samples or floats. `vorbis::decoder` reads an Ogg Vorbis stream's frames as it's asked for them, which the mixer does for a streamed sound. `audio_output::headless()` is an output of no device, mixed only as the program asks by `render`, as tests and servers want. + +A project reads it by requiring this folder, or its remote, and naming `malunal.audio`, whose module is `malunal::audio`, among a target's `deps`: + +```yaml +requires: +- ../audio +targets: +- name: game + type: program + deps: [malunal.audio] +``` + +## Layout +`audio/` is the module `malunal::audio`, and each format a module beneath it, as `malunal::audio::vorbis`. + +| Path | Holds | +|---|---| +| `audio.sakura` | `sound`, `audio_error`, `max_frames`, tones, and channels mixed down to two | +| `formats.sakura` | `format`, which format bytes, or an extension, say, `decode`, `load`, and `save` | +| `mixer.sakura` | `mixer`, `sound_id`, `voice`, and `playback`: sounds held, decoded or streamed | +| `voices.sakura` | Voices played, changed, paused, and stopped; buses and the master gain | +| `mixing.sakura` | Voices mixed: resampled, panned, ramped, and streams decoded as they play | +| `output.sakura` | `audio_output`: the mixer shared with the device's thread, or headless | +| `wasapi.sakura` | The device on Windows: WASAPI's shared mode, through COM's tables | +| `elsewhere.sakura` | The device elsewhere: none yet | +| `windows/` | `ole32.dll`, `kernel32.dll`, and `avrt.dll`'s functions, as `malunal::audio::windows` | + +`wav/`, `audio::wav`: + +| Path | Holds | +|---|---| +| `wav.sakura` | RIFF's chunks read, samples of each size made floats, and `encode` | + +`vorbis/`, `audio::vorbis`: + +| Path | Holds | +|---|---| +| `vorbis.sakura` | `decoder`: the headers, frames read and timed by granule positions, and `decode` | +| `ogg.sakura` | Ogg's pages, checked by their CRCs, and one stream's packets | +| `bits.sakura` | A packet's bits, read lowest first, and Vorbis's floats | +| `codebooks.sakura` | Codebooks: their Huffman codes by table and tree, and their vectors | +| `setup.sakura` | The identification and setup headers: floors, residues, mappings, and modes | +| `floors.sakura` | Floor 1's posts read, and its curve drawn | +| `residues.sakura` | Residues of types 0, 1, and 2, read from the setup header and decoded | +| `mdct.sakura` | The inverse MDCT, by an FFT of a quarter of the block, and the window's slopes | +| `blocks.sakura` | An audio packet decoded: channels uncoupled, blocks windowed and overlapped | + +## What's read +- **WAV**: PCM of 8 bits, unsigned, and of 16, 24, and 32 bits, signed; and floats of 32 and 64 bits; each plain or in `WAVE_FORMAT_EXTENSIBLE`, of up to eight channels. A `data` chunk said to be longer than the file is read as far as the file goes, as writers streaming WAV leave its size unwritten. ADPCM, A-law, and µ-law are `unsupported`, and chunks besides `fmt ` and `data`, as `smpl`'s loop points, are skipped. +- **Ogg Vorbis**: every Vorbis I stream but those of floor 0, which no encoder has written since before Vorbis 1.0: codebooks of every lookup, floor 1, residues 0, 1, and 2, coupled channels, and both block sizes, of 64 to 8192 samples. Each page's CRC is checked. Frames are cut from the start and end as the first and last pages' granule positions say, so a stream gives exactly the frames it was encoded from. The first Vorbis stream of a file is read; one chained after it, or multiplexed beside it, isn't. Comments are skipped. + +Every sound is 32-bit floats of one channel or two. A file of more channels, up to eight, is mixed down to two as it's read, by ITU-R BS.775's weights: the front's sides whole, the center and each surround at -3 dB to its side, the back's center at -6 dB to each, and the low frequencies left out, scaled so neither side sums past 1. A WAV file's channels are placed by its channel mask, or Windows's default order, and a Vorbis stream's by Vorbis's order for its count. + +## Mixing +- **Sounds** are held by a mixer and named by a `sound_id`: decoded, by `add`, or kept as their Ogg Vorbis bytes, by `add_streamed`, so each voice decodes what it plays as it plays it, a few thousand frames ahead. A sound of any rate plays at the mixer's. +- **Voices** play a sound as `playback` says: at a `gain`; panned from -1, all left, to 1, all right; at a `pitch`, a multiple of its rate; looping or not; paused or not; on one of 16 buses; and faded in over some seconds. `change`, `set_gain`, `set_pan`, `set_pitch`, and `pause` change one as it plays, and `stop` ends it at once or faded out. A voice that ended, or whose sound was removed, names nothing after, though its place plays another. +- **Gains**: a voice is multiplied by its own gain, its bus's, and the master's. A mono voice is panned by the constant power law, so at the middle each side has it at -3 dB, as loud in all as it is from one side; a stereo voice's pan turns down the side it moves from. Whatever changes is ramped across the next frames mixed, from the gains the last frame had, so nothing clicks. The mix isn't limited: voices summing past 1 clip as the device clips them. +- **Resampling**: a voice is read at its sound's rate over the mixer's, times its pitch, by cubic Hermite interpolation, Catmull and Rom's spline through the four frames about where it plays. A sound of the mixer's rate at its own pitch is read exactly. A looping voice reads across its end into its start; a streamed one loops by decoding its stream again from its start, seamlessly. + +## The output +`audio_output::open` opens the system's default device, at the rate the system mixes at, and starts a thread that waits on the device's event and fills its buffer, about `latency` seconds of it, 20 ms unless asked, from the mixer, holding its lock while it mixes. `lock` holds the mixer for the program, so a game makes a frame's changes under one lock; `add`, `play`, and the rest each lock it once. + +On Windows the device is WASAPI's default render endpoint in shared mode, given frames of two 32-bit floats, which Windows converts to the device's format and maps to its speakers. The thread runs under the Multimedia Class Scheduler Service as "Pro Audio" does. A device that stops, as unplugged headphones do, is let go, and the default device opened again as soon as there is one, every quarter second; the voices wait meanwhile. Elsewhere there's no device yet, so `open` says `no_device`, and a game plays on with a headless output. + +## Speed +`blossom build`, then run `malunal.audio.bench`, here on a Ryzen 9 9950X3D, the best of three, given one of Factorio's music files, 68 seconds of 44.1 kHz stereo: + +| What | Time | Real time | +|---|---|---| +| 32 voices mixed, half resampled, panned, for 10 s at 48 kHz | 94 ms | 105× | +| WAV of 16 bits, 10 s, written and read | 6 ms | 1600× | +| Ogg Vorbis decoded whole | 97 ms | 700× | +| Ogg Vorbis streamed, resampled to 48 kHz | 138 ms | 490× | + +So a voice costs about 6 ns a frame mixed, and 32 of them about one percent of a core. + +## Testing +`blossom test` runs `tests/`: tones, formats by their bytes and extensions, and channels mixed down; WAV written and read back, of every sample size, of four channels placed by their mask, cut short, and refused where compressed; and the mixer's voices at their gains and pans, ramped, ended and looped at their ends, resampled and pitched, on buses, faded, and streamed, exactly as the sound decoded whole plays. A headless output is mixed as asked, and the default device, where there is one, is played to silently until it took 2000 frames. + +The tests' Ogg Vorbis streams are made by a small encoder in `tests/streams.sakura`, written as `tests/pages.sakura` packs bits and laces pages, of both block sizes, single and coupled channels, and residues of types 1 and 2, with the frames each should decode to worked out by `tests/spec.sakura` as the spec defines them, directly: the inverse MDCT as its sum, and the windowed blocks laid on one timeline. Each decodes to within 1e-4 of those, cut where its last granule position says; read in pieces of 13 frames and again from the start, the same; and changed, cut short, of floor 0, or not Vorbis, refused. + +What's read was checked further against outside references, which aren't part of the repository: +- **Ogg Vorbis**: 63 files from 1 KB to 9 MB, Factorio's sounds and music, Ableton Live's previews, and three songs, against Xiph's libvorbisfile: every one the same length, and every sample within 5e-7. +- **Fuzzing**: a checked build was given 6300 files with bytes changed, their pages' CRCs worked out again so the changes reach past them, decoded whole and streamed, and faulted at none. + +## Not yet +- MP3, FLAC, and Opus. +- Loop points from files, as WAV's `smpl` chunk and Vorbis comments give them. +- Seeking a streamed voice anywhere but its start. +- Effects: filters, reverb, and a limiter on the mix. +- A device chosen by name, following the default as it changes, and output on Linux. diff --git a/audio/audio.sakura b/audio/audio.sakura new file mode 100644 index 0000000..dc4b548 --- /dev/null +++ b/audio/audio.sakura @@ -0,0 +1,143 @@ +#! Contains `sound`, samples read from WAV or Ogg Vorbis, or made, and why one +#! couldn't be read, written, or played. +#! +#! Each format is a module of its own beneath this one, `audio::wav` and +#! `audio::vorbis`, which this one's functions choose between by the bytes' +#! first few. Each gives the same `sound`: 32-bit floats, nominally within -1 to +#! 1, of one channel or two, interleaved. A file of more channels is mixed down +#! to two as it's read, as `downmix` says. +#! +#! A `mixer` plays sounds, as voices, and an `audio_output` pulls what it mixes into +#! the system's audio device, as `mixer.sakura` and `output.sakura` say. + +import std::math; +module malunal::audio; + + +#! The most frames a sound may have: 64 M, about 23 minutes at 48 kHz, or 512 MiB +#! of stereo. One said to have more is refused before its samples are read, as +#! `too_large`; a longer Ogg Vorbis file is played streamed instead. +pub const max_frames: u64 = 0x4000000; + +#! Why a sound could not be read, written, or played. +pub enum audio_error: u8 { + unreadable, #! The file could not be read. + unwritable, #! The file could not be written. + unrecognized, #! The bytes are neither WAV nor Ogg Vorbis, or a file's extension names neither. + malformed, #! The data breaks its format, or is cut short, or a page's CRC is wrong. + unsupported, #! The data is well formed, but uses what isn't read, as WAV's ADPCM or Vorbis's floor 0. + too_large, #! The sound has more frames than `max_frames`. + no_device, #! There's no audio device to play to, or the system's audio service isn't running. + refused, #! The device refused to play as asked. +} + +#! Samples: `channels` floats a frame, one for each channel, left before right, +#! `rate` frames a second. +pub struct sound { + pub var rate: u32; #! Frames a second, as 48000. + pub var channels: u32; #! 1, or 2 for left and right. + pub var samples: vector; #! `frames * channels` floats, a frame's together. +} + +#! How many frames the sound has. +pub val sound::frames: u64 { + get => this.channels == 0 ? 0 : this.samples.length / this.channels as u64; +} + +#! How long the sound plays, in seconds. +pub val sound::seconds: f64 { + get => this.rate == 0 ? 0 : this.frames as f64 / this.rate as f64; +} + +#! Makes a sound of samples. +#! @param rate Frames a second. +#! @param channels 1 or 2. +#! @param samples The samples, a frame's together. +#! @returns The sound, holding a copy of them. +pub def sound::of(rate: u32, channels: u32, samples: span): sound { + var held := vector::::new(); + held.extend(samples); + return sound{ rate = rate, channels = channels, samples = move(held) }; +} + +#! Makes a sound of one channel, a sine wave of a frequency, faded in and out +#! over its first and last 5 ms so it doesn't click, as a test or a placeholder +#! wants. +#! @param frequency The frequency, in hertz. +#! @param seconds How long it plays. +#! @param rate Frames a second. +#! @param gain How loud, as its highest sample. +#! @returns The sound. +pub def sound::tone(frequency: f32, seconds: f32, rate: u32 = 48000, gain: f32 = 0.5): sound { + val frames := (seconds * rate as f32) as u64; + val fade := math::min((rate / 200) as u64, frames / 2); + var samples := vector::::new(); + samples.resize(frames); + val step := math::tau * frequency as f64 / rate as f64; + for i in 0..frames { + var level := gain; + if i < fade { + level *= i as f32 / fade as f32; + } else if i >= frames - fade { + level *= (frames - i) as f32 / fade as f32; + } + samples[i] = math::sin(step * i as f64) as f32 * level; + } + return sound{ rate = rate, channels = 1, samples = move(samples) }; +} + +#! Where a channel is heard from, which says how it's mixed down to two. +pub enum speaker: u8 { + front_left, front_right, center, low_frequency, side_left, side_right, + back_left, back_right, back_center, +} + +#! How much of a channel goes into the left and right of two, by where it's +#! heard from, as ITU-R BS.775 mixes down: the front's own side whole, the +#! center and each surround's side at -3 dB, the back's center at -6 dB to each, +#! and the low frequencies' channel left out. `downmix` scales the sum so it +#! never exceeds what the loudest channel would be alone. +#! @param from Where the channel is heard from. +#! @returns Its weights, left then right. +pub def downmix_weights(from: speaker): f32[2] { + return match from { + front_left => [1, 0], + front_right => [0, 1], + center => [0.70710677, 0.70710677], + low_frequency => [0, 0], + side_left => [0.70710677, 0], + side_right => [0, 0.70710677], + back_left => [0.70710677, 0], + back_right => [0, 0.70710677], + back_center => [0.5, 0.5], + }; +} + +#! Mixes frames of more than two channels down to two. +#! @param frames The frames, `count * speakers.length` floats, a frame's together. +#! @param count How many frames. +#! @param speakers Where each channel is heard from, in a frame's order. +#! @param into Where the two channels go, `count * 2` floats. +pub def downmix(frames: span, count: u64, speakers: span, into: slice): void { + var total: f32[2] = [0, 0]; + for c in 0..speakers.length { + val w := downmix_weights(speakers[c]); + total[0] += w[0]; + total[1] += w[1]; + } + val left: f32 = total[0] > 1 ? 1 / total[0] : 1; + val right: f32 = total[1] > 1 ? 1 / total[1] : 1; + val width := speakers.length; + for i in 0..count { + var l: f32 = 0; + var r: f32 = 0; + for c in 0..width { + val w := downmix_weights(speakers[c]); + val x := frames[i * width + c]; + l += x * w[0]; + r += x * w[1]; + } + into[i * 2] = l * left; + into[i * 2 + 1] = r * right; + } +} diff --git a/audio/elsewhere.sakura b/audio/elsewhere.sakura new file mode 100644 index 0000000..18d499f --- /dev/null +++ b/audio/elsewhere.sakura @@ -0,0 +1,12 @@ +#! Contains the device an output plays to on systems besides Windows: none yet, +#! so `audio_output::open` says `no_device`, and a game plays on, silent, with a +#! headless output instead. + +module malunal::audio when os != windows; + + +def play_device(state: *mut output_state): void { + val s := &mut through(state); + s.failure = audio_error::no_device; + say_opened(s, 2); +} diff --git a/audio/formats.sakura b/audio/formats.sakura new file mode 100644 index 0000000..a94f035 --- /dev/null +++ b/audio/formats.sakura @@ -0,0 +1,85 @@ +#! Contains the formats, how bytes, or a file's name, say which one they're in, +#! and reading and writing a sound in whichever it is. + +import std::io; +module malunal::audio; + + +#! The formats a sound is read from, the first of which it's written to. +pub enum format: u8 { + wav, #! WAV: PCM of 8, 16, 24, or 32 bits, or floats of 32 or 64, plain or extensible. + vorbis, #! Ogg Vorbis: the first Vorbis stream of an Ogg file. +} + +#! Which format bytes are in, by how they begin: `RIFF` and `WAVE` for WAV, and +#! `OggS` for Ogg, whose first packet must then be Vorbis's. +#! @param bytes The bytes. +#! @returns The format, or `nothing` where they're neither. +pub def format_of(bytes: span): maybe { + if bytes.length >= 12 && bytes[0] == 'R' && bytes[1] == 'I' && bytes[2] == 'F' && bytes[3] == 'F' + && bytes[8] == 'W' && bytes[9] == 'A' && bytes[10] == 'V' && bytes[11] == 'E' { + return format::wav; + } + if bytes.length >= 4 && bytes[0] == 'O' && bytes[1] == 'g' && bytes[2] == 'g' && bytes[3] == 'S' { + return format::vorbis; + } + return nothing {}; +} + +#! Which format a file's extension names, whatever the case of its letters: +#! `wav` or `wave`, and `ogg` or `oga`. +#! @param extension The extension, without its `.`. +#! @returns The format, or `nothing` where it names neither. +pub def format_named(extension: strview): maybe { + val lowered := extension.lower(); + val name := lowered.view(); + return format::wav if name == "wav" || name == "wave"; + return format::vorbis if name == "ogg" || name == "oga"; + return nothing {}; +} + +#! Reads a sound from bytes in either format, which their first few say, whole: +#! an Ogg Vorbis file is decoded to its end. +#! @param bytes The bytes. +#! @returns The sound, or why it couldn't be read. +pub def decode(bytes: span): result { + val which := format_of(bytes) else { return audio_error::unrecognized; }; + return match which { + wav => audio::wav::decode(bytes), + vorbis => audio::vorbis::decode(bytes), + }; +} + +#! Reads a sound from a file in either format, whole. +#! @param at The file's path. +#! @returns The sound, or why it couldn't be read: `unreadable` where the file +#! couldn't be. +pub def load(at: &path): result { + val bytes := io::read_file(at) else (_) { return audio_error::unreadable; }; + return decode(bytes.view()); +} + +#! Reads a sound from a file named by text, as `load` does. +#! @param at The file's path, as text. +#! @returns The sound, or why it couldn't be read. +pub def load(at: strview): result { + val named := path::parse(at) else (_) { return audio_error::unreadable; }; + return load(&named); +} + +#! Writes a sound to a file as WAV, of 16-bit samples, or of floats where +#! `floats` says so. Its extension must name WAV. +#! @param played The sound. +#! @param at The file's path, as text. +#! @param floats Whether to write 32-bit floats rather than 16-bit integers. +#! @returns Nothing, or why it couldn't be written: `unrecognized` where the +#! extension doesn't name WAV, and `unwritable` where the file +#! couldn't be. +pub def save(played: &sound, at: strview, floats: bool = false): result { + val named := path::parse(at) else (_) { return audio_error::unwritable; }; + val which := format_named(named.extension) else { return audio_error::unrecognized; }; + return audio_error::unrecognized if which != format::wav; + val bytes := audio::wav::encode(played, floats) else (e) { return e; }; + io::write_file(&named, bytes.view()) else (_) { return audio_error::unwritable; }; + return; +} diff --git a/audio/mixer.sakura b/audio/mixer.sakura new file mode 100644 index 0000000..66cdaf2 --- /dev/null +++ b/audio/mixer.sakura @@ -0,0 +1,264 @@ +#! Contains `mixer`: the sounds a game plays, held by id, and the voices playing +#! them, mixed into frames of two channels at the mixer's rate as an output asks. +#! +#! A voice plays its sound at its gain, panned, at its pitch, looping or not, on +#! one of 16 buses, each with a gain of its own, as music and effects are set +#! apart, all under the master gain. What changes as a voice plays is ramped +#! across the next frames mixed, so nothing clicks. A sound of another rate is +#! resampled as it plays, by cubic Hermite interpolation, as its pitch is. +#! +#! A sound added streamed is kept as its Ogg Vorbis bytes, each voice decoding +#! what it plays as it plays it, so music takes little memory. + +import std::math; +module malunal::audio; + + +#! How many buses a mixer has. +pub const bus_count: u32 = 16; + +#! A sound a mixer holds, by which it's played. The zero id names none. +pub struct sound_id { + var index: u32; + var generation: u32; +} + +#! Whether the id names nothing. +pub val sound_id::is_none: bool { + get => this.generation == 0; +} + +pub def sound_id::equals(&this, other: &sound_id): bool { + return this.index == other.index && this.generation == other.generation; +} + +#! The id as one number, its generation above its index, as a table keeping +#! handles of every kind keeps it. +pub val sound_id::bits: u64 { + get => ((this.generation as u64) << 32) | this.index as u64; +} + +#! The id `bits` gave as a number. +pub def sound_id::of_bits(bits: u64): sound_id { + return sound_id{ index = (bits & 0xFFFFFFFF) as u32, generation = (bits >> 32) as u32 }; +} + +#! A sound playing. The zero voice names none, and one that ended names none +#! after. +pub struct voice { + var index: u32; + var generation: u32; +} + +pub val voice::is_none: bool { + get => this.generation == 0; +} + +pub def voice::equals(&this, other: &voice): bool { + return this.index == other.index && this.generation == other.generation; +} + +#! The voice as one number, its generation above its index. +pub val voice::bits: u64 { + get => ((this.generation as u64) << 32) | this.index as u64; +} + +#! The voice `bits` gave as a number. +pub def voice::of_bits(bits: u64): voice { + return voice{ index = (bits & 0xFFFFFFFF) as u32, generation = (bits >> 32) as u32 }; +} + +#! How a voice plays. +pub struct playback { + pub var gain: f32 = 1; #! How loud, as a multiple of the sound's samples. + pub var pan: f32 = 0; #! From -1, all left, to 1, all right. + pub var pitch: f32 = 1; #! How fast, as a multiple of the sound's rate. + pub var looping: bool = false; #! Whether it starts again as it ends. + pub var paused: bool = false; #! Whether it waits where it is. + pub var bus: u32 = 0; #! Which bus, below `bus_count`. + pub var fade_in: f32 = 0; #! Seconds it rises over from silence as it starts. +} + +# A sound the mixer holds. +struct held_sound { + var generation: u32; + var live: bool; + var decoded: sound; # Its samples, unless it's streamed. + var encoded: vector; # Its Ogg Vorbis bytes, where it's streamed. + var streamed: bool; + var rate: u32; + var channels: u32; + var frames: u64; +} + +# What a streamed voice decodes, and the frames it decoded, about where it plays. +struct streaming { + var decoding: vorbis::decoder; + var window: vector; # Frames decoded, `channels` floats each. + var base: u64; # The voice's frame `window` begins at. + var ended: bool; # Whether the stream ended, not looping. + var end: u64; # The voice's frame it ended at. +} + +# A voice. +struct voice_state { + var generation: u32; + var live: bool; + var sound: sound_id; + var how: playback; + var position: f64; # Where it plays, in its sound's frames. + var gains: f32[2]; # The left and right gains the last frame mixed was given. + var level: f32; # How far faded in, from 0 to 1. + var fade: f32; # How much `level` changes each frame. + var stopping: bool; # Whether it ends once faded out. + var started: bool; # Whether a frame of it was mixed. + var stream: maybe>; +} + +#! Sounds, and the voices playing them, mixed into frames of two channels. +pub struct mixer { + var mix_rate: u32; + var bank: vector; + var unused: vector; # Places in `bank` free. + var voices: vector; + var idle: vector; # Places in `voices` free. + var buses: f32[16]; + var master_gain: f32; +} + +#! Makes a mixer, of no sounds, every gain 1. +#! @param rate The frames a second it mixes. +pub def mixer::new(rate: u32): mixer { + var made := mixer{ + mix_rate = rate, bank = vector::::new(), unused = vector::::new(), + voices = vector::::new(), idle = vector::::new(), master_gain = 1, + }; + for b in 0..bus_count { + made.buses[b as u64] = 1; + } + return made; +} + +#! The frames a second the mixer mixes, which an output sets to its device's. +pub val mixer::rate: u32 { + get => this.mix_rate; +} + +#! Holds a sound, decoded. +#! @param given The sound, which the mixer owns from now on. +#! @returns Its id, or none where it has no frames or more than two channels. +pub def mixer::add(&mut this, given: sound): sound_id { + return sound_id{} if given.channels == 0 || given.channels > 2 || given.rate == 0 || given.frames == 0; + val index := this.place(); + val at := &mut this.bank[index as u64]; + at.live = true; + at.streamed = false; + at.rate = given.rate; + at.channels = given.channels; + at.frames = given.frames; + at.decoded = move(given); + return sound_id{ index = index, generation = at.generation }; +} + +#! Holds an Ogg Vorbis file, to be decoded as each voice plays it. +#! @param bytes The file's bytes, which the mixer keeps a copy of. +#! @returns Its id, or why the stream can't be read, as `vorbis::decoder::open` +#! says. +pub def mixer::add_streamed(&mut this, bytes: span): result { + val opened := vorbis::decoder::open(bytes) else (e) { return e; }; + val index := this.place(); + val at := &mut this.bank[index as u64]; + at.live = true; + at.streamed = true; + at.rate = opened.rate; + at.channels = opened.channels; + at.frames = opened.frames; + at.encoded.clear(); + at.encoded.extend(bytes); + return sound_id{ index = index, generation = at.generation }; +} + +#! Whether an id names a sound the mixer holds. +pub def mixer::holds(&this, id: sound_id): bool { + return false if id.generation == 0 || id.index as u64 >= this.bank.length; + val at := &this.bank[id.index as u64]; + return at.live && at.generation == id.generation; +} + +#! How long a sound plays, in seconds, or 0 where the id names none or a +#! stream says nothing of its length. +pub def mixer::seconds(&this, id: sound_id): f64 { + return 0 if !this.holds(id); + val at := &this.bank[id.index as u64]; + return at.frames as f64 / at.rate as f64; +} + +#! Makes a sound held another, keeping its id, as an asset table makes one +#! again as its file changes. The voices playing it end. +#! @param id The sound. +#! @param given What it is now, which the mixer owns from now on. +#! @returns Whether the id names a sound, and what it's given has frames of one +#! or two channels; where not, the sound is as it was. +pub def mixer::replace(&mut this, id: sound_id, given: sound): bool { + return false if !this.holds(id) || given.channels == 0 || given.channels > 2 || given.rate == 0 || given.frames == 0; + this.end_voices_of(id); + val at := &mut this.bank[id.index as u64]; + at.streamed = false; + at.rate = given.rate; + at.channels = given.channels; + at.frames = given.frames; + at.encoded.clear(); + at.decoded = move(given); + return true; +} + +#! Makes a sound held an Ogg Vorbis file, streamed, keeping its id, as +#! `replace` does. +#! @returns Nothing, or why the stream can't be read, or `unrecognized` where +#! the id names no sound; where not, the sound is as it was. +pub def mixer::replace_streamed(&mut this, id: sound_id, bytes: span): result { + return audio_error::unrecognized if !this.holds(id); + val opened := vorbis::decoder::open(bytes) else (e) { return e; }; + this.end_voices_of(id); + val at := &mut this.bank[id.index as u64]; + at.streamed = true; + at.rate = opened.rate; + at.channels = opened.channels; + at.frames = opened.frames; + at.decoded.samples.clear(); + at.encoded.clear(); + at.encoded.extend(bytes); + return; +} + +# Ends every voice playing a sound. +def mixer::end_voices_of(&mut this, id: sound_id): void { + for i in 0..this.voices.length { + if this.voices[i].live && this.voices[i].sound.equals(&id) { + this.end_voice(i); + } + } +} + +#! Lets go of a sound, ending the voices playing it at once. +pub def mixer::remove(&mut this, id: sound_id): void { + return if !this.holds(id); + this.end_voices_of(id); + val at := &mut this.bank[id.index as u64]; + at.live = false; + at.generation = at.generation == 0xFFFFFFFF ? 1 : at.generation + 1; + at.decoded.samples.clear(); + at.encoded.clear(); + this.unused.append(id.index); +} + +# A free place in the bank. +def mixer::place(&mut this): u32 { + if !this.unused.is_empty { + val index := this.unused.last(); + this.unused.truncate(); + return index; + } + this.bank.append(held_sound{ generation = 1, decoded = sound{ samples = vector::::new() }, encoded = vector::::new() }); + return (this.bank.length - 1) as u32; +} diff --git a/audio/mixing.sakura b/audio/mixing.sakura new file mode 100644 index 0000000..ac93245 --- /dev/null +++ b/audio/mixing.sakura @@ -0,0 +1,212 @@ +#! Contains a mixer's voices mixed into frames: each read from its sound at its +#! pitch, by cubic Hermite interpolation between the four frames about where it +#! plays, panned, and its gains ramped from the last frames mixed to these. +#! +#! A mono voice is panned by the constant power law, so at the middle each side +#! has it at -3 dB, as loud in all as it is from one side; a stereo voice's pan +#! turns down the side it moves from, its middle both sides whole. + +import std::math; +module malunal::audio; + + +# How many frames a streamed voice decodes at a time. +const stream_chunk: u64 = 2048; + +# Changes the rate the mixer mixes at, as an output's device says. +def mixer::set_rate(&mut this, rate: u32): void { + this.mix_rate = rate; +} + +#! Mixes the voices into frames of two channels, replacing what they held, and +#! ends those that played to their end. +#! @param into The frames, a frame's left and right together. +pub def mixer::mix(&mut this, into: slice): void { + for i in 0..into.length { + into[i] = 0; + } + val frames := into.length / 2; + return if frames == 0; + for v in 0..this.voices.length { + continue if !this.voices[v].live || this.voices[v].how.paused; + val state := address(&mut this.voices[v]); + val held := address(&this.bank[this.voices[v].sound.index as u64]); + val gain := this.buses[this.voices[v].how.bus as u64] * this.master_gain; + if mix_voice(&mut through(state), &through(held), this.mix_rate, gain, into, frames) { + this.end_voice(v); + } + } +} + +# Mixes one voice into frames. +# @returns Whether it ended. +def mix_voice(at: &mut voice_state, held: &held_sound, rate: u32, bus: f32, into: slice, frames: u64): bool { + val step := held.rate as f64 / rate as f64 * math::max(at.how.pitch, 0 as f32) as f64; + val gain := bus * at.how.gain; + val pan := math::clamp(at.how.pan, -1 as f32, 1 as f32); + var target: f32[2]; + if held.channels == 1 { + val angle := (pan + 1) * math::pi as f32 / 4; + target = [math::cos(angle) * gain, math::sin(angle) * gain]; + } else { + target = [math::min(1 - pan, 1 as f32) * gain, math::min(1 + pan, 1 as f32) * gain]; + } + val level := math::clamp(at.level + at.fade * frames as f32, 0 as f32, 1 as f32); + var start := at.gains; + if !at.started { + start = [target[0] * at.level, target[1] * at.level]; + } + val end: f32[2] = [target[0] * level, target[1] * level]; + + val channels := held.channels as u64; + val looping := at.how.looping; + var position := at.position; + var finished := false; + + # The frames read from: the sound's, or those a stream decoded about where + # the voice plays, from `base` on, and where a stream ended, if it did. + var data: *mut f32 = null; + var base: i64 = 0; + var count: i64 = 0; + var ends_at: f64 = held.streamed ? -1 : held.frames as f64; + if held.streamed { + if at.stream is some(&mut s) { + val first := position >= 1 ? (math::floor(position) - 1) as u64 : 0; + val last := math::floor(position + step * frames as f64) as u64 + 3; + val window := &mut s.get(); + window.ensure(first, last, channels, looping); + data = window.window.data; + base = window.base as i64; + count = (window.window.length / channels) as i64; + ends_at = window.ended ? window.end as f64 : -1; + } else { + return true; + } + } else { + data = held.decoded.samples.data; + count = held.frames as i64; + } + + for i in 0..frames { + val sooner := held.streamed ? ends_at >= 0 && position >= ends_at : !looping && position >= ends_at; + if sooner { + finished = true; + break; + } + val index := position as i64; + val t := (position - index as f64) as f32; + val near := index - base; + var left: f32 = 0; + var right: f32 = 0; + if near >= 1 && near + 2 < count { + # Within what's held: the four frames read where they are. + val from := data + (near as u64 - 1) * channels; + if channels == 1 { + val p1: f32 = through(from + 1); + left = t == 0 ? p1 : hermite(through(from), p1, through(from + 2), through(from + 3), t); + right = left; + } else { + val l1: f32 = through(from + 2); + val r1: f32 = through(from + 3); + left = t == 0 ? l1 : hermite(through(from), l1, through(from + 4), through(from + 6), t); + right = t == 0 ? r1 : hermite(through(from + 1), r1, through(from + 5), through(from + 7), t); + } + } else { + # About an end: wrapped around where the voice loops, silent where not. + val p0 := frame_of(at, held, index - 1, looping); + val p1 := frame_of(at, held, index, looping); + val p2 := frame_of(at, held, index + 1, looping); + val p3 := frame_of(at, held, index + 2, looping); + left = hermite(p0[0], p1[0], p2[0], p3[0], t); + right = channels == 1 ? left : hermite(p0[1], p1[1], p2[1], p3[1], t); + } + val ramp := (i + 1) as f32 / frames as f32; + into[i * 2] += left * (start[0] + (end[0] - start[0]) * ramp); + into[i * 2 + 1] += right * (start[1] + (end[1] - start[1]) * ramp); + position += step; + if looping && !held.streamed && position >= held.frames as f64 { + position -= held.frames as f64; + } + } + at.position = position; + at.gains = end; + at.level = level; + at.started = true; + return finished || (at.stopping && level <= 0); +} + +# A frame of a voice's sound, its left and right, a mono one's twice: wrapped +# around where the voice loops, and silence outside it where it doesn't. +def frame_of(at: &mut voice_state, held: &held_sound, index: i64, looping: bool): f32[2] { + val channels := held.channels as u64; + if held.streamed { + if at.stream is some(&mut s) { + val window := &s.get(); + return [0, 0] if index < window.base as i64; + val k := (index - window.base as i64) as u64; + return [0, 0] if (k + 1) * channels > window.window.length; + val first := window.window[k * channels]; + return [first, channels == 1 ? first : window.window[k * channels + 1]]; + } + return [0, 0]; + } + val count := held.frames as i64; + var k := index; + if looping { + k = ((k % count) + count) % count; + } else if k < 0 || k >= count { + return [0, 0]; + } + val at_sample := k as u64 * channels; + val first := held.decoded.samples[at_sample]; + return [first, channels == 1 ? first : held.decoded.samples[at_sample + 1]]; +} + +# The cubic Hermite curve, as Catmull and Rom's spline, through four samples, at +# a place between the middle two. +def hermite(p0: f32, p1: f32, p2: f32, p3: f32, t: f32): f32 { + val c1 := 0.5 * (p2 - p0); + val c2 := p0 - 2.5 * p1 + 2 * p2 - 0.5 * p3; + val c3 := 0.5 * (p3 - p0) + 1.5 * (p1 - p2); + return ((c3 * t + c2) * t + c1) * t + p1; +} + +# Decodes until the window holds the frames from one to before another, letting +# go of those before the first, and starting the stream again as it ends where +# the voice loops. +def streaming::ensure(&mut this, first: u64, last: u64, channels: u64, looping: bool): void { + val held := this.window.length / channels; + if first > this.base { + val drop := first - this.base < held ? first - this.base : held; + val kept := (held - drop) * channels; + for i in 0..kept { + this.window[i] = this.window[i + drop * channels]; + } + this.window.resize(kept); + this.base += drop; + } + var dry: u32 = 0; + while !this.ended && this.base + this.window.length / channels < last { + val old := this.window.length; + this.window.resize(old + stream_chunk * channels); + val into := slice::::over(this.window.data + old, stream_chunk * channels); + var got: u64 = 0; + if this.decoding.read(into) is value(count) { + got = count; + } else { + this.window.resize(old); + this.ended = true; + this.end = this.base + old / channels; + break; + } + this.window.resize(old + got * channels); + continue if got == stream_chunk; + if looping && dry < 2 { + dry = got == 0 ? dry + 1 : 0; + this.decoding.rewind(); + continue; + } + this.ended = true; + this.end = this.base + this.window.length / channels; + } +} diff --git a/audio/output.sakura b/audio/output.sakura new file mode 100644 index 0000000..0a35558 --- /dev/null +++ b/audio/output.sakura @@ -0,0 +1,158 @@ +#! Contains `audio_output`: a mixer, and the system's audio device playing what it +#! mixes, pulled by a thread of the output's own as the device wants frames; or +#! no device at all, mixed only as the program asks, as tests and servers want. +#! +#! The mixer is shared with that thread, so it's reached by `lock`, which holds +#! it until what it gives closes: a game makes its changes of a frame under one +#! lock, which the device's thread waits on at most that long. The output's own +#! `add`, `play`, and the rest each lock it for one change. +#! +#! On Windows the device is WASAPI's default one, as `wasapi.sakura` says. A +#! device lost, as headphones unplugged are, is opened again, the default then, +#! as soon as one is; the voices wait meanwhile. + +import system; +import std::thread; +module malunal::audio; + + +# What the device's thread and the program share. +struct output_state { + var mixing: thread::mutex; + var running: atomic; # 1 while the thread should play. + var opened: atomic; # 0 while the thread opens the device, 1 once it did, 2 once it couldn't. + var failure: audio_error; # Why it couldn't. + var latency: f32; # The seconds of frames the device should hold. + var played: atomic; # How many frames the device took. +} + +#! A mixer, and the device playing it. +pub struct audio_output : owning { + var shared: box; + var threads: vector>; # The device's thread, where there's a device. +} + +#! Opens the system's default audio device, and plays a mixer to it. +#! @param latency About how many seconds of frames the device holds ahead of +#! what it plays: more is steadier, and less heard sooner. +#! @returns The output, mixing at the device's rate, or why the device couldn't +#! be opened: `no_device` where there's none, or no audio service, and +#! `refused` where it wouldn't play as asked. +pub def audio_output::open(latency: f32 = 0.02): result { + var made := audio_output::made(48000, latency); + val state := address(made.shared.get()); + val s := &mut through(state); + s.running.store(1, order::release); + var started := thread::spawn_with(play_device, state) else (_) { return audio_error::refused; }; + made.threads.append(move(started)); + while s.opened.load(order::acquire) == 0 { + _ = system::futex_wait(word_of(&mut s.opened), 0, -1); + } + if s.opened.load(order::acquire) == 2 { + val why := s.failure; + made.close(); + return why; + } + return made; +} + +#! Makes an output of no device, mixed only by `render`. +#! @param rate The frames a second it mixes. +#! @returns The output. +pub def audio_output::headless(rate: u32 = 48000): audio_output { + var made := audio_output::made(rate, 0); + made.shared.get().opened.store(1, order::release); + return made; +} + +def audio_output::made(rate: u32, latency: f32): audio_output { + var state := output_state{ + mixing = thread::mutex::::new(mixer::new(rate)), running = atomic::::new(0), + opened = atomic::::new(0), latency = latency, played = atomic::::new(0), + }; + return audio_output{ shared = box::new(move(state)), threads = vector::>::new() }; +} + +#! Whether the output plays to a device, rather than being headless. +pub val audio_output::has_device: bool { + get => !this.threads.is_empty; +} + +#! How many frames the device took, or `render` mixed. +pub val audio_output::played: u64 { + get => this.shared.get().played.load(order::relaxed); +} + +#! Holds the mixer, so no frames are mixed until what this gives closes. +pub def audio_output::lock(&mut this): thread::guard { + return this.shared.get().mixing.lock(); +} + +#! The frames a second the mixer mixes: the device's. +pub def audio_output::rate(&mut this): u32 { + var held := this.lock(); + return held.value().rate; +} + +#! Mixes frames, as a device would take them, for an output of none. +#! @param into The frames, a frame's left and right together. +pub def audio_output::render(&mut this, into: slice): void { + var held := this.lock(); + held.value().mix(into); + _ = this.shared.get().played.fetch_add(into.length / 2, order::relaxed); +} + +#! Holds a sound, as `mixer::add` does. +pub def audio_output::add(&mut this, given: sound): sound_id { + var held := this.lock(); + return held.value().add(move(given)); +} + +#! Holds an Ogg Vorbis file, streamed, as `mixer::add_streamed` does. +pub def audio_output::add_streamed(&mut this, bytes: span): result { + var held := this.lock(); + return held.value().add_streamed(bytes); +} + +#! Lets go of a sound, as `mixer::remove` does. +pub def audio_output::remove(&mut this, id: sound_id): void { + var held := this.lock(); + held.value().remove(id); +} + +#! Plays a sound, as `mixer::play` does. +pub def audio_output::play(&mut this, id: sound_id, how: playback = playback{}): voice { + var held := this.lock(); + return held.value().play(id, how); +} + +#! Ends a voice, as `mixer::stop` does. +pub def audio_output::stop(&mut this, which: voice, fade: f32 = 0): void { + var held := this.lock(); + held.value().stop(which, fade); +} + +#! Whether a voice plays, as `mixer::playing` says. +pub def audio_output::playing(&mut this, which: voice): bool { + var held := this.lock(); + return held.value().playing(which); +} + +#! Stops the device's thread, and closes the device, then the mixer. +pub def audio_output::close(&mut this): void { + if !this.threads.is_empty { + this.shared.get().running.store(0, order::release); + this.threads.close(); + } +} + +# The word of an atomic, which the system's futexes wait on. +def word_of(of: &mut atomic): *mut u32 { + return (address(of) as *mut atomic) as *mut u32; +} + +# Says the device opened, or couldn't, waking `open`. +def say_opened(state: &mut output_state, how: u32): void { + state.opened.store(how, order::release); + _ = system::futex_wake(word_of(&mut state.opened), 1); +} diff --git a/audio/voices.sakura b/audio/voices.sakura new file mode 100644 index 0000000..01c04bf --- /dev/null +++ b/audio/voices.sakura @@ -0,0 +1,164 @@ +#! Contains a mixer's voices started, changed, and stopped, and its buses' and +#! master gains. + +import std::math; +module malunal::audio; + + +#! Plays a sound. +#! @param id The sound. +#! @param how How it plays. +#! @returns The voice playing it, or none where the id names no sound, or a +#! streamed one's bytes can't be read again. +pub def mixer::play(&mut this, id: sound_id, how: playback = playback{}): voice { + return voice{} if !this.holds(id); + var stream: maybe> = nothing {}; + if this.bank[id.index as u64].streamed { + val bytes := this.bank[id.index as u64].encoded.view(); + var opened := vorbis::decoder::open(bytes) else (_) { return voice{}; }; + var made := streaming{ decoding = move(opened), window = vector::::new() }; + stream = box::new(move(made)); + } + val index := this.slot(); + val at := &mut this.voices[index as u64]; + at.live = true; + at.sound = id; + at.how = how; + at.how.bus = how.bus < bus_count ? how.bus : 0; + at.position = 0; + at.gains = [0, 0]; + at.started = false; + at.stopping = false; + at.level = how.fade_in > 0 ? 0 : 1; + at.fade = how.fade_in > 0 ? 1 / (how.fade_in * this.mix_rate as f32) : 0; + at.stream = move(stream); + return voice{ index = index, generation = at.generation }; +} + +#! Whether a voice is playing, or paused, rather than ended. +pub def mixer::playing(&this, which: voice): bool { + return false if which.generation == 0 || which.index as u64 >= this.voices.length; + val at := &this.voices[which.index as u64]; + return at.live && at.generation == which.generation; +} + +#! How far into its sound a voice plays, in seconds, or 0 where it ended. +pub def mixer::position(&this, which: voice): f64 { + return 0 if !this.playing(which); + val at := &this.voices[which.index as u64]; + val rate := this.bank[at.sound.index as u64].rate as f64; + return at.position / rate; +} + +#! Ends a voice, at once, or faded out over some seconds. +pub def mixer::stop(&mut this, which: voice, fade: f32 = 0): void { + return if !this.playing(which); + if fade <= 0 { + this.end_voice(which.index as u64); + return; + } + val at := &mut this.voices[which.index as u64]; + at.stopping = true; + at.fade = -1 / (fade * this.mix_rate as f32); +} + +#! Ends every voice at once. +pub def mixer::stop_all(&mut this): void { + for i in 0..this.voices.length { + if this.voices[i].live { + this.end_voice(i); + } + } +} + +#! Changes how a voice plays: its gain, pan, pitch, whether it loops, whether +#! it's paused, and its bus. Its fade in is what it was. +pub def mixer::change(&mut this, which: voice, how: playback): void { + return if !this.playing(which); + val at := &mut this.voices[which.index as u64]; + val fade_in := at.how.fade_in; + at.how = how; + at.how.fade_in = fade_in; + at.how.bus = how.bus < bus_count ? how.bus : 0; +} + +#! How a voice plays, or as `playback{}` says where it ended. +pub def mixer::how(&this, which: voice): playback { + return playback{} if !this.playing(which); + return this.voices[which.index as u64].how; +} + +#! Changes a voice's gain. +pub def mixer::set_gain(&mut this, which: voice, gain: f32): void { + return if !this.playing(which); + this.voices[which.index as u64].how.gain = gain; +} + +#! Changes a voice's pan. +pub def mixer::set_pan(&mut this, which: voice, pan: f32): void { + return if !this.playing(which); + this.voices[which.index as u64].how.pan = math::clamp(pan, -1 as f32, 1 as f32); +} + +#! Changes a voice's pitch. +pub def mixer::set_pitch(&mut this, which: voice, pitch: f32): void { + return if !this.playing(which); + this.voices[which.index as u64].how.pitch = pitch; +} + +#! Pauses a voice, or plays it on from where it paused. +pub def mixer::pause(&mut this, which: voice, paused: bool = true): void { + return if !this.playing(which); + this.voices[which.index as u64].how.paused = paused; +} + +#! A bus's gain. +pub def mixer::bus(&this, which: u32): f32 { + return which < bus_count ? this.buses[which as u64] : 0; +} + +#! Changes a bus's gain, which every voice on it is multiplied by. +pub def mixer::set_bus(&mut this, which: u32, gain: f32): void { + return if which >= bus_count; + this.buses[which as u64] = gain; +} + +#! The gain every voice is multiplied by. +pub val mixer::master: f32 { + get => this.master_gain; +} + +pub def mixer::set_master(&mut this, gain: f32): void { + this.master_gain = gain; +} + +#! How many voices are playing, paused ones among them. +pub def mixer::voice_count(&this): u32 { + var count: u32 = 0; + for i in 0..this.voices.length { + if this.voices[i].live { + count++; + } + } + return count; +} + +# A free place for a voice. +def mixer::slot(&mut this): u32 { + if !this.idle.is_empty { + val index := this.idle.last(); + this.idle.truncate(); + return index; + } + this.voices.append(voice_state{ generation = 1, stream = nothing {} }); + return (this.voices.length - 1) as u32; +} + +# Ends a voice, freeing its place. +def mixer::end_voice(&mut this, index: u64): void { + val at := &mut this.voices[index]; + at.live = false; + at.generation = at.generation == 0xFFFFFFFF ? 1 : at.generation + 1; + at.stream = nothing {}; + this.idle.append(index as u32); +} diff --git a/audio/vorbis/bits.sakura b/audio/vorbis/bits.sakura new file mode 100644 index 0000000..18e8e44 --- /dev/null +++ b/audio/vorbis/bits.sakura @@ -0,0 +1,99 @@ +#! Contains the reader of a packet's bits, as Vorbis packs them: each number's +#! lowest bit first, from each byte's lowest bit up. +#! +#! Reading past a packet's end gives zeros and marks the reader `past`, which +#! the decoder takes as the packet ending, as Vorbis says to. + +import std::math; +module malunal::audio::vorbis; + + +struct bits { + var data: span; + var at: u64; # The next byte not yet held. + var held: u64; # Bits read from the bytes and not yet taken, the next lowest. + var count: u32; # How many. + var past: bool; # Whether a read went past the end. +} + +def bits::of(data: span): bits { + return bits{ data = data }; +} + +# Holds as many more bits as fit, or as are left. +def bits::fill(&mut this): void { + while this.count <= 56 && this.at < this.data.length { + this.held |= (this.data[this.at] as u64) << this.count; + this.count += 8; + this.at++; + } +} + +# Reads a number of up to 32 bits, or 0 past the end. +def bits::read(&mut this, width: u32): u32 { + return 0 if width == 0; + if this.count < width { + this.fill(); + if this.count < width { + this.ended(); + return 0; + } + } + val one: u64 = 1; + val value := (this.held & ((one << width) - 1)) as u32; + this.held >>= width; + this.count -= width; + return value; +} + +# The next bits, up to 32, without taking them: zeros past the end. +def bits::peek(&mut this, width: u32): u32 { + if this.count < width { + this.fill(); + } + val one: u64 = 1; + return (this.held & ((one << width) - 1)) as u32; +} + +# Takes bits a `peek` saw. +# @returns Whether there were as many. +def bits::skip(&mut this, width: u32): bool { + if this.count < width { + this.fill(); + if this.count < width { + this.ended(); + return false; + } + } + this.held >>= width; + this.count -= width; + return true; +} + +def bits::ended(&mut this): void { + this.past = true; + this.held = 0; + this.count = 0; + this.at = this.data.length; +} + +# Reads a float as Vorbis packs one: a 21-bit mantissa, a 10-bit exponent +# biased by 788, and a sign. +def bits::float(&mut this): f32 { + val packed := this.read(32); + val mantissa := (packed & 0x1FFFFF) as f64; + val exponent := ((packed >> 21) & 0x3FF) as f64; + val value := mantissa * math::pow(2.0, exponent - 788); + return ((packed & 0x80000000) != 0 ? -value : value) as f32; +} + +# How many bits a number needs: 0 for 0, 1 for 1, 2 for 2 and 3, and so on. +def ilog(value: u32): u32 { + var width: u32 = 0; + var left := value; + while left != 0 { + width++; + left >>= 1; + } + return width; +} diff --git a/audio/vorbis/blocks.sakura b/audio/vorbis/blocks.sakura new file mode 100644 index 0000000..11e8d4e --- /dev/null +++ b/audio/vorbis/blocks.sakura @@ -0,0 +1,225 @@ +#! Contains an audio packet decoded, as Vorbis I's fourth section does: its mode +#! and window, each channel's floor, the residues of each submap, the coupled +#! channels taken apart, each spectrum shaped by its floor, made a block by the +#! inverse MDCT, windowed, and overlapped with the block before. A packet gives +#! the frames from the middle of the block before to the middle of its own, and +#! the first gives none. + +module malunal::audio::vorbis; + + +# Where the channels of a stream of three to eight are heard from, in Vorbis's +# order for each count. +const speakers3: speaker[3] = [speaker::front_left, speaker::center, speaker::front_right]; +const speakers4: speaker[4] = [speaker::front_left, speaker::front_right, speaker::back_left, speaker::back_right]; +const speakers5: speaker[5] = [speaker::front_left, speaker::center, speaker::front_right, speaker::back_left, speaker::back_right]; +const speakers6: speaker[6] = [ + speaker::front_left, speaker::center, speaker::front_right, speaker::back_left, speaker::back_right, + speaker::low_frequency, +]; +const speakers7: speaker[7] = [ + speaker::front_left, speaker::center, speaker::front_right, speaker::side_left, speaker::side_right, + speaker::back_center, speaker::low_frequency, +]; +const speakers8: speaker[8] = [ + speaker::front_left, speaker::center, speaker::front_right, speaker::side_left, speaker::side_right, + speaker::back_left, speaker::back_right, speaker::low_frequency, +]; + +# Decodes an audio packet, adding the frames it gives to those pending. +# @returns How many frames it gave: none for the first, or one that isn't +# audio. +def decoder::decode_packet(&mut this, data: span): u64 { + var b := bits::of(data); + return 0 if b.read(1) != 0; + val modes := this.head.modes.length as u32; + val index := b.read(ilog(modes - 1)); + return 0 if index >= modes || b.past; + val mode := this.head.modes[index as u64]; + val long := mode.long; + val n := this.head.sizes[long ? 1 : 0] as u64; + var before_long := false; + var after_long := false; + if long { + before_long = b.read(1) != 0; + after_long = b.read(1) != 0; + } + return 0 if b.past; + val half := n / 2; + val channels := this.head.channels as u64; + val stride := this.head.sizes[1] as u64 / 2; + val mapping := this.head.mappings[mode.mapping as u64]; + + # Each channel's floor, and whose residue is decoded: those with a floor, and + # those coupled with one. + for c in 0..channels { + val floor := mapping.floors[mapping.mux[c] as u64] as u64; + val ys := part(&mut this.ys, c * most_posts, most_posts); + this.floored[c] = read_floor1(&this.head.floors[floor], &this.head.books, &mut b, ys); + this.skip[c] = !this.floored[c]; + } + for s in 0..mapping.steps as u64 { + val m := mapping.magnitudes[s] as u64; + val a := mapping.angles[s] as u64; + if !this.skip[m] || !this.skip[a] { + this.skip[m] = false; + this.skip[a] = false; + } + } + + # Each submap's residue. + val spectra := this.spectra.slice(); + for c in 0..channels { + for i in 0..half { + spectra[c * stride + i] = 0; + } + } + for s in 0..mapping.submaps as u64 { + var members: u32[256]; + var left_out: bool[256]; + var count: u64 = 0; + for c in 0..channels { + if mapping.mux[c] as u64 == s { + members[count] = c as u32; + left_out[count] = this.skip[c]; + count++; + } + } + val residue := mapping.residues[s] as u64; + decode_residue(&this.head.residues[residue], &this.head.books, &mut b, spectra, stride, + members[0:count], left_out[0:count], half, &mut this.scratch, &mut this.classes); + } + + # The coupled channels taken apart, the last coupled first. + for k in 0..mapping.steps as u64 { + val s := mapping.steps as u64 - 1 - k; + val magnitudes := mapping.magnitudes[s] as u64 * stride; + val angles := mapping.angles[s] as u64 * stride; + for i in 0..half { + val m := spectra[magnitudes + i]; + val a := spectra[angles + i]; + if m > 0 { + spectra[magnitudes + i] = a > 0 ? m : m + a; + spectra[angles + i] = a > 0 ? m - a : m; + } else { + spectra[magnitudes + i] = a > 0 ? m : m - a; + spectra[angles + i] = a > 0 ? m + a : m; + } + } + } + + # The window: its rise and fall, each the short block's where the block beside + # this long one is short. + val short_n := this.head.sizes[0] as u64; + var left_from: u64 = 0; + var left_to := half; + var right_from := half; + var right_to := n; + if long && !before_long { + left_from = n / 4 - short_n / 4; + left_to = n / 4 + short_n / 4; + } + if long && !after_long { + right_from = n * 3 / 4 - short_n / 4; + right_to = n * 3 / 4 + short_n / 4; + } + val left_short := !long || !before_long; + val right_short := !long || !after_long; + val overlap := left_to - left_from; + val fits := this.primed && this.tail_to - this.tail_from == overlap; + + # Each channel's spectrum shaped, made a block, windowed, and overlapped. + var frames: u64 = 0; + for c in 0..channels { + val spectrum := part(&mut this.spectra, c * stride, half); + if this.floored[c] { + val floor := mapping.floors[mapping.mux[c] as u64] as u64; + apply_floor1(&this.head.floors[floor], part(&mut this.ys, c * most_posts, most_posts), + this.flags.slice(), spectrum, half as u32); + } else { + for i in 0..half { + spectrum[i] = 0; + } + } + val block := part(&mut this.blocks, c * stride * 2, n); + if long { + this.long.inverse(spectrum.view(), block, this.re.slice(), this.im.slice(), this.folded.slice()); + } else { + this.short.inverse(spectrum.view(), block, this.re.slice(), this.im.slice(), this.folded.slice()); + } + for i in 0..left_from { + block[i] = 0; + } + for i in left_from..left_to { + block[i] *= left_short ? this.short.slope[i - left_from] : this.long.slope[i - left_from]; + } + for i in right_from..right_to { + block[i] *= right_short ? this.short.slope[right_to - 1 - i] : this.long.slope[right_to - 1 - i]; + } + for i in right_to..n { + block[i] = 0; + } + + val tail := part(&mut this.tails, c * stride, stride); + if fits { + val out := part(&mut this.made, c * stride, stride); + var k: u64 = 0; + for i in 0..this.tail_from { + out[k] = tail[i]; + k++; + } + for i in 0..overlap { + out[k] = tail[this.tail_from + i] + block[left_from + i]; + k++; + } + for i in left_to..half { + out[k] = block[i]; + k++; + } + frames = k; + } + for i in 0..half { + tail[i] = block[half + i]; + } + } + this.tail_from = right_from - half; + this.tail_to = right_to - half; + this.primed = true; + return 0 if frames == 0; + + # The frames, a frame's channels together, mixed down to two where there are + # more. + val start := this.pending.length; + if channels <= 2 { + this.pending.resize(start + frames * channels); + for i in 0..frames { + for c in 0..channels { + this.pending[start + i * channels + c] = this.made[c * stride + i]; + } + } + return frames; + } + this.scratch.clear(); + this.scratch.resize(frames * channels); + for i in 0..frames { + for c in 0..channels { + this.scratch[i * channels + c] = this.made[c * stride + i]; + } + } + this.pending.resize(start + frames * 2); + val into := part(&mut this.pending, start, frames * 2); + var order := speakers8[:]; + if channels == 3 { + order = speakers3[:]; + } else if channels == 4 { + order = speakers4[:]; + } else if channels == 5 { + order = speakers5[:]; + } else if channels == 6 { + order = speakers6[:]; + } else if channels == 7 { + order = speakers7[:]; + } + audio::downmix(this.scratch.view(), frames, order, into); + return frames; +} diff --git a/audio/vorbis/codebooks.sakura b/audio/vorbis/codebooks.sakura new file mode 100644 index 0000000..73d8252 --- /dev/null +++ b/audio/vorbis/codebooks.sakura @@ -0,0 +1,224 @@ +#! Contains codebooks: the Huffman codes of a setup's entries, and the vectors +#! some entries stand for, as Vorbis I's third section reads them. +#! +#! Each used entry is given the lowest codeword of its length not yet taken, +#! in order, as the spec says. A code of up to `fast_bits` bits is decoded by one +#! look in a table, and a longer one by walking a tree from its first bit. A +#! book whose lengths would need more codewords than there are is `malformed`; +#! one needing fewer is read, its unused codewords decoding to nothing. + +import std::math; +module malunal::audio::vorbis; + + +# The bits a codebook's table decodes at once. +const fast_bits: u32 = 10; + +# What a table's place holds, besides an entry: the first bits of a longer code, +# and of none. +const longer: i32 = -1; +const no_code: i32 = -2; + +# A codebook. +struct codebook { + var dimensions: u32; + var entries: u32; + var lengths: vector; # Each entry's codeword's length, 0 where it's unused. + var fast: vector; # By the next `fast_bits` bits: the entry, `longer`, or `no_code`. + var tree: vector; # Pairs, a node's children by the next bit: a node, -(entry + 1), or 0 for none. + var lookup: u32; # 0 where its entries stand for no vectors. + var values: vector; # Each entry's vector, `dimensions` floats. +} + +# Reads a codebook from a setup header. +def read_codebook(b: &mut bits): result { + return audio_error::malformed if b.read(24) != 0x564342; + var book := codebook{ + lengths = vector::::new(), fast = vector::::new(), tree = vector::::new(), + values = vector::::new(), + }; + book.dimensions = b.read(16); + book.entries = b.read(24); + return audio_error::malformed if book.dimensions == 0 || b.past; + val entries := book.entries as u64; + book.lengths.resize(entries); + if b.read(1) == 0 { + val sparse := b.read(1) != 0; + for e in 0..entries { + if !sparse || b.read(1) != 0 { + book.lengths[e] = (b.read(5) + 1) as u8; + } + } + } else { + var current: u32 = 0; + var length := b.read(5) + 1; + while current < book.entries { + val count := b.read(ilog(book.entries - current)); + return audio_error::malformed if current + count > book.entries || length > 32 || b.past; + for e in current..current + count { + book.lengths[e as u64] = length as u8; + } + current += count; + length++; + } + } + + book.lookup = b.read(4); + if book.lookup == 1 || book.lookup == 2 { + val minimum := b.float(); + val delta := b.float(); + val width := b.read(4) + 1; + val sequence := b.read(1) != 0; + val dims := book.dimensions as u64; + return audio_error::unsupported if entries * dims > 0x400000; + val count := book.lookup == 1 ? lookup1_values(book.entries, book.dimensions) : entries * dims; + var multiplicands := vector::::new(); + multiplicands.resize(count); + for i in 0..count { + multiplicands[i] = b.read(width); + } + return audio_error::malformed if b.past || count == 0; + book.values.resize(entries * dims); + for e in 0..entries { + var last: f32 = 0; + var divisor: u64 = 1; + for j in 0..dims { + val offset := book.lookup == 1 ? (e / divisor) % count : e * dims + j; + val value := multiplicands[offset] as f32 * delta + minimum + last; + if sequence { + last = value; + } + book.values[e * dims + j] = value; + if book.lookup == 1 { + divisor *= count; + } + } + } + } else if book.lookup != 0 { + return audio_error::malformed; + } + return audio_error::malformed if b.past; + book.assign() else (e) { return e; }; + return book; +} + +# The number of values a lookup of type 1 holds: the most whose power of the +# dimensions is no more than the entries. +def lookup1_values(entries: u32, dimensions: u32): u64 { + var root := math::floor(math::pow(entries as f64, 1.0 / dimensions as f64)) as u64; + while power_at_most(root + 1, dimensions, entries as u64) { + root++; + } + while root > 0 && !power_at_most(root, dimensions, entries as u64) { + root--; + } + return root; +} + +# Whether a number to a power is no more than a limit. +def power_at_most(base: u64, power: u32, limit: u64): bool { + var made: u64 = 1; + for _ in 0..power { + made *= base; + return false if made > limit; + } + return true; +} + +# Gives each used entry its codeword, as the spec says, into the table and the +# tree. Codewords are kept as their bits come, first lowest, so the table looks +# them up by the bits as read. +def codebook::assign(&mut this): result { + this.fast.resize(1 << fast_bits as u64, no_code); + this.tree.append(0); + this.tree.append(0); + var available: u64[33]; + var first := true; + for e in 0..this.entries as u64 { + val length := this.lengths[e] as u32; + continue if length == 0; + if first { + first = false; + this.add(e as i32, 0, length) else (x) { return x; }; + for i in 1..length + 1 { + available[i as u64] = (1 as u64) << (32 - i); + } + continue; + } + var level := length; + while level > 0 && available[level as u64] == 0 { + level--; + } + return audio_error::malformed if level == 0; + val code := available[level as u64]; + available[level as u64] = 0; + this.add(e as i32, code, length) else (x) { return x; }; + var deeper := length; + while deeper > level { + available[deeper as u64] = code + ((1 as u64) << (32 - deeper)); + deeper--; + } + } + return; +} + +# Adds an entry's codeword, given with its first bit highest of 32. +def codebook::add(&mut this, entry: i32, code: u64, length: u32): result { + val reversed := reverse_bits(code as u32); + if length <= fast_bits { + val one: u32 = 1; + for fill in 0..(one << (fast_bits - length)) { + this.fast[(reversed | (fill << length)) as u64] = entry; + } + } else { + val one: u32 = 1; + this.fast[(reversed & ((one << fast_bits) - 1)) as u64] = longer; + } + var node: u64 = 0; + for i in 0..length { + val slot := node * 2 + ((reversed >> i) & 1) as u64; + if i == length - 1 { + return audio_error::malformed if this.tree[slot] != 0; + this.tree[slot] = -(entry + 1); + } else { + return audio_error::malformed if this.tree[slot] < 0; + if this.tree[slot] == 0 { + this.tree[slot] = (this.tree.length / 2) as i32; + this.tree.append(0); + this.tree.append(0); + } + node = this.tree[slot] as u64; + } + } + return; +} + +# A 32-bit number's bits the other way around. +def reverse_bits(value: u32): u32 { + var v := value; + v = ((v >> 1) & 0x55555555) | ((v & 0x55555555) << 1); + v = ((v >> 2) & 0x33333333) | ((v & 0x33333333) << 2); + v = ((v >> 4) & 0x0F0F0F0F) | ((v & 0x0F0F0F0F) << 4); + v = ((v >> 8) & 0x00FF00FF) | ((v & 0x00FF00FF) << 8); + return (v >> 16) | ((v & 0xFFFF) << 16); +} + +# Reads an entry's codeword. +# @returns The entry, or -1 where the packet ended or the bits are no codeword. +def codebook::decode(&this, b: &mut bits): i32 { + val found := this.fast[b.peek(fast_bits) as u64]; + if found >= 0 { + return b.skip(this.lengths[found as u64] as u32) ? found : -1; + } + return -1 if found == no_code; + var node: u64 = 0; + while true { + val bit := b.read(1); + return -1 if b.past; + val child := this.tree[node * 2 + bit as u64]; + return -(child + 1) if child < 0; + return -1 if child == 0; + node = child as u64; + } + return -1; +} diff --git a/audio/vorbis/floors.sakura b/audio/vorbis/floors.sakura new file mode 100644 index 0000000..ab627fc --- /dev/null +++ b/audio/vorbis/floors.sakura @@ -0,0 +1,154 @@ +#! Contains floor 1, the curve each channel's spectrum is shaped by: its posts' +#! Y values read from a packet, each predicted from its neighbors and moved by +#! what was read, then lines drawn between them, as Vorbis I's seventh section +#! draws them, in integers, so every decoder draws the same curve. + +import std::math; +module malunal::audio::vorbis; + + +# What a floor's Y values, each a step of about 0.55 dB, multiply the spectrum +# by: from about -140 dB at 0 to 1 at 255, as the spec's table gives them. +def inverse_db_table(): f32[256] { + var table: f32[256]; + val step := math::log(1.0 / 1.0649863e-07) / 255.0; + for i in 0u..256u { + table[i] = math::exp((i as f64 - 255.0) * step) as f32; + } + return table; +} + +const inverse_db: f32[256] = inverse_db_table(); + +# The Y values' range, by the floor's multiplier. +const floor_ranges: u32[4] = [256, 128, 86, 64]; + +# Reads a channel's floor from a packet. +# @param ys Where its posts' Y values go, as read. +# @returns Whether the channel has a floor this packet: none where its first +# bit says so, or the packet ended while it was read. +def read_floor1(floor: &floor_setup, books: &vector, b: &mut bits, ys: slice): bool { + return false if b.read(1) == 0; + val width := ilog(floor_ranges[(floor.multiplier - 1) as u64] - 1); + ys[0] = b.read(width) as i32; + ys[1] = b.read(width) as i32; + var post: u64 = 2; + for p in 0..floor.partitions { + val class := floor.classes[p as u64] as u64; + val count := floor.dimensions[class] as u64; + val sub := floor.subclasses[class] as u32; + val one: i32 = 1; + val mask := (one << sub) - 1; + var choice: i32 = 0; + if sub > 0 { + choice = books[floor.masterbooks[class] as u64].decode(b); + return false if choice < 0; + } + for j in 0..count { + val book := floor.subbooks[class * 8 + (choice & mask) as u64]; + choice >>= sub; + if book >= 0 { + val y := books[book as u64].decode(b); + return false if y < 0; + ys[post + j] = y; + } else { + ys[post + j] = 0; + } + } + post += count; + } + return !b.past; +} + +# Multiplies a channel's spectrum by its floor's curve. +# @param ys The posts' Y values, as read; worked out in place. +# @param flags Where whether each post is drawn to goes. +# @param spectrum The spectrum, of `half` values. +def apply_floor1(floor: &floor_setup, ys: slice, flags: slice, spectrum: slice, half: u32): void { + val range := floor_ranges[(floor.multiplier - 1) as u64] as i32; + val count := floor.posts as u64; + flags[0] = true; + flags[1] = true; + for i in 2..count { + val low := floor.low[i] as u64; + val high := floor.high[i] as u64; + val predicted := render_point(floor.xs[low] as i32, ys[low], floor.xs[high] as i32, ys[high], floor.xs[i] as i32); + val value := ys[i]; + val high_room := range - predicted; + val low_room := predicted; + val room := (high_room < low_room ? high_room : low_room) * 2; + if value == 0 { + flags[i] = false; + ys[i] = predicted; + continue; + } + flags[low] = true; + flags[high] = true; + flags[i] = true; + if value >= room { + ys[i] = high_room > low_room ? value - low_room + predicted : predicted - value + high_room - 1; + } else if (value & 1) != 0 { + ys[i] = predicted - (value + 1) / 2; + } else { + ys[i] = predicted + value / 2; + } + } + + val multiplier := floor.multiplier as i32; + var lx: i32 = 0; + var ly := ys[0] * multiplier; + for k in 1..count { + val i := floor.order[k] as u64; + continue if !flags[i]; + val hx := floor.xs[i] as i32; + val hy := ys[i] * multiplier; + render_line(lx, ly, hx, hy, half as i32, spectrum); + lx = hx; + ly = hy; + } + if lx < half as i32 { + val scale := inverse_db[clamp_y(ly)]; + for x in lx as u64..half as u64 { + spectrum[x] *= scale; + } + } +} + +# Where the line between two posts is at an X, as the spec rounds it. +def render_point(x0: i32, y0: i32, x1: i32, y1: i32, x: i32): i32 { + val dy := y1 - y0; + val across := x1 - x0; + val off := (dy < 0 ? -dy : dy) * (x - x0) / across; + return dy < 0 ? y0 - off : y0 + off; +} + +# Multiplies a spectrum by a line between two posts, from the first's X up to +# the second's, short of `end`, stepping as Bresenham's lines do. +def render_line(x0: i32, y0: i32, x1: i32, y1: i32, end: i32, spectrum: slice): void { + val dy := y1 - y0; + val across := x1 - x0; + val rise := dy < 0 ? -dy : dy; + val whole := rise / across; + val base := dy < 0 ? -whole : whole; + val step := dy < 0 ? base - 1 : base + 1; + val left := rise - whole * across; + val last := x1 < end ? x1 : end; + return if x0 >= last; + var y := y0; + var error: i32 = 0; + spectrum[x0 as u64] *= inverse_db[clamp_y(y)]; + for x in (x0 + 1) as u64..last as u64 { + error += left; + if error >= across { + error -= across; + y += step; + } else { + y += base; + } + spectrum[x] *= inverse_db[clamp_y(y)]; + } +} + +def clamp_y(y: i32): u64 { + return (y < 0 ? 0 : (y > 255 ? 255 : y)) as u64; +} diff --git a/audio/vorbis/mdct.sakura b/audio/vorbis/mdct.sakura new file mode 100644 index 0000000..fb12632 --- /dev/null +++ b/audio/vorbis/mdct.sakura @@ -0,0 +1,134 @@ +#! Contains the inverse MDCT, which makes a block of `n` samples of a spectrum of +#! `n / 2` values, and the slopes of Vorbis's window. +#! +#! The inverse MDCT is Vorbis's, unscaled, as libvorbis's is: +#! +#! y[t] = Σ X[k] cos(2π/n (t + 1/2 + n/4)(k + 1/2)), k < n/2 +#! +#! worked as the DCT-IV of the spectrum, which is a complex FFT of `n / 4` +#! points between two turns, its `n / 2` values then folded out to `n`. +#! A DCT-IV `u` of `M` values gives `u[2j]` and `-u[M - 1 - 2j]` as the real +#! and imaginary parts of +#! +#! e^(-iπ(j + 1/4)/M) Σ (X[2m] + i X[M - 1 - 2m]) e^(-iπm/M) e^(-2πi jm/(M/2)), +#! +#! and the block is `u` from its middle on, then backward and negated, then +#! from its start negated. + +import std::math; +module malunal::audio::vorbis; + + +# What the inverse MDCT of one block size is worked with. +struct transform { + var n: u64; + var turns: vector; # Before the FFT: cos and sin of πm/M, a pair a value. + var after: vector; # After it: cos and sin of π(j + 1/4)/M. + var roots: vector; # The FFT's: cos and sin of 2πk/F, for k below F / 2. + var reversed: vector; # Each of the FFT's places with its bits the other way around. + var slope: vector; # The window's rise over `n / 2` samples. +} + +def transform::of(n: u64): transform { + val m := n / 2; + val f := n / 4; + var made := transform{ + n = n, turns = vector::::new(), after = vector::::new(), roots = vector::::new(), + reversed = vector::::new(), slope = vector::::new(), + }; + for k in 0..f { + val a := math::pi * k as f64 / m as f64; + made.turns.append(math::cos(a) as f32); + made.turns.append(math::sin(a) as f32); + val b := math::pi * (k as f64 + 0.25) / m as f64; + made.after.append(math::cos(b) as f32); + made.after.append(math::sin(b) as f32); + } + for k in 0..f / 2 { + val a := math::tau * k as f64 / f as f64; + made.roots.append(math::cos(a) as f32); + made.roots.append(math::sin(a) as f32); + } + val width := ilog((f - 1) as u32); + for k in 0..f { + var r: u32 = 0; + var left := k as u32; + for _ in 0..width { + r = (r << 1) | (left & 1); + left >>= 1; + } + made.reversed.append(r); + } + for i in 0..m { + val s := math::sin((i as f64 + 0.5) / m as f64 * math::pi / 2); + made.slope.append(math::sin(math::pi / 2 * s * s) as f32); + } + return made; +} + +# The inverse MDCT of a spectrum. +# @param spectrum `n / 2` values. +# @param block Where the `n` samples go. +# @param re Scratch of at least `n / 4` floats, as `im` is. +# @param folded Scratch of at least `n / 2` floats. +def transform::inverse(&this, spectrum: span, block: slice, re: slice, im: slice, folded: slice): void { + val m := this.n / 2; + val f := this.n / 4; + + # Turned, into the FFT's order. + for k in 0..f { + val xr := spectrum[2 * k]; + val xi := spectrum[m - 1 - 2 * k]; + val c := this.turns[2 * k]; + val s := this.turns[2 * k + 1]; + val at := this.reversed[k] as u64; + re[at] = xr * c + xi * s; + im[at] = xi * c - xr * s; + } + + # The FFT, by halves joined. + var size: u64 = 2; + while size <= f { + val half := size / 2; + val step := f / size; + var start: u64 = 0; + while start < f { + for k in 0..half { + val wr := this.roots[2 * k * step]; + val wi := -this.roots[2 * k * step + 1]; + val a := start + k; + val b := a + half; + val tr := re[b] * wr - im[b] * wi; + val ti := re[b] * wi + im[b] * wr; + re[b] = re[a] - tr; + im[b] = im[a] - ti; + re[a] = re[a] + tr; + im[a] = im[a] + ti; + } + start += size; + } + size *= 2; + } + + # Turned again, into the DCT-IV. + for j in 0..f { + val c := this.after[2 * j]; + val s := this.after[2 * j + 1]; + val vr := re[j]; + val vi := im[j]; + folded[2 * j] = vr * c + vi * s; + folded[m - 1 - 2 * j] = vr * s - vi * c; + } + + # Folded out to the block. + val quarter := m / 2; + for t in 0..quarter { + block[t] = folded[t + quarter]; + } + for t in quarter..3 * quarter { + block[t] = -folded[3 * quarter - 1 - t]; + } + for t in 3 * quarter..2 * m { + block[t] = -folded[t - 3 * quarter]; + } +} diff --git a/audio/vorbis/ogg.sakura b/audio/vorbis/ogg.sakura new file mode 100644 index 0000000..b60faab --- /dev/null +++ b/audio/vorbis/ogg.sakura @@ -0,0 +1,220 @@ +#! Contains Ogg's pages, each checked by its CRC, and the packets of one logical +#! stream gathered from them, as RFC 3533 frames them. +#! +#! A packet is laced as segments of 255 bytes and one shorter, which ends it, so +#! a packet may span pages. Pages of other logical streams, multiplexed with +#! this one, are passed over. A page of the stream missing, as its sequence +#! number says, is `malformed`. + +module malunal::audio::vorbis; + + +# A page's flags. +const continued: u8 = 1; # Its first packet began on the page before. +const first_page: u8 = 2; # It begins its logical stream. +const last_page: u8 = 4; # It ends its logical stream. + +# The granule position of a page on which no packet ends. +const no_granule: u64 = 0xFFFFFFFFFFFFFFFF; + +# A page: where it is, what its header says, and where its segments' sizes and +# its body are. +struct page { + var at: u64; # Where it begins. + var flags: u8; + var granule: u64; # The frames decoded once its last packet is, or `no_granule`. + var serial: u32; # The logical stream it's of. + var sequence: u32; # Its place among its stream's pages. + var segments: u32; # How many segments it laces. + var table: u64; # Where its segments' sizes are. + var body: u64; # Where its body begins. + var length: u64; # How long its body is. + var last_end: i64; # The last of its segments ending a packet, or -1 for none. +} + +# The CRC Ogg checks each page by: the polynomial 0x04C11DB7, not reflected, +# from 0, over the page with its CRC field taken as zeros. +def ogg_crc_table(): u32[256] { + var table: u32[256]; + for index in 0u..256u { + var crc: u64 = index << 24; + for _ in 0..8 { + crc = (crc & 0x80000000) != 0 ? ((crc << 1) ^ 0x04C11DB7) & 0xFFFFFFFF : (crc << 1) & 0xFFFFFFFF; + } + table[index] = crc as u32; + } + return table; +} + +const ogg_crc_bytes: u32[256] = ogg_crc_table(); + +# The CRC of a page, its CRC field taken as zeros. +def page_crc(bytes: span, at: u64, end: u64): u32 { + var crc: u64 = 0; + for i in at..end { + val byte: u64 = (i >= at + 22 && i < at + 26) ? 0 : bytes[i] as u64; + crc = ((crc << 8) & 0xFFFFFFFF) ^ ogg_crc_bytes[((crc >> 24) ^ byte) & 0xFF] as u64; + } + return crc as u32; +} + +# The page beginning at a place, checked: its capture pattern, its version, that +# it's whole, and its CRC. +def page_at(bytes: span, at: u64): result { + return audio_error::malformed if at + 27 > bytes.length; + return audio_error::malformed if bytes[at] != 'O' || bytes[at + 1] != 'g' || bytes[at + 2] != 'g' || bytes[at + 3] != 'S'; + return audio_error::unsupported if bytes[at + 4] != 0; + val segments := bytes[at + 26] as u32; + val table := at + 27; + return audio_error::malformed if table + segments as u64 > bytes.length; + var length: u64 = 0; + var last_end: i64 = -1; + for s in 0..segments { + val size := bytes[table + s as u64]; + length += size as u64; + if size < 255 { + last_end = s as i64; + } + } + val body := table + segments as u64; + return audio_error::malformed if body + length > bytes.length; + return audio_error::malformed if page_crc(bytes, at, body + length) != u32_at(bytes, at + 22); + var granule: u64 = 0; + for k in 0u..8u { + granule |= (bytes[at + 6 + k] as u64) << (k * 8) as u32; + } + return page{ + at = at, flags = bytes[at + 5], granule = granule, serial = u32_at(bytes, at + 14), + sequence = u32_at(bytes, at + 18), segments = segments, table = table, body = body, + length = length, last_end = last_end, + }; +} + +# A packet: its bytes, the granule position of the page it ends on where it's +# the last packet ending there, and whether it's the stream's last. +struct packet { + var data: span; + var granule: u64; + var last: bool; +} + +# The packets of one logical stream, read from its pages in order. +struct packets { + var bytes: span; + var serial: u32; + var at: u64; # Where the next page to look at begins. + var current: page; # The page whose segments are being read. + var held: bool; # Whether there is one. + var segment: u32; # Its next segment. + var offset: u64; # Where that segment's bytes are. + var expected: u32; # The sequence number the next page should have. + var counting: bool; # Whether a page has been read, so the next has one expected. + var joined: vector; # A packet begun on a page before, as it's gathered. + var joining: bool; + var skipping: bool; # Passing over the end of a packet begun before where reading began. + var done: bool; # The stream's last page was read, or the bytes ended. +} + +# Reads a stream's packets from a page on. +def packets::of(bytes: span, serial: u32, at: u64): packets { + return packets{ bytes = bytes, serial = serial, at = at, joined = vector::::new() }; +} + +# Reads the stream's packets again from a page on. +def packets::rewind(&mut this, at: u64): void { + this.at = at; + this.held = false; + this.counting = false; + this.joined.clear(); + this.joining = false; + this.skipping = false; + this.done = false; +} + +# The stream's next packet, which holds until the next is asked for. +# @returns Whether there was one, or why the pages couldn't be read. +def packets::next(&mut this, out: &mut packet): result { + if !this.joining { + this.joined.clear(); + } + while true { + if !this.held || this.segment == this.current.segments { + if this.held && (this.current.flags & last_page) != 0 { + this.done = true; + } + return false if this.done; + val moved := this.next_page() else (e) { return e; }; + if !moved { + this.done = true; + return false; + } + } + + # The packet's segments on this page, to the one shorter than 255. + val start := this.offset; + var size: u64 = 0; + var ended := false; + while this.segment < this.current.segments { + val length := this.bytes[this.current.table + this.segment as u64]; + size += length as u64; + this.segment++; + if length < 255 { + ended = true; + break; + } + } + this.offset = start + size; + if this.skipping { + this.skipping = !ended; + continue; + } + if !ended { + this.joined.extend(this.bytes[start:size]); + this.joining = true; + continue; + } + + val ends_page := (this.segment - 1) as i64 == this.current.last_end; + out.granule = ends_page ? this.current.granule : no_granule; + out.last = ends_page && (this.current.flags & last_page) != 0; + if this.joining { + this.joined.extend(this.bytes[start:size]); + this.joining = false; + out.data = this.joined.view(); + } else { + out.data = this.bytes[start:size]; + } + return true; + } + return false; +} + +# Moves to the stream's next page, passing over those of other streams. +# @returns Whether there was one, or why it couldn't be read. +def packets::next_page(&mut this): result { + while true { + return false if this.at >= this.bytes.length; + val found := page_at(this.bytes, this.at) else (e) { return e; }; + this.at = found.body + found.length; + continue if found.serial != this.serial; + return audio_error::malformed if this.counting && found.sequence != this.expected; + this.expected = found.sequence == 0xFFFFFFFF ? 0 : found.sequence + 1; + this.counting = true; + if (found.flags & continued) == 0 { + # A packet said to go on here doesn't. + return audio_error::malformed if this.joining; + } else if !this.joining { + this.skipping = true; + } + this.current = found; + this.held = true; + this.segment = 0; + this.offset = found.body; + return true; + } + return false; +} + +def u32_at(bytes: span, at: u64): u32 { + return (bytes[at] as u32) | ((bytes[at + 1] as u32) << 8) | ((bytes[at + 2] as u32) << 16) | ((bytes[at + 3] as u32) << 24); +} diff --git a/audio/vorbis/residues.sakura b/audio/vorbis/residues.sakura new file mode 100644 index 0000000..3f93bff --- /dev/null +++ b/audio/vorbis/residues.sakura @@ -0,0 +1,183 @@ +#! Contains residues, the detail of each channel's spectrum the floor's curve +#! shapes: partitions of its values, each of a class read first, then coded by +#! that class's book in each of eight passes, the vectors of their entries +#! added in, as Vorbis I's eighth section reads them. +#! +#! Type 0 interleaves a partition's vector entries, type 1 lays them end to end, +#! and type 2 codes the channels as one vector interleaving them, decoded as +#! type 1 is. The packet ending partway leaves the rest as it is, zero. + +module malunal::audio::vorbis; + + +# A residue: which of a vector's values it codes, in partitions of a size, each +# of a class saying which book codes it in each of eight passes. +struct residue_setup { + var kind: u32; + var begin: u32; + var end: u32; + var size: u32; + var classifications: u32; + var classbook: u32; + var books: i16[512]; # `class * 8 + pass`, or -1 for none. +} + +# Reads a residue from a setup header, checking the books it names. +def setup::read_residue(&mut this, b: &mut bits): result { + var residue: residue_setup; + residue.kind = b.read(16); + return audio_error::malformed if residue.kind > 2; + residue.begin = b.read(24); + residue.end = b.read(24); + residue.size = b.read(24) + 1; + residue.classifications = b.read(6) + 1; + residue.classbook = b.read(8); + return audio_error::malformed if residue.classbook as u64 >= this.books.length; + return audio_error::malformed if this.books[residue.classbook as u64].dimensions == 0; + var cascades: u32[64]; + for c in 0..residue.classifications { + var cascade := b.read(3); + if b.read(1) != 0 { + cascade |= b.read(5) << 3; + } + cascades[c as u64] = cascade; + } + val passes: u32 = 8; + for c in 0..residue.classifications { + for pass in 0..passes { + var book: i32 = -1; + if ((cascades[c as u64] >> pass) & 1) != 0 { + book = b.read(8) as i32; + return audio_error::malformed if book as u64 >= this.books.length; + return audio_error::malformed if this.books[book as u64].lookup == 0; + } + residue.books[(c * 8 + pass) as u64] = book as i16; + } + } + return audio_error::malformed if b.past; + return residue; +} + +# Decodes a submap's residue into the spectra of its channels. +# @param spectra Every channel's spectrum, `stride` values apart. +# @param members The channels of the submap. +# @param skip Whether each of them is left out, as having no floor. +# @param half How many values a spectrum has this packet. +# @param scratch What type 2's one vector is gathered in. +# @param classes What partitions' classes are kept in. +def decode_residue( + residue: &residue_setup, books: &vector, b: &mut bits, spectra: slice, stride: u64, + members: span, skip: span, half: u64, scratch: &mut vector, classes: &mut vector +): void { + if residue.kind != 2 { + var offsets: u64[256]; + for m in 0..members.length { + offsets[m] = members[m] as u64 * stride; + } + decode_partitions(residue, books, b, spectra, offsets[0:members.length], skip, half, residue.kind, classes); + return; + } + + # Type 2: the channels as one vector, decoded, then taken apart. + var any := false; + for m in 0..members.length { + any = any || !skip[m]; + } + return if !any; + val count := members.length; + scratch.clear(); + scratch.resize(half * count); + val one: u64[1] = [0]; + val none: bool[1] = [false]; + decode_partitions(residue, books, b, scratch.slice(), one[:], none[:], half * count, 1, classes); + for m in 0..count { + val at := members[m] as u64 * stride; + for i in 0..half { + spectra[at + i] += scratch[i * count + m]; + } + } +} + +# Decodes partitions of vectors laid in one buffer. +# @param offsets Where each vector begins in the buffer. +# @param size How many values each vector has. +# @param format 0 to interleave a partition's entries, 1 to lay them end to end. +def decode_partitions( + residue: &residue_setup, books: &vector, b: &mut bits, buffer: slice, + offsets: span, skip: span, size: u64, format: u32, classes: &mut vector +): void { + val begin := (residue.begin as u64) < size ? residue.begin as u64 : size; + val end := (residue.end as u64) < size ? residue.end as u64 : size; + return if end <= begin; + val psize := residue.size as u64; + val partitions := (end - begin) / psize; + return if partitions == 0; + val classbook := &books[residue.classbook as u64]; + val words := classbook.dimensions as u64; + val kinds := residue.classifications as u64; + val count := offsets.length; + val stride := partitions + words; + classes.resize(count * stride); + val passes: u64 = 8; + for pass in 0..passes { + var p: u64 = 0; + while p < partitions { + if pass == 0 { + for v in 0..count { + continue if skip[v]; + val read := classbook.decode(b); + return if read < 0; + var left := read as u64; + for k in 0..words { + classes[v * stride + p + words - 1 - k] = (left % kinds) as u8; + left /= kinds; + } + } + } + var i: u64 = 0; + while i < words && p < partitions { + for v in 0..count { + continue if skip[v]; + val class := classes[v * stride + p] as u64; + val book := residue.books[class * 8 + pass]; + if book >= 0 { + val at := offsets[v] + begin + p * psize; + return if !decode_partition(&books[book as u64], b, buffer, at, psize, format); + } + } + i++; + p++; + } + } + } +} + +# Decodes one partition of a vector by a book, adding its entries' vectors in. +# @returns Whether the packet held it whole. +def decode_partition(book: &codebook, b: &mut bits, buffer: slice, at: u64, psize: u64, format: u32): bool { + val dims := book.dimensions as u64; + if format == 0 { + val step := psize / dims; + for j in 0..step { + val entry := book.decode(b); + return false if entry < 0; + val base := entry as u64 * dims; + for k in 0..dims { + buffer[at + j + k * step] += book.values[base + k]; + } + } + return true; + } + var i: u64 = 0; + while i < psize { + val entry := book.decode(b); + return false if entry < 0; + val base := entry as u64 * dims; + for k in 0..dims { + break if i >= psize; + buffer[at + i] += book.values[base + k]; + i++; + } + } + return true; +} diff --git a/audio/vorbis/setup.sakura b/audio/vorbis/setup.sakura new file mode 100644 index 0000000..9801d3c --- /dev/null +++ b/audio/vorbis/setup.sakura @@ -0,0 +1,247 @@ +#! Contains a Vorbis stream's three headers read: the identification header's +#! channels, rate, and block sizes; the comment header, checked and passed over; +#! and the setup header's codebooks, floors, residues, mappings, and modes, each +#! checked against what it names, so decoding a packet never reaches past them. +#! +#! Floor 0, which no encoder has written since before Vorbis 1.0, is +#! `unsupported`. + +module malunal::audio::vorbis; + + +# The most X positions a floor of type 1 has: two, and 31 partitions of a class +# of eight. +const most_posts: u64 = 250; + +# A floor of type 1: the X positions of its curve's posts, and the books their +# Y values are read with. +struct floor_setup { + var partitions: u32; + var classes: u8[31]; # Each partition's class. + var dimensions: u8[16]; # How many posts each class reads. + var subclasses: u8[16]; # How many bits of its master book's entry choose each post's book. + var masterbooks: u8[16]; + var subbooks: i16[128]; # A class's books, `class * 8 + choice`, or -1 for a post read as 0. + var multiplier: u32; + var posts: u32; + var xs: u32[250]; + var order: u8[250]; # The posts in order of their X. + var low: u8[250]; # Each post's neighbor before it, of those read before it, nearest by X. + var high: u8[250]; # And after it. +} + + +# A mapping: the channels coupled, and the floor and residue of each submap. +struct mapping_setup { + var submaps: u32; + var steps: u32; + var magnitudes: u8[256]; + var angles: u8[256]; + var mux: u8[256]; # Each channel's submap. + var floors: u8[16]; + var residues: u8[16]; +} + +struct mode_setup { + var long: bool; + var mapping: u32; +} + +# What a stream's headers say. +struct setup { + var channels: u32; + var rate: u32; + var sizes: u32[2]; # The short and long block sizes. + var books: vector; + var floors: vector; + var residues: vector; + var mappings: vector; + var modes: vector; +} + +def setup::new(): setup { + return setup{ + books = vector::::new(), floors = vector::::new(), + residues = vector::::new(), mappings = vector::::new(), + modes = vector::::new(), + }; +} + +# Whether a packet is a header of a type: its type byte, then `vorbis`. +def is_header(data: span, kind: u8): bool { + return data.length >= 7 && data[0] == kind && data[1] == 'v' && data[2] == 'o' && data[3] == 'r' + && data[4] == 'b' && data[5] == 'i' && data[6] == 's'; +} + +def setup::read_identification(&mut this, data: span): result { + return audio_error::unrecognized if !is_header(data, 1); + return audio_error::malformed if data.length < 30; + return audio_error::unsupported if u32_at(data, 7) != 0; + this.channels = data[11] as u32; + this.rate = u32_at(data, 12); + val one: u32 = 1; + this.sizes[0] = one << (data[28] & 15) as u32; + this.sizes[1] = one << (data[28] >> 4) as u32; + return audio_error::malformed if this.channels == 0 || this.rate == 0 || (data[29] & 1) == 0; + return audio_error::malformed if this.sizes[0] < 64 || this.sizes[1] > 8192 || this.sizes[0] > this.sizes[1]; + return audio_error::unsupported if this.channels > 8; + return; +} + +def setup::read_setup(&mut this, data: span): result { + return audio_error::malformed if !is_header(data, 5); + var b := bits::of(data[7:data.length - 7]); + + val books := b.read(8) + 1; + for _ in 0..books { + var book := read_codebook(&mut b) else (e) { return e; }; + this.books.append(move(book)); + } + + val transforms := b.read(6) + 1; + for _ in 0..transforms { + return audio_error::malformed if b.read(16) != 0; + } + + val floors := b.read(6) + 1; + for _ in 0..floors { + val kind := b.read(16); + return audio_error::unsupported if kind == 0; + return audio_error::malformed if kind != 1; + val floor := this.read_floor(&mut b) else (e) { return e; }; + this.floors.append(floor); + } + + val residues := b.read(6) + 1; + for _ in 0..residues { + val residue := this.read_residue(&mut b) else (e) { return e; }; + this.residues.append(residue); + } + + val mappings := b.read(6) + 1; + for _ in 0..mappings { + val mapping := this.read_mapping(&mut b) else (e) { return e; }; + this.mappings.append(mapping); + } + + val modes := b.read(6) + 1; + for _ in 0..modes { + var mode := mode_setup{ long = b.read(1) != 0 }; + return audio_error::malformed if b.read(16) != 0 || b.read(16) != 0; + mode.mapping = b.read(8); + return audio_error::malformed if mode.mapping >= this.mappings.length as u32; + this.modes.append(mode); + } + return audio_error::malformed if b.read(1) != 1 || b.past; + return; +} + +def setup::read_floor(&mut this, b: &mut bits): result { + var floor: floor_setup; + floor.partitions = b.read(5); + var classes: u32 = 0; + for p in 0..floor.partitions { + val class := b.read(4); + floor.classes[p as u64] = class as u8; + classes = class + 1 > classes ? class + 1 : classes; + } + for c in 0..classes { + val at := c as u64; + floor.dimensions[at] = (b.read(3) + 1) as u8; + floor.subclasses[at] = b.read(2) as u8; + if floor.subclasses[at] != 0 { + floor.masterbooks[at] = b.read(8) as u8; + return audio_error::malformed if floor.masterbooks[at] as u64 >= this.books.length; + } + val one: u32 = 1; + for j in 0..(one << floor.subclasses[at] as u32) { + val book := b.read(8) as i32 - 1; + return audio_error::malformed if book >= this.books.length as i32; + floor.subbooks[at * 8 + j as u64] = book as i16; + } + } + floor.multiplier = b.read(2) + 1; + val range := b.read(4); + val one: u32 = 1; + floor.xs[0] = 0; + floor.xs[1] = one << range; + floor.posts = 2; + for p in 0..floor.partitions { + val class := floor.classes[p as u64] as u64; + for _ in 0..floor.dimensions[class] { + return audio_error::malformed if floor.posts as u64 >= most_posts; + floor.xs[floor.posts as u64] = b.read(range); + floor.posts++; + } + } + return audio_error::malformed if b.past; + + # The posts in order of X, which must differ, and each one's neighbors. + val count := floor.posts as u64; + for i in 0..count { + floor.order[i] = i as u8; + } + for i in 1..count { + var j := i; + while j > 0 && floor.xs[floor.order[j - 1] as u64] > floor.xs[floor.order[j] as u64] { + val held := floor.order[j]; + floor.order[j] = floor.order[j - 1]; + floor.order[j - 1] = held; + j--; + } + } + for i in 1..count { + return audio_error::malformed if floor.xs[floor.order[i] as u64] == floor.xs[floor.order[i - 1] as u64]; + } + for i in 2..count { + var low: u64 = 0; + var high: u64 = 1; + for j in 0..i { + val x := floor.xs[j]; + if x < floor.xs[i] && x > floor.xs[low] { + low = j; + } + if x > floor.xs[i] && x < floor.xs[high] { + high = j; + } + } + floor.low[i] = low as u8; + floor.high[i] = high as u8; + } + return floor; +} + +def setup::read_mapping(&mut this, b: &mut bits): result { + return audio_error::malformed if b.read(16) != 0; + var mapping: mapping_setup; + mapping.submaps = b.read(1) != 0 ? b.read(4) + 1 : 1; + if b.read(1) != 0 { + mapping.steps = b.read(8) + 1; + val width := ilog(this.channels - 1); + for s in 0..mapping.steps { + val magnitude := b.read(width); + val angle := b.read(width); + return audio_error::malformed if magnitude == angle || magnitude >= this.channels || angle >= this.channels; + mapping.magnitudes[s as u64] = magnitude as u8; + mapping.angles[s as u64] = angle as u8; + } + } + return audio_error::malformed if b.read(2) != 0; + if mapping.submaps > 1 { + for c in 0..this.channels { + val submap := b.read(4); + return audio_error::malformed if submap >= mapping.submaps; + mapping.mux[c as u64] = submap as u8; + } + } + for s in 0..mapping.submaps { + _ = b.read(8); + val floor := b.read(8); + val residue := b.read(8); + return audio_error::malformed if floor as u64 >= this.floors.length || residue as u64 >= this.residues.length; + mapping.floors[s as u64] = floor as u8; + mapping.residues[s as u64] = residue as u8; + } + return audio_error::malformed if b.past; + return mapping; +} diff --git a/audio/vorbis/vorbis.sakura b/audio/vorbis/vorbis.sakura new file mode 100644 index 0000000..cca535a --- /dev/null +++ b/audio/vorbis/vorbis.sakura @@ -0,0 +1,258 @@ +#! Contains `decoder`, which reads an Ogg Vorbis stream's frames as it's asked +#! for them, so a long one plays without being held decoded, and `decode`, which +#! reads one whole. +#! +#! Every Vorbis I stream is read but those of floor 0, which no encoder has +#! written since before Vorbis 1.0, and of more than eight channels, whose +#! order Vorbis leaves to the application. The first Vorbis stream of a file is +#! read; another chained after it, or multiplexed beside it, isn't. Frames are +#! cut from the start and end as the granule positions of the first and last +#! pages say, as the Ogg mapping of Vorbis does, so a stream gives exactly the +#! frames it was encoded from. A stream of more than two channels is mixed down +#! to two, its channels heard from where Vorbis's order places them. + +import std::math; +module malunal::audio::vorbis; + + +#! Reads an Ogg Vorbis stream's frames as it's asked for them. Its bytes must +#! stay where they are while it reads them. +pub struct decoder { + var head: setup; + var stream: packets; + var audio_at: u64; # Where the first page of audio begins. + var short: transform; + var long: transform; + var spectra: vector; # Each channel's spectrum, `stride` values apart. + var blocks: vector; # Each channel's block, `stride * 2` values apart. + var tails: vector; # Each channel's last block's second half, windowed. + var tail_from: u64; # Where the last block's falling slope begins in its tail. + var tail_to: u64; # And ends. + var primed: bool; # Whether a block was decoded, which the next overlaps. + var re: vector; + var im: vector; + var folded: vector; + var ys: vector; # Each channel's floor's posts. + var flags: vector; + var floored: vector; # Whether each channel has a floor this packet. + var skip: vector; # Whether each channel's residue is left out. + var scratch: vector; + var classes: vector; + var made: vector; # The frames a packet gave, each channel's `stride` apart. + var pending: vector; # Frames decoded and not yet read, a frame's together. + var taken: u64; # How many floats of `pending` were read. + var timed: bool; # Whether a granule position was met, so frames are where it says. + var clock: u64; # The granule position of the end of what was decoded. + var total: u64; # How many frames the stream has, as its last page says. +} + +#! Opens an Ogg Vorbis stream, reading its headers. +#! @param bytes The file's bytes, which must stay where they are while the +#! decoder reads them. +#! @returns The decoder, or why the stream can't be read: `unrecognized` where +#! it's no Ogg file or has no Vorbis stream, `malformed` where a +#! header or page is broken, and `unsupported` where it uses what +#! isn't read. +pub def decoder::open(bytes: span): result { + # The first stream whose first page begins with Vorbis's identification. + var at: u64 = 0; + var serial: u32 = 0; + var found := false; + while !found { + return audio_error::unrecognized if at >= bytes.length; + val first := page_at(bytes, at) else (e) { return e; }; + return audio_error::unrecognized if (first.flags & first_page) == 0; + if is_header(bytes[first.body:first.length], 1) { + serial = first.serial; + found = true; + } else { + at = first.body + first.length; + } + } + + var made := decoder{ + head = setup::new(), stream = packets::of(bytes, serial, at), spectra = vector::::new(), + blocks = vector::::new(), tails = vector::::new(), re = vector::::new(), + im = vector::::new(), folded = vector::::new(), ys = vector::::new(), + flags = vector::::new(), floored = vector::::new(), skip = vector::::new(), + scratch = vector::::new(), classes = vector::::new(), made = vector::::new(), + pending = vector::::new(), + }; + var next := packet{}; + for kind in 0..3 { + val had := made.stream.next(&mut next) else (e) { return e; }; + return audio_error::malformed if !had; + if kind == 0 { + made.head.read_identification(next.data) else (e) { return e; }; + } else if kind == 1 { + return audio_error::malformed if !is_header(next.data, 3); + } else { + made.head.read_setup(next.data) else (e) { return e; }; + } + } + # Audio begins on a page of its own. + made.audio_at = made.stream.at; + return audio_error::malformed if made.stream.segment != made.stream.current.segments; + + made.short = transform::of(made.head.sizes[0] as u64); + made.long = transform::of(made.head.sizes[1] as u64); + val channels := made.head.channels as u64; + val stride := made.head.sizes[1] as u64 / 2; + made.spectra.resize(channels * stride); + made.blocks.resize(channels * stride * 2); + made.tails.resize(channels * stride); + made.made.resize(channels * stride); + made.re.resize(stride / 2); + made.im.resize(stride / 2); + made.folded.resize(stride); + made.ys.resize(channels * most_posts); + made.flags.resize(most_posts); + made.floored.resize(channels); + made.skip.resize(channels); + made.total = last_granule(bytes, serial); + return made; +} + +#! How many channels the frames read have: one, or two. +pub val decoder::channels: u32 { + get => this.head.channels > 2 ? 2 : this.head.channels; +} + +#! Frames a second. +pub val decoder::rate: u32 { + get => this.head.rate; +} + +#! How many frames the stream has, as its last page says, or 0 where it says +#! nothing. +pub val decoder::frames: u64 { + get => this.total; +} + +#! Reads frames. +#! @param into Where they go, a frame's `channels` floats together. +#! @returns How many frames were read: fewer than fit only once the stream +#! ends; or why the stream couldn't be read. +pub def decoder::read(&mut this, into: slice): result { + val width := this.channels as u64; + val wanted := into.length / width; + var given: u64 = 0; + while given < wanted { + val held := (this.pending.length - this.taken) / width; + if held > 0 && (this.timed || this.stream.done) { + val count := held < wanted - given ? held : wanted - given; + for i in 0..count * width { + into[given * width + i] = this.pending[this.taken + i]; + } + this.taken += count * width; + given += count; + continue; + } + if this.taken == this.pending.length { + this.pending.clear(); + this.taken = 0; + } + var next := packet{}; + val had := this.stream.next(&mut next) else (e) { return e; }; + if !had { + # The stream ended before any page said where its frames are. + this.timed = true; + break if this.pending.length == this.taken; + continue; + } + val count := this.decode_packet(next.data); + this.time(count, next.granule, next.last); + } + return given; +} + +#! Reads the stream again from its first frame. +pub def decoder::rewind(&mut this): void { + this.stream.rewind(this.audio_at); + this.primed = false; + this.pending.clear(); + this.taken = 0; + this.timed = false; + this.clock = 0; +} + +# Keeps the frames a packet gave where the granule positions say: those before +# the first page's position cut from the start, and those past the last page's +# from the end. +def decoder::time(&mut this, count: u64, granule: u64, last: bool): void { + val width := this.channels as u64; + if !this.timed { + if granule == no_granule { + return; + } + val decoded := (this.pending.length - this.taken) / width; + this.timed = true; + this.clock = granule; + if decoded > granule { + val extra := (decoded - granule) * width; + if last { + this.pending.resize(this.pending.length - extra); + } else { + this.taken += extra; + } + } + return; + } + this.clock += count; + if last && granule != no_granule && this.clock > granule { + val held := (this.pending.length - this.taken) / width; + val extra := this.clock - granule < held ? this.clock - granule : held; + this.pending.resize(this.pending.length - extra * width); + this.clock = granule; + } else if granule != no_granule { + this.clock = granule; + } +} + +#! Reads an Ogg Vorbis file whole. +#! @param bytes The file's bytes. +#! @returns The sound, of two channels where the stream has more, or why it +#! couldn't be read: as `decoder::open` and `decoder::read` say, and +#! `too_large` where it has more frames than `max_frames`. +pub def decode(bytes: span): result { + var reading := decoder::open(bytes) else (e) { return e; }; + return audio_error::too_large if reading.frames > max_frames; + val width := reading.channels as u64; + var samples := vector::::new(); + samples.reserve(reading.frames * width); + var chunk := vector::::new(); + chunk.resize(4096 * width); + while true { + val count := reading.read(chunk.slice()) else (e) { return e; }; + break if count == 0; + samples.extend(span::::over(chunk.data, count * width)); + return audio_error::too_large if samples.length / width > max_frames; + } + return sound{ rate = reading.rate, channels = reading.channels, samples = move(samples) }; +} + +# The granule position of a stream's last page, or 0 where none is found among +# the last 64 KiB. +def last_granule(bytes: span, serial: u32): u64 { + val from := bytes.length > 65536 + 27 ? bytes.length - 65536 - 27 : 0; + var granule: u64 = 0; + var at := from; + while at + 27 <= bytes.length { + if bytes[at] == 'O' && bytes[at + 1] == 'g' && bytes[at + 2] == 'g' && bytes[at + 3] == 'S' { + if page_at(bytes, at) is value(found) { + if found.serial == serial && found.granule != no_granule { + granule = found.granule; + } + at = found.body + found.length; + continue; + } + } + at++; + } + return granule; +} + +# A part of a vector, to work on in place. +def part(of: &mut vector, at: u64, length: u64): slice { + return slice::::over(of.data + at, length); +} diff --git a/audio/wasapi.sakura b/audio/wasapi.sakura new file mode 100644 index 0000000..ddcf963 --- /dev/null +++ b/audio/wasapi.sakura @@ -0,0 +1,221 @@ +#! Contains the device an output plays to on Windows: WASAPI's default render +#! endpoint, in shared mode, asked for frames of two 32-bit floats at the rate +#! the system mixes at, its event waking the output's thread each time the +#! device wants more, so a buffer of about the output's latency is kept full. +#! Windows maps the two channels to the device's speakers. The thread asks the +#! Multimedia Class Scheduler Service to run it as "Pro Audio" does. +#! +#! COM's objects are reached through their tables of functions, a method by its +#! place in its interface, as `IMMDeviceEnumerator`, `IMMDevice`, +#! `IAudioClient`, and `IAudioRenderClient` order them. + +import system; +import system::windows; +import std::thread; +import std::time; +import malunal::audio::windows; +module malunal::audio when os == windows; + + +const enumerator_class: guid = guid{ a = 0xBCDE0395, b = 0xE52F, c = 0x467C, d = [0x8E, 0x3D, 0xC4, 0x57, 0x92, 0x91, 0x69, 0x2E] }; +const enumerator_interface: guid = guid{ a = 0xA95664D2, b = 0x9614, c = 0x4F35, d = [0xA7, 0x46, 0xDE, 0x8D, 0xB6, 0x36, 0x17, 0xE6] }; +const client_interface: guid = guid{ a = 0x1CB9AD4C, b = 0xDBFA, c = 0x4C32, d = [0xB1, 0x78, 0xC2, 0xF5, 0x68, 0xA7, 0x03, 0xB2] }; +const render_interface: guid = guid{ a = 0xF294ACFC, b = 0x3146, c = 0x4483, d = [0xA7, 0xBF, 0xAD, 0xDC, 0xA7, 0xC2, 0x60, 0xE2] }; +const float_samples: guid = guid{ a = 0x00000003, b = 0x0000, c = 0x0010, d = [0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71] }; + +# Shared mode, woken by an event, converting the floats to the device's format +# and rate where they differ. +const stream_flags: u32 = 0x00040000 | 0x80000000 | 0x08000000; + +type release_fn = cfn; +type default_endpoint_fn = cfn; +type activate_fn = cfn; +type initialize_fn = cfn; +type count_fn = cfn; +type mix_format_fn = cfn; +type call_fn = cfn; +type set_event_fn = cfn; +type service_fn = cfn; +type get_buffer_fn = cfn; +type release_buffer_fn = cfn; + +# The device open: its COM objects, its event, its rate, and its buffer's size. +struct device { + var enumerator: u64; + var endpoint: u64; + var client: u64; + var render: u64; + var event: u64; + var rate: u32; + var frames: u32; +} + +# A COM object's method, by its place in the object's table. +def method(object: u64, index: u64): u64 { + val table := through(object as *u64); + return through((table + index * 8) as *u64); +} + +def release(object: u64): void { + return if object == 0; + val f := method(object, 2) as release_fn; + _ = f(object); +} + +# Opens the default device, and starts it. +def open_device(latency: f32): result { + var d := device{}; + if CoCreateInstance(&enumerator_class, 0, CLSCTX_ALL, &enumerator_interface, &mut d.enumerator) < 0 { + return audio_error::no_device; + } + val endpoint := method(d.enumerator, 4) as default_endpoint_fn; + if endpoint(d.enumerator, 0, 0, &mut d.endpoint) < 0 { + close_device(&mut d); + return audio_error::no_device; + } + val activate := method(d.endpoint, 3) as activate_fn; + if activate(d.endpoint, &client_interface, CLSCTX_ALL, null, &mut d.client) < 0 { + close_device(&mut d); + return audio_error::refused; + } + + # The rate the system mixes at, which the mixer then mixes at. + var format: u64 = 0; + val mix_format := method(d.client, 8) as mix_format_fn; + if mix_format(d.client, &mut format) < 0 { + close_device(&mut d); + return audio_error::refused; + } + d.rate = through((format + 4) as *u32); + CoTaskMemFree(format); + + # WAVEFORMATEXTENSIBLE, packed as C packs it: two channels of 32-bit floats. + var wave: u8[40]; + put(&mut wave, 0, 0xFFFE, 2); + put(&mut wave, 2, 2, 2); + put(&mut wave, 4, d.rate, 4); + put(&mut wave, 8, d.rate * 8, 4); + put(&mut wave, 12, 8, 2); + put(&mut wave, 14, 32, 2); + put(&mut wave, 16, 22, 2); + put(&mut wave, 18, 32, 2); + put(&mut wave, 20, 3, 4); + put(&mut wave, 24, float_samples.a, 4); + put(&mut wave, 28, float_samples.b as u32, 2); + put(&mut wave, 30, float_samples.c as u32, 2); + for i in 0u..8u { + wave[32 + i] = float_samples.d[i]; + } + val duration := (latency as f64 * 10000000.0) as i64; + val initialize := method(d.client, 3) as initialize_fn; + if initialize(d.client, 0, stream_flags, duration, 0, address(&wave) as u64 as *u8, null) < 0 { + close_device(&mut d); + return audio_error::refused; + } + val buffer_size := method(d.client, 4) as count_fn; + d.event = CreateEventW(null, 0, 0, null); + val set_event := method(d.client, 13) as set_event_fn; + val service := method(d.client, 14) as service_fn; + val start := method(d.client, 10) as call_fn; + if buffer_size(d.client, &mut d.frames) < 0 || d.event == 0 || set_event(d.client, d.event) < 0 + || service(d.client, &render_interface, &mut d.render) < 0 || start(d.client) < 0 { + close_device(&mut d); + return audio_error::refused; + } + return d; +} + +# Stops the device, and lets go of what was opened of it. +def close_device(d: &mut device): void { + if d.client != 0 { + val stop := method(d.client, 11) as call_fn; + _ = stop(d.client); + } + release(d.render); + release(d.client); + release(d.endpoint); + release(d.enumerator); + if d.event != 0 { + _ = CloseHandle(d.event); + } + d.render = 0; + d.client = 0; + d.endpoint = 0; + d.enumerator = 0; + d.event = 0; +} + +# Puts a little-endian number of some bytes into a buffer. +def put(into: &mut u8[40], at: u64, value: u32, bytes: u64): void { + for i in 0..bytes { + into[at + i] = (value >> (i * 8) as u32) as u8; + } +} + +# What the output's thread does: opens the device, says whether it did, then +# fills the device's buffer each time it wakes, until the output closes. +def play_device(state: *mut output_state): void { + val s := &mut through(state); + _ = CoInitializeEx(null, COINIT_MULTITHREADED); + var d := open_device(s.latency) else (e) { + s.failure = e; + say_opened(s, 2); + CoUninitialize(); + return; + }; + { + var held := s.mixing.lock(); + held.value().set_rate(d.rate); + } + say_opened(s, 1); + + # "Pro Audio", as UTF-16. + val task: u16[10] = [0x50, 0x72, 0x6F, 0x20, 0x41, 0x75, 0x64, 0x69, 0x6F, 0]; + var task_index: u32 = 0; + val raised := AvSetMmThreadCharacteristicsW(address(&task) as u64 as *u16, &mut task_index); + + var open := true; + while s.running.load(order::acquire) == 1 { + if !open { + thread::sleep(time::milliseconds(250)); + if open_device(s.latency) is value(again) { + d = again; + open = true; + var held := s.mixing.lock(); + held.value().set_rate(d.rate); + } + continue; + } + _ = WaitForSingleObject(d.event, 50); + var padding: u32 = 0; + val current_padding := method(d.client, 6) as count_fn; + if current_padding(d.client, &mut padding) < 0 { + close_device(&mut d); + open = false; + continue; + } + val free := d.frames - padding; + continue if free == 0; + var data: u64 = 0; + val get_buffer := method(d.render, 3) as get_buffer_fn; + if get_buffer(d.render, free, &mut data) < 0 { + close_device(&mut d); + open = false; + continue; + } + { + var held := s.mixing.lock(); + held.value().mix(slice::::over(data as *mut f32, free as u64 * 2)); + } + val release_buffer := method(d.render, 4) as release_buffer_fn; + _ = release_buffer(d.render, free, 0); + _ = s.played.fetch_add(free as u64, order::relaxed); + } + if raised != 0 { + _ = AvRevertMmThreadCharacteristics(raised); + } + if open { + close_device(&mut d); + } + CoUninitialize(); +} diff --git a/audio/wav/wav.sakura b/audio/wav/wav.sakura new file mode 100644 index 0000000..a445328 --- /dev/null +++ b/audio/wav/wav.sakura @@ -0,0 +1,223 @@ +#! Contains WAV read and written: RIFF's chunks, `fmt ` saying what the samples +#! are, and `data` holding them. +#! +#! Every kind of sample games keep is read: PCM of 8 bits, unsigned, and of 16, +#! 24, and 32, signed; and floats of 32 and 64 bits, each plain or in +#! `WAVE_FORMAT_EXTENSIBLE`. Compressed kinds, as ADPCM, A-law, and µ-law, are +#! `unsupported`. A `data` chunk said to be longer than the file is read as far +#! as the file goes, as writers streaming WAV leave its size unwritten. Chunks +#! besides those two, as `LIST` and `smpl`, are skipped. +#! +#! A sound is written as PCM of 16 bits, rounded, or as 32-bit floats. + +import std::math; +module malunal::audio::wav; + + +# The format tags `fmt ` names its samples' kind by. +const pcm: u16 = 1; +const ieee_float: u16 = 3; +const extensible: u16 = 0xFFFE; + +# Where the channels of a file of more than two are heard from, by the bits of +# its channel mask, in order, as `WAVE_FORMAT_EXTENSIBLE` gives them. The front's +# left and right of center are heard as the front's, and those above as the +# center. +const mask_speakers: speaker[11] = [ + speaker::front_left, speaker::front_right, speaker::center, speaker::low_frequency, + speaker::back_left, speaker::back_right, speaker::front_left, speaker::front_right, + speaker::back_center, speaker::side_left, speaker::side_right, +]; + +#! Reads a WAV file. +#! @param bytes The file's bytes. +#! @returns The sound, of two channels where the file has more; or +#! `unrecognized` where the bytes aren't RIFF's WAVE, `malformed` where +#! a chunk is broken or `fmt ` or `data` is missing, `unsupported` +#! where the samples are compressed or of more than eight channels, and +#! `too_large` where there are more frames than `max_frames`. +pub def decode(bytes: span): result { + val found := audio::format_of(bytes) else { return audio_error::unrecognized; }; + return audio_error::unrecognized if found != format::wav; + + var tag: u16 = 0; + var channels: u32 = 0; + var rate: u32 = 0; + var align: u32 = 0; + var bits: u32 = 0; + var mask: u32 = 0; + var data_at: u64 = 0; + var data_length: u64 = 0; + var had_format := false; + var had_data := false; + var at: u64 = 12; + while at + 8 <= bytes.length { + val id := bytes[at:4]; + val size := u32_at(bytes, at + 4) as u64; + val body := at + 8; + if id[0] == 'f' && id[1] == 'm' && id[2] == 't' && id[3] == ' ' { + return audio_error::malformed if size < 16 || body + size > bytes.length; + tag = u16_at(bytes, body); + channels = u16_at(bytes, body + 2) as u32; + rate = u32_at(bytes, body + 4); + align = u16_at(bytes, body + 12) as u32; + bits = u16_at(bytes, body + 14) as u32; + if tag == extensible { + return audio_error::malformed if size < 40; + mask = u32_at(bytes, body + 20); + tag = u16_at(bytes, body + 24); + } + had_format = true; + } else if id[0] == 'd' && id[1] == 'a' && id[2] == 't' && id[3] == 'a' { + data_at = body; + data_length = body + size > bytes.length ? bytes.length - body : size; + had_data = true; + } + at = body + size + (size & 1); + } + return audio_error::malformed if !had_format || !had_data; + return audio_error::unsupported if tag != pcm && tag != ieee_float; + return audio_error::malformed if channels == 0 || rate == 0; + return audio_error::unsupported if channels > 8; + val known := tag == pcm ? bits == 8 || bits == 16 || bits == 24 || bits == 32 : bits == 32 || bits == 64; + return audio_error::unsupported if !known; + return audio_error::malformed if align != channels * bits / 8; + + val frames := data_length / align as u64; + return audio_error::too_large if frames > max_frames; + val count := frames * channels as u64; + var samples := vector::::new(); + samples.resize(count); + val step := (bits / 8) as u64; + for i in 0..count { + samples[i] = sample_at(bytes, data_at + i * step, tag, bits); + } + return sound{ rate = rate, channels = channels, samples = move(samples) } if channels <= 2; + + # More than two channels: mixed down, as their speakers say. + var speakers: speaker[8]; + var placed: u32 = 0; + for b in 0u..32u { + break if placed == channels; + if ((mask >> (b as u32)) & 1) != 0 { + speakers[placed as u64] = b < 11 ? mask_speakers[b] : speaker::center; + placed++; + } + } + if placed < channels { + for c in 0..channels { + speakers[c as u64] = default_speaker(channels, c); + } + } + var two := vector::::new(); + two.resize(frames * 2); + audio::downmix(samples.view(), frames, speakers[0:channels as u64], two.slice()); + return sound{ rate = rate, channels = 2, samples = move(two) }; +} + +#! Writes a sound as a WAV file. +#! @param played The sound. +#! @param floats Whether to write 32-bit floats rather than 16-bit integers, +#! each rounded from its float, held within -1 to 1. +#! @returns The file's bytes, or `malformed` where the sound has no channels or +#! rate, or samples of no whole number of frames. +pub def encode(played: &sound, floats: bool = false): result, audio_error> { + val channels := played.channels; + return audio_error::malformed if channels == 0 || played.rate == 0 || played.samples.length % channels as u64 != 0; + val width: u32 = floats ? 4 : 2; + val data_length := played.samples.length * width as u64; + return audio_error::too_large if data_length + 36 > 0xFFFFFFFF; + + var out := vector::::new(); + out.reserve(44 + data_length); + put_text(&mut out, "RIFF"); + put_u32(&mut out, (36 + data_length) as u32); + put_text(&mut out, "WAVEfmt "); + put_u32(&mut out, 16); + put_u16(&mut out, floats ? ieee_float : pcm); + put_u16(&mut out, channels as u16); + put_u32(&mut out, played.rate); + put_u32(&mut out, played.rate * channels * width); + put_u16(&mut out, (channels * width) as u16); + put_u16(&mut out, (width * 8) as u16); + put_text(&mut out, "data"); + put_u32(&mut out, data_length as u32); + for i in 0..played.samples.length { + val x := played.samples[i]; + if floats { + put_u32(&mut out, math::bits_of(x)); + } else { + val held := math::clamp(x, -1 as f32, 1 as f32); + val scaled := math::round(held * 32767) as i32; + put_u16(&mut out, (scaled < 0 ? scaled + 65536 : scaled) as u16); + } + } + return out; +} + +# One sample, of a kind and size, read at a place, as a float. +def sample_at(bytes: span, at: u64, tag: u16, bits: u32): f32 { + if tag == ieee_float { + return math::real_of_bits(u32_at(bytes, at)) if bits == 32; + val low := u32_at(bytes, at) as u64; + val high := u32_at(bytes, at + 4) as u64; + return math::real_of_bits(low | (high << 32)) as f32; + } + if bits == 8 { + return (bytes[at] as f32 - 128) / 128; + } + if bits == 16 { + var v := u16_at(bytes, at) as i32; + v = v >= 0x8000 ? v - 0x10000 : v; + return v as f32 / 32768; + } + if bits == 24 { + var v := (bytes[at] as i32) | ((bytes[at + 1] as i32) << 8) | ((bytes[at + 2] as i32) << 16); + v = v >= 0x800000 ? v - 0x1000000 : v; + return v as f32 / 8388608; + } + var w := u32_at(bytes, at) as i64; + w = w >= 0x80000000 ? w - 0x100000000 : w; + return (w as f64 / 2147483648.0) as f32; +} + +# Where a channel is heard from, in a file of more than two channels that gives +# no channel mask, as Windows places them by default. +def default_speaker(channels: u32, channel: u32): speaker { + val quad: speaker[4] = [speaker::front_left, speaker::front_right, speaker::back_left, speaker::back_right]; + val five: speaker[5] = [speaker::front_left, speaker::front_right, speaker::center, speaker::back_left, speaker::back_right]; + val seven: speaker[7] = [speaker::front_left, speaker::front_right, speaker::center, speaker::low_frequency, + speaker::back_center, speaker::side_left, speaker::side_right]; + val eight: speaker[8] = [speaker::front_left, speaker::front_right, speaker::center, speaker::low_frequency, + speaker::back_left, speaker::back_right, speaker::side_left, speaker::side_right]; + return quad[channel as u64] if channels == 4; + return five[channel as u64] if channels == 5; + return seven[channel as u64] if channels == 7; + return eight[channel as u64]; +} + +def u16_at(bytes: span, at: u64): u16 { + return (bytes[at] as u16) | ((bytes[at + 1] as u16) << 8); +} + +def u32_at(bytes: span, at: u64): u32 { + return (bytes[at] as u32) | ((bytes[at + 1] as u32) << 8) | ((bytes[at + 2] as u32) << 16) | ((bytes[at + 3] as u32) << 24); +} + +def put_u16(out: &mut vector, value: u16): void { + out.append(value as u8); + out.append((value >> 8) as u8); +} + +def put_u32(out: &mut vector, value: u32): void { + out.append(value as u8); + out.append((value >> 8) as u8); + out.append((value >> 16) as u8); + out.append((value >> 24) as u8); +} + +def put_text(out: &mut vector, text: strview): void { + for i in 0..text.length { + out.append(text[i] as u8); + } +} diff --git a/audio/windows/avrt.sakura b/audio/windows/avrt.sakura new file mode 100644 index 0000000..7cc3f5f --- /dev/null +++ b/audio/windows/avrt.sakura @@ -0,0 +1,9 @@ +#! Contains the functions of `avrt.dll` that ask the Multimedia Class Scheduler +#! Service to run the device's thread first, as audio's threads are. + +extern import "avrt.dll" when os == windows; + +extern module malunal::audio::windows when os == windows; + +pub def AvSetMmThreadCharacteristicsW(task: *u16, index: &mut u32): u64; +pub def AvRevertMmThreadCharacteristics(handle: u64): i32; diff --git a/audio/windows/kernel32.sakura b/audio/windows/kernel32.sakura new file mode 100644 index 0000000..71b9dcf --- /dev/null +++ b/audio/windows/kernel32.sakura @@ -0,0 +1,8 @@ +#! Contains the functions of `kernel32.dll` the device's thread waits with, +#! which `system::windows` leaves out. + +extern import "kernel32.dll" when os == windows; + +extern module malunal::audio::windows when os == windows; + +pub def CreateEventW(security: *u8, manual: i32, initial: i32, name: *u16): u64; diff --git a/audio/windows/ole32.sakura b/audio/windows/ole32.sakura new file mode 100644 index 0000000..16209c1 --- /dev/null +++ b/audio/windows/ole32.sakura @@ -0,0 +1,23 @@ +#! Contains `malunal::audio::windows`: the functions of `ole32.dll` COM is +#! begun and its objects made with, and the GUIDs that name them, as C lays +#! them out. + +extern import "ole32.dll" when os == windows; + +extern module malunal::audio::windows when os == windows; + +#! A GUID, as C lays one out. +pub struct guid { + pub var a: u32; + pub var b: u16; + pub var c: u16; + pub var d: u8[8]; +} + +pub def CoInitializeEx(reserved: *u8, flags: u32): i32; +pub def CoUninitialize(): void; +pub def CoCreateInstance(class: &guid, outer: u64, context: u32, interface: &guid, made: &mut u64): i32; +pub def CoTaskMemFree(memory: u64): void; + +pub const COINIT_MULTITHREADED: u32 = 0; +pub const CLSCTX_ALL: u32 = 0x17; diff --git a/blossomfile b/blossomfile new file mode 100644 index 0000000..f19c18e --- /dev/null +++ b/blossomfile @@ -0,0 +1,56 @@ +name: audio +gpid: malunal +semv: 1.0.0 + +options: + level: 2 + +requires: +- https://git.malunal.studio/sakura/std@v1.0.0 + +targets: +- name: malunal.audio + type: library + root: ./audio + deps: + - std.containers + - std.io + - std.math + - std.thread + - std.time + +# Times decoding each format and mixing voices; see its header. +- name: malunal.audio.bench + type: program + level: ${level} + deps: + - malunal.audio + - std.io + - std.time + srcs: + - tools/bench.sakura + +tests: +# Those of `output.sakura` open the default device where there is one, and +# pass without one. +- name: malunal.audio.tests + type: program + deps: [malunal.audio, std.io, std.math, std.testing, std.time] + srcs: + - tests/main.sakura + - tests/support.sakura + - tests/pages.sakura + - tests/spec.sakura + - tests/streams.sakura + - tests/sounds.sakura + - tests/wav.sakura + - tests/vorbis.sakura + - tests/mixer.sakura + - tests/output.sakura + +exports: +- malunal.audio + +package: + desc: Sound read from WAV and Ogg Vorbis, mixed, and played, as voices of a mixer an output device pulls from, Ogg Vorbis streamed as it plays. + auth: John Christman diff --git a/tests/main.sakura b/tests/main.sakura new file mode 100644 index 0000000..f2e3b84 --- /dev/null +++ b/tests/main.sakura @@ -0,0 +1,10 @@ +#! Contains the `main` that runs audio's tests, each in a copy of the program of +#! its own. `blossom test` runs them, and `-- --only TEXT` those whose name +#! holds the text. + +import system; +import std::testing; + +def main(args: span): void { + exit(tester::run(args)); +} diff --git a/tests/mixer.sakura b/tests/mixer.sakura new file mode 100644 index 0000000..f051778 --- /dev/null +++ b/tests/mixer.sakura @@ -0,0 +1,159 @@ +#! Contains the tests of `mixer`: voices mixed at their gains, panned, ramped +#! as they change, ended or looped at their sounds' ends, resampled and +#! pitched, faded, on buses, and streamed as they play. + +import std::math; +import std::testing; +import malunal::audio; + +# A sound of one channel, every sample the same. +def flat(rate: u32, frames: u64, value: f32): sound { + var samples := vector::::new(); + samples.resize(frames, value); + return sound{ rate = rate, channels = 1, samples = move(samples) }; +} + +# Mixes some frames. +def mixed(m: &mut mixer, frames: u64): vector { + var out := vector::::new(); + out.resize(frames * 2); + m.mix(out.slice()); + return out; +} + +@test def mixes_a_mono_voice_at_its_gain_and_pan(t: &mut tester): void { + var m := mixer::new(48000); + val id := m.add(flat(48000, 1000, 0.5)); + val v := m.play(id); + val middle := mixed(&mut m, 100); + # The constant power law: -3 dB each side at the middle. + t.expects(math::abs(middle[0] - 0.5 * 0.70710677) < 1e-6 && math::abs(middle[199] - middle[198]) < 1e-6); + + # Panned all left, ramped there across the next frames. + m.set_pan(v, -1); + val left := mixed(&mut m, 100); + t.expects(math::abs(left[198] - 0.5) < 1e-6 && math::abs(left[199]) < 1e-6); + t.expects(left[1] > 0 && left[1] < middle[1]); + val held := mixed(&mut m, 100); + t.expects(math::abs(held[0] - 0.5) < 1e-6 && held[1] == 0); + + # Two voices add. + m.set_pan(v, 0); + _ = mixed(&mut m, 10); + _ = m.play(id); + val two := mixed(&mut m, 10); + t.expects(math::abs(two[0] - 2 * 0.5 * 0.70710677) < 1e-6); + t.expects(m.voice_count() == 2); +} + +@test def pans_a_stereo_voice_by_turning_down_one_side(t: &mut tester): void { + var m := mixer::new(48000); + val pairs: f32[6] = [0.5, 0.25, 0.5, 0.25, 0.5, 0.25]; + val id := m.add(sound::of(48000, 2, pairs[:])); + _ = m.play(id, playback{ pan = 0.5 }); + val out := mixed(&mut m, 2); + t.expects(math::abs(out[0] - 0.25) < 1e-6 && math::abs(out[1] - 0.25) < 1e-6); + t.expects(m.add(sound::of(48000, 3, pairs[0:3])).is_none); +} + +@test def ends_voices_at_their_ends_and_loops_those_that_loop(t: &mut tester): void { + var m := mixer::new(48000); + val id := m.add(flat(48000, 100, 0.5)); + val once := m.play(id, playback{ pan = -1 }); + val out := mixed(&mut m, 150); + t.expects(out[2 * 99] == 0.5 && out[2 * 100] == 0 && out[2 * 149] == 0); + t.expects(!m.playing(once) && m.voice_count() == 0); + + val looped := m.play(id, playback{ pan = -1, looping = true }); + val again := mixed(&mut m, 250); + t.expects(again[2 * 150] == 0.5 && again[2 * 249] == 0.5 && m.playing(looped)); + t.expects(math::abs(m.position(looped) - 50.0 / 48000) < 1e-9); + m.stop(looped); + t.expects(!m.playing(looped)); + # A voice ended names none after, though its place is played again. + val next := m.play(id); + t.expects(m.playing(next) && !m.playing(looped)); +} + +@test def resamples_and_pitches_as_it_plays(t: &mut tester): void { + # A sine of 1 kHz at 24 kHz, played at 48 kHz: as long again, and as near the + # same sine as cubic interpolation reaches. + var m := mixer::new(48000); + val id := m.add(sound::tone(1000, 0.05, 24000, 0.5)); + val v := m.play(id, playback{ pan = -1 }); + val out := mixed(&mut m, 2500); + t.expects(!m.playing(v) && out[2 * 2390] != 0 && out[2 * 2405] == 0); + var worst: f32 = 0; + for i in 300u..2000u { + val want := 0.5 * math::sin(math::tau * 1000 * i as f64 / 48000) as f32; + worst = math::max(worst, math::abs(out[2 * i] - want)); + } + t.expects(worst < 0.01); + + # At twice its pitch, it plays at its own rate, as long as it is. + val fast := m.play(id, playback{ pan = -1, pitch = 2 }); + val quick := mixed(&mut m, 1300); + t.expects(!m.playing(fast) && quick[2 * 1100] != 0 && quick[2 * 1205] == 0); +} + +@test def multiplies_by_buses_and_the_master(t: &mut tester): void { + var m := mixer::new(48000); + val id := m.add(flat(48000, 100, 0.5)); + m.set_bus(3, 0.5); + m.set_master(0.5); + _ = m.play(id, playback{ pan = -1, bus = 3 }); + val out := mixed(&mut m, 4); + t.expects(math::abs(out[0] - 0.125) < 1e-6 && m.bus(3) == 0.5 && m.master == 0.5); +} + +@test def fades_voices_in_and_out(t: &mut tester): void { + var m := mixer::new(48000); + val id := m.add(flat(48000, 10000, 0.5)); + val v := m.play(id, playback{ pan = -1, fade_in = 0.01 }); + val rising := mixed(&mut m, 480); + t.expects(rising[0] < 0.01 && math::abs(rising[2 * 479] - 0.5) < 1e-5 && rising[2 * 240] < 0.3); + m.stop(v, 0.01); + val falling := mixed(&mut m, 480); + t.expects(falling[0] > 0.49 && falling[2 * 479] < 1e-5 && !m.playing(v)); +} + +@test def plays_a_stream_as_it_plays_the_sound_whole(t: &mut tester): void { + val made := made_vorbis(2, 0); + var m := mixer::new(48000); + val streamed := m.add_streamed(made.bytes.view()) else (e) { t.expects(false); return; }; + var whole := audio::decode(made.bytes.view()) else (e) { t.expects(false); return; }; + val frames := whole.frames; + val decoded := m.add(move(whole)); + t.expects(math::abs(m.seconds(streamed) - m.seconds(decoded)) < 1e-9); + + val a := m.play(streamed); + val from_stream := mixed(&mut m, frames + 10); + t.expects(!m.playing(a)); + val b := m.play(decoded); + val from_sound := mixed(&mut m, frames + 10); + t.expects(!m.playing(b)); + t.expects(apart(from_stream.view(), from_sound.view()) < 1e-6); + + # Looped, it plays its first frames again after its last. + val c := m.play(streamed, playback{ looping = true }); + val round := mixed(&mut m, frames + 50); + t.expects(m.playing(c)); + t.expects(math::abs(round[2 * (frames + 40)] - from_sound[2 * 40]) < 1e-6); + + m.remove(streamed); + t.expects(!m.playing(c) && !m.holds(streamed) && m.play(streamed).is_none); +} + +@test def makes_a_sound_another_under_its_id(t: &mut tester): void { + var m := mixer::new(48000); + val id := m.add(flat(48000, 100, 0.5)); + val v := m.play(id, playback{ pan = -1 }); + t.expects(m.replace(id, flat(48000, 100, 0.25)) && !m.playing(v)); + _ = m.play(id, playback{ pan = -1 }); + val out := mixed(&mut m, 2); + t.expects(out[0] == 0.25 && sound_id::of_bits(id.bits).equals(&id)); + val made := made_vorbis(1, 0); + t.expects(m.replace_streamed(id, made.bytes.view()) is value(_)); + t.expects(math::abs(m.seconds(id) - made.expected.length as f64 / 48000) < 1e-9); + t.expects(!m.replace(sound_id{}, flat(48000, 1, 0))); +} \ No newline at end of file diff --git a/tests/output.sakura b/tests/output.sakura new file mode 100644 index 0000000..bdc6555 --- /dev/null +++ b/tests/output.sakura @@ -0,0 +1,38 @@ +#! Contains the tests of `audio_output`: one of no device, mixed as the test +#! asks, and the system's default device, where there is one. + +import std::testing; +import std::thread; +import std::time; +import malunal::audio; + +@test def mixes_for_no_device_as_asked(t: &mut tester): void { + var out := audio_output::headless(44100); + t.expects(!out.has_device && out.rate() == 44100); + val id := out.add(sound::tone(440, 0.1, 44100)); + val v := out.play(id, playback{ pan = -1 }); + var frames := vector::::new(); + frames.resize(2 * 441); + out.render(frames.slice()); + t.expects(out.played == 441 && frames[2 * 200] != 0 && frames[2 * 200 + 1] == 0); + t.expects(out.playing(v)); + out.stop(v); + t.expects(!out.playing(v)); +} + +@test def plays_to_the_default_device_where_there_is_one(t: &mut tester): void { + var out := audio_output::open() else (e) { + # A machine of no audio device, as a build server, passes. + t.expects(e == audio_error::no_device); + return; + }; + t.expects(out.has_device && out.rate() >= 8000); + # Silent, so the test isn't heard. + val id := out.add(sound::tone(440, 0.05, out.rate(), 0)); + _ = out.play(id); + val started := time::instant::now(); + while out.played < 2000 && started.elapsed().compare(&time::seconds(2)) < 0 { + thread::sleep(time::milliseconds(10)); + } + t.expects(out.played >= 2000); +} diff --git a/tests/pages.sakura b/tests/pages.sakura new file mode 100644 index 0000000..c6497dc --- /dev/null +++ b/tests/pages.sakura @@ -0,0 +1,108 @@ +#! Contains how the tests write what they encode: bits as Vorbis packs them, +#! and Ogg's pages, each laced and checked by its CRC, worked out bit by bit as +#! RFC 3533 defines it, apart from how the decoder works it out. + +# Bits written as Vorbis packs them: each number's lowest bit first. +struct bit_writer { + var bytes: vector; + var held: u32; + var count: u32; +} + +def bit_writer::new(): bit_writer { + return bit_writer{ bytes = vector::::new() }; +} + +def bit_writer::put(&mut this, value: u32, width: u32): void { + for i in 0..width { + this.held |= ((value >> i) & 1) << this.count; + this.count++; + if this.count == 8 { + this.bytes.append(this.held as u8); + this.held = 0; + this.count = 0; + } + } +} + +# A codeword, its first bit highest, as a codebook's are read. +def bit_writer::code(&mut this, codeword: u32, length: u32): void { + for i in 0..length { + this.put((codeword >> (length - 1 - i)) & 1, 1); + } +} + +def bit_writer::text(&mut this, text: strview): void { + for i in 0..text.length { + this.put(text[i] as u32, 8); + } +} + +def bit_writer::finish(&mut this): vector { + if this.count > 0 { + this.bytes.append(this.held as u8); + } + return move(this.bytes); +} + +# A packet's lacing: 255 for each whole 255 bytes, then what's left. +def lace(into: &mut vector, length: u64): void { + var left := length; + while left >= 255 { + into.append(255); + left -= 255; + } + into.append(left as u8); +} + +# A page of up to two packets. +def page_of(out: &mut vector, flags: u8, granule: u64, sequence: u32, one: span, two: span): void { + var lacing := vector::::new(); + var body := vector::::new(); + lace(&mut lacing, one.length); + body.extend(one); + if two.length > 0 { + lace(&mut lacing, two.length); + body.extend(two); + } + page_laced(out, flags, granule, sequence, lacing.view(), body.view()); +} + +# A page, its CRC worked out bit by bit, as RFC 3533 defines it. +def page_laced(out: &mut vector, flags: u8, granule: u64, sequence: u32, lacing: span, body: span): void { + val start := out.length; + for c in "OggS" { + out.append(c as u8); + } + out.append(0); + out.append(flags); + for i in 0u..8u { + out.append((granule >> (i * 8) as u32) as u8); + } + put_u32(out, 0x51A7); + put_u32(out, sequence); + put_u32(out, 0); + out.append(lacing.length as u8); + out.extend(lacing); + out.extend(body); + var crc: u32 = 0; + for i in start..out.length { + crc ^= (out[i] as u32) << 24; + for _ in 0..8 { + val high := (crc & 0x80000000) != 0; + crc = (crc & 0x7FFFFFFF) << 1; + if high { + crc ^= 0x04C11DB7; + } + } + } + for i in 0u..4u { + out[start + 22 + i] = (crc >> (i * 8) as u32) as u8; + } +} + +def put_u32(out: &mut vector, value: u32): void { + for i in 0u..4u { + out.append((value >> (i * 8) as u32) as u8); + } +} diff --git a/tests/sounds.sakura b/tests/sounds.sakura new file mode 100644 index 0000000..ff9853a --- /dev/null +++ b/tests/sounds.sakura @@ -0,0 +1,58 @@ +#! Contains the tests of `audio`'s own functions: sounds made, which format +#! bytes, or a file's extension, say they're in, and channels mixed down. + +import std::math; +import std::testing; +import malunal::audio; + +@test def makes_tones(t: &mut tester): void { + val beep := sound::tone(1000, 0.25, 48000, 0.5); + t.expects(beep.rate == 48000 && beep.channels == 1 && beep.frames == 12000); + t.expects(math::abs(beep.seconds - 0.25) < 1e-9); + # Faded in from silence, and out to it, and as loud as asked between. + t.expects(beep.samples[0] == 0 && math::abs(beep.samples[11999]) < 0.01); + var loudest: f32 = 0; + for i in 0..beep.samples.length { + loudest = math::max(loudest, math::abs(beep.samples[i])); + } + t.expects(loudest > 0.49 && loudest <= 0.5); + val given: f32[4] = [0.5, -0.5, 0.25, -0.25]; + val made := sound::of(22050, 2, given[:]); + t.expects(made.frames == 2 && made.samples[3] == -0.25); +} + +@test def finds_each_format_by_its_first_bytes(t: &mut tester): void { + t.expects(audio::format_of("RIFF\x24\x00\x00\x00WAVEfmt ") is some(_)); + t.expects(audio::format_of("RIFF\x24\x00\x00\x00WAVEfmt ").unwrap() == audio::format::wav); + t.expects(audio::format_of("OggS\x00\x02").unwrap() == audio::format::vorbis); + t.expects(audio::format_of("RIFF\x24\x00\x00\x00AVI ") is none); + t.expects(audio::format_of("ID3\x04") is none); + t.expects(fails(audio::decode("plain text"), audio_error::unrecognized)); + t.expects(fails(audio::load("tests/missing.wav"), audio_error::unreadable)); +} + +@test def names_formats_by_their_extensions(t: &mut tester): void { + t.expects(audio::format_named("wav").unwrap() == audio::format::wav); + t.expects(audio::format_named("WAVE").unwrap() == audio::format::wav); + t.expects(audio::format_named("ogg").unwrap() == audio::format::vorbis); + t.expects(audio::format_named("Oga").unwrap() == audio::format::vorbis); + t.expects(audio::format_named("mp3") is none); +} + +@test def mixes_more_channels_down_to_two(t: &mut tester): void { + # 5.1 in Windows's order: the front's sides whole, the center to both, the + # low frequencies left out, the backs to their sides. + val speakers: speaker[6] = [ + speaker::front_left, speaker::front_right, speaker::center, speaker::low_frequency, + speaker::back_left, speaker::back_right, + ]; + val frame: f32[6] = [1, 0, 0, 1, 0, 0]; + var two: f32[2]; + audio::downmix(frame[:], 1, speakers[:], two[:]); + # Each side sums to 1 + 0.707 + 0.707, so is scaled by its inverse. + val scale := 1 / (1 + 2 * 0.70710677); + t.expects(math::abs(two[0] - scale) < 1e-6 && two[1] == 0); + val middle: f32[6] = [0, 0, 1, 0, 0, 0]; + audio::downmix(middle[:], 1, speakers[:], two[:]); + t.expects(math::abs(two[0] - 0.70710677 * scale) < 1e-6 && math::abs(two[0] - two[1]) < 1e-9); +} diff --git a/tests/spec.sakura b/tests/spec.sakura new file mode 100644 index 0000000..588081d --- /dev/null +++ b/tests/spec.sakura @@ -0,0 +1,104 @@ +#! Contains the frames a stream the tests make should decode to, worked out as +#! the spec defines them, directly: each block's spectrum, its residue, the +#! coupled channels taken apart; its inverse MDCT as its sum; windowed, the +#! window's slopes short beside a short block; and laid at its place on one +#! timeline, read from the first block's middle to the last's. + +import std::math; + +# The frames a stream of `pattern`'s blocks decodes to, each packet's residue +# given, `trimmed` frames cut from its end. +def defined_frames(channels: u32, trimmed: u64, residues: &vector>): vector { + val sizes: u64[2] = [64, 256]; + val count := 9u; + var centers := vector::::new(); + var center := sizes[pattern[0] ? 1 : 0] / 2; + for k in 0..count { + if k > 0 { + center += sizes[pattern[k - 1] ? 1 : 0] / 4 + sizes[pattern[k] ? 1 : 0] / 4; + } + centers.append(center); + } + val length := centers[count - 1] + 128; + var timeline := vector::::new(); + timeline.resize(length * channels as u64); + for k in 0..count { + val long := pattern[k]; + val n := sizes[long ? 1 : 0]; + val half := n / 2; + val start := centers[k] - half; + for c in 0..channels as u64 { + var spectrum := vector::::new(); + spectrum.resize(half); + for i in 0..half { + if channels == 1 { + spectrum[i] = residues[k][i] as f64; + } else { + # Taken apart, as the magnitude and angle were coupled. + val m := residues[k][2 * i] as f64; + val a := residues[k][2 * i + 1] as f64; + var mag := m; + var ang := a; + if m > 0 { + if a > 0 { ang = m - a; } else { ang = m; mag = m + a; } + } else { + if a > 0 { ang = m + a; } else { ang = m; mag = m - a; } + } + spectrum[i] = c == 0 ? mag : ang; + } + } + val before_short := long && k > 0 && !pattern[k - 1]; + val after_short := long && k + 1 < count && !pattern[k + 1]; + for t in 0..n { + var sum: f64 = 0; + for i in 0..half { + sum += spectrum[i] * math::cos(math::tau / n as f64 * (t as f64 + 0.5 + n as f64 / 4) * (i as f64 + 0.5)); + } + timeline[(start + t) * channels as u64 + c] += sum * window_at(n, t, before_short, after_short); + } + } + } + val first := centers[0]; + val total := centers[count - 1] - first - trimmed; + var expected := vector::::new(); + for f in 0..total { + for c in 0..channels as u64 { + expected.append(timeline[(first + f) * channels as u64 + c] as f32); + } + } + return expected; +} + +# Vorbis's window, at a sample of a block of a size, its slopes short beside a +# short block, as the spec defines it. +def window_at(n: u64, t: u64, before_short: bool, after_short: bool): f64 { + val short: u64 = 64; + val half := n / 2; + var rise_from: u64 = 0; + var rise := half; + if before_short { + rise_from = n / 4 - short / 4; + rise = short / 2; + } + var fall_from := half; + var fall := half; + if after_short { + fall_from = n * 3 / 4 - short / 4; + fall = short / 2; + } + if t < rise_from { + return 0; + } + if t < rise_from + rise { + val s := math::sin(((t - rise_from) as f64 + 0.5) / rise as f64 * math::pi / 2); + return math::sin(math::pi / 2 * s * s); + } + if t < fall_from { + return 1; + } + if t < fall_from + fall { + val s := math::sin(((t - fall_from) as f64 + 0.5) / fall as f64 * math::pi / 2 + math::pi / 2); + return math::sin(math::pi / 2 * s * s); + } + return 0; +} diff --git a/tests/streams.sakura b/tests/streams.sakura new file mode 100644 index 0000000..d06a161 --- /dev/null +++ b/tests/streams.sakura @@ -0,0 +1,196 @@ +#! Contains Ogg Vorbis streams made by a small encoder of the tests' own, and the +#! frames each should decode to, as `spec.sakura` works them out. +#! +#! A stream's setup has a book of two classes and a book of 16 vectors of two +#! dimensions, a floor of type 1 whose posts are both 255, a curve of 1, so each +#! spectrum is its residue, partitions of 8 values, each silent or coded, and +#! blocks of 64 and 256 samples. Two channels are coupled, and coded by a +#! residue of type 2; one is coded by a residue of type 1. + +import std::math; +import malunal::audio; + +# What a stream made by the tests holds. +struct made_stream { + var bytes: vector; + var expected: vector; # The frames it decodes to, a frame's channels together. + var channels: u32; +} + +# The blocks a stream is made of: long or short, in order. +const pattern: bool[9] = [true, true, false, false, true, false, true, true, false]; + +# A coded partition's entries, and whether a partition is coded. +def entry_at(packet: u64, partition: u64, j: u64): u32 { + return ((packet * 7 + partition * 5 + j * 3) % 16) as u32; +} + +def coded(packet: u64, partition: u64): bool { + return (packet + partition) % 3 != 0; +} + +# The values a vector entry stands for: a grid of four from -1.5, twice over. +def entry_value(entry: u32, dimension: u32): f32 { + val index := dimension == 0 ? entry % 4 : (entry / 4) % 4; + return -1.5 + index as f32; +} + +# Makes a stream of one or two channels, `trimmed` frames cut from its end by +# its last page's granule position. +# @param floor_zero Whether its floor says it's of type 0, which isn't read. +def made_vorbis(channels: u32, trimmed: u64, floor_zero: bool = false): made_stream { + val sizes: u64[2] = [64, 256]; + val count := 9u; + + # The headers. + var id := bit_writer::new(); + id.put(1, 8); + id.text("vorbis"); + id.put(0, 32); + id.put(channels, 8); + id.put(48000, 32); + id.put(0, 32); + id.put(0, 32); + id.put(0, 32); + id.put(6 | (8 << 4), 8); + id.put(1, 8); + var comment := bit_writer::new(); + comment.put(3, 8); + comment.text("vorbis"); + comment.put(0, 32); + comment.put(0, 32); + comment.put(1, 8); + var setup := bit_writer::new(); + setup.put(5, 8); + setup.text("vorbis"); + setup.put(1, 8); # two books + setup.put(0x564342, 24); # book 0: the classes + setup.put(1, 16); + setup.put(2, 24); + setup.put(0, 2); + setup.put(0, 5); + setup.put(0, 5); + setup.put(0, 4); + setup.put(0x564342, 24); # book 1: the vectors + setup.put(2, 16); + setup.put(16, 24); + setup.put(0, 2); + for _ in 0..16 { + setup.put(3, 5); + } + setup.put(1, 4); + setup.put(0x80000000 | (787 << 21) | 3, 32); # minimum -1.5 + setup.put((788 << 21) | 1, 32); # delta 1 + setup.put(1, 4); + setup.put(0, 1); + for v in 0u..4u { + setup.put(v as u32, 2); + } + setup.put(0, 6); # one time transform + setup.put(0, 16); + setup.put(0, 6); # one floor + setup.put(floor_zero ? 0 : 1, 16); + setup.put(0, 5); + setup.put(0, 2); + setup.put(7, 4); + setup.put(0, 6); # one residue + setup.put(channels == 2 ? 2 : 1, 16); + setup.put(0, 24); + setup.put(channels * 128, 24); + setup.put(7, 24); + setup.put(1, 6); + setup.put(0, 8); + setup.put(0, 4); + setup.put(1, 4); + setup.put(1, 8); + setup.put(0, 6); # one mapping + setup.put(0, 16); + setup.put(0, 1); + if channels == 2 { + setup.put(1, 1); + setup.put(0, 8); + setup.put(0, 1); + setup.put(1, 1); + } else { + setup.put(0, 1); + } + setup.put(0, 2); + setup.put(0, 24); + setup.put(1, 6); # two modes + for long in 0u..2u { + setup.put(long as u32, 1); + setup.put(0, 32); + setup.put(0, 8); + } + setup.put(1, 1); + + # The packets, and the residue each codes. + var packets := vector::>::new(); + var residues := vector::>::new(); + for k in 0..count { + val long := pattern[k]; + val half := sizes[long ? 1 : 0] / 2; + var w := bit_writer::new(); + w.put(0, 1); + w.put(long ? 1 : 0, 1); + if long { + w.put(k == 0 || pattern[k - 1] ? 1 : 0, 1); + w.put(k + 1 == count || pattern[k + 1] ? 1 : 0, 1); + } + for _ in 0..channels { + w.put(1, 1); + w.put(255, 8); + w.put(255, 8); + } + val size := half * channels as u64; + var residue := vector::::new(); + residue.resize(size); + for p in 0..size / 8 { + val on := coded(k, p); + w.code(on ? 1 : 0, 1); + continue if !on; + for j in 0u..4u { + val e := entry_at(k, p, j); + w.code(e, 4); + residue[p * 8 + j * 2] = entry_value(e, 0); + residue[p * 8 + j * 2 + 1] = entry_value(e, 1); + } + } + packets.append(w.finish()); + residues.append(move(residue)); + } + + var expected := defined_frames(channels, trimmed, &residues); + + # The pages: the identification alone, the comment and setup, then the audio + # three packets to a page, each page's granule position the frames decoded + # once its last packet is. + var bytes := vector::::new(); + var sequence: u32 = 0; + val ident := id.finish(); + page_of(&mut bytes, 2, 0, sequence, ident.view(), span::::empty()); + sequence++; + val comments := comment.finish(); + val setups := setup.finish(); + page_of(&mut bytes, 0, 0, sequence, comments.view(), setups.view()); + sequence++; + var decoded: u64 = 0; + var k: u64 = 0; + while k < count { + val end := math::min(k + 3, count); + var body := vector::::new(); + var lacing := vector::::new(); + for j in k..end { + if j > 0 { + decoded += sizes[pattern[j - 1] ? 1 : 0] / 4 + sizes[pattern[j] ? 1 : 0] / 4; + } + lace(&mut lacing, packets[j].length); + body.extend(packets[j].view()); + } + val last := end == count; + page_laced(&mut bytes, last ? 4 : 0, last ? decoded - trimmed : decoded, sequence, lacing.view(), body.view()); + sequence++; + k = end; + } + return made_stream{ bytes = move(bytes), expected = move(expected), channels = channels }; +} diff --git a/tests/support.sakura b/tests/support.sakura new file mode 100644 index 0000000..14ad742 --- /dev/null +++ b/tests/support.sakura @@ -0,0 +1,24 @@ +#! Contains what the tests of `audio` share: whether a result failed as it +#! should, and how far one run of samples strays from another. The Ogg Vorbis +#! streams they decode are made in `streams.sakura`. + +import std::math; +import malunal::audio; + +# Whether a result failed with an error. +def fails(made: result, why: audio_error): bool { + if made is error(e) { + return e == why; + } + return false; +} +# How far one run of samples strays from another at most, or 1000 where they're +# of other lengths. +def apart(a: span, b: span): f32 { + return 1000 if a.length != b.length; + var most: f32 = 0; + for i in 0..a.length { + most = math::max(most, math::abs(a[i] - b[i])); + } + return most; +} diff --git a/tests/vorbis.sakura b/tests/vorbis.sakura new file mode 100644 index 0000000..7e6ef40 --- /dev/null +++ b/tests/vorbis.sakura @@ -0,0 +1,74 @@ +#! Contains the tests of Ogg Vorbis: streams the tests make decoded to the +#! frames the spec defines, coupled channels and single, short blocks and long, +#! cut where their granule positions say; read in pieces and from the start +#! again; and broken streams refused. +#! +#! Real encoders' files were checked apart from these: 63 of them, from 1 KB to +#! 9 MB, decoded as libvorbis decodes them, every sample within 5e-7. + +import std::testing; +import malunal::audio; + +@test def decodes_two_coupled_channels_as_the_spec_defines(t: &mut tester): void { + val made := made_vorbis(2, 0); + val read := audio::decode(made.bytes.view()) else (e) { t.expects(false); return; }; + t.expects(read.rate == 48000 && read.channels == 2); + t.expects(read.frames == made.expected.length / 2); + t.expects(apart(read.samples.view(), made.expected.view()) < 1e-4); +} + +@test def decodes_one_channel_as_the_spec_defines(t: &mut tester): void { + val made := made_vorbis(1, 0); + val read := audio::decode(made.bytes.view()) else (e) { t.expects(false); return; }; + t.expects(read.channels == 1 && read.frames == made.expected.length); + t.expects(apart(read.samples.view(), made.expected.view()) < 1e-4); +} + +@test def cuts_the_frames_its_last_granule_position_leaves_out(t: &mut tester): void { + val made := made_vorbis(2, 37); + val read := audio::decode(made.bytes.view()) else (e) { t.expects(false); return; }; + t.expects(read.frames == made.expected.length / 2); + t.expects(apart(read.samples.view(), made.expected.view()) < 1e-4); + val opened := audio::vorbis::decoder::open(made.bytes.view()) else (e) { t.expects(false); return; }; + t.expects(opened.frames == read.frames && opened.rate == 48000 && opened.channels == 2); +} + +@test def reads_in_any_pieces_and_from_the_start_again(t: &mut tester): void { + val made := made_vorbis(2, 5); + var reading := audio::vorbis::decoder::open(made.bytes.view()) else (e) { t.expects(false); return; }; + for _ in 0..2 { + var all := vector::::new(); + var piece := vector::::new(); + piece.resize(2 * 13); + while true { + val count := reading.read(piece.slice()) else (e) { t.expects(false); return; }; + break if count == 0; + for i in 0..count * 2 { + all.append(piece[i]); + } + } + t.expects(apart(all.view(), made.expected.view()) < 1e-4); + reading.rewind(); + } +} + +@test def refuses_broken_streams(t: &mut tester): void { + # A byte of a page changed, so its CRC is wrong. + var changed := made_vorbis(1, 0); + changed.bytes[changed.bytes.length - 3] ^= 0x10; + t.expects(fails(audio::decode(changed.bytes.view()), audio_error::malformed)); + + # Cut short, partway through its last page. + var cut := made_vorbis(1, 0); + cut.bytes.truncate(); + t.expects(fails(audio::decode(cut.bytes.view()), audio_error::malformed)); + + # A floor of type 0. + val old := made_vorbis(1, 0, true); + t.expects(fails(audio::decode(old.bytes.view()), audio_error::unsupported)); + + # An Ogg file of something besides Vorbis. + var other := vector::::new(); + page_of(&mut other, 2, 0, 0, "\x80theora", span::::empty()); + t.expects(fails(audio::decode(other.view()), audio_error::unrecognized)); +} diff --git a/tests/wav.sakura b/tests/wav.sakura new file mode 100644 index 0000000..5659d0a --- /dev/null +++ b/tests/wav.sakura @@ -0,0 +1,134 @@ +#! Contains the tests of WAV: sounds written and read back, as integers and as +#! floats, files of each sample size, more channels mixed down, a `data` chunk +#! longer than the file, and what isn't read. + +import std::io; +import std::math; +import std::testing; +import malunal::audio; + +# A WAV file of samples given as their bytes. +def wav_of(tag: u16, channels: u32, rate: u32, bits: u32, data: span, extensible: bool = false, mask: u32 = 0): vector { + var out := vector::::new(); + val fmt_size: u32 = extensible ? 40 : 16; + text(&mut out, "RIFF"); + number(&mut out, 4 + 8 + fmt_size + 8 + data.length as u32, 4); + text(&mut out, "WAVEfmt "); + number(&mut out, fmt_size, 4); + number(&mut out, extensible ? 0xFFFE : tag as u32, 2); + number(&mut out, channels, 2); + number(&mut out, rate, 4); + number(&mut out, rate * channels * bits / 8, 4); + number(&mut out, channels * bits / 8, 2); + number(&mut out, bits, 2); + if extensible { + number(&mut out, 22, 2); + number(&mut out, bits, 2); + number(&mut out, mask, 4); + number(&mut out, tag as u32, 2); + for b in [0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71] { + out.append(b as u8); + } + } + text(&mut out, "data"); + number(&mut out, data.length as u32, 4); + out.extend(data); + return out; +} + +def text(out: &mut vector, value: strview): void { + for c in value { + out.append(c as u8); + } +} + +def number(out: &mut vector, value: u32, bytes: u32): void { + for i in 0..bytes { + out.append((value >> (i * 8)) as u8); + } +} + +@test def writes_and_reads_sounds_back(t: &mut tester): void { + val tone := sound::tone(440, 0.05, 44100); + val floats := audio::wav::encode(&tone, true) else (_) { t.expects(false); return; }; + val back := audio::decode(floats.view()) else (_) { t.expects(false); return; }; + t.expects(back.rate == 44100 && back.channels == 1 && back.frames == tone.frames); + t.expects(apart(back.samples.view(), tone.samples.view()) == 0); + + val whole := audio::wav::encode(&tone) else (_) { t.expects(false); return; }; + t.expects(whole.length == 44 + tone.frames * 2); + val rounded := audio::decode(whole.view()) else (_) { t.expects(false); return; }; + t.expects(apart(rounded.samples.view(), tone.samples.view()) < 1.0 / 32767); + + # Through a file. + audio::save(&tone, ".blossom/written.wav") else (_) { t.expects(false); return; }; + val loaded := audio::load(".blossom/written.wav") else (_) { t.expects(false); return; }; + t.expects(loaded.frames == tone.frames); + t.expects(fails_writing(audio::save(&tone, ".blossom/written.ogg"), audio_error::unrecognized)); +} + +@test def reads_each_sample_size(t: &mut tester): void { + # 8 bits, unsigned: 0, 255, and 128 are -1, nearly 1, and 0. + val eight_data: u8[3] = [0, 255, 128]; + val eight := wav_of(1, 1, 8000, 8, eight_data[:]); + val read8 := audio::decode(eight.view()) else (_) { t.expects(false); return; }; + t.expects(read8.samples[0] == -1 && math::abs(read8.samples[1] - 127.0 / 128) < 1e-7 && read8.samples[2] == 0); + # 16 bits: -32768 and 16384. + val sixteen_data: u8[4] = [0x00, 0x80, 0x00, 0x40]; + val sixteen := wav_of(1, 2, 8000, 16, sixteen_data[:]); + val read16 := audio::decode(sixteen.view()) else (_) { t.expects(false); return; }; + t.expects(read16.channels == 2 && read16.samples[0] == -1 && read16.samples[1] == 0.5); + # 24 bits: -8388608 and 4194304. + val twenty_four_data: u8[6] = [0x00, 0x00, 0x80, 0x00, 0x00, 0x40]; + val twenty_four := wav_of(1, 1, 8000, 24, twenty_four_data[:]); + val read24 := audio::decode(twenty_four.view()) else (_) { t.expects(false); return; }; + t.expects(read24.samples[0] == -1 && read24.samples[1] == 0.5); + # 32 bits, in an extensible header. + val thirty_two_data: u8[4] = [0x00, 0x00, 0x00, 0xC0]; + val thirty_two := wav_of(1, 1, 8000, 32, thirty_two_data[:], true, 4); + val read32 := audio::decode(thirty_two.view()) else (_) { t.expects(false); return; }; + t.expects(read32.samples[0] == -0.5); + # 64-bit floats: 0.25. + val doubles_data: u8[8] = [0, 0, 0, 0, 0, 0, 0xD0, 0x3F]; + val doubles := wav_of(3, 1, 8000, 64, doubles_data[:]); + val read64 := audio::decode(doubles.view()) else (_) { t.expects(false); return; }; + t.expects(read64.samples[0] == 0.25); +} + +@test def mixes_more_channels_down_as_their_mask_places_them(t: &mut tester): void { + # Four channels, front left and right and back left and right, as the mask + # says: a sample in the back left is heard in the left alone. + val data: u8[8] = [0, 0, 0, 0, 0x00, 0x40, 0, 0]; + val quad := wav_of(1, 4, 8000, 16, data[:], true, 0x33); + val read := audio::decode(quad.view()) else (_) { t.expects(false); return; }; + t.expects(read.channels == 2 && read.frames == 1); + t.expects(read.samples[0] > 0.2 && read.samples[1] == 0); +} + +@test def reads_a_data_chunk_longer_than_the_file_as_far_as_it_goes(t: &mut tester): void { + val cut_data: u8[6] = [0x00, 0x40, 0x00, 0x40, 0x00, 0x40]; + var cut := wav_of(1, 1, 8000, 16, cut_data[:]); + cut.truncate(); + val read := audio::decode(cut.view()) else (_) { t.expects(false); return; }; + t.expects(read.frames == 2); +} + +@test def refuses_what_it_does_not_read(t: &mut tester): void { + # ADPCM, and a file of no `fmt `. + val zeros: u8[3] = [0, 0, 0]; + val adpcm := wav_of(2, 1, 8000, 4, zeros[0:2]); + t.expects(fails(audio::decode(adpcm.view()), audio_error::unsupported)); + var headless := vector::::new(); + text(&mut headless, "RIFF\x0C\x00\x00\x00WAVEdata\x00\x00\x00\x00"); + t.expects(fails(audio::decode(headless.view()), audio_error::malformed)); + val wrong := wav_of(1, 2, 8000, 12, zeros[:]); + t.expects(fails(audio::decode(wrong.view()), audio_error::unsupported)); +} + +# Whether writing failed with an error. +def fails_writing(made: result, why: audio_error): bool { + if made is error(e) { + return e == why; + } + return false; +} diff --git a/tools/bench.sakura b/tools/bench.sakura new file mode 100644 index 0000000..8f11649 --- /dev/null +++ b/tools/bench.sakura @@ -0,0 +1,80 @@ +#! Times what `malunal::audio` does most: mixing voices, at the rate and at +#! another, panned and ramped, as a game's are; WAV written and read; and an +#! Ogg Vorbis file, given as its argument, decoded whole and streamed. Each is +#! the best of three, as a multiple of real time: how many seconds of sound a +#! second of work makes. +#! +#! `blossom build`, then run `malunal.audio.bench`, as an executable: the VM's +#! times aren't the program's. + +import system; +import std::io; +import std::time; +import malunal::audio; + +# The best of three runs of something, in seconds. +def best(run: def(): void): f64 { + var fastest: f64 = 1e9; + for _ in 0..3 { + val started := time::instant::now(); + run(); + val took := started.elapsed().div(&time::seconds(1)); + fastest = took < fastest ? took : fastest; + } + return fastest; +} + +def report(what: strview, seconds_of_sound: f64, took: f64): void { + io::println($"{what}: {(took * 1000) as u64} ms for {seconds_of_sound as u64} s, {(seconds_of_sound / took) as u64}x real time"); +} + +def main(args: span): void { + # 32 voices of tones, half at 44.1 kHz resampled to 48 kHz, each panned + # across, for 10 seconds, mixed 480 frames at a time, as a device takes them. + val voices: u32 = 32; + val mixing := best(def(): void { + var m := mixer::new(48000); + val near := m.add(sound::tone(440, 1, 48000, 0.1)); + val far := m.add(sound::tone(330, 1, 44100, 0.1)); + for v in 0..voices { + _ = m.play(v % 2 == 0 ? near : far, playback{ looping = true, pan = (v as f32 / voices as f32) * 2 - 1 }); + } + var frames := vector::::new(); + frames.resize(480 * 2); + for block in 0..1000 { + if block % 10 == 0 { + m.set_master(block % 20 == 0 ? 1 : 0.9); + } + m.mix(frames.slice()); + } + }); + report($"mixing {voices} voices", 10, mixing); + + val tone := sound::tone(440, 10, 48000); + val wav := best(def(): void { + val bytes := audio::wav::encode(&tone) else (_) { return; }; + _ = audio::decode(bytes.view()); + }); + report("WAV, 16-bit, written and read", 10, wav); + + return if args.length == 0; + val named := path::parse(args[0]) else (_) { exit(2); }; + val file := io::read_file(&named) else (e) { io::println($"unreadable: {e}"); exit(1); }; + val length := audio::vorbis::decoder::open(file.view()) else (e) { io::println($"not Ogg Vorbis: {e}"); exit(1); }; + val seconds := length.frames as f64 / length.rate as f64; + val whole := best(def(): void { + _ = audio::decode(file.view()); + }); + report("Ogg Vorbis decoded whole", seconds, whole); + val streamed := best(def(): void { + var m := mixer::new(48000); + val id := m.add_streamed(file.view()) else (_) { return; }; + val v := m.play(id); + var frames := vector::::new(); + frames.resize(480 * 2); + while m.playing(v) { + m.mix(frames.slice()); + } + }); + report("Ogg Vorbis streamed, resampled to 48 kHz", seconds, streamed); +}