From 6a2f64e904596000f343782441a0e4b8a15f79af 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 | 165 +++++ audio/audio.sakura | 178 +++++ audio/effects.sakura | 255 +++++++ audio/elsewhere.sakura | 16 + audio/flac/flac.sakura | 353 ++++++++++ audio/flac/frames.sakura | 339 +++++++++ audio/formats.sakura | 105 +++ audio/mixer.sakura | 321 +++++++++ audio/mixing.sakura | 400 +++++++++++ audio/mp3/layer3.sakura | 1028 ++++++++++++++++++++++++++++ audio/mp3/mp3.sakura | 275 ++++++++ audio/mp3/tables.sakura | 289 ++++++++ audio/ogg/ogg.sakura | 296 ++++++++ audio/opus/celt.sakura | 585 ++++++++++++++++ audio/opus/celt_alloc.sakura | 352 ++++++++++ audio/opus/celt_bands.sakura | 934 +++++++++++++++++++++++++ audio/opus/celt_mdct.sakura | 315 +++++++++ audio/opus/celt_tables.sakura | 732 ++++++++++++++++++++ audio/opus/opus.sakura | 687 +++++++++++++++++++ audio/opus/range.sakura | 207 ++++++ audio/opus/silk.sakura | 1216 +++++++++++++++++++++++++++++++++ audio/opus/silk_math.sakura | 145 ++++ audio/opus/silk_tables.sakura | 659 ++++++++++++++++++ audio/output.sakura | 177 +++++ audio/streams.sakura | 94 +++ audio/tags.sakura | 100 +++ audio/voices.sakura | 245 +++++++ 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/residues.sakura | 183 +++++ audio/vorbis/setup.sakura | 252 +++++++ audio/vorbis/vorbis.sakura | 271 ++++++++ audio/wasapi.sakura | 397 +++++++++++ audio/wav/wav.sakura | 236 +++++++ audio/windows/avrt.sakura | 9 + audio/windows/kernel32.sakura | 8 + audio/windows/ole32.sakura | 24 + blossomfile | 60 ++ tests/effects.sakura | 100 +++ tests/files/tone.mp3 | Bin 0 -> 18853 bytes tests/files/tone.opus | Bin 0 -> 26433 bytes tests/files/tone16.opus | Bin 0 -> 2071 bytes tests/files/tone22.mp3 | Bin 0 -> 4511 bytes tests/files/tone_mono.opus | Bin 0 -> 3874 bytes tests/flac.sakura | 104 +++ tests/flacs.sakura | 423 ++++++++++++ tests/main.sakura | 10 + tests/mixer.sakura | 230 +++++++ tests/mp3.sakura | 86 +++ tests/opus.sakura | 186 +++++ tests/output.sakura | 65 ++ tests/pages.sakura | 108 +++ tests/sounds.sakura | 60 ++ tests/spec.sakura | 104 +++ tests/streams.sakura | 204 ++++++ tests/support.sakura | 24 + tests/vorbis.sakura | 100 +++ tests/wav.sakura | 145 ++++ tools/bench.sakura | 82 +++ 64 files changed, 14785 insertions(+) create mode 100644 .editorconfig create mode 100644 .gitignore create mode 100644 README.md create mode 100644 audio/audio.sakura create mode 100644 audio/effects.sakura create mode 100644 audio/elsewhere.sakura create mode 100644 audio/flac/flac.sakura create mode 100644 audio/flac/frames.sakura create mode 100644 audio/formats.sakura create mode 100644 audio/mixer.sakura create mode 100644 audio/mixing.sakura create mode 100644 audio/mp3/layer3.sakura create mode 100644 audio/mp3/mp3.sakura create mode 100644 audio/mp3/tables.sakura create mode 100644 audio/ogg/ogg.sakura create mode 100644 audio/opus/celt.sakura create mode 100644 audio/opus/celt_alloc.sakura create mode 100644 audio/opus/celt_bands.sakura create mode 100644 audio/opus/celt_mdct.sakura create mode 100644 audio/opus/celt_tables.sakura create mode 100644 audio/opus/opus.sakura create mode 100644 audio/opus/range.sakura create mode 100644 audio/opus/silk.sakura create mode 100644 audio/opus/silk_math.sakura create mode 100644 audio/opus/silk_tables.sakura create mode 100644 audio/output.sakura create mode 100644 audio/streams.sakura create mode 100644 audio/tags.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/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/effects.sakura create mode 100644 tests/files/tone.mp3 create mode 100644 tests/files/tone.opus create mode 100644 tests/files/tone16.opus create mode 100644 tests/files/tone22.mp3 create mode 100644 tests/files/tone_mono.opus create mode 100644 tests/flac.sakura create mode 100644 tests/flacs.sakura create mode 100644 tests/main.sakura create mode 100644 tests/mixer.sakura create mode 100644 tests/mp3.sakura create mode 100644 tests/opus.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..f246bcd --- /dev/null +++ b/README.md @@ -0,0 +1,165 @@ +# audio +Sound read from WAV, Ogg Vorbis, FLAC, MP3, and Ogg Opus, mixed, and played: a `mixer` of sounds and the voices playing them, filtered, sent to buses of reverb, and limited, and an `audio_output` playing what it mixes to a device the system plays to, on a thread of its own. Long compressed files are streamed, decoded as they play, and sought anywhere. It's Sakura's, built with [blossom](https://git.malunal.studio/sakura/blossom), reads std's `containers`, `io`, `math`, and `thread`, and plays through WASAPI on Windows. Its decoders, its mixer, its effects, and its output are its own. + +```sakura +import malunal::audio; + +var out := audio_output::open() else (e) { ... }; # the default device, followed as it changes +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 its file, decoded as it plays + +_ = out.play(coin, playback{ gain = 0.8, pan = -0.3, low_pass = 2000 }); +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_bus_effects(2, bus_effects{ reverb = reverb{ wet = 0.4, room = 0.8 } }); + held.value().set_limiter(limiter{ on = true }); + held.value().seek(playing, 30) else (e) { ... }; # half a minute in +} +out.stop(playing, 1.5); # faded out over 1.5 s +``` +`audio::decode(bytes)` reads bytes already in memory in any format, and `audio::format_of(bytes)` says which, by their first few. `audio::save` writes a WAV file, of 16-bit samples or floats. `stream::open(bytes)` reads a compressed file's frames as it's asked for them, and from anywhere it's sought, which the mixer does for a streamed sound; each format's `decoder` does so for its own. `audio_output::devices()` lists the devices the system plays to, and `audio_output::open(latency, name)` opens one of them by its name. `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`, `loop_range`, `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` | +| `streams.sakura` | `stream`: a compressed file of any format read as it's asked, rewound, and sought | +| `tags.sakura` | Loop points of the comments of Vorbis, FLAC, and Opus, and ID3v2 tags passed | +| `mixer.sakura` | `mixer`, `sound_id`, `voice`, and `playback`: sounds held, decoded or streamed | +| `voices.sakura` | Voices played, changed, sought, paused, and stopped; buses, their effects, the master, and the limiter | +| `mixing.sakura` | Voices mixed: resampled, filtered, panned, ramped, sent, and streams decoded as they play | +| `effects.sakura` | `bus_effects`, `reverb`, and `limiter`: biquad filters, Freeverb, and the look-ahead limiter | +| `output.sakura` | `audio_output` and `audio_device`: the mixer shared with the device's thread, or headless | +| `wasapi.sakura` | The device on Windows: WASAPI's shared mode, through COM's tables, chosen by name or following the default | +| `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, `smpl`'s loop read and written, and `encode` | + +`ogg/`, `audio::ogg`, which Vorbis and Opus share: + +| Path | Holds | +|---|---| +| `ogg.sakura` | Ogg's pages, checked by their CRCs, one stream's packets, and pages found by their granule positions | + +`vorbis/`, `audio::vorbis`: + +| Path | Holds | +|---|---| +| `vorbis.sakura` | `decoder`: the headers, frames read and timed by granule positions, seeking, and `decode` | +| `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 | + +`flac/`, `audio::flac`: + +| Path | Holds | +|---|---| +| `flac.sakura` | `decoder`: the metadata, frames read, seeking by the seek table or by searching, and `decode` | +| `frames.sakura` | A frame: its header and CRCs, each subframe, its residual, and side channels made whole | + +`mp3/`, `audio::mp3`: + +| Path | Holds | +|---|---| +| `mp3.sakura` | `decoder`: frames found, Xing and LAME's gaps cut, seeking, and `decode` | +| `layer3.sakura` | A frame of Layer III: side information, the reservoir, Huffman, stereo, the IMDCT, and synthesis | +| `tables.sakura` | Layer III's tables, as minimp3 keeps them | + +`opus/`, `audio::opus`, a port of libopus's decoder, whose license is in `opus.sakura`: + +| Path | Holds | +|---|---| +| `opus.sakura` | `decoder`: the Ogg Opus headers, packets' frames, the move between SILK, hybrid, and CELT, seeking, and `decode` | +| `range.sakura` | The range decoder every frame is coded with | +| `celt.sakura` | CELT's decoder: energies, the post-filter, and de-emphasis | +| `celt_alloc.sakura` | CELT's bit allocation | +| `celt_bands.sakura` | CELT's bands: pulse vectors, splits, stereo, folding, and anti-collapse | +| `celt_mdct.sakura` | CELT's inverse MDCT, by a mixed-radix FFT | +| `celt_tables.sakura` | CELT's tables, generated from libopus's | +| `silk.sakura` | SILK's decoder: side information, pulses, NLSFs to LPC, LTP and LPC synthesis, stereo, and the resampler | +| `silk_math.sakura` | SILK's fixed-point arithmetic | +| `silk_tables.sakura` | SILK's tables, generated from libopus's | + +## 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. A `smpl` chunk's first loop is where a voice playing it loops. ADPCM, A-law, and µ-law are `unsupported`, and other chunks 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. +- **FLAC**: every stream, of one to eight channels, of 4 to 32 bits a sample, at any rate, its blocks fixed or varying in size, each subframe constant, verbatim, of a fixed predictor, or of linear prediction, its residual Rice-coded or raw. Each frame's header is checked by its CRC-8, and the frame by its CRC-16. An ID3v2 tag before it is passed. FLAC within Ogg isn't read. +- **MP3**: MPEG-1, 2, and 2.5's Layer III, of one channel or two, of any bit rate but the free format, as minimp3, which is in the public domain, decodes it. A Xing or LAME frame says how much the encoder added before the sound and after, which is cut, as FFmpeg cuts it, so a stream gives the frames it was encoded from. An ID3v2 tag before it is passed. Layers I and II aren't read. +- **Ogg Opus**: every Opus stream of one or two channels, of mapping family 0, decoded as libopus's float build decodes it: SILK's frames, of speech, at 8, 12, or 16 kHz, resampled to 48 kHz as libopus resamples them; CELT's, of music, of 2.5 to 20 ms; hybrid frames of both; frames of 10 to 120 ms a packet; and the move between them, by CELT's redundant frames, or a crossfade. The head's pre-skip is cut from the start, and the end where the last page's granule position says, and its output gain applied. A sound of Opus is always of 48 kHz. + +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 Vorbis's and FLAC's by their orders for their counts. + +Where a sound loops is its `loop_points`: a WAV file's `smpl` chunk, or the comments of Vorbis, FLAC, and Opus, `LOOPSTART` and `LOOPLENGTH` or `LOOPEND`, in frames, in any case, as RPG Maker and the tools after it write them. Of a file that says nothing, all of it loops. + +## Mixing +- **Sounds** are held by a mixer and named by a `sound_id`: decoded, by `add`, or kept as their file's 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; faded in over some seconds; filtered, low pass and high pass, as through a wall or a radio; sent, at some gain, to another bus too, as to one of reverb; and waiting some seconds before it's heard, as a far sound is. `change`, `set_gain`, `set_pan`, `set_pitch`, and `pause` change one as it plays, `seek` moves it to anywhere in its sound, and `stop` ends it at once or faded out. A voice `silent` plays on unheard, its place moving, as one left out of too many does. 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. +- **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 loop's end into its start; a streamed one loops by seeking its stream, seamlessly. +- **Seeking**: a voice is sought by seconds, decoded or streamed, exactly as it plays from its start: a streamed Vorbis stream by halving its pages, FLAC by its seek table, or by searching its frames' headers, and MP3 by its frames, found as it's opened. Opus is sought by halving its pages too, then decoded from half a second before, so its decoder settles, to within a few ten-thousandths of decoding straight through. +- **Effects**: each bus has `bus_effects`, a low and a high pass, and reverb, as Jezar's Freeverb, which is in the public domain, makes it, of eight combs and four all-passes a side, its room's size, damping, and width as asked; its echoes go on after what feeds it ends. Filters are Butterworth's, of two poles, as Robert Bristow-Johnson's cookbook makes them. The mix has a limiter, off at first, which, on, looks ahead its `lookahead`, 1.5 ms, and turns the mix down before each peak past its `ceiling` so that nothing passes it, then up again over its `release`; the mix is that late. + +## The output +`audio_output::open` opens a device, at the rate the system mixes it 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 a WASAPI 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. `devices` lists the endpoints plugged in and on, each by its friendly name and id, and which is the default; `open` takes either, or none, for the default, which it then follows: every quarter second of what it plays, it asks which is the default, and moves to another the system made so. A device that stops, as unplugged headphones do, is let go and opened again as soon as it can be; the voices wait meanwhile. The thread reads no clock, telling time by the frames it plays. 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`, given compressed files, here on a Ryzen 9 9950X3D, the best of three: + +| What | Real time | +|---|---| +| 32 voices mixed, half resampled, panned, for 10 s at 48 kHz | 109× | +| WAV of 16 bits, 10 s, written and read | 2200× | +| Ogg Vorbis decoded whole, 68 s of 44.1 kHz stereo music | 700× | +| FLAC decoded whole, 31 files of real encoders | 900× | +| MP3 decoded whole, 127 files of every rate of MPEG-1, 2, and 2.5 | 760× | +| Opus decoded whole, RFC 8251's test vectors, of CELT, hybrid, and SILK | 390× to 660× | +| Opus streamed, at 48 kHz | 355× to 560× | + +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, refused where compressed, and its `smpl` loop kept; the mixer's voices at their gains and pans, ramped, ended and looped at their ends and their loop points, resampled and pitched, on buses, faded, sought, delayed, played silent, and streamed, exactly as the sound decoded whole plays; voices and buses filtered, sent to reverb whose echoes go on and die away, and the limiter holding the mix at its ceiling; and a headless output mixed as asked, the default device, where there is one, played to silently until it took 2000 frames, and the system's devices listed and one opened by its name. + +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; sought anywhere, the same; its comments' loop points read; and changed, cut short, of floor 0, or not Vorbis, refused. FLAC's streams are made by an encoder in `tests/flacs.sakura`, of every kind of subframe, channel assignment, and residual, of 24 bits, wasted bits, and blocks of every size, and of six channels, each decoded to exactly the samples it was made of, sought by its seek table and by searching. MP3 and Opus are read of `tests/files/`, tones encoded by LAME and libopus, through FFmpeg, of sines: each near its sines, MP3 sought exactly, and Opus, made again of its packets a page each, sought by its pages, its gain and its comments' loop points read, and what isn't read 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. +- **FLAC**: 31 files of real encoders, each decoded to the samples its STREAMINFO's MD5 is of. +- **MP3**: 73 files of real encoders, and 54 LAME made of every rate of MPEG-1, 2, and 2.5, of one channel and two, of 16 to 160 kilobits a second, each decoded to as many frames as FFmpeg decodes it to, every sample within 6.4e-6 of FFmpeg's. +- **Opus**: RFC 8251's 12 test vectors, decoded in stereo within one step of 16 bits of libopus's own output, those of SILK alone exactly; and in one channel, 63 dB or nearer to libopus's mix of them; all 24 decoded by a checked build, faulting at none. CELT's frames match FFmpeg's within 1.5e-7. +- **Fuzzing**: a checked build was given 6300 Ogg Vorbis 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 +- Output on Linux, in Phase 4. +- Opus's concealment: a lost or empty frame decodes as silence, rather than carrying on what came before as libopus does, and a frame's redundant copy, kept for loss, is passed over. Streams of more than two channels, of mapping families 1 and 255, aren't read. +- Chained streams of Ogg, FLAC within Ogg, MP3's free format, and Layers I and II. diff --git a/audio/audio.sakura b/audio/audio.sakura new file mode 100644 index 0000000..bcf0a63 --- /dev/null +++ b/audio/audio.sakura @@ -0,0 +1,178 @@ +#! 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. +} + +#! Where a looping voice of a sound goes back to, and from where, in frames, as +#! its file may say: from `end`, or the sound's end where it's 0, back to +#! `start`. A voice plays from the sound's start the first time, so music +#! plays its introduction once. +pub struct loop_range { + pub var start: u64; + pub var end: u64; +} + +#! 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. + pub var loop_points: loop_range; #! Where a looping voice goes back to, and from where, as its file said; all of it at first. +} + +#! 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], + }; +} + +#! Where a channel is heard from, of a sound of more than two whose file says +#! nothing of where, in the order WAV's `WAVE_FORMAT_EXTENSIBLE` places them by +#! default, which FLAC's and Opus's of up to eight follow: front left and +#! right, center, the low frequencies, back left and right, then side left and +#! right; of seven, the back's center before the sides. +#! @param channels How many channels, from 3 to 8. +#! @param channel Which of them. +#! @returns Where it's heard from. +pub def standard_speaker(channels: u32, channel: u32): speaker { + 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]; + if channels == 4 { + val quad: speaker[4] = [speaker::front_left, speaker::front_right, speaker::back_left, speaker::back_right]; + return quad[channel as u64]; + } + if channels == 5 { + val five: speaker[5] = [speaker::front_left, speaker::front_right, speaker::center, speaker::back_left, speaker::back_right]; + return five[channel as u64]; + } + return seven[channel as u64] if channels == 7; + return eight[channel as u64]; +} + +#! 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/effects.sakura b/audio/effects.sakura new file mode 100644 index 0000000..9f53fb2 --- /dev/null +++ b/audio/effects.sakura @@ -0,0 +1,255 @@ +#! Contains the effects a mixer puts on what it mixes: filters, of a voice or +#! of a bus, low and high pass; reverb, of a bus, as Jezar's Freeverb, which +#! is in the public domain, makes it, of a room of eight combs and four +#! all-passes each side; and the limiter on the mix, which looks ahead so far +#! that no peak passes its ceiling. + +import std::math; +module malunal::audio; + + +#! The effects on a bus, put on what its voices mix into it before its gain. +pub struct bus_effects { + pub var low_pass: f32 = 0; #! The frequency, in hertz, above which it's quieter, as one hears through a wall; 0, none. + pub var high_pass: f32 = 0; #! The frequency below which it's quieter, as a radio sounds; 0, none. + pub var reverb: reverb; #! Reverb, as of a room it's heard in; none at first. +} + +#! Reverb, as of the room a sound is heard in. +pub struct reverb { + pub var wet: f32 = 0; #! How much of the room's echoes are heard; 0, none. + pub var dry: f32 = 1; #! How much of what's mixed is heard as it is. + pub var room: f32 = 0.5; #! How large the room, from 0 to 1, which its echoes take longer to die in. + pub var damping: f32 = 0.5; #! How much its walls soften the echoes' highs, from 0 to 1. + pub var width: f32 = 1; #! How far apart its echoes are, left and right, from 0, the same, to 1. +} + +#! The limiter on a mixer's mix: where it's `on`, the mix is turned down ahead +#! of each peak past `ceiling` so the peak reaches it and no further, and up +#! again over `release` seconds, all `lookahead` seconds late. +pub struct limiter { + pub var on: bool = false; + pub var ceiling: f32 = 0.98; #! The highest a sample of the mix reaches. + pub var release: f32 = 0.1; #! Seconds it takes to come most of the way back up. + pub var lookahead: f32 = 0.0015; #! Seconds it sees ahead, by which the mix is late. +} + +# A biquad filter of one channel, as Robert Bristow-Johnson's cookbook makes +# them, of the frequency it was made for, and its state. +struct biquad { + var b0: f32; + var b1: f32; + var b2: f32; + var a1: f32; + var a2: f32; + var z1: f32; + var z2: f32; + var made_for: f32; +} + +# Makes a filter of two poles, Butterworth's, low or high pass, at a frequency +# of a rate, keeping its state. +def biquad::tune(&mut this, frequency: f32, rate: u32, high: bool): void { + return if frequency == this.made_for; + this.made_for = frequency; + val f := math::clamp(frequency, 10 as f32, rate as f32 * 0.49); + val w := math::tau * f as f64 / rate as f64; + val alpha := math::sin(w) / (2 * 0.70710678); + val c := math::cos(w); + val a0 := 1 + alpha; + if high { + this.b0 = ((1 + c) / 2 / a0) as f32; + this.b1 = (-(1 + c) / a0) as f32; + } else { + this.b0 = ((1 - c) / 2 / a0) as f32; + this.b1 = ((1 - c) / a0) as f32; + } + this.b2 = this.b0; + this.a1 = (-2 * c / a0) as f32; + this.a2 = ((1 - alpha) / a0) as f32; +} + +def biquad::run(&mut this, x: f32): f32 { + val y := this.b0 * x + this.z1; + this.z1 = this.b1 * x - this.a1 * y + this.z2; + this.z2 = this.b2 * x - this.a2 * y; + return y; +} + +# The filters of a voice or a bus, low and high pass, each side. +struct filters { + var low: biquad[2]; + var high: biquad[2]; +} + +# Filters frames of two channels, low pass, then high pass, as asked. +def filters::run(&mut this, frames: slice, low_pass: f32, high_pass: f32, rate: u32): void { + val count := frames.length / 2; + if low_pass > 0 { + this.low[0].tune(low_pass, rate, false); + this.low[1].tune(low_pass, rate, false); + for i in 0..count { + frames[i * 2] = this.low[0].run(frames[i * 2]); + frames[i * 2 + 1] = this.low[1].run(frames[i * 2 + 1]); + } + } + if high_pass > 0 { + this.high[0].tune(high_pass, rate, true); + this.high[1].tune(high_pass, rate, true); + for i in 0..count { + frames[i * 2] = this.high[0].run(frames[i * 2]); + frames[i * 2 + 1] = this.high[1].run(frames[i * 2 + 1]); + } + } +} + +# Freeverb's delays, in frames at 44.1 kHz: its combs', its all-passes', and +# how much longer the right's are. +const comb_tunings: u32[8] = [1116, 1188, 1277, 1356, 1422, 1491, 1557, 1617]; +const allpass_tunings: u32[4] = [556, 441, 341, 225]; +const stereo_spread: u32 = 23; + +# A delay line of Freeverb's: a comb, feeding back through a damping low pass, +# or an all-pass. +struct delay_line { + var held: vector; + var at: u64; + var store: f32; # A comb's damping's last. +} + +def delay_line::of(length: u64): delay_line { + var made := delay_line{ held = vector::::new() }; + made.held.resize(length > 0 ? length : 1u); + return made; +} + +def delay_line::comb(&mut this, x: f32, feedback: f32, damp: f32): f32 { + val y := this.held[this.at]; + this.store = y * (1 - damp) + this.store * damp; + this.held[this.at] = x + this.store * feedback; + this.at = this.at + 1 == this.held.length ? 0u : this.at + 1; + return y; +} + +def delay_line::allpass(&mut this, x: f32): f32 { + val kept := this.held[this.at]; + val y := kept - x; + this.held[this.at] = x + kept * 0.5; + this.at = this.at + 1 == this.held.length ? 0u : this.at + 1; + return y; +} + +# Freeverb's state, of each side. +struct reverb_state { + var combs: vector; # The left's eight, then the right's. + var allpasses: vector; # The left's four, then the right's. +} + +def reverb_state::of(rate: u32): reverb_state { + var made := reverb_state{ combs = vector::::new(), allpasses = vector::::new() }; + val scale := rate as f64 / 44100; + for side in 0..2u { + val spread := side == 0 ? 0u : stereo_spread; + for &each in comb_tunings { + made.combs.append(delay_line::of(((each + spread) as f64 * scale) as u64)); + } + for &each in allpass_tunings { + made.allpasses.append(delay_line::of(((each + spread) as f64 * scale) as u64)); + } + } + return made; +} + +# Reverberates frames of two channels in place, as Freeverb does: both sides +# summed into each side's combs, then all-passes, the wet of each mixed with +# the other's by the width. +def reverb_state::run(&mut this, frames: slice, how: &reverb): void { + val feedback := math::clamp(how.room, 0 as f32, 1 as f32) * 0.28 + 0.7; + val damp := math::clamp(how.damping, 0 as f32, 1 as f32) * 0.4; + val wet := how.wet * 3; + val wet1 := wet * (how.width / 2 + 0.5); + val wet2 := wet * ((1 - how.width) / 2); + val dry := how.dry; + for i in 0..frames.length / 2 { + val l := frames[i * 2]; + val r := frames[i * 2 + 1]; + val input := (l + r) * 0.015; + var out_l: f32 = 0; + var out_r: f32 = 0; + for c in 0..8u { + out_l += this.combs[c].comb(input, feedback, damp); + out_r += this.combs[8 + c].comb(input, feedback, damp); + } + for a in 0..4u { + out_l = this.allpasses[a].allpass(out_l); + out_r = this.allpasses[4 + a].allpass(out_r); + } + frames[i * 2] = out_l * wet1 + out_r * wet2 + l * dry; + frames[i * 2 + 1] = out_r * wet1 + out_l * wet2 + r * dry; + } +} + +# How many frames a reverb's echoes go on after what feeds it ends: until its +# combs' feedback has brought them down 60 dB, the longest comb's delay at a +# time. +def reverb_tail(how: &reverb, rate: u32): u64 { + val feedback := math::clamp(how.room, 0 as f32, 1 as f32) * 0.28 + 0.7; + val longest := (comb_tunings[7] + stereo_spread) as f64 * rate as f64 / 44100; + val passes := math::log(0.001) / math::log(feedback as f64 * 0.999); + return (longest * passes) as u64 + rate as u64 / 10; +} + +# The limiter's state: the mix delayed by its lookahead, the gain each frame +# needed, the least of those over the lookahead and the frame leaving it, +# released, and averaged over the lookahead; so the gain each frame leaving is +# given is at most what it needed. +struct limiter_state { + var delayed: vector; # The lookahead's frames, two floats each, a ring. + var released: vector; # The gains, as released, a ring the average is over, beside it. + var at: u64; + var needed: vector; # The gain each of the lookahead's frames and the one before them needed, a ring. + var need_at: u64; + var sum: f64; # Of `released`. + var last: f32; # The released gain of the last frame. +} + +def limiter_state::of(lookahead: u64): limiter_state { + var made := limiter_state{ delayed = vector::::new(), needed = vector::::new(), released = vector::::new(), last = 1 }; + val length := lookahead > 0 ? lookahead : 1u; + made.delayed.resize(length * 2); + made.released.resize(length, 1); + made.needed.resize(length + 1, 1); + made.sum = length as f64; + return made; +} + +# Limits frames of two channels in place, each the frame its lookahead before. +def limiter_state::run(&mut this, frames: slice, how: &limiter, rate: u32): void { + val length := this.released.length; + val ceiling := math::max(how.ceiling, 1e-6 as f32); + val back := 1 - math::exp(-1 / (math::max(how.release, 1e-3 as f32) as f64 * rate as f64)) as f32; + for i in 0..frames.length / 2 { + val l := frames[i * 2]; + val r := frames[i * 2 + 1]; + val peak := math::max(math::abs(l), math::abs(r)); + this.needed[this.need_at] = peak > ceiling ? ceiling / peak : 1; + this.need_at = this.need_at + 1 == this.needed.length ? 0u : this.need_at + 1; + var least: f32 = 1; + for k in 0..this.needed.length { + least = math::min(least, this.needed[k]); + } + # Down at once, up as it's released. + val gain := least < this.last ? least : this.last + (least - this.last) * back; + this.last = gain; + this.sum += gain as f64 - this.released[this.at] as f64; + this.released[this.at] = gain; + val applied := math::min((this.sum / length as f64) as f32, 1 as f32); + val out_l := this.delayed[this.at * 2]; + val out_r := this.delayed[this.at * 2 + 1]; + this.delayed[this.at * 2] = l; + this.delayed[this.at * 2 + 1] = r; + this.at = this.at + 1 == length ? 0u : this.at + 1; + frames[i * 2] = out_l * applied; + frames[i * 2 + 1] = out_r * applied; + } +} \ No newline at end of file diff --git a/audio/elsewhere.sakura b/audio/elsewhere.sakura new file mode 100644 index 0000000..6a795ad --- /dev/null +++ b/audio/elsewhere.sakura @@ -0,0 +1,16 @@ +#! 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); +} + +def system_devices(): vector { + return vector::::new(); +} diff --git a/audio/flac/flac.sakura b/audio/flac/flac.sakura new file mode 100644 index 0000000..f26f457 --- /dev/null +++ b/audio/flac/flac.sakura @@ -0,0 +1,353 @@ +#! Contains `decoder`, which reads a FLAC stream's frames as it's asked for +#! them, so a long one plays without being held decoded, and from anywhere it's +#! sought, and `decode`, which reads one whole. +#! +#! Every FLAC stream is read: of one to eight channels, apart or of a side +#! channel, of 4 to 32 bits a sample, at any rate, its blocks fixed or varying +#! in size, each subframe constant, verbatim, of a fixed predictor, or of +#! linear prediction, its residual Rice-coded or raw. Each frame's header is +#! checked by its CRC-8, and the frame whole by its CRC-16. A stream of more +#! than two channels is mixed down to two, its channels heard from where FLAC's +#! order places them. Where its comments say it loops, as +#! `audio::loop_of_comments` reads them, so does a voice playing it. An ID3v2 tag before it is skipped. +#! FLAC within Ogg isn't read. + +import std::math; +module malunal::audio::flac; + + +# A point of a seek table: a frame of the stream, the first of a frame of +# FLAC's, and where that begins past the first's beginning. +struct seek_point { + var frame: u64; + var offset: u64; +} + +#! Reads a FLAC stream's frames as it's asked for them. Its bytes must stay +#! where they are while it reads them. +pub struct decoder { + var bytes: span; + var first: u64; # Where the first frame begins. + var stream_rate: u32; + var width: u32; # Its channels. + var bits: u32; # Its bits a sample. + var most: u64; # The most frames a block holds. + var total: u64; # How many frames it has, or 0 where it says nothing. + var points: vector; + var looped: loop_range; + var table: u16[256]; + var at: u64; # Where the next frame begins. + var clock: u64; # The frame of the stream the next block begins at. + var skip: u64; # How many frames of the next blocks to leave out, as a seek asks. + var samples: vector; # A block's samples, each channel's `most` apart. + var floats: vector; # A block's frames, of every channel, together. + var pending: vector; # Frames decoded and not yet read, a frame's together. + var taken: u64; # How many floats of `pending` were read. + var ended: bool; +} + +#! Opens a FLAC stream, reading its metadata. +#! @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 FLAC, `malformed` where its information is broken, and +#! `unsupported` where it has more than eight channels. +pub def decoder::open(bytes: span): result { + var at := audio::past_id3(bytes); + return audio_error::unrecognized if at + 4 > bytes.length || bytes[at] != 'f' || bytes[at + 1] != 'L' || bytes[at + 2] != 'a' || bytes[at + 3] != 'C'; + at += 4; + var made := decoder{ + bytes = bytes, points = vector::::new(), samples = vector::::new(), floats = vector::::new(), + pending = vector::::new(), table = crc16_table(), + }; + var had_info := false; + var last := false; + while !last { + return audio_error::malformed if at + 4 > bytes.length; + last = (bytes[at] & 0x80) != 0; + val kind := bytes[at] & 0x7F; + val length := (bytes[at + 1] as u64) << 16 | (bytes[at + 2] as u64) << 8 | bytes[at + 3] as u64; + val body := at + 4; + return audio_error::malformed if body + length > bytes.length; + if kind == 0 { + return audio_error::malformed if length < 34; + val info := bytes[body:34]; + made.most = (info[2] as u64) << 8 | info[3] as u64; + made.stream_rate = (info[10] as u32) << 12 | (info[11] as u32) << 4 | (info[12] >> 4) as u32; + made.width = ((info[12] >> 1) & 7) as u32 + 1; + made.bits = (((info[12] & 1) as u32) << 4 | (info[13] >> 4) as u32) + 1; + made.total = ((info[13] & 0x0F) as u64) << 32 | (info[14] as u64) << 24 | (info[15] as u64) << 16 | (info[16] as u64) << 8 | info[17] as u64; + had_info = true; + } else if kind == 3 { + var p := body; + while p + 18 <= body + length { + val frame := big_endian(bytes, p, 8); + if frame != 0xFFFFFFFFFFFFFFFF { + made.points.append(seek_point{ frame = frame, offset = big_endian(bytes, p + 8, 8) }); + } + p += 18; + } + } else if kind == 4 { + made.looped = audio::loop_of_comments(bytes[body:length]); + } + at = body + length; + } + return audio_error::malformed if !had_info || made.stream_rate == 0 || made.most < 16 || made.bits < 4; + made.first = at; + made.at = at; + made.samples.resize(made.most * made.width as u64); + made.floats.resize(made.most * made.width as u64); + return made; +} + +#! How many channels the frames read have: one, or two. +pub val decoder::channels: u32 { + get => this.width > 2 ? 2 : this.width; +} + +#! Frames a second. +pub val decoder::rate: u32 { + get => this.stream_rate; +} + +#! How many frames the stream has, or 0 where it says nothing. +pub val decoder::frames: u64 { + get => this.total; +} + +#! Where the stream says a voice playing it loops, as its comments say. +pub val decoder::loop_points: loop_range { + get => this.looped; +} + +#! 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 { + 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; + } + this.pending.clear(); + this.taken = 0; + val had := this.next_block() else (e) { return e; }; + break if !had; + } + return given; +} + +#! Reads the stream again from its first frame. +pub def decoder::rewind(&mut this): void { + this.at = this.first; + this.clock = 0; + this.skip = 0; + this.pending.clear(); + this.taken = 0; + this.ended = false; +} + +#! Reads on from a frame of the stream: from the block its seek table, or a +#! search of its blocks' headers, finds before it, the frames between left out. +#! @param frame The frame, past the end where the stream ends there. +#! @returns Nothing, or why the stream couldn't be read. +pub def decoder::seek(&mut this, frame: u64): result { + this.rewind(); + if this.total != 0 && frame >= this.total { + this.ended = true; + return; + } + # The furthest point of the seek table not past it, then the search's. + for i in 0..this.points.length { + val point := this.points[i]; + if point.frame <= frame && point.frame >= this.clock && this.first + point.offset < this.bytes.length { + this.at = this.first + point.offset; + this.clock = point.frame; + } + } + var low := this.at; + var high := this.bytes.length; + while high - low > 4096 { + val middle := low + (high - low) / 2; + val found := this.head_after(middle) else { high = middle; continue; }; + if found.at >= high { + high = middle; + continue; + } + val starts := this.first_frame_of(&found.head); + if starts <= frame { + low = found.at; + this.at = found.at; + this.clock = starts; + } else { + high = middle; + } + } + this.skip = frame - this.clock; + return; +} + +# A frame's header, the first after a place, and where it is. +struct found_head { + var at: u64; + var head: frame_head; +} + +def decoder::head_after(&this, from: u64): maybe { + var at := from; + while at + 1 < this.bytes.length { + if this.bytes[at] == 0xFF && (this.bytes[at + 1] & 0xFE) == 0xF8 { + if head_at(this.bytes, at, this.stream_rate, this.bits) is some(&head) { + if head.block <= this.most && head.bits == this.bits { + return found_head{ at = at, head = head }; + } + } + } + at++; + } + return nothing {}; +} + +# The stream's frame a block of FLAC's begins at. +def decoder::first_frame_of(&this, head: &frame_head): u64 { + return head.variable ? head.number : head.number * this.most; +} + +# Decodes the next block into what's pending, leaving out what a seek asks to. +# @returns Whether there was one. +def decoder::next_block(&mut this): result { + while true { + return false if this.ended || this.at >= this.bytes.length; + val head := head_at(this.bytes, this.at, this.stream_rate, this.bits) else { + # Bytes after the last frame, as a tag left there, end it; before it, + # they're broken. + return audio_error::malformed if this.total != 0 && this.clock < this.total; + this.ended = true; + return false; + }; + val assigned: u32 = head.assignment < 8 ? head.assignment + 1 : 2; + return audio_error::malformed if head.block > this.most || assigned != this.width; + this.decode_block(&head) else (e) { return e; }; + this.clock += head.block; + if this.skip >= head.block { + this.skip -= head.block; + continue; + } + this.give(head.block, this.skip); + this.skip = 0; + return true; + } + return false; +} + +# Decodes the block a header begins, checking it by its CRC-16, into each +# channel's samples, and moves past it. +def decoder::decode_block(&mut this, head: &frame_head): result { + var r := reader::of(this.bytes, this.at + head.length); + val block := head.block; + for c in 0..this.width as u64 { + # A side channel takes a bit more. + var bits := head.bits; + if (head.assignment == 8 && c == 1) || (head.assignment == 9 && c == 0) || (head.assignment == 10 && c == 1) { + bits++; + } + val channel := slice::::over(this.samples.data + c * this.most, block); + read_subframe(&mut r, channel, bits) else (e) { return e; }; + } + r.align(); + val end := r.at; + return audio_error::malformed if end + 2 > this.bytes.length; + val said := (this.bytes[end] as u16) << 8 | this.bytes[end + 1] as u16; + return audio_error::malformed if crc16(&this.table, this.bytes[this.at:end - this.at]) != said; + this.at = end + 2; + + # The channels apart again. + if head.assignment >= 8 { + val left := this.samples.data; + val right := this.samples.data + this.most; + for i in 0..block { + val a: i64 = through(left + i); + val b: i64 = through(right + i); + if head.assignment == 8 { + through(right + i) = a - b; + } else if head.assignment == 9 { + through(left + i) = a + b; + } else { + val mid := (a << 1) | (b & 1); + through(left + i) = (mid + b) >> 1; + through(right + i) = (mid - b) >> 1; + } + } + } + return; +} + +# Gives a block's frames, past so many left out, as floats, mixed down to two +# channels where it has more. +def decoder::give(&mut this, block: u64, from: u64): void { + val scale := 1.0 / ((1 as u64) << (this.bits - 1)) as f64; + val width := this.width as u64; + val count := block - from; + if width <= 2 { + for i in from..block { + for c in 0..width { + this.pending.append((this.samples[c * this.most + i] as f64 * scale) as f32); + } + } + return; + } + for i in from..block { + for c in 0..width { + this.floats[(i - from) * width + c] = (this.samples[c * this.most + i] as f64 * scale) as f32; + } + } + var speakers: speaker[8]; + for c in 0..width { + speakers[c] = audio::standard_speaker(this.width, c as u32); + } + val old := this.pending.length; + this.pending.resize(old + count * 2); + audio::downmix(this.floats.span[0:count * width], count, speakers[0:width], slice::::over(this.pending.data + old, count * 2)); +} + +#! Reads a FLAC file whole. +#! @param bytes The file's bytes. +#! @returns The sound, of two channels where the stream has more, its loop +#! points as its comments say, 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), loop_points = reading.loop_points }; +} + +# A number of so many bytes, highest first. +def big_endian(bytes: span, at: u64, count: u64): u64 { + var value: u64 = 0; + for i in 0..count { + value = (value << 8) | bytes[at + i] as u64; + } + return value; +} diff --git a/audio/flac/frames.sakura b/audio/flac/frames.sakura new file mode 100644 index 0000000..d4c1a73 --- /dev/null +++ b/audio/flac/frames.sakura @@ -0,0 +1,339 @@ +#! Contains a FLAC frame read: its header, checked by its CRC-8, and each +#! channel's subframe, constant, verbatim, of a fixed predictor, or of linear +#! prediction, whose residual is Rice-coded or raw, then the channels made +#! independent again where one is a side channel, and the frame checked by its +#! CRC-16. + +import std::math; +module malunal::audio::flac; + + +# A frame's header: how many frames it holds, its rate, how its channels are +# assigned, its bits a sample, the number coded in it, which is of the frame +# or, where the stream's blocks vary, of its first sample, and how many bytes +# it takes. +struct frame_head { + var block: u64; + var rate: u32; + var assignment: u32; # 0 to 7, that many channels less one, apart; 8 left and side, 9 side and right, 10 mid and side. + var bits: u32; + var number: u64; + var variable: bool; + var length: u64; +} + +# Reads a stream's bits, highest first, by a cache of up to 64 of them. Bytes +# read past the end are zeros, which `past` notes. +struct reader { + var bytes: span; + var next: u64; # The next byte cached. + var cache: u64; # The bits held, the first highest. + var held: u32; # How many. +} + +def reader::of(bytes: span, at: u64): reader { + return reader{ bytes = bytes, next = at }; +} + +# Fills the cache to 57 bits or more. +def reader::fill(&mut this): void { + while this.held <= 56 { + val byte: u64 = this.next < this.bytes.length ? this.bytes[this.next] as u64 : 0; + this.cache = this.cache | (byte << (56 - this.held)); + this.held += 8; + this.next++; + } +} + +# Reads so many bits, up to 56, as a number. +def reader::take(&mut this, count: u32): u64 { + return 0 if count == 0; + if this.held < count { + this.fill(); + } + val value := this.cache >> (64 - count); + this.cache = count == 64 ? 0 : this.cache << count; + this.held -= count; + return value; +} + +# Reads so many bits, up to 56, as a number of two's complement. +def reader::signed(&mut this, count: u32): i64 { + return 0 if count == 0; + val value := this.take(count) as i64; + return value >= ((1 as i64) << (count - 1)) ? value - ((1 as i64) << count) : value; +} + +# Reads a run of zeros, ended by a one, as how many zeros there were. +def reader::unary(&mut this): u64 { + var count: u64 = 0; + while true { + if this.held == 0 { + this.fill(); + } + val zeros := leading_zeros(this.cache) as u32; + if zeros < this.held { + count += zeros as u64; + this.cache = this.cache << (zeros + 1); + this.held -= zeros + 1; + return count; + } + count += this.held as u64; + this.cache = 0; + this.held = 0; + # A run of zeros past the end is broken, and the caller finds it past. + return count if this.past; + } + return count; +} + +# Where the next bit read is, in bytes, rounded down. +val reader::at: u64 { + get => (this.next * 8 - this.held as u64) / 8; +} + +# Skips to the next whole byte. +def reader::align(&mut this): void { + val extra := this.held % 8; + this.cache = this.cache << extra; + this.held -= extra; +} + +# Whether bits were read past the end. +val reader::past: bool { + get => this.at > this.bytes.length; +} + +# The CRC-8 of a run of bytes, of the polynomial x^8 + x^2 + x + 1, as a +# frame's header is checked by. +def crc8(bytes: span): u8 { + var crc: u32 = 0; + for i in 0..bytes.length { + crc = crc ^ bytes[i] as u32; + for _ in 0..8 { + crc = (crc & 0x80) != 0 ? ((crc << 1) ^ 0x07) & 0xFF : (crc << 1) & 0xFF; + } + } + return crc as u8; +} + +# The table of the CRC-16 of the polynomial x^16 + x^15 + x^2 + 1, a byte at a +# time, as a frame whole is checked by. +def crc16_table(): u16[256] { + var made: u16[256]; + for i in 0..256u { + var crc: u32 = (i as u32) << 8; + for _ in 0..8 { + crc = (crc & 0x8000) != 0 ? ((crc << 1) ^ 0x8005) & 0xFFFF : (crc << 1) & 0xFFFF; + } + made[i] = crc as u16; + } + return made; +} + +def crc16(table: &u16[256], bytes: span): u16 { + var crc: u32 = 0; + for i in 0..bytes.length { + crc = ((crc << 8) & 0xFFFF) ^ table[((crc >> 8) ^ bytes[i] as u32) as u64] as u32; + } + return crc as u16; +} + +# Reads the header of a frame where its sync code is, checked by its CRC-8; the +# rate and bits a sample a stream's information gives where the header says +# its own. Nothing where it isn't one. +def head_at(bytes: span, at: u64, rate: u32, bits: u32): maybe { + return nothing {} if at + 6 > bytes.length || bytes[at] != 0xFF || (bytes[at + 1] & 0xFE) != 0xF8; + var made := frame_head{ variable = (bytes[at + 1] & 1) != 0 }; + val block_code := (bytes[at + 2] >> 4) as u32; + val rate_code := (bytes[at + 2] & 0x0F) as u32; + made.assignment = (bytes[at + 3] >> 4) as u32; + val bits_code := ((bytes[at + 3] >> 1) & 7) as u32; + return nothing {} if block_code == 0 || rate_code == 15 || made.assignment > 10 || bits_code == 3 || (bytes[at + 3] & 1) != 0; + + # The coded number, as UTF-8 codes a character, of up to 36 bits. + var p := at + 4; + val lead := bytes[p] as u32; + var more: u32 = 0; + var number: u64 = 0; + if lead < 0x80 { + number = lead as u64; + } else if lead >= 0xC0 && lead <= 0xFE { + more = 1; + while more < 6 && ((lead << (more + 1)) & 0x80) != 0 { + more++; + } + number = (lead & (0x3F >> more)) as u64; + } else { + return nothing {}; + } + p++; + for _ in 0..more { + return nothing {} if p >= bytes.length || (bytes[p] & 0xC0) != 0x80; + number = (number << 6) | (bytes[p] & 0x3F) as u64; + p++; + } + made.number = number; + + # The block size and rate, of what's coded after where they're said to be. + return nothing {} if p + 3 > bytes.length; + if block_code == 1 { + made.block = 192; + } else if block_code <= 5 { + made.block = 576 << (block_code - 2); + } else if block_code == 6 { + made.block = bytes[p] as u64 + 1; + p++; + } else if block_code == 7 { + made.block = ((bytes[p] as u64) << 8 | bytes[p + 1] as u64) + 1; + p += 2; + } else { + made.block = 256 << (block_code - 8); + } + val rates: u32[12] = [0, 88200, 176400, 192000, 8000, 16000, 22050, 24000, 32000, 44100, 48000, 96000]; + if rate_code == 0 { + made.rate = rate; + } else if rate_code < 12 { + made.rate = rates[rate_code as u64]; + } else if rate_code == 12 { + made.rate = bytes[p] as u32 * 1000; + p++; + } else { + val said := (bytes[p] as u32) << 8 | bytes[p + 1] as u32; + made.rate = rate_code == 13 ? said : said * 10; + p += 2; + } + val sizes: u32[8] = [0, 8, 12, 0, 16, 20, 24, 32]; + made.bits = bits_code == 0 ? bits : sizes[bits_code as u64]; + return nothing {} if p >= bytes.length || made.bits == 0 || made.rate == 0; + return nothing {} if crc8(bytes[at:p - at]) != bytes[p]; + made.length = p + 1 - at; + return made; +} + +# Reads a channel's subframe, of so many bits a sample, into its samples. +def read_subframe(r: &mut reader, into: slice, bits: u32): result { + val block := into.length; + return audio_error::malformed if r.take(1) != 0; + val kind := r.take(6) as u32; + var wasted: u32 = 0; + if r.take(1) != 0 { + wasted = r.unary() as u32 + 1; + return audio_error::malformed if wasted >= bits; + } + val width := bits - wasted; + if kind == 0 { + val value := r.signed(width); + for i in 0..block { + into[i] = value; + } + } else if kind == 1 { + for i in 0..block { + into[i] = r.signed(width); + } + } else if kind >= 8 && kind <= 12 { + val order := (kind - 8) as u64; + return audio_error::malformed if order > block; + for i in 0..order { + into[i] = r.signed(width); + } + read_residual(r, into, order) else (e) { return e; }; + restore_fixed(into, order); + } else if kind >= 32 { + val order := (kind - 31) as u64; + return audio_error::malformed if order > block; + for i in 0..order { + into[i] = r.signed(width); + } + val precision := r.take(4) as u32 + 1; + return audio_error::malformed if precision == 16; + val shift := r.signed(5); + return audio_error::malformed if shift < 0; + var coefficients: i64[32]; + for j in 0..order { + coefficients[j] = r.signed(precision); + } + read_residual(r, into, order) else (e) { return e; }; + restore_lpc(into, order, &coefficients, shift as u32); + } else { + return audio_error::malformed; + } + if wasted > 0 { + for i in 0..block { + into[i] = into[i] << wasted; + } + } + return audio_error::malformed if r.past; + return; +} + +# Reads a residual after a predictor's warm-up samples, into the samples after +# them: partitions of Rice codes of a parameter each, or of raw bits. +def read_residual(r: &mut reader, into: slice, order: u64): result { + val block := into.length; + val method := r.take(2) as u32; + return audio_error::malformed if method > 1; + val parameter_bits: u32 = method == 0 ? 4 : 5; + val escape: u64 = method == 0 ? 15 : 31; + val partition_order := r.take(4) as u32; + val partitions: u64 = (1 as u64) << partition_order; + return audio_error::malformed if block % partitions != 0 || block / partitions < order; + val each := block / partitions; + var at := order; + for p in 0..partitions { + val count := p == 0 ? each - order : each; + val parameter := r.take(parameter_bits); + if parameter == escape { + val raw := r.take(5) as u32; + for _ in 0..count { + into[at] = r.signed(raw); + at++; + } + continue; + } + val k := parameter as u32; + for _ in 0..count { + val high := r.unary(); + return audio_error::malformed if high > 0xFFFFFFFF; + val folded := (high << k) | r.take(k); + into[at] = (folded >> 1) as i64 ^ -((folded & 1) as i64); + at++; + } + return audio_error::malformed if r.past; + } + return; +} + +# Adds a fixed predictor's predictions to the residual after its warm-up. +def restore_fixed(s: slice, order: u64): void { + val block := s.length; + if order == 1 { + for i in 1..block { + s[i] += s[i - 1]; + } + } else if order == 2 { + for i in 2..block { + s[i] += 2 * s[i - 1] - s[i - 2]; + } + } else if order == 3 { + for i in 3..block { + s[i] += 3 * s[i - 1] - 3 * s[i - 2] + s[i - 3]; + } + } else if order == 4 { + for i in 4..block { + s[i] += 4 * s[i - 1] - 6 * s[i - 2] + 4 * s[i - 3] - s[i - 4]; + } + } +} + +# Adds linear prediction's predictions to the residual after its warm-up: each +# coefficient times the sample so many before, summed, shifted down. +def restore_lpc(s: slice, order: u64, coefficients: &i64[32], shift: u32): void { + for i in order..s.length { + var sum: i64 = 0; + for j in 0..order { + sum += coefficients[j] * s[i - 1 - j]; + } + s[i] += sum >> shift; + } +} diff --git a/audio/formats.sakura b/audio/formats.sakura new file mode 100644 index 0000000..fc4ce77 --- /dev/null +++ b/audio/formats.sakura @@ -0,0 +1,105 @@ +#! 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. + flac, #! FLAC: of one to eight channels, of 4 to 32 bits a sample. + mp3, #! MP3: MPEG-1, 2, or 2.5's Layer III. + opus, #! Ogg Opus: the first Opus stream of an Ogg file, of one or two channels. +} + +#! Which format bytes are in, by how they begin: `RIFF` and `WAVE` for WAV, +#! `OggS` for Ogg, Opus where its first packet is Opus's head and Vorbis where +#! it's not, `fLaC`, after any ID3v2 tag, for FLAC, and a frame of Layer III, +#! after any ID3v2 tag, for MP3. +#! @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' { + val body := 27 + (bytes.length > 26 ? bytes[26] as u64 : 0); + return format::opus if body + 8 <= bytes.length && bytes[body] == 'O' && bytes[body + 1] == 'p' && bytes[body + 2] == 'u' && bytes[body + 3] == 's' && bytes[body + 4] == 'H'; + return format::vorbis; + } + val at := past_id3(bytes); + if at + 4 <= bytes.length && bytes[at] == 'f' && bytes[at + 1] == 'L' && bytes[at + 2] == 'a' && bytes[at + 3] == 'C' { + return format::flac; + } + if at < bytes.length && audio::mp3::begins(bytes[at:bytes.length - at]) { + return format::mp3; + } + return nothing {}; +} + +#! Which format a file's extension names, whatever the case of its letters: +#! `wav` or `wave`, `ogg` or `oga`, `flac`, `mp3`, and `opus`. +#! @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.span; + return format::wav if name == "wav" || name == "wave"; + return format::vorbis if name == "ogg" || name == "oga"; + return format::flac if name == "flac"; + return format::mp3 if name == "mp3"; + return format::opus if name == "opus"; + return nothing {}; +} + +#! Reads a sound from bytes in any format, which their first few say, whole: +#! a compressed 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), + flac => audio::flac::decode(bytes), + mp3 => audio::mp3::decode(bytes), + opus => audio::opus::decode(bytes), + }; +} + +#! Reads a sound from a file in any 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.span); +} + +#! 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.span) else (_) { return audio_error::unwritable; }; + return; +} diff --git a/audio/mixer.sakura b/audio/mixer.sakura new file mode 100644 index 0000000..8862b2b --- /dev/null +++ b/audio/mixer.sakura @@ -0,0 +1,321 @@ +#! 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, +#! filtered or not, on one of 16 buses, and sent to another as much as it says, +#! as to a bus of reverb. Each bus puts effects of its own, filters and reverb, +#! on what's mixed into it, then its gain, as music and effects are set apart; +#! then the master gain is put on them all, and the limiter, where it's on. +#! What changes as a voice plays is ramped across the next frames mixed, as a +#! bus's gain and the master's are, 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 file's bytes, Ogg Vorbis, FLAC, or +#! MP3, each voice decoding what it plays as it plays it, so music takes little +#! memory. A looping voice goes back to where its sound's loop points say, as +#! its file said, and a voice is sought anywhere, decoded or streamed. + +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. + pub var low_pass: f32 = 0; #! The frequency, in hertz, above which it's quieter, as through a wall; 0, none. + pub var high_pass: f32 = 0; #! The frequency below which it's quieter; 0, none. + pub var send: f32 = 0; #! How much of it is mixed into another bus too, as into one of reverb, + pub var send_bus: u32 = 0; #! and which. + pub var delay: f32 = 0; #! Seconds it waits as it starts, as a far sound is heard later. + pub var silent: bool = false; #! Whether it plays on unheard, as a voice left out of too many does: its place moves on, but none of it is mixed. +} + +# 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 file's bytes, where it's streamed. + var streamed: bool; + var rate: u32; + var channels: u32; + var frames: u64; + var loop_points: loop_range; +} + +# Where a streamed voice's frames are of its sound's: from the voice's frame +# `voice` on, its sound's from `sound`, until the next mark, as it loops or is +# sought. +struct stream_mark { + var voice: u64; + var sound: u64; +} + +# What a streamed voice decodes, and the frames it decoded, about where it +# plays, each its own frame, counted from where it began whatever it looped or +# sought. +struct streaming { + var decoding: stream; + var window: vector; # Frames decoded, `channels` floats each. + var base: u64; # The voice's frame `window` begins at. + var at: u64; # The sound's frame the stream decodes next. + var marks: vector; # Where the window's frames are of the sound's, the first before it. + 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, or, streamed, its own, as `streaming` counts them. + 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>; + var filtering: filters; + var waiting: u64; # Frames it waits yet before it's heard. +} + +# A bus's effects, and what they keep from one mix to the next: its filters, +# its reverb, made as it's first on, how many frames its echoes go on after +# what feeds it ends, and the gain it was given last, and whether it was mixed +# then. +struct bus_state { + var effects: bus_effects; + var filtering: filters; + var echoes: maybe>; + var tail: u64; + var applied: f32; + var live: bool; +} + +#! 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; + var bus_states: vector; + var master_applied: f32; + var master_live: bool; + var limits: limiter; + var limited: maybe>; + var mixed: vector; # Each bus's frames, as its voices mix into it. + var scratch: vector; # A voice's, as it's mixed. +} + +#! 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, + bus_states = vector::::new(), mixed = vector::::new(), scratch = vector::::new(), limited = nothing {}, + }; + for b in 0..bus_count { + made.buses[b as u64] = 1; + made.bus_states.append(bus_state{ echoes = nothing {}, applied = 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.loop_points = given.loop_points; + at.decoded = move(given); + return sound_id{ index = index, generation = at.generation }; +} + +#! Holds a file of a compressed format, Ogg Vorbis or FLAC, 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 `stream::open` says. +pub def mixer::add_streamed(&mut this, bytes: span): result { + val opened := stream::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.loop_points = opened.loop_points; + 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; +} + +#! Whether a sound is streamed, decoded as it plays, rather than held decoded. +pub def mixer::streamed(&this, id: sound_id): bool { + return this.holds(id) && this.bank[id.index as u64].streamed; +} + +#! 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.loop_points = given.loop_points; + at.encoded.clear(); + at.decoded = move(given); + return true; +} + +#! Makes a sound held a file of a compressed format, 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 := stream::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.loop_points = opened.loop_points; + 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.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..3f99a82 --- /dev/null +++ b/audio/mixing.sakura @@ -0,0 +1,400 @@ +#! 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: each voice into its bus, filtered +#! where it says, and into the bus it's sent to; then each bus's effects, and +#! its gain, the master's, and the limiter, where it's on. +#! @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; + val width := frames * 2; + if this.mixed.length != bus_count as u64 * width { + this.mixed.resize(bus_count as u64 * width); + } + if this.scratch.length != width { + this.scratch.resize(width); + } + var fed: bool[16]; + 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 voice := slice::::over(this.scratch.data, width); + for i in 0..width { + voice[i] = 0; + } + # A voice waiting is heard from where its wait ends; one unheard moves on. + val waits := math::min(through(state).waiting, frames); + through(state).waiting -= waits; + continue if waits == frames; + val heard := slice::::over(this.scratch.data + waits * 2, width - waits * 2); + val how := through(state).how; + if how.silent && !through(held).streamed { + if pass_silently(&mut through(state), &through(held), this.mix_rate, frames - waits) { + this.end_voice(v); + } + continue; + } + val ended := mix_voice(&mut through(state), &through(held), this.mix_rate, heard, frames - waits); + if how.silent { + through(state).gains = [0, 0]; + if ended { + this.end_voice(v); + } + continue; + } + if how.low_pass > 0 || how.high_pass > 0 { + through(state).filtering.run(voice, how.low_pass, how.high_pass, this.mix_rate); + } + this.feed(&mut fed, how.bus, voice, 1); + if how.send > 0 && how.send_bus < bus_count && how.send_bus != how.bus { + this.feed(&mut fed, how.send_bus, voice, how.send); + } + if ended { + this.end_voice(v); + } + } + + # Each bus: its effects, then its gain, ramped from what it was given last; + # or, of one silent before, given whole. Reverb goes on as long as its echoes + # do after what feeds it ends. + var any := false; + for b in 0..bus_count as u64 { + val state := &mut this.bus_states[b]; + if !fed[b] && state.tail == 0 { + state.live = false; + continue; + } + val part := slice::::over(this.mixed.data + b * width, width); + if !fed[b] { + for i in 0..width { + part[i] = 0; + } + } + val effects := state.effects; + if effects.low_pass > 0 || effects.high_pass > 0 { + state.filtering.run(part, effects.low_pass, effects.high_pass, this.mix_rate); + } + if effects.reverb.wet > 0 { + if state.echoes is none { + state.echoes = box::new(reverb_state::of(this.mix_rate)); + } + if state.echoes is some(&mut echoes) { + echoes.get().run(part, &effects.reverb); + } + state.tail = fed[b] ? reverb_tail(&effects.reverb, this.mix_rate) : (state.tail > frames ? state.tail - frames : 0u); + } else { + state.tail = 0; + } + val target := this.buses[b]; + val from := state.live ? state.applied : target; + for i in 0..frames { + val gain := from + (target - from) * (i + 1) as f32 / frames as f32; + into[i * 2] += part[i * 2] * gain; + into[i * 2 + 1] += part[i * 2 + 1] * gain; + } + state.applied = target; + state.live = true; + any = true; + } + + # The master's gain, as a bus's is, then the limiter. + val target := this.master_gain; + val from := this.master_live ? this.master_applied : target; + if from != 1 || target != 1 { + for i in 0..frames { + val gain := from + (target - from) * (i + 1) as f32 / frames as f32; + into[i * 2] *= gain; + into[i * 2 + 1] *= gain; + } + } + this.master_applied = target; + this.master_live = any; + if this.limits.on { + if this.limited is none { + this.limited = box::new(limiter_state::of((this.limits.lookahead * this.mix_rate as f32) as u64)); + } + if this.limited is some(&mut held) { + held.get().run(into, &this.limits, this.mix_rate); + } + } +} + +# Moves a voice of a decoded sound on, unheard, as it would play, its gains +# where they'd be. +# @returns Whether it ended. +def pass_silently(at: &mut voice_state, held: &held_sound, rate: u32, frames: u64): bool { + val step := held.rate as f64 / rate as f64 * math::max(at.how.pitch, 0 as f32) as f64; + at.level = math::clamp(at.level + at.fade * frames as f32, 0 as f32, 1 as f32); + # Heard again, it rises from nothing, as gains ramp. + at.gains = [0, 0]; + at.started = true; + at.position += step * frames as f64; + if at.how.looping { + val loop_end := loop_end_of(held); + val loop_start := held.loop_points.start < loop_end ? held.loop_points.start : 0u; + if at.position >= loop_end as f64 { + val length := (loop_end - loop_start) as f64; + val past := at.position - loop_start as f64; + at.position = loop_start as f64 + past - math::floor(past / length) * length; + } + return at.stopping && at.level <= 0; + } + return at.position >= held.frames as f64 || (at.stopping && at.level <= 0); +} + +# Adds a voice's frames, by an amount, into a bus's, or, the first this mix, +# sets them. +def mixer::feed(&mut this, fed: &mut bool[16], bus: u32, voice: slice, amount: f32): void { + val width := voice.length; + val part := slice::::over(this.mixed.data + bus as u64 * width, width); + if !fed[bus as u64] { + for i in 0..width { + part[i] = voice[i] * amount; + } + fed[bus as u64] = true; + return; + } + for i in 0..width { + part[i] += voice[i] * amount; + } +} + +# Mixes one voice into frames, at its own gain. +# @returns Whether it ended. +def mix_voice(at: &mut voice_state, held: &held_sound, rate: u32, 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 := 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; + # Where a looping decoded voice goes back from, and to. + val loop_end := loop_end_of(held); + val loop_start := held.loop_points.start < loop_end ? held.loop_points.start : 0u; + + # 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, held.loop_points); + 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; + # Read where they are only short of where a looping voice goes back from. + count = looping ? loop_end as i64 : 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, loop_start, loop_end); + val p1 := frame_of(at, held, index, looping, loop_start, loop_end); + val p2 := frame_of(at, held, index + 1, looping, loop_start, loop_end); + val p3 := frame_of(at, held, index + 2, looping, loop_start, loop_end); + 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 >= loop_end as f64 { + position -= (loop_end - loop_start) as f64; + } + } + at.position = position; + at.gains = end; + at.level = level; + at.started = true; + return finished || (at.stopping && level <= 0); +} + +# Where a looping voice of a decoded sound goes back from: its loop's end, or +# its own. +def loop_end_of(held: &held_sound): u64 { + val end := held.loop_points.end; + return end != 0 && end < held.frames ? end : held.frames; +} + +# A frame of a voice's sound, its left and right, a mono one's twice: past +# where a looping voice goes back from, where it goes back to, and before its +# start, a whole sound looping's end; silence outside it where it doesn't loop. +def frame_of(at: &mut voice_state, held: &held_sound, index: i64, looping: bool, loop_start: u64, loop_end: u64): 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 >= loop_end as i64 { + val length := (loop_end - loop_start) as i64; + k = loop_start as i64 + (k - loop_end as i64) % length; + } else if looping && k < 0 && loop_start == 0 { + k = loop_end as i64 + k; + } + 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, where the voice loops, seeking the stream +# back to where its sound loops to as it reaches where it loops from, or its +# end, marking where its frames go on from. +def streaming::ensure(&mut this, first: u64, last: u64, channels: u64, looping: bool, looped: loop_range): 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; + } + # What's marked before the window's first frame is let go of, but the mark + # it goes on from. + while this.marks.length > 1 && this.marks[1].voice <= this.base { + this.marks.remove_at(0); + } + var dry: u32 = 0; + while !this.ended && this.base + this.window.length / channels < last { + var wanted := stream_chunk; + if looping && looped.end > this.at && looped.end - this.at < wanted { + wanted = looped.end - this.at; + } + val reached := looping && looped.end != 0 && this.at >= looped.end; + var got: u64 = 0; + if !reached { + val old := this.window.length; + this.window.resize(old + wanted * channels); + val into := slice::::over(this.window.data + old, wanted * channels); + 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); + this.at += got; + continue if got == wanted && !(looping && looped.end != 0 && this.at >= looped.end); + } + if looping && dry < 2 { + dry = got == 0 ? dry + 1 : 0; + val back := looped.end != 0 && looped.start >= looped.end ? 0u : looped.start; + val sought := back == 0 ? ok_seeking(&mut this.decoding) : this.decoding.seek(back); + if sought is error(_) { + this.ended = true; + this.end = this.base + this.window.length / channels; + break; + } + this.at = back; + this.marks.append(stream_mark{ voice = this.base + this.window.length / channels, sound = back }); + continue; + } + this.ended = true; + this.end = this.base + this.window.length / channels; + } +} + +# Reads a stream again from its start, as a seek to it does, without one. +def ok_seeking(decoding: &mut stream): result { + decoding.rewind(); + return; +} diff --git a/audio/mp3/layer3.sakura b/audio/mp3/layer3.sakura new file mode 100644 index 0000000..37f0648 --- /dev/null +++ b/audio/mp3/layer3.sakura @@ -0,0 +1,1028 @@ +#! Contains a frame of MPEG audio's Layer III decoded, as minimp3, which is in +#! the public domain, decodes it: its side information, its main data gathered +#! from the bit reservoir, each granule's scale factors and Huffman-coded +#! values, requantized, its stereo of mid and side or of intensity, short +#! blocks reordered, aliasing reduced, each subband's IMDCT overlapped with the +#! granule before, and the polyphase filterbank's synthesis of its frames. + +import std::math; +module malunal::audio::mp3; + + +# The most bytes a frame's main data may reach back for, and a frame holds. +const most_reservoir: u64 = 511; +const most_payload: u64 = 2304; + +# What a header says, by its bytes. +def is_mono(h: span): bool { return (h[3] & 0xC0) == 0xC0; } +def is_mid_side(h: span): bool { return (h[3] & 0xE0) == 0x60; } +def has_crc(h: span): bool { return (h[1] & 1) == 0; } +def is_mpeg1(h: span): bool { return (h[1] & 0x08) != 0; } +def is_mpeg25(h: span): bool { return (h[1] & 0x10) == 0; } +def is_intensity(h: span): bool { return (h[3] & 0x10) != 0; } +def is_ms(h: span): bool { return (h[3] & 0x20) != 0; } +def layer_bits(h: span): u32 { return ((h[1] >> 1) & 3) as u32; } +def rate_bits(h: span): u32 { return ((h[2] >> 2) & 3) as u32; } + +# Which of the nine rates a header's is, MPEG-2.5's first, then MPEG-2's, +# then MPEG-1's. +def rate_index(h: span): u32 { + return rate_bits(h) + (((h[1] >> 3) & 1) as u32 + ((h[1] >> 4) & 1) as u32) * 3; +} + +# Whether bytes begin a header of Layer III, of a bit rate said. +def header_valid(h: span): bool { + return h.length >= 4 && h[0] == 0xFF && ((h[1] & 0xF0) == 0xF0 || (h[1] & 0xFE) == 0xE2) + && layer_bits(h) == 1 && (h[2] >> 4) != 15 && (h[2] >> 4) != 0 && rate_bits(h) != 3; +} + +# Whether a header is of the same stream as another: its version, layer, and +# rate. +def same_stream(a: span, b: span): bool { + return header_valid(b) && ((a[1] ^ b[1]) & 0xFE) == 0 && ((a[2] ^ b[2]) & 0x0C) == 0; +} + +def bitrate_kbps(h: span): u32 { + val row: u64 = (is_mpeg1(h) ? 3 : 0) + (layer_bits(h) - 1) as u64; + return 2 * half_rates[row * 15 + (h[2] >> 4) as u64] as u32; +} + +def sample_rate(h: span): u32 { + return rates[rate_bits(h) as u64] >> (is_mpeg1(h) ? 0 : 1) >> (is_mpeg25(h) ? 1 : 0); +} + +# How many frames of sound a frame gives: 1152 of MPEG-1, 576 of the others. +def frame_samples(h: span): u32 { + return (h[1] & 14) == 2 ? 576 : 1152; +} + +# How many bytes a frame takes, its padding with it. +def frame_length(h: span): u64 { + return (frame_samples(h) * bitrate_kbps(h) * 125 / sample_rate(h)) as u64 + ((h[2] & 2) != 0 ? 1u : 0u); +} + +# Bits read highest first, past whose end are zeros. +struct bits { + var data: *u8; + var pos: u64; + var limit: u64; +} + +def bits::get(&mut this, n: u32): u32 { + return 0 if n == 0; + val s := (this.pos & 7) as u32; + var shl := (n + s) as i32; + var p := this.data + (this.pos >> 3); + this.pos += n as u64; + return 0 if this.pos > this.limit; + var next: u32 = (through(p) as u32) & (255 >> s); + p = p + 1; + var cache: u32 = 0; + shl -= 8; + while shl > 0 { + cache = cache | (next << shl as u32); + next = through(p) as u32; + p = p + 1; + shl -= 8; + } + return cache | (next >> (-shl) as u32); +} + +# A granule's side information, of one channel: its bands' widths, of which +# kind of block, as a row of `scf_long`, `scf_short`, or `scf_mixed`. +struct granule { + var bands: span; + var part23: u32; + var big_values: u32; + var compress: u32; + var global_gain: u32; + var block_type: u32; + var mixed: u32; + var long_bands: u32; + var short_bands: u32; + var tables: u32[3]; + var regions: u32[3]; + var subblock: u32[3]; + var preflag: u32; + var scale: u32; + var count1_table: u32; + var scfsi: u32; +} + +# What decoding Layer III keeps from one frame to the next, and its scratch. +struct layer3 { + var overlap: vector; # Each channel's IMDCTs' second halves, 9 of each of 32 subbands. + var qmf: vector; # The synthesis's last 15 rows of 64. + var reservoir: vector; # The main data a frame left for those after. + var reserved: u64; + var main: vector; # A frame's main data, the reservoir's before it, then zeros to read past. + var bs: bits; + var grbuf: vector; # Each channel's 576 values of a granule. + var scf: vector; + var syn: vector; # The synthesis's rows. + var ist_pos: vector; # Each channel's intensity positions, 39 each. + var gr: granule[4]; + var scratch: vector; +} + +def layer3::new(): layer3 { + var made := layer3{ + overlap = vector::::new(), qmf = vector::::new(), reservoir = vector::::new(), main = vector::::new(), + grbuf = vector::::new(), scf = vector::::new(), syn = vector::::new(), ist_pos = vector::::new(), + scratch = vector::::new(), + }; + made.overlap.resize(2 * 288); + made.qmf.resize(15 * 64); + made.reservoir.resize(most_reservoir); + # Zeros past it, as far as a broken frame's codes may read. + made.main.resize(most_reservoir + most_payload + 4096); + made.grbuf.resize(2 * 576); + made.scf.resize(40); + made.syn.resize(33 * 64); + made.ist_pos.resize(2 * 39); + made.scratch.resize(576); + return made; +} + +# Forgets what frames before left, as decoding begins again elsewhere. +def layer3::reset(&mut this): void { + for i in 0..this.overlap.length { + this.overlap[i] = 0; + } + for i in 0..this.qmf.length { + this.qmf[i] = 0; + } + this.reserved = 0; +} + +# Reads a frame's side information. +# @returns Where its main data begins before its own, or -1 where it's broken. +def layer3::read_side_info(&mut this, bs: &mut bits, h: span): i64 { + var r := rate_index(h); + if r != 0 { + r--; + } + val row := r as u64; + var count: u32 = is_mono(h) ? 1 : 2; + var scfsi: u32 = 0; + var main_data_begin: i64 = 0; + if is_mpeg1(h) { + count *= 2; + main_data_begin = bs.get(9) as i64; + scfsi = bs.get(7 + count); + } else { + main_data_begin = (bs.get(8 + count) >> count) as i64; + } + var sum: u64 = 0; + for g in 0..count as u64 { + if is_mono(h) { + scfsi = scfsi << 4; + } + val gr := &mut this.gr[g]; + gr.part23 = bs.get(12); + sum += gr.part23 as u64; + gr.big_values = bs.get(9); + return -1 if gr.big_values > 288; + gr.global_gain = bs.get(8); + gr.compress = bs.get(is_mpeg1(h) ? 4 : 9); + gr.bands = scf_long[row * 23:23]; + gr.long_bands = 22; + gr.short_bands = 0; + var tables: u32 = 0; + if bs.get(1) != 0 { + gr.block_type = bs.get(2); + return -1 if gr.block_type == 0; + gr.mixed = bs.get(1); + gr.regions[0] = 7; + gr.regions[1] = 255; + if gr.block_type == 2 { + scfsi = scfsi & 0x0F0F; + if gr.mixed == 0 { + gr.regions[0] = 8; + gr.bands = scf_short[row * 40:40]; + gr.long_bands = 0; + gr.short_bands = 39; + } else { + gr.bands = scf_mixed[row * 40:40]; + gr.long_bands = is_mpeg1(h) ? 8 : 6; + gr.short_bands = 30; + } + } + tables = bs.get(10) << 5; + gr.subblock[0] = bs.get(3); + gr.subblock[1] = bs.get(3); + gr.subblock[2] = bs.get(3); + } else { + gr.block_type = 0; + gr.mixed = 0; + tables = bs.get(15); + gr.regions[0] = bs.get(4); + gr.regions[1] = bs.get(3); + gr.regions[2] = 255; + } + gr.tables[0] = tables >> 10; + gr.tables[1] = (tables >> 5) & 31; + gr.tables[2] = tables & 31; + gr.preflag = is_mpeg1(h) ? bs.get(1) : (gr.compress >= 500 ? 1u : 0u); + gr.scale = bs.get(1); + gr.count1_table = bs.get(1); + # Only a second granule shares the first's scale factors. + gr.scfsi = g < (count / 2) as u64 || !is_mpeg1(h) ? 0u : (scfsi >> 12) & 15; + scfsi = scfsi << 4; + } + return -1 if sum + bs.pos > bs.limit + main_data_begin as u64 * 8; + return main_data_begin; +} + +# Reads a granule's scale factors, sharing those `scfsi` says the granule +# before had, and keeping each as an intensity position. +def read_scalefactors(scf: &mut u8[40], ist: slice, sizes: &u8[4], counts: span, bs: &mut bits, given: i32): void { + var at: u64 = 0; + var scfsi := given; + for i in 0..4u { + break if counts[i] == 0; + val count := counts[i] as u64; + if (scfsi & 8) != 0 { + for k in 0..count { + scf[at + k] = ist[at + k]; + } + } else { + val size := sizes[i] as u32; + if size == 0 { + for k in 0..count { + scf[at + k] = 0; + ist[at + k] = 0; + } + } else { + val most: i64 = scfsi < 0 ? ((1 as i64) << size) - 1 : -1; + for k in 0..count { + val s := bs.get(size) as i64; + ist[at + k] = (s == most ? 255 : s) as u8; + scf[at + k] = s as u8; + } + } + } + at += count; + scfsi *= 2; + } + scf[at] = 0; + scf[at + 1] = 0; + scf[at + 2] = 0; +} + +# A float times two to the minus quarter of a count, a quarter at a time. +def ldexp_q2(y: f32, given: i32): f32 { + var e: i32 = 0; + var left := given; + var v := y; + while true { + e = left < 120 ? left : 120; + v *= expfrac[(e & 3) as u64] * ((1 << 30) >> (e >> 2) as u32) as f32; + left -= e; + break if left <= 0; + } + return v; +} + +# Reads a channel's scale factors, and works out each band's gain. +def layer3::decode_scalefactors(&mut this, h: span, g: u64, bs: &mut bits, ch: u64): void { + val gr: granule = this.gr[g]; + var partition_row: u64 = (gr.short_bands != 0 ? 1u : 0u) + (gr.long_bands == 0 ? 1u : 0u); + var partition_at: u64 = partition_row * 28; + var sizes: u8[4]; + var scfsi := gr.scfsi as i32; + if is_mpeg1(h) { + val part := scfc_decode[gr.compress as u64]; + sizes[0] = part >> 2; + sizes[1] = part >> 2; + sizes[2] = part & 3; + sizes[3] = part & 3; + } else { + val ist: u32 = is_intensity(h) && ch != 0 ? 1 : 0; + var sfc := (gr.compress >> ist) as i32; + var k := (ist * 3 * 4) as u64; + while sfc >= 0 { + var modprod: i32 = 1; + var i: i32 = 3; + while i >= 0 { + sizes[i as u64] = ((sfc / modprod) % scf_moduli[k + i as u64] as i32) as u8; + modprod *= scf_moduli[k + i as u64] as i32; + i--; + } + sfc -= modprod; + k += 4; + } + partition_at += k; + scfsi = -16; + } + var iscf: u8[40]; + val ist := slice::::over(this.ist_pos.data + ch * 39, 39); + read_scalefactors(&mut iscf, ist, &sizes, scf_partitions[partition_at:4], bs, scfsi); + + val shift := gr.scale + 1; + if gr.short_bands != 0 { + val sh := 3 - shift; + var i: u64 = 0; + while i < gr.short_bands as u64 { + for w in 0..3u { + val at := gr.long_bands as u64 + i + w; + iscf[at] = (iscf[at] as u32 + (gr.subblock[w] << sh)) as u8; + } + i += 3; + } + } else if gr.preflag != 0 { + for i in 0..10u { + iscf[11 + i] += preamp[i]; + } + } + # The gain of each band: global, by its scale factor. + val gain_exp := gr.global_gain as i32 - 4 - 210 - (is_mid_side(h) ? 2 : 0); + val most: i32 = ((255 - 4 - 210) + 3) & -4; + val gain := ldexp_q2(((1 as i32) << (most / 4) as u32) as f32, most - gain_exp); + for i in 0..(gr.long_bands + gr.short_bands) as u64 { + this.scf[i] = ldexp_q2(gain, (iscf[i] as i32) << shift); + } +} + +# A value to the four thirds, past those `pow43` holds. +def pow_43(given: i32): f32 { + var x := given; + return pow43[16 + x as u64] if x < 129; + var mult: f32 = 256; + if x < 1024 { + mult = 16; + x = x << 3; + } + val sign := (2 * x) & 64; + val frac := ((x & 63) - sign) as f32 / ((x & -64) + sign) as f32; + return pow43[16 + ((x + sign) >> 6) as u64] * (1 + frac * ((4.0 / 3) as f32 + frac * (2.0 / 9) as f32)) * mult; +} + +# Reads a channel's values of a granule, by its tables' Huffman codes, each +# requantized by its band's gain, up to where its part of the main data ends. +def layer3::huffman(&mut this, ch: u64, bs: &mut bits, g: u64, limit: u64): void { + val gr: granule = this.gr[g]; + val buf := this.main.data; + var next := bs.pos / 8; + var cache: u32 = ((buf[next] as u32 * 256 + buf[next + 1] as u32) * 256 + buf[next + 2] as u32) * 256 + buf[next + 3] as u32; + cache = cache << (bs.pos & 7) as u32; + var sh: i32 = (bs.pos & 7) as i32 - 8; + next += 4; + var dst := ch * 576; + var sfb: u64 = 0; + var scf: u64 = 0; + var one: f32 = 0; + var big := gr.big_values as i32; + var region: u64 = 0; + while big > 0 { + val table := gr.tables[region] as u64; + var count := gr.regions[region] as i32; + region++; + val book := huffman_at[table] as u64; + val extra := linbits[table] as u32; + while true { + val np := (gr.bands[sfb] / 2) as i32; + sfb++; + var pairs := big < np ? big : np; + one = this.scf[scf]; + scf++; + while true { + var w: u32 = 5; + var leaf := huffman[book + (cache >> (32 - w)) as u64] as i32; + while leaf < 0 { + cache = cache << w; + sh += w as i32; + w = (leaf & 7) as u32; + leaf = huffman[(book as i64 + (cache >> (32 - w)) as i64 - (leaf >> 3) as i64) as u64] as i32; + } + cache = cache << (leaf >> 8) as u32; + sh += leaf >> 8; + for _ in 0..2 { + var lsb := leaf & 15; + if extra != 0 && lsb == 15 { + lsb += (cache >> (32 - extra)) as i32; + cache = cache << extra; + sh += extra as i32; + while sh >= 0 { + cache = cache | ((buf[next] as u32) << sh as u32); + next++; + sh -= 8; + } + val signed: f32 = (cache as i32) < 0 ? -1 : 1; + this.grbuf[dst] = one * pow_43(lsb) * signed; + } else { + this.grbuf[dst] = pow43[(16 + lsb - 16 * (cache >> 31) as i32) as u64] * one; + } + if lsb != 0 { + cache = cache << 1; + sh += 1; + } + dst++; + leaf = leaf >> 4; + } + while sh >= 0 { + cache = cache | ((buf[next] as u32) << sh as u32); + next++; + sh -= 8; + } + pairs--; + break if pairs <= 0; + } + big -= np; + count--; + break if big <= 0 || count < 0; + } + } + + # Then the quadruples of ones, to the end of its part. + var np: i32 = 1 - big; + while true { + val quads := gr.count1_table != 0 ? count1_b[:] : count1_a[:]; + var leaf := quads[(cache >> 28) as u64] as u32; + if (leaf & 8) == 0 { + leaf = quads[((leaf >> 3) + ((cache << 4) >> (32 - (leaf & 3)))) as u64] as u32; + } + cache = cache << (leaf & 7); + sh += (leaf & 7) as i32; + val position := (next * 8) as i64 - 24 + sh as i64; + break if position > limit as i64; + np--; + if np == 0 { + np = (gr.bands[sfb] / 2) as i32; + sfb++; + break if np == 0; + one = this.scf[scf]; + scf++; + } + for s in 0..2u { + if (leaf & (128 >> s as u32)) != 0 { + this.grbuf[dst + s] = (cache as i32) < 0 ? -one : one; + cache = cache << 1; + sh += 1; + } + } + np--; + if np == 0 { + np = (gr.bands[sfb] / 2) as i32; + sfb++; + break if np == 0; + one = this.scf[scf]; + scf++; + } + for s in 2..4u { + if (leaf & (128 >> s as u32)) != 0 { + this.grbuf[dst + s] = (cache as i32) < 0 ? -one : one; + cache = cache << 1; + sh += 1; + } + } + while sh >= 0 { + cache = cache | ((buf[next] as u32) << sh as u32); + next++; + sh -= 8; + } + dst += 4; + } + bs.pos = limit; +} + +# Mid and side made left and right, of so many values. +def layer3::midside(&mut this, from: u64, n: u64): void { + for i in from..from + n { + val a := this.grbuf[i]; + val b := this.grbuf[i + 576]; + this.grbuf[i] = a + b; + this.grbuf[i + 576] = a - b; + } +} + +# Intensity stereo: the right channel of the bands above where it has values +# made of the left, as their positions say. +def layer3::intensity(&mut this, g: u64, h: span): void { + val gr: granule = this.gr[g]; + val total := (gr.long_bands + gr.short_bands) as u64; + val blocks: u64 = gr.short_bands != 0 ? 3 : 1; + # The highest band of each window with a value on the right. + var top: i64[3] = [-1, -1, -1]; + var at: u64 = 576; + for i in 0..total { + val width := gr.bands[i] as u64; + var k: u64 = 0; + while k < width { + if this.grbuf[at + k] != 0 || this.grbuf[at + k + 1] != 0 { + top[i % 3] = i as i64; + break; + } + k += 2; + } + at += width; + } + if gr.long_bands != 0 { + val most := math::max(math::max(top[0], top[1]), top[2]); + top = [most, most, most]; + } + val positions := slice::::over(this.ist_pos.data + 39, 39); + for i in 0..blocks { + val home: u8 = is_mpeg1(h) ? 3 : 0; + val itop := total - blocks + i; + val before := itop - blocks; + positions[itop] = top[i] >= before as i64 ? home : positions[before]; + } + # Each band, of intensity where it's above the top and its position is + # within range, else of mid and side where the frame says. + val shift: u32 = this.gr[g + 1].compress & 1; + val most_pos: u32 = is_mpeg1(h) ? 7 : 64; + var left: u64 = 0; + var i: u64 = 0; + while gr.bands[i] != 0 { + val width := gr.bands[i] as u64; + val pos := positions[i] as u32; + if (i as i64) > top[i % 3] && pos < most_pos { + val s: f32 = is_ms(h) ? 1.41421356 : 1; + var kl: f32 = 1; + var kr: f32 = 1; + if is_mpeg1(h) { + kl = intensity_pan[2 * pos as u64]; + kr = intensity_pan[2 * pos as u64 + 1]; + } else { + kr = ldexp_q2(1, (((pos + 1) >> 1) << shift) as i32); + if (pos & 1) != 0 { + kl = kr; + kr = 1; + } + } + for k in left..left + width { + this.grbuf[k + 576] = this.grbuf[k] * kr * s; + this.grbuf[k] = this.grbuf[k] * kl * s; + } + } else if is_ms(h) { + this.midside(left, width); + } + left += width; + i++; + } +} + +# Short blocks' values reordered, from each window's band after band to each +# band's windows side by side. +def layer3::reorder(&mut this, at: u64, bands: span): void { + var src := at; + var dst: u64 = 0; + var b: u64 = 0; + while bands[b] != 0 { + val len := bands[b] as u64; + for i in 0..len { + this.scratch[dst] = this.grbuf[src + i]; + this.scratch[dst + 1] = this.grbuf[src + i + len]; + this.scratch[dst + 2] = this.grbuf[src + i + 2 * len]; + dst += 3; + } + src += 3 * len; + b += 3; + } + for i in 0..dst { + this.grbuf[at + i] = this.scratch[i]; + } +} + +# The aliasing between neighboring subbands reduced, of so many of them. +def layer3::antialias(&mut this, at: u64, count: i32): void { + var base := at; + var n := count; + while n > 0 { + for i in 0..8u { + val u := this.grbuf[base + 18 + i]; + val d := this.grbuf[base + 17 - i]; + this.grbuf[base + 18 + i] = u * antialias[i] - d * antialias[8 + i]; + this.grbuf[base + 17 - i] = u * antialias[8 + i] + d * antialias[i]; + } + n--; + base += 18; + } +} + +# A DCT-III of nine values in place. +def dct3_9(y: &mut f32[9]): void { + var s0 := y[0]; + var s2 := y[2]; + var s4 := y[4]; + var s6 := y[6]; + var s8 := y[8]; + var t0 := s0 + s6 * 0.5; + s0 -= s6; + var t4 := (s4 + s2) * 0.93969262; + var t2 := (s8 + s2) * 0.76604444; + s6 = (s4 - s8) * 0.17364818; + s4 += s8 - s2; + s2 = s0 - s4 * 0.5; + y[4] = s4 + s0; + s8 = t0 - t2 + s6; + s0 = t0 - t4 + t2; + s4 = t0 + t4 - s6; + var s1 := y[1]; + var s3 := y[3]; + var s5 := y[5]; + var s7 := y[7]; + s3 *= 0.86602540; + t0 = (s5 + s1) * 0.98480775; + t4 = (s5 - s7) * 0.34202014; + t2 = (s1 + s7) * 0.64278761; + s1 = (s1 - s5 - s7) * 0.86602540; + s5 = t0 - s3 - t2; + s7 = t4 - s3 - t0; + s3 = t4 + s3 - t2; + y[0] = s4 - s7; + y[1] = s2 + s1; + y[2] = s0 - s3; + y[3] = s8 + s5; + y[5] = s8 - s5; + y[6] = s0 + s3; + y[7] = s2 - s1; + y[8] = s4 + s7; +} + +# Each of so many subbands' 36-point IMDCT, windowed, overlapped with the +# granule before's. +def layer3::imdct36(&mut this, at: u64, over: u64, window: u64, count: u64): void { + for j in 0..count { + val g := at + j * 18; + val o := over + j * 9; + var co: f32[9]; + var si: f32[9]; + co[0] = -this.grbuf[g]; + si[0] = this.grbuf[g + 17]; + for i in 0..4u { + si[8 - 2 * i] = this.grbuf[g + 4 * i + 1] - this.grbuf[g + 4 * i + 2]; + co[1 + 2 * i] = this.grbuf[g + 4 * i + 1] + this.grbuf[g + 4 * i + 2]; + si[7 - 2 * i] = this.grbuf[g + 4 * i + 4] - this.grbuf[g + 4 * i + 3]; + co[2 + 2 * i] = -(this.grbuf[g + 4 * i + 3] + this.grbuf[g + 4 * i + 4]); + } + dct3_9(&mut co); + dct3_9(&mut si); + si[1] = -si[1]; + si[3] = -si[3]; + si[5] = -si[5]; + si[7] = -si[7]; + for i in 0..9u { + val ovl := this.overlap[o + i]; + val sum := co[i] * twiddle9[9 + i] + si[i] * twiddle9[i]; + this.overlap[o + i] = co[i] * twiddle9[i] - si[i] * twiddle9[9 + i]; + this.grbuf[g + i] = ovl * mdct_window[window + i] - sum * mdct_window[window + 9 + i]; + this.grbuf[g + 17 - i] = ovl * mdct_window[window + 9 + i] + sum * mdct_window[window + i]; + } + } +} + +def idct3(x0: f32, x1: f32, x2: f32, dst: &mut f32[3]): void { + val m1 := x1 * 0.86602540; + val a1 := x0 - x2 * 0.5; + dst[1] = x0 + x2; + dst[0] = a1 + m1; + dst[2] = a1 - m1; +} + +# A 12-point IMDCT of a window's values, every third from `x`, into six of +# `dst`, overlapped with three of `overlap`. +def imdct12(x: &f32[18], from: u64, dst: slice, overlap: slice): void { + var co: f32[3]; + var si: f32[3]; + idct3(-x[from], x[from + 6] + x[from + 3], x[from + 12] + x[from + 9], &mut co); + idct3(x[from + 15], x[from + 12] - x[from + 9], x[from + 6] - x[from + 3], &mut si); + si[1] = -si[1]; + for i in 0..3u { + val ovl := overlap[i]; + val sum := co[i] * twiddle3[3 + i] + si[i] * twiddle3[i]; + overlap[i] = co[i] * twiddle3[i] - si[i] * twiddle3[3 + i]; + dst[i] = ovl * twiddle3[2 - i] - sum * twiddle3[5 - i]; + dst[5 - i] = ovl * twiddle3[5 - i] + sum * twiddle3[2 - i]; + } +} + +# Each of so many subbands' three short windows' IMDCTs, overlapped. +def layer3::imdct_short(&mut this, at: u64, over: u64, count: u64): void { + for j in 0..count { + val g := at + j * 18; + val o := over + j * 9; + var tmp: f32[18]; + for i in 0..18u { + tmp[i] = this.grbuf[g + i]; + } + for i in 0..6u { + this.grbuf[g + i] = this.overlap[o + i]; + } + val grbuf := this.grbuf.data; + val overlap := this.overlap.data; + imdct12(&tmp, 0, slice::::over(grbuf + g + 6, 6), slice::::over(overlap + o + 6, 3)); + imdct12(&tmp, 1, slice::::over(grbuf + g + 12, 6), slice::::over(overlap + o + 6, 3)); + imdct12(&tmp, 2, slice::::over(overlap + o, 6), slice::::over(overlap + o + 6, 3)); + } +} + +# Every other value of every odd subband negated, as the synthesis takes them. +def layer3::change_sign(&mut this, at: u64): void { + var b: u64 = 0; + var g := at + 18; + while b < 32 { + var i: u64 = 1; + while i < 18 { + this.grbuf[g + i] = -this.grbuf[g + i]; + i += 2; + } + b += 2; + g += 36; + } +} + +def layer3::imdct_granule(&mut this, ch: u64, block_type: u32, long_bands: u64): void { + var at := ch * 576; + var over := ch * 288; + if long_bands > 0 { + this.imdct36(at, over, 0, long_bands); + at += 18 * long_bands; + over += 9 * long_bands; + } + if block_type == 2 { + this.imdct_short(at, over, 32 - long_bands); + } else { + this.imdct36(at, over, block_type == 3 ? 18u : 0u, 32 - long_bands); + } +} + +# Decodes the granules of a frame's channels, from its main data on, into +# each channel's 576 values, ready for synthesis. +def layer3::decode_granule(&mut this, h: span, g: u64, channels: u64): void { + for ch in 0..channels { + val limit := this.bs.pos + this.gr[g + ch].part23 as u64; + var bs := this.bs; + this.decode_scalefactors(h, g + ch, &mut bs, ch); + this.huffman(ch, &mut bs, g + ch, limit); + this.bs = bs; + } + if is_intensity(h) { + this.intensity(g, h); + } else if is_mid_side(h) { + this.midside(0, 576); + } + for ch in 0..channels { + val gr: granule = this.gr[g + ch]; + var aa: i32 = 31; + val long_bands := ((gr.mixed != 0 ? 2u : 0u) << (rate_index(h) == 2 ? 1u : 0u)) as u64; + if gr.short_bands != 0 { + aa = long_bands as i32 - 1; + this.reorder(ch * 576 + long_bands * 18, gr.bands[gr.long_bands as u64:gr.bands.length - gr.long_bands as u64]); + } + this.antialias(ch * 576, aa); + this.imdct_granule(ch, gr.block_type, long_bands); + this.change_sign(ch * 576); + } +} + +# The DCT-II of the polyphase synthesis, of each of so many of a channel's +# rows of 32 subbands' values, 18 apart. +def layer3::dct_ii(&mut this, at: u64, n: u64): void { + for k in 0..n { + var t: f32[32]; + val y := at + k; + for i in 0..8u { + val x0 := this.grbuf[y + i * 18]; + val x1 := this.grbuf[y + (15 - i) * 18]; + val x2 := this.grbuf[y + (16 + i) * 18]; + val x3 := this.grbuf[y + (31 - i) * 18]; + val t0 := x0 + x3; + val t1 := x1 + x2; + val t2 := (x1 - x2) * secants[3 * i]; + val t3 := (x0 - x3) * secants[3 * i + 1]; + t[i] = t0 + t1; + t[8 + i] = (t0 - t1) * secants[3 * i + 2]; + t[16 + i] = t3 + t2; + t[24 + i] = (t3 - t2) * secants[3 * i + 2]; + } + for q in 0..4u { + val b := q * 8; + var x0 := t[b]; + var x1 := t[b + 1]; + var x2 := t[b + 2]; + var x3 := t[b + 3]; + var x4 := t[b + 4]; + var x5 := t[b + 5]; + var x6 := t[b + 6]; + var x7 := t[b + 7]; + var xt := x0 - x7; + x0 += x7; + x7 = x1 - x6; + x1 += x6; + x6 = x2 - x5; + x2 += x5; + x5 = x3 - x4; + x3 += x4; + x4 = x0 - x3; + x0 += x3; + x3 = x1 - x2; + x1 += x2; + t[b] = x0 + x1; + t[b + 4] = (x0 - x1) * 0.70710677; + x5 = x5 + x6; + x6 = (x6 + x7) * 0.70710677; + x7 = x7 + xt; + x3 = (x3 + x4) * 0.70710677; + x5 -= x7 * 0.198912367; + x7 += x5 * 0.382683432; + x5 -= x7 * 0.198912367; + x0 = xt - x6; + xt += x6; + t[b + 1] = (xt + x7) * 0.50979561; + t[b + 2] = (x4 + x3) * 0.54119611; + t[b + 3] = (x0 - x5) * 0.60134488; + t[b + 5] = (x0 + x5) * 0.89997619; + t[b + 6] = (x4 - x3) * 1.30656302; + t[b + 7] = (xt - x7) * 2.56291556; + } + var p := y; + for i in 0..7u { + this.grbuf[p] = t[i]; + this.grbuf[p + 18] = t[16 + i] + t[24 + i] + t[24 + i + 1]; + this.grbuf[p + 36] = t[8 + i] + t[8 + i + 1]; + this.grbuf[p + 54] = t[16 + i + 1] + t[24 + i] + t[24 + i + 1]; + p += 72; + } + this.grbuf[p] = t[7]; + this.grbuf[p + 18] = t[23] + t[31]; + this.grbuf[p + 36] = t[15]; + this.grbuf[p + 54] = t[31]; + } +} + +# Two frames of a channel, as the synthesis's rows give them. +def layer3::synth_pair(&this, pcm: slice, at: u64, nch: u64, z: u64): void { + val s := &this.syn; + var a := (s[z + 14 * 64] - s[z]) * 29; + a += (s[z + 64] + s[z + 13 * 64]) * 213; + a += (s[z + 12 * 64] - s[z + 2 * 64]) * 459; + a += (s[z + 3 * 64] + s[z + 11 * 64]) * 2037; + a += (s[z + 10 * 64] - s[z + 4 * 64]) * 5153; + a += (s[z + 5 * 64] + s[z + 9 * 64]) * 6574; + a += (s[z + 8 * 64] - s[z + 6 * 64]) * 37489; + a += s[z + 7 * 64] * 75038; + pcm[at] = a * (1.0 / 32768.0); + val y := z + 2; + var b := s[y + 14 * 64] * 104; + b += s[y + 12 * 64] * 1567; + b += s[y + 10 * 64] * 9727; + b += s[y + 8 * 64] * 64019; + b += s[y + 6 * 64] * -9975; + b += s[y + 4 * 64] * -45; + b += s[y + 2 * 64] * 146; + b += s[y] * -5; + pcm[at + 16 * nch] = b * (1.0 / 32768.0); +} + +# 64 frames of each channel, of two rows of subbands' values from `xl`, the +# right's 576 after, into `pcm` from `out`, as the synthesis's rows from `lins` +# on hold them. +def layer3::synth(&mut this, xl: u64, pcm: slice, out: u64, nch: u64, lins: u64): void { + val xr := xl + 576 * (nch - 1); + val left := out; + val right := out + (nch - 1); + val z := lins + 15 * 64; + this.syn[z + 60] = this.grbuf[xl + 18 * 16]; + this.syn[z + 61] = this.grbuf[xr + 18 * 16]; + this.syn[z + 62] = this.grbuf[xl]; + this.syn[z + 63] = this.grbuf[xr]; + this.syn[z + 124] = this.grbuf[xl + 1 + 18 * 16]; + this.syn[z + 125] = this.grbuf[xr + 1 + 18 * 16]; + this.syn[z + 126] = this.grbuf[xl + 1]; + this.syn[z + 127] = this.grbuf[xr + 1]; + this.synth_pair(pcm, right, nch, lins + 60 + 1); + this.synth_pair(pcm, right + 32 * nch, nch, lins + 60 + 64 + 1); + this.synth_pair(pcm, left, nch, lins + 60); + this.synth_pair(pcm, left + 32 * nch, nch, lins + 60 + 64); + + var i: i64 = 14; + while i >= 0 { + val u := i as u64; + var a: f32[4]; + var b: f32[4]; + this.syn[z + 4 * u] = this.grbuf[xl + 18 * (31 - u)]; + this.syn[z + 4 * u + 1] = this.grbuf[xr + 18 * (31 - u)]; + this.syn[z + 4 * u + 2] = this.grbuf[xl + 1 + 18 * (31 - u)]; + this.syn[z + 4 * u + 3] = this.grbuf[xr + 1 + 18 * (31 - u)]; + this.syn[z + 4 * (u + 16)] = this.grbuf[xl + 1 + 18 * (1 + u)]; + this.syn[z + 4 * (u + 16) + 1] = this.grbuf[xr + 1 + 18 * (1 + u)]; + this.syn[z + 4 * u - 64 + 2] = this.grbuf[xl + 18 * (1 + u)]; + this.syn[z + 4 * u - 64 + 3] = this.grbuf[xr + 18 * (1 + u)]; + val w := (14 - u) * 16; + for k in 0..8u { + val w0 := synthesis_window[w + k * 2]; + val w1 := synthesis_window[w + k * 2 + 1]; + val vz := z + 4 * u - k * 64; + val vy := z + 4 * u - (15 - k) * 64; + for j in 0..4u { + val zz := this.syn[vz + j]; + val yy := this.syn[vy + j]; + if k == 0 { + b[j] = zz * w1 + yy * w0; + a[j] = zz * w0 - yy * w1; + } else if k % 2 == 1 { + b[j] += zz * w1 + yy * w0; + a[j] += yy * w1 - zz * w0; + } else { + b[j] += zz * w1 + yy * w0; + a[j] += zz * w0 - yy * w1; + } + } + } + val scale: f32 = 1.0 / 32768.0; + pcm[right + (15 - u) * nch] = a[1] * scale; + pcm[right + (17 + u) * nch] = b[1] * scale; + pcm[left + (15 - u) * nch] = a[0] * scale; + pcm[left + (17 + u) * nch] = b[0] * scale; + pcm[right + (47 - u) * nch] = a[3] * scale; + pcm[right + (49 + u) * nch] = b[3] * scale; + pcm[left + (47 - u) * nch] = a[2] * scale; + pcm[left + (49 + u) * nch] = b[2] * scale; + i--; + } +} + +# A granule's 576 frames of each channel, synthesized of its subbands' values. +def layer3::synth_granule(&mut this, pcm: slice, out: u64, nch: u64): void { + for ch in 0..nch { + this.dct_ii(ch * 576, 18); + } + for i in 0..15u * 64 { + this.syn[i] = this.qmf[i]; + } + var i: u64 = 0; + while i < 18 { + this.synth(i, pcm, out + 32 * nch * i, nch, i * 64); + i += 2; + } + for k in 0..15u * 64 { + this.qmf[k] = this.syn[18 * 64 + k]; + } +} + +# Decodes a frame of Layer III into its frames of sound, a frame's channels +# together, `frame_samples` of them. +# @returns Whether its main data was all there: where it reaches back past +# what's held, as the first frames after a seek may, it's silent. +def layer3::decode_frame(&mut this, frame: span, pcm: slice): bool { + val h := frame[0:4]; + val nch: u64 = is_mono(h) ? 1 : 2; + var bs := bits{ data = frame.data + 4, limit = (frame.length - 4) * 8 }; + if has_crc(h) { + _ = bs.get(16); + } + val main_data_begin := this.read_side_info(&mut bs, h); + val granules: u64 = is_mpeg1(h) ? 2 : 1; + for i in 0..pcm.length { + pcm[i] = 0; + } + if main_data_begin < 0 || bs.pos > bs.limit { + this.reserved = 0; + return false; + } + # The main data: what the reservoir holds of where it begins, then the + # frame's own after its side information. + val begin := main_data_begin as u64; + val payload := (bs.limit - bs.pos) / 8; + val have := this.reserved < begin ? this.reserved : begin; + val from := this.reserved > begin ? this.reserved - begin : 0u; + for i in 0..have { + this.main[i] = this.reservoir[from + i]; + } + val start := 4 + bs.pos / 8; + for i in 0..payload { + this.main[have + i] = frame[start + i]; + } + for i in have + payload..this.main.length { + this.main[i] = 0; + } + this.bs = bits{ data = this.main.data, limit = (have + payload) * 8 }; + val whole := this.reserved >= begin; + if whole { + for g in 0..granules { + for i in 0..this.grbuf.length { + this.grbuf[i] = 0; + } + this.decode_granule(h, g * nch, nch); + this.synth_granule(pcm, g * 576 * nch, nch); + } + } + # What's left of the main data, kept for the frames after. + var keep_at := (this.bs.pos + 7) / 8; + var remains: i64 = (this.bs.limit / 8) as i64 - keep_at as i64; + if remains > most_reservoir as i64 { + keep_at += remains as u64 - most_reservoir; + remains = most_reservoir as i64; + } + if remains > 0 { + for i in 0..remains as u64 { + this.reservoir[i] = this.main[keep_at + i]; + } + this.reserved = remains as u64; + } else { + this.reserved = 0; + } + return whole; +} diff --git a/audio/mp3/mp3.sakura b/audio/mp3/mp3.sakura new file mode 100644 index 0000000..4c2ef5d --- /dev/null +++ b/audio/mp3/mp3.sakura @@ -0,0 +1,275 @@ +#! Contains `decoder`, which reads an MP3 stream's frames as it's asked for +#! them, so a long one plays without being held decoded, and from anywhere it's +#! sought, and `decode`, which reads one whole. +#! +#! MPEG-1, MPEG-2, and MPEG-2.5's Layer III is read, of one channel or two, of +#! any bit rate but the free format, as `layer3.sakura` decodes it. Its frames +#! are found as it's opened, each where the one before ends, or, past what +#! isn't one, at the next of the same stream, so it's sought to any frame. An +#! ID3v2 tag before them is skipped. A Xing or Info frame first, as LAME and +#! FFmpeg write, isn't sound; where it says how much silence the encoder added +#! before the sound and after, those frames are cut, as FFmpeg cuts them, the +#! decoder's own delay of 529 frames with the first, so a stream gives the +#! frames it was encoded from. + +import std::math; +module malunal::audio::mp3; + + +# How many frames of MP3's are decoded before one sought, so its main data's +# reservoir and its filters are as they'd be had it been decoded from the start. +const preroll: u64 = 10; +# The frames a decoder's output lags its sound by. +const decoder_delay: u64 = 529; + +#! Reads an MP3 stream's frames as it's asked for them. Its bytes must stay +#! where they are while it reads them. +pub struct decoder { + var bytes: span; + var starts: vector; # Where each frame of MP3's begins. + var width: u32; # Its channels. + var stream_rate: u32; + var per: u64; # The frames of sound each gives. + var skip: u64; # Those decoded before the sound begins. + var total: u64; # How many frames of sound it has. + var state: layer3; + var next: u64; # The frame of MP3's decoded next. + var clock: u64; # The frame of what's decoded `next` begins at, before `skip`. + var pcm: vector; # A frame's sound. + var pending: vector; # Frames decoded and not yet read, a frame's together. + var taken: u64; + var from: u64; # The frame, before `skip`, a seek asked for. +} + +#! Opens an MP3 stream, finding its frames. +#! @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 +#! no run of frames of Layer III is found. +pub def decoder::open(bytes: span): result { + var made := decoder{ + bytes = bytes, starts = vector::::new(), state = layer3::new(), pcm = vector::::new(), + pending = vector::::new(), + }; + val first := first_frame(bytes, audio::past_id3(bytes)) else { return audio_error::unrecognized; }; + val head := bytes[first:4]; + made.width = is_mono(head) ? 1 : 2; + made.stream_rate = sample_rate(head); + made.per = frame_samples(head) as u64; + # Every frame of the stream, past what isn't one. + var at := first; + while at + 4 <= bytes.length { + val here := bytes[at:4]; + if same_stream(head, here) && at + frame_length(here) <= bytes.length { + made.starts.append(at); + at += frame_length(here); + continue; + } + at++; + while at + 4 <= bytes.length && !(bytes[at] == 0xFF && same_stream(head, bytes[at:4])) { + at++; + } + } + # A Xing or Info frame first: no sound, but maybe what the encoder added. + if made.info_frame() is some(&gap) { + made.starts.remove_at(0); + made.skip = gap[0] + decoder_delay; + val all := made.starts.length as u64 * made.per; + made.total = all > gap[0] + gap[1] ? all - gap[0] - gap[1] : 0u; + if gap[0] == 0 && gap[1] == 0 { + made.skip = 0; + made.total = all; + } + } else { + made.total = made.starts.length as u64 * made.per; + } + return audio_error::unrecognized if made.starts.empty; + made.pcm.resize(made.per * made.width as u64); + return made; +} + +# The first frame of a run of three of the same stream, each where the one +# before ends, from a place on. +def first_frame(bytes: span, from: u64): maybe { + var at := from; + while at + 4 <= bytes.length { + if bytes[at] == 0xFF && header_valid(bytes[at:4]) { + val head := bytes[at:4]; + var p := at; + var run: u32 = 0; + while run < 3 && p + 4 <= bytes.length && same_stream(head, bytes[p:4]) { + p += frame_length(bytes[p:4]); + run++; + } + # A file of fewer frames than that, whole. + return at if run == 3 || (run > 0 && p >= bytes.length); + } + at++; + } + return nothing {}; +} + +# Where the first frame is of Xing's or Info's, what the encoder added before +# the sound and after, as its LAME tag says, or none where it says nothing. +def decoder::info_frame(&this): maybe { + return nothing {} if this.starts.empty; + val at := this.starts[0]; + val head := this.bytes[at:4]; + val side: u64 = is_mpeg1(head) ? (is_mono(head) ? 17 : 32) : (is_mono(head) ? 9 : 17); + var p := at + 4 + side + (has_crc(head) ? 2u : 0u); + val end := at + frame_length(head); + return nothing {} if p + 8 > end; + val tag := this.bytes[p:4]; + val xing := tag[0] == 'X' && tag[1] == 'i' && tag[2] == 'n' && tag[3] == 'g'; + val info := tag[0] == 'I' && tag[1] == 'n' && tag[2] == 'f' && tag[3] == 'o'; + return nothing {} if !xing && !info; + val flags := this.bytes[p + 7] as u32; + p += 8; + if (flags & 1) != 0 { + p += 4; + } + if (flags & 2) != 0 { + p += 4; + } + if (flags & 4) != 0 { + p += 100; + } + if (flags & 8) != 0 { + p += 4; + } + var gap: u64[2] = [0, 0]; + # LAME's tag, or FFmpeg's of the same layout: its delays 21 bytes in. + if p + 24 <= end { + val name := this.bytes[p:4]; + val lame := name[0] == 'L' && ((name[1] == 'A' && name[2] == 'M' && name[3] == 'E') || (name[1] == 'a' && name[2] == 'v')); + if lame { + val v := (this.bytes[p + 21] as u64) << 16 | (this.bytes[p + 22] as u64) << 8 | this.bytes[p + 23] as u64; + gap = [v >> 12, v & 4095]; + } + } + return gap; +} + +#! How many channels the frames read have: one, or two. +pub val decoder::channels: u32 { + get => this.width; +} + +#! Frames a second. +pub val decoder::rate: u32 { + get => this.stream_rate; +} + +#! How many frames the stream has. +pub val decoder::frames: u64 { + get => this.total; +} + +#! Where the stream says a voice playing it loops: MP3 says nothing, so all of +#! it. +pub val decoder::loop_points: loop_range { + get => loop_range{}; +} + +#! 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.width 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 { + 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; + } + this.pending.clear(); + this.taken = 0; + break if !this.next_frame(); + } + return given; +} + +#! Reads the stream again from its first frame. +pub def decoder::rewind(&mut this): void { + this.state.reset(); + this.next = 0; + this.clock = 0; + this.from = 0; + this.pending.clear(); + this.taken = 0; +} + +#! Reads on from a frame of the stream: from a few frames of MP3's before it, +#! decoded so what's sought is as it'd be from the start, those left out. +#! @param frame The frame, past the end where the stream ends there. +#! @returns Nothing: every frame was found as the stream was opened. +pub def decoder::seek(&mut this, frame: u64): result { + this.rewind(); + val wanted := (frame < this.total ? frame : this.total) + this.skip; + val holding := wanted / this.per; + this.next = holding > preroll ? holding - preroll : 0u; + this.clock = this.next * this.per; + this.from = wanted; + return; +} + +# Decodes the next frame of MP3's into what's pending: but those frames of +# sound before where the sound begins, or a seek asked for, or past where it +# ends. +# @returns Whether there was one. +def decoder::next_frame(&mut this): bool { + val end := this.skip + this.total; + while true { + return false if this.next >= this.starts.length as u64 || this.clock >= end; + val at := this.starts[this.next]; + val frame := this.bytes[at:frame_length(this.bytes[at:4])]; + _ = this.state.decode_frame(frame, this.pcm.slice); + this.next++; + val begins := this.clock; + this.clock += this.per; + # The frames of sound of it kept. + val low := math::max(begins, math::max(this.from, this.skip)); + val high := math::min(this.clock, end); + continue if low >= high; + val width := this.width as u64; + for i in (low - begins) * width..(high - begins) * width { + this.pending.append(this.pcm[i]); + } + return true; + } + return false; +} + +#! Whether bytes begin a frame of MP3's, of Layer III. +#! @param bytes The bytes, past any ID3v2 tag. +pub def begins(bytes: span): bool { + return bytes.length >= 4 && header_valid(bytes[0:4]); +} + +#! Reads an MP3 file whole. +#! @param bytes The file's bytes. +#! @returns The sound, or why it couldn't be read: as `decoder::open` says, 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 sound{ rate = reading.rate, channels = reading.channels, samples = move(samples) }; +} diff --git a/audio/mp3/tables.sakura b/audio/mp3/tables.sakura new file mode 100644 index 0000000..e327641 --- /dev/null +++ b/audio/mp3/tables.sakura @@ -0,0 +1,289 @@ +#! Contains the tables MPEG audio's Layer III is decoded by: its scale factor +#! bands, its Huffman codes, packed as minimp3 packs them, its powers, and the +#! windows and twiddles of its IMDCTs and its polyphase synthesis, each as +#! minimp3, which is in the public domain, keeps them. + +module malunal::audio::mp3; + + +# The bit rates of each version and layer, in kilobits a second, halved: of +# MPEG-2 and 2.5, then MPEG-1, each of layers III, II, and I. +const half_rates: u8[90] = [ + 0, 4, 8, 12, 16, 20, 24, 28, 32, 40, 48, 56, 64, 72, 80, + 0, 4, 8, 12, 16, 20, 24, 28, 32, 40, 48, 56, 64, 72, 80, + 0, 16, 24, 28, 32, 40, 48, 56, 64, 72, 80, 88, 96, 112, 128, + 0, 16, 20, 24, 28, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, + 0, 16, 24, 28, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, + 0, 16, 32, 48, 64, 80, 96, 112, 128, 144, 160, 176, 192, 208, 224, +]; + +# The rates of MPEG-1, halved for MPEG-2 and quartered for 2.5. +const rates: u32[3] = [44100, 48000, 32000]; + +# Of each rate's long blocks, 23 a rate, its scale factor bands' widths, ended by 0, in the order `rate_index` says. +const scf_long: u8[184] = [ + 6, 6, 6, 6, 6, 6, 8, 10, 12, 14, 16, 20, 24, 28, 32, 38, 46, 52, 60, 68, 58, 54, 0, 12, 12, 12, 12, 12, 12, 16, 20, + 24, 28, 32, 40, 48, 56, 64, 76, 90, 2, 2, 2, 2, 2, 0, 6, 6, 6, 6, 6, 6, 8, 10, 12, 14, 16, 20, 24, 28, 32, 38, 46, + 52, 60, 68, 58, 54, 0, 6, 6, 6, 6, 6, 6, 8, 10, 12, 14, 16, 18, 22, 26, 32, 38, 46, 54, 62, 70, 76, 36, 0, 6, 6, 6, + 6, 6, 6, 8, 10, 12, 14, 16, 20, 24, 28, 32, 38, 46, 52, 60, 68, 58, 54, 0, 4, 4, 4, 4, 4, 4, 6, 6, 8, 8, 10, 12, + 16, 20, 24, 28, 34, 42, 50, 54, 76, 158, 0, 4, 4, 4, 4, 4, 4, 6, 6, 6, 8, 10, 12, 16, 18, 22, 28, 34, 40, 46, 54, + 54, 192, 0, 4, 4, 4, 4, 4, 4, 6, 6, 8, 10, 12, 16, 20, 24, 30, 38, 46, 56, 68, 84, 102, 26, 0, +]; + +# Of short blocks, 40 a rate, each band's width three times over, a window's each. +const scf_short: u8[320] = [ + 4, 4, 4, 4, 4, 4, 4, 4, 4, 6, 6, 6, 8, 8, 8, 10, 10, 10, 12, 12, 12, 14, 14, 14, 18, 18, 18, 24, 24, 24, 30, 30, + 30, 40, 40, 40, 18, 18, 18, 0, 8, 8, 8, 8, 8, 8, 8, 8, 8, 12, 12, 12, 16, 16, 16, 20, 20, 20, 24, 24, 24, 28, 28, + 28, 36, 36, 36, 2, 2, 2, 2, 2, 2, 2, 2, 2, 26, 26, 26, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 6, 6, 6, 6, 6, 6, 8, 8, 8, 10, + 10, 10, 14, 14, 14, 18, 18, 18, 26, 26, 26, 32, 32, 32, 42, 42, 42, 18, 18, 18, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 6, 6, + 6, 8, 8, 8, 10, 10, 10, 12, 12, 12, 14, 14, 14, 18, 18, 18, 24, 24, 24, 32, 32, 32, 44, 44, 44, 12, 12, 12, 0, 4, + 4, 4, 4, 4, 4, 4, 4, 4, 6, 6, 6, 8, 8, 8, 10, 10, 10, 12, 12, 12, 14, 14, 14, 18, 18, 18, 24, 24, 24, 30, 30, 30, + 40, 40, 40, 18, 18, 18, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 6, 6, 6, 8, 8, 8, 10, 10, 10, 12, 12, 12, 14, 14, + 14, 18, 18, 18, 22, 22, 22, 30, 30, 30, 56, 56, 56, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 6, 6, 6, 6, 6, 6, 10, + 10, 10, 12, 12, 12, 14, 14, 14, 16, 16, 16, 20, 20, 20, 26, 26, 26, 66, 66, 66, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, + 4, 6, 6, 6, 8, 8, 8, 12, 12, 12, 16, 16, 16, 20, 20, 20, 26, 26, 26, 34, 34, 34, 42, 42, 42, 12, 12, 12, 0, +]; + +# Of mixed blocks, 40 a rate: the long bands below, then the short. +const scf_mixed: u8[320] = [ + 6, 6, 6, 6, 6, 6, 6, 6, 6, 8, 8, 8, 10, 10, 10, 12, 12, 12, 14, 14, 14, 18, 18, 18, 24, 24, 24, 30, 30, 30, 40, 40, 40, 18, 18, 18, 0, 0, 0, 0, + 12, 12, 12, 4, 4, 4, 8, 8, 8, 12, 12, 12, 16, 16, 16, 20, 20, 20, 24, 24, 24, 28, 28, 28, 36, 36, 36, 2, 2, 2, 2, 2, 2, 2, 2, 2, 26, 26, 26, 0, + 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 8, 8, 8, 10, 10, 10, 14, 14, 14, 18, 18, 18, 26, 26, 26, 32, 32, 32, 42, 42, 42, 18, 18, 18, 0, 0, 0, 0, + 6, 6, 6, 6, 6, 6, 6, 6, 6, 8, 8, 8, 10, 10, 10, 12, 12, 12, 14, 14, 14, 18, 18, 18, 24, 24, 24, 32, 32, 32, 44, 44, 44, 12, 12, 12, 0, 0, 0, 0, + 6, 6, 6, 6, 6, 6, 6, 6, 6, 8, 8, 8, 10, 10, 10, 12, 12, 12, 14, 14, 14, 18, 18, 18, 24, 24, 24, 30, 30, 30, 40, 40, 40, 18, 18, 18, 0, 0, 0, 0, + 4, 4, 4, 4, 4, 4, 6, 6, 4, 4, 4, 6, 6, 6, 8, 8, 8, 10, 10, 10, 12, 12, 12, 14, 14, 14, 18, 18, 18, 22, 22, 22, 30, 30, 30, 56, 56, 56, 0, 0, + 4, 4, 4, 4, 4, 4, 6, 6, 4, 4, 4, 6, 6, 6, 6, 6, 6, 10, 10, 10, 12, 12, 12, 14, 14, 14, 16, 16, 16, 20, 20, 20, 26, 26, 26, 66, 66, 66, 0, 0, + 4, 4, 4, 4, 4, 4, 6, 6, 4, 4, 4, 6, 6, 6, 8, 8, 8, 12, 12, 12, 16, 16, 16, 20, 20, 20, 26, 26, 26, 34, 34, 34, 42, 42, 42, 12, 12, 12, 0, 0, +]; + +# How many scale factors each of MPEG-2's four partitions has, by the kind of block, 28 each. +const scf_partitions: u8[84] = [ + 6, 5, 5, 5, 6, 5, 5, 5, 6, 5, 7, 3, 11, 10, 0, 0, 7, 7, 7, 0, 6, 6, 6, 3, 8, 8, 5, 0, 8, 9, 6, 12, 6, 9, 9, 9, 6, + 9, 12, 6, 15, 18, 0, 0, 6, 15, 12, 0, 6, 12, 9, 6, 6, 18, 9, 0, 9, 9, 6, 12, 9, 9, 9, 9, 9, 9, 12, 6, 18, 18, 0, 0, + 12, 12, 12, 0, 12, 9, 9, 6, 15, 12, 9, 0, +]; + +# MPEG-1's scale factors' sizes, of `scalefac_compress`, the first two partitions' in the high bits. +const scfc_decode: u8[16] = [ + 0, 1, 2, 3, 12, 5, 6, 7, 9, 10, 11, 13, 14, 15, 18, 19, +]; + +# The moduli MPEG-2's `scalefac_compress` is made of, four a range. +const scf_moduli: u8[24] = [ + 5, 5, 4, 4, 5, 5, 4, 1, 4, 3, 1, 1, 5, 6, 6, 1, 4, 4, 4, 1, 4, 3, 1, 1, +]; + +# What `preflag` adds to the scale factors of the long bands from the 12th. +const preamp: u8[10] = [ + 1, 1, 1, 1, 2, 2, 3, 3, 3, 2, +]; + +# Two to the quarters, below two to the -30, which `ldexp_q2` steps by. +const expfrac: f32[4] = [ + 9.31322575e-10, 7.83145814e-10, 6.58544508e-10, 5.53767716e-10, +]; + +# Each magnitude to the four thirds, negated first, from -15, then from 0 to 128. +const pow43: f32[145] = [ + 0, -1, -2.519842, -4.326749, -6.349604, -8.549880, -10.902724, -13.390518, -16.000000, -18.720754, -21.544347, + -24.463781, -27.473142, -30.567351, -33.741992, -36.993181, 0, 1, 2.519842, 4.326749, 6.349604, 8.549880, + 10.902724, 13.390518, 16.000000, 18.720754, 21.544347, 24.463781, 27.473142, 30.567351, 33.741992, 36.993181, + 40.317474, 43.711787, 47.173345, 50.699631, 54.288352, 57.937408, 61.644865, 65.408941, 69.227979, 73.100443, + 77.024898, 81.000000, 85.024491, 89.097188, 93.216975, 97.382800, 101.593667, 105.848633, 110.146801, 114.487321, + 118.869381, 123.292209, 127.755065, 132.257246, 136.798076, 141.376907, 145.993119, 150.646117, 155.335327, + 160.060199, 164.820202, 169.614826, 174.443577, 179.305980, 184.201575, 189.129918, 194.090580, 199.083145, + 204.107210, 209.162385, 214.248292, 219.364564, 224.510845, 229.686789, 234.892058, 240.126328, 245.389280, + 250.680604, 256.000000, 261.347174, 266.721841, 272.123723, 277.552547, 283.008049, 288.489971, 293.998060, + 299.532071, 305.091761, 310.676898, 316.287249, 321.922592, 327.582707, 333.267377, 338.976394, 344.709550, + 350.466646, 356.247482, 362.051866, 367.879608, 373.730522, 379.604427, 385.501143, 391.420496, 397.362314, + 403.326427, 409.312672, 415.320884, 421.350905, 427.402579, 433.475750, 439.570269, 445.685987, 451.822757, + 457.980436, 464.158883, 470.357960, 476.577530, 482.817459, 489.077615, 495.357868, 501.658090, 507.978156, + 514.317941, 520.677324, 527.056184, 533.454404, 539.871867, 546.308458, 552.764065, 559.238575, 565.731879, + 572.243870, 578.774440, 585.323483, 591.890898, 598.476581, 605.080431, 611.702349, 618.342238, 625.000000, + 631.675540, 638.368763, 645.079578, +]; + +# The Huffman tables of pairs, as lookups by the next bits: a leaf, its length above its two values, or, negative, a jump to a table of more bits. +const huffman: i16[2164] = [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 785, 785, 785, 785, + 784, 784, 784, 784, 513, 513, 513, 513, 513, 513, 513, 513, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, + 256, 256, 256, 256, 256, -255, 1313, 1298, 1282, 785, 785, 785, 785, 784, 784, 784, 784, 769, 769, 769, 769, 256, + 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 290, 288, -255, 1313, 1298, 1282, 769, + 769, 769, 769, 529, 529, 529, 529, 529, 529, 529, 529, 528, 528, 528, 528, 528, 528, 528, 528, 512, 512, 512, 512, + 512, 512, 512, 512, 290, 288, -253, -318, -351, -367, 785, 785, 785, 785, 784, 784, 784, 784, 769, 769, 769, 769, + 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 819, 818, 547, 547, 275, 275, 275, + 275, 561, 560, 515, 546, 289, 274, 288, 258, -254, -287, 1329, 1299, 1314, 1312, 1057, 1057, 1042, 1042, 1026, + 1026, 784, 784, 784, 784, 529, 529, 529, 529, 529, 529, 529, 529, 769, 769, 769, 769, 768, 768, 768, 768, 563, 560, + 306, 306, 291, 259, -252, -413, -477, -542, 1298, -575, 1041, 1041, 784, 784, 784, 784, 769, 769, 769, 769, 256, + 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, -383, -399, 1107, 1092, 1106, 1061, 849, + 849, 789, 789, 1104, 1091, 773, 773, 1076, 1075, 341, 340, 325, 309, 834, 804, 577, 577, 532, 532, 516, 516, 832, + 818, 803, 816, 561, 561, 531, 531, 515, 546, 289, 289, 288, 258, -252, -429, -493, -559, 1057, 1057, 1042, 1042, + 529, 529, 529, 529, 529, 529, 529, 529, 784, 784, 784, 784, 769, 769, 769, 769, 512, 512, 512, 512, 512, 512, 512, + 512, -382, 1077, -415, 1106, 1061, 1104, 849, 849, 789, 789, 1091, 1076, 1029, 1075, 834, 834, 597, 581, 340, 340, + 339, 324, 804, 833, 532, 532, 832, 772, 818, 803, 817, 787, 816, 771, 290, 290, 290, 290, 288, 258, -253, -349, + -414, -447, -463, 1329, 1299, -479, 1314, 1312, 1057, 1057, 1042, 1042, 1026, 1026, 785, 785, 785, 785, 784, 784, + 784, 784, 769, 769, 769, 769, 768, 768, 768, 768, -319, 851, 821, -335, 836, 850, 805, 849, 341, 340, 325, 336, + 533, 533, 579, 579, 564, 564, 773, 832, 578, 548, 563, 516, 321, 276, 306, 291, 304, 259, -251, -572, -733, -830, + -863, -879, 1041, 1041, 784, 784, 784, 784, 769, 769, 769, 769, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, + 256, 256, 256, 256, 256, 256, -511, -527, -543, 1396, 1351, 1381, 1366, 1395, 1335, 1380, -559, 1334, 1138, 1138, + 1063, 1063, 1350, 1392, 1031, 1031, 1062, 1062, 1364, 1363, 1120, 1120, 1333, 1348, 881, 881, 881, 881, 375, 374, + 359, 373, 343, 358, 341, 325, 791, 791, 1123, 1122, -703, 1105, 1045, -719, 865, 865, 790, 790, 774, 774, 1104, + 1029, 338, 293, 323, 308, -799, -815, 833, 788, 772, 818, 803, 816, 322, 292, 307, 320, 561, 531, 515, 546, 289, + 274, 288, 258, -251, -525, -605, -685, -765, -831, -846, 1298, 1057, 1057, 1312, 1282, 785, 785, 785, 785, 784, + 784, 784, 784, 769, 769, 769, 769, 512, 512, 512, 512, 512, 512, 512, 512, 1399, 1398, 1383, 1367, 1382, 1396, + 1351, -511, 1381, 1366, 1139, 1139, 1079, 1079, 1124, 1124, 1364, 1349, 1363, 1333, 882, 882, 882, 882, 807, 807, + 807, 807, 1094, 1094, 1136, 1136, 373, 341, 535, 535, 881, 775, 867, 822, 774, -591, 324, 338, -671, 849, 550, 550, + 866, 864, 609, 609, 293, 336, 534, 534, 789, 835, 773, -751, 834, 804, 308, 307, 833, 788, 832, 772, 562, 562, 547, + 547, 305, 275, 560, 515, 290, 290, -252, -397, -477, -557, -622, -653, -719, -735, -750, 1329, 1299, 1314, 1057, + 1057, 1042, 1042, 1312, 1282, 1024, 1024, 785, 785, 785, 785, 784, 784, 784, 784, 769, 769, 769, 769, -383, 1127, + 1141, 1111, 1126, 1140, 1095, 1110, 869, 869, 883, 883, 1079, 1109, 882, 882, 375, 374, 807, 868, 838, 881, 791, + -463, 867, 822, 368, 263, 852, 837, 836, -543, 610, 610, 550, 550, 352, 336, 534, 534, 865, 774, 851, 821, 850, + 805, 593, 533, 579, 564, 773, 832, 578, 578, 548, 548, 577, 577, 307, 276, 306, 291, 516, 560, 259, 259, -250, + -2107, -2507, -2764, -2909, -2974, -3007, -3023, 1041, 1041, 1040, 1040, 769, 769, 769, 769, 256, 256, 256, 256, + 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, -767, -1052, -1213, -1277, -1358, -1405, -1469, -1535, + -1550, -1582, -1614, -1647, -1662, -1694, -1726, -1759, -1774, -1807, -1822, -1854, -1886, 1565, -1919, -1935, + -1951, -1967, 1731, 1730, 1580, 1717, -1983, 1729, 1564, -1999, 1548, -2015, -2031, 1715, 1595, -2047, 1714, -2063, + 1610, -2079, 1609, -2095, 1323, 1323, 1457, 1457, 1307, 1307, 1712, 1547, 1641, 1700, 1699, 1594, 1685, 1625, 1442, + 1442, 1322, 1322, -780, -973, -910, 1279, 1278, 1277, 1262, 1276, 1261, 1275, 1215, 1260, 1229, -959, 974, 974, + 989, 989, -943, 735, 478, 478, 495, 463, 506, 414, -1039, 1003, 958, 1017, 927, 942, 987, 957, 431, 476, 1272, + 1167, 1228, -1183, 1256, -1199, 895, 895, 941, 941, 1242, 1227, 1212, 1135, 1014, 1014, 490, 489, 503, 487, 910, + 1013, 985, 925, 863, 894, 970, 955, 1012, 847, -1343, 831, 755, 755, 984, 909, 428, 366, 754, 559, -1391, 752, 486, + 457, 924, 997, 698, 698, 983, 893, 740, 740, 908, 877, 739, 739, 667, 667, 953, 938, 497, 287, 271, 271, 683, 606, + 590, 712, 726, 574, 302, 302, 738, 736, 481, 286, 526, 725, 605, 711, 636, 724, 696, 651, 589, 681, 666, 710, 364, + 467, 573, 695, 466, 466, 301, 465, 379, 379, 709, 604, 665, 679, 316, 316, 634, 633, 436, 436, 464, 269, 424, 394, + 452, 332, 438, 363, 347, 408, 393, 448, 331, 422, 362, 407, 392, 421, 346, 406, 391, 376, 375, 359, 1441, 1306, + -2367, 1290, -2383, 1337, -2399, -2415, 1426, 1321, -2431, 1411, 1336, -2447, -2463, -2479, 1169, 1169, 1049, 1049, + 1424, 1289, 1412, 1352, 1319, -2495, 1154, 1154, 1064, 1064, 1153, 1153, 416, 390, 360, 404, 403, 389, 344, 374, + 373, 343, 358, 372, 327, 357, 342, 311, 356, 326, 1395, 1394, 1137, 1137, 1047, 1047, 1365, 1392, 1287, 1379, 1334, + 1364, 1349, 1378, 1318, 1363, 792, 792, 792, 792, 1152, 1152, 1032, 1032, 1121, 1121, 1046, 1046, 1120, 1120, 1030, + 1030, -2895, 1106, 1061, 1104, 849, 849, 789, 789, 1091, 1076, 1029, 1090, 1060, 1075, 833, 833, 309, 324, 532, + 532, 832, 772, 818, 803, 561, 561, 531, 560, 515, 546, 289, 274, 288, 258, -250, -1179, -1579, -1836, -1996, -2124, + -2253, -2333, -2413, -2477, -2542, -2574, -2607, -2622, -2655, 1314, 1313, 1298, 1312, 1282, 785, 785, 785, 785, + 1040, 1040, 1025, 1025, 768, 768, 768, 768, -766, -798, -830, -862, -895, -911, -927, -943, -959, -975, -991, + -1007, -1023, -1039, -1055, -1070, 1724, 1647, -1103, -1119, 1631, 1767, 1662, 1738, 1708, 1723, -1135, 1780, 1615, + 1779, 1599, 1677, 1646, 1778, 1583, -1151, 1777, 1567, 1737, 1692, 1765, 1722, 1707, 1630, 1751, 1661, 1764, 1614, + 1736, 1676, 1763, 1750, 1645, 1598, 1721, 1691, 1762, 1706, 1582, 1761, 1566, -1167, 1749, 1629, 767, 766, 751, + 765, 494, 494, 735, 764, 719, 749, 734, 763, 447, 447, 748, 718, 477, 506, 431, 491, 446, 476, 461, 505, 415, 430, + 475, 445, 504, 399, 460, 489, 414, 503, 383, 474, 429, 459, 502, 502, 746, 752, 488, 398, 501, 473, 413, 472, 486, + 271, 480, 270, -1439, -1455, 1357, -1471, -1487, -1503, 1341, 1325, -1519, 1489, 1463, 1403, 1309, -1535, 1372, + 1448, 1418, 1476, 1356, 1462, 1387, -1551, 1475, 1340, 1447, 1402, 1386, -1567, 1068, 1068, 1474, 1461, 455, 380, + 468, 440, 395, 425, 410, 454, 364, 467, 466, 464, 453, 269, 409, 448, 268, 432, 1371, 1473, 1432, 1417, 1308, 1460, + 1355, 1446, 1459, 1431, 1083, 1083, 1401, 1416, 1458, 1445, 1067, 1067, 1370, 1457, 1051, 1051, 1291, 1430, 1385, + 1444, 1354, 1415, 1400, 1443, 1082, 1082, 1173, 1113, 1186, 1066, 1185, 1050, -1967, 1158, 1128, 1172, 1097, 1171, + 1081, -1983, 1157, 1112, 416, 266, 375, 400, 1170, 1142, 1127, 1065, 793, 793, 1169, 1033, 1156, 1096, 1141, 1111, + 1155, 1080, 1126, 1140, 898, 898, 808, 808, 897, 897, 792, 792, 1095, 1152, 1032, 1125, 1110, 1139, 1079, 1124, + 882, 807, 838, 881, 853, 791, -2319, 867, 368, 263, 822, 852, 837, 866, 806, 865, -2399, 851, 352, 262, 534, 534, + 821, 836, 594, 594, 549, 549, 593, 593, 533, 533, 848, 773, 579, 579, 564, 578, 548, 563, 276, 276, 577, 576, 306, + 291, 516, 560, 305, 305, 275, 259, -251, -892, -2058, -2620, -2828, -2957, -3023, -3039, 1041, 1041, 1040, 1040, + 769, 769, 769, 769, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, -511, -527, + -543, -559, 1530, -575, -591, 1528, 1527, 1407, 1526, 1391, 1023, 1023, 1023, 1023, 1525, 1375, 1268, 1268, 1103, + 1103, 1087, 1087, 1039, 1039, 1523, -604, 815, 815, 815, 815, 510, 495, 509, 479, 508, 463, 507, 447, 431, 505, + 415, 399, -734, -782, 1262, -815, 1259, 1244, -831, 1258, 1228, -847, -863, 1196, -879, 1253, 987, 987, 748, -767, + 493, 493, 462, 477, 414, 414, 686, 669, 478, 446, 461, 445, 474, 429, 487, 458, 412, 471, 1266, 1264, 1009, 1009, + 799, 799, -1019, -1276, -1452, -1581, -1677, -1757, -1821, -1886, -1933, -1997, 1257, 1257, 1483, 1468, 1512, 1422, + 1497, 1406, 1467, 1496, 1421, 1510, 1134, 1134, 1225, 1225, 1466, 1451, 1374, 1405, 1252, 1252, 1358, 1480, 1164, + 1164, 1251, 1251, 1238, 1238, 1389, 1465, -1407, 1054, 1101, -1423, 1207, -1439, 830, 830, 1248, 1038, 1237, 1117, + 1223, 1148, 1236, 1208, 411, 426, 395, 410, 379, 269, 1193, 1222, 1132, 1235, 1221, 1116, 976, 976, 1192, 1162, + 1177, 1220, 1131, 1191, 963, 963, -1647, 961, 780, -1663, 558, 558, 994, 993, 437, 408, 393, 407, 829, 978, 813, + 797, 947, -1743, 721, 721, 377, 392, 844, 950, 828, 890, 706, 706, 812, 859, 796, 960, 948, 843, 934, 874, 571, + 571, -1919, 690, 555, 689, 421, 346, 539, 539, 944, 779, 918, 873, 932, 842, 903, 888, 570, 570, 931, 917, 674, + 674, -2575, 1562, -2591, 1609, -2607, 1654, 1322, 1322, 1441, 1441, 1696, 1546, 1683, 1593, 1669, 1624, 1426, 1426, + 1321, 1321, 1639, 1680, 1425, 1425, 1305, 1305, 1545, 1668, 1608, 1623, 1667, 1592, 1638, 1666, 1320, 1320, 1652, + 1607, 1409, 1409, 1304, 1304, 1288, 1288, 1664, 1637, 1395, 1395, 1335, 1335, 1622, 1636, 1394, 1394, 1319, 1319, + 1606, 1621, 1392, 1392, 1137, 1137, 1137, 1137, 345, 390, 360, 375, 404, 373, 1047, -2751, -2767, -2783, 1062, + 1121, 1046, -2799, 1077, -2815, 1106, 1061, 789, 789, 1105, 1104, 263, 355, 310, 340, 325, 354, 352, 262, 339, 324, + 1091, 1076, 1029, 1090, 1060, 1075, 833, 833, 788, 788, 1088, 1028, 818, 818, 803, 803, 561, 561, 531, 531, 816, + 771, 546, 546, 289, 274, 288, 258, -253, -317, -381, -446, -478, -509, 1279, 1279, -811, -1179, -1451, -1756, + -1900, -2028, -2189, -2253, -2333, -2414, -2445, -2511, -2526, 1313, 1298, -2559, 1041, 1041, 1040, 1040, 1025, + 1025, 1024, 1024, 1022, 1007, 1021, 991, 1020, 975, 1019, 959, 687, 687, 1018, 1017, 671, 671, 655, 655, 1016, + 1015, 639, 639, 758, 758, 623, 623, 757, 607, 756, 591, 755, 575, 754, 559, 543, 543, 1009, 783, -575, -621, -685, + -749, 496, -590, 750, 749, 734, 748, 974, 989, 1003, 958, 988, 973, 1002, 942, 987, 957, 972, 1001, 926, 986, 941, + 971, 956, 1000, 910, 985, 925, 999, 894, 970, -1071, -1087, -1102, 1390, -1135, 1436, 1509, 1451, 1374, -1151, + 1405, 1358, 1480, 1420, -1167, 1507, 1494, 1389, 1342, 1465, 1435, 1450, 1326, 1505, 1310, 1493, 1373, 1479, 1404, + 1492, 1464, 1419, 428, 443, 472, 397, 736, 526, 464, 464, 486, 457, 442, 471, 484, 482, 1357, 1449, 1434, 1478, + 1388, 1491, 1341, 1490, 1325, 1489, 1463, 1403, 1309, 1477, 1372, 1448, 1418, 1433, 1476, 1356, 1462, 1387, -1439, + 1475, 1340, 1447, 1402, 1474, 1324, 1461, 1371, 1473, 269, 448, 1432, 1417, 1308, 1460, -1711, 1459, -1727, 1441, + 1099, 1099, 1446, 1386, 1431, 1401, -1743, 1289, 1083, 1083, 1160, 1160, 1458, 1445, 1067, 1067, 1370, 1457, 1307, + 1430, 1129, 1129, 1098, 1098, 268, 432, 267, 416, 266, 400, -1887, 1144, 1187, 1082, 1173, 1113, 1186, 1066, 1050, + 1158, 1128, 1143, 1172, 1097, 1171, 1081, 420, 391, 1157, 1112, 1170, 1142, 1127, 1065, 1169, 1049, 1156, 1096, + 1141, 1111, 1155, 1080, 1126, 1154, 1064, 1153, 1140, 1095, 1048, -2159, 1125, 1110, 1137, -2175, 823, 823, 1139, + 1138, 807, 807, 384, 264, 368, 263, 868, 838, 853, 791, 867, 822, 852, 837, 866, 806, 865, 790, -2319, 851, 821, + 836, 352, 262, 850, 805, 849, -2399, 533, 533, 835, 820, 336, 261, 578, 548, 563, 577, 532, 532, 832, 772, 562, + 562, 547, 547, 305, 275, 560, 515, 290, 290, 288, 258, +]; + +# The table of quadruples A. +const count1_a: u8[28] = [ + 130, 162, 193, 209, 44, 28, 76, 140, 9, 9, 9, 9, 9, 9, 9, 9, 190, 254, 222, 238, 126, 94, 157, 157, 109, 61, 173, + 205, +]; + +# The table of quadruples B. +const count1_b: u8[16] = [ + 252, 236, 220, 204, 188, 172, 156, 140, 124, 108, 92, 76, 60, 44, 28, 12, +]; + +# Where each of the 32 tables begins among `huffman`. +const huffman_at: i16[32] = [ + 0, 32, 64, 98, 0, 132, 180, 218, 292, 364, 426, 538, 648, 746, 0, 1126, 1460, 1460, 1460, 1460, 1460, 1460, 1460, + 1460, 1842, 1842, 1842, 1842, 1842, 1842, 1842, 1842, +]; + +# How many bits each table adds to a value of 15. +const linbits: u8[32] = [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 6, 8, 10, 13, 4, 5, 6, 7, 8, 9, 11, 13, +]; + +# MPEG-1's intensity positions' left and right, of 0 to 6. +const intensity_pan: f32[14] = [ + 0, 1, 0.21132487, 0.78867513, 0.36602540, 0.63397460, 0.5, 0.5, 0.63397460, 0.36602540, 0.78867513, 0.21132487, 1, + 0, +]; + +# The butterflies' cs, then ca. +const antialias: f32[16] = [ + 0.85749293, 0.88174200, 0.94962865, 0.98331459, 0.99551782, 0.99916056, 0.99989920, 0.99999316, 0.51449576, + 0.47173197, 0.31337745, 0.18191320, 0.09457419, 0.04096558, 0.01419856, 0.00369997, +]; + +# The 36-point IMDCT's twiddles. +const twiddle9: f32[18] = [ + 0.73727734, 0.79335334, 0.84339145, 0.88701083, 0.92387953, 0.95371695, 0.97629601, 0.99144486, 0.99904822, + 0.67559021, 0.60876143, 0.53729961, 0.46174861, 0.38268343, 0.30070580, 0.21643961, 0.13052619, 0.04361938, +]; + +# The 12-point IMDCT's twiddles. +const twiddle3: f32[6] = [ + 0.79335334, 0.92387953, 0.99144486, 0.60876143, 0.38268343, 0.13052619, +]; + +# The windows of a normal long block, then of a stop block, 18 each. +const mdct_window: f32[36] = [ + 0.99904822, 0.99144486, 0.97629601, 0.95371695, 0.92387953, 0.88701083, 0.84339145, 0.79335334, 0.73727734, + 0.04361938, 0.13052619, 0.21643961, 0.30070580, 0.38268343, 0.46174861, 0.53729961, 0.60876143, 0.67559021, 1, 1, + 1, 1, 1, 1, 0.99144486, 0.92387953, 0.79335334, 0, 0, 0, 0, 0, 0, 0.13052619, 0.38268343, 0.60876143, +]; + +# The DCT-II's secants, three a step. +const secants: f32[24] = [ + 10.19000816, 0.50060302, 0.50241929, 3.40760851, 0.50547093, 0.52249861, 2.05778098, 0.51544732, 0.56694406, + 1.48416460, 0.53104258, 0.64682180, 1.16943991, 0.55310392, 0.78815460, 0.97256821, 0.58293498, 1.06067765, + 0.83934963, 0.62250412, 1.72244716, 0.74453628, 0.67480832, 5.10114861, +]; + +# The polyphase synthesis window, two of each eight at a time, fifteen rows. +const synthesis_window: f32[240] = [ + -1, 26, -31, 208, 218, 401, -519, 2063, 2000, 4788, -5517, 7134, 5959, 35640, -39336, 74992, -1, 24, -35, 202, 222, + 347, -581, 2080, 1952, 4425, -5879, 7640, 5288, 33791, -41176, 74856, -1, 21, -38, 196, 225, 294, -645, 2087, 1893, + 4063, -6237, 8092, 4561, 31947, -43006, 74630, -1, 19, -41, 190, 227, 244, -711, 2085, 1822, 3705, -6589, 8492, + 3776, 30112, -44821, 74313, -1, 17, -45, 183, 228, 197, -779, 2075, 1739, 3351, -6935, 8840, 2935, 28289, -46617, + 73908, -1, 16, -49, 176, 228, 153, -848, 2057, 1644, 3004, -7271, 9139, 2037, 26482, -48390, 73415, -2, 14, -53, + 169, 227, 111, -919, 2032, 1535, 2663, -7597, 9389, 1082, 24694, -50137, 72835, -2, 13, -58, 161, 224, 72, -991, + 2001, 1414, 2330, -7910, 9592, 70, 22929, -51853, 72169, -2, 11, -63, 154, 221, 36, -1064, 1962, 1280, 2006, -8209, + 9750, -998, 21189, -53534, 71420, -2, 10, -68, 147, 215, 2, -1137, 1919, 1131, 1692, -8491, 9863, -2122, 19478, + -55178, 70590, -3, 9, -73, 139, 208, -29, -1210, 1870, 970, 1388, -8755, 9935, -3300, 17799, -56778, 69679, -3, 8, + -79, 132, 200, -57, -1283, 1817, 794, 1095, -8998, 9966, -4533, 16155, -58333, 68692, -4, 7, -85, 125, 189, -83, + -1356, 1759, 605, 814, -9219, 9959, -5818, 14548, -59838, 67629, -4, 7, -91, 117, 177, -106, -1428, 1698, 402, 545, + -9416, 9916, -7154, 12980, -61289, 66494, -5, 6, -97, 111, 163, -127, -1498, 1634, 185, 288, -9585, 9838, -8540, + 11455, -62684, 65290, +]; diff --git a/audio/ogg/ogg.sakura b/audio/ogg/ogg.sakura new file mode 100644 index 0000000..08c8493 --- /dev/null +++ b/audio/ogg/ogg.sakura @@ -0,0 +1,296 @@ +#! Contains Ogg's pages, each checked by its CRC, and the packets of one logical +#! stream gathered from them, as RFC 3533 frames them, which the Vorbis and +#! Opus decoders read; and the pages of a stream found by their granule +#! positions, as they're sought. +#! +#! 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::ogg; + + +#! A page's flags: its first packet began on the page before. +pub const continued: u8 = 1; +#! It begins its logical stream. +pub const first_page: u8 = 2; +#! It ends its logical stream. +pub const last_page: u8 = 4; + +#! The granule position of a page on which no packet ends. +pub const no_granule: u64 = 0xFFFFFFFFFFFFFFFF; + +#! A page: where it is, what its header says, and where its segments' sizes and +#! its body are. +pub struct page { + pub var at: u64; #! Where it begins. + pub var flags: u8; + pub var granule: u64; #! Where its last packet ends, as its codec counts, or `no_granule`. + pub var serial: u32; #! The logical stream it's of. + pub var sequence: u32; #! Its place among its stream's pages. + pub var segments: u32; #! How many segments it laces. + pub var table: u64; #! Where its segments' sizes are. + pub var body: u64; #! Where its body begins. + pub var length: u64; #! How long its body is. + pub 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. +pub 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. +pub struct packet { + pub var data: span; + pub var granule: u64; + pub var last: bool; +} + +#! The packets of one logical stream, read from its pages in order. +pub struct packets { + pub var bytes: span; + pub var serial: u32; + pub var at: u64; #! Where the next page to look at begins. + pub var current: page; #! The page whose segments are being read. + var held: bool; # Whether there is one. + pub 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. + pub var done: bool; #! The stream's last page was read, or the bytes ended. +} + +#! Reads a stream's packets from a page on. +pub 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. +pub 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. +pub 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.span; + } 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; +} + +#! Where to read a stream's packets from, so the first ends after a granule +#! position: the end of the stream's last page whose position is at or before +#! it, found by halving the pages between where it could be, then page by page. +#! @param bytes The file's bytes. +#! @param serial The stream. +#! @param audio_at Where its first page of audio begins, which is returned +#! where no page is at or before the position. +#! @param granule The position. +pub def resume_at(bytes: span, serial: u32, audio_at: u64, granule: u64): u64 { + var low := audio_at; + var high := bytes.length; + var after := audio_at; + while high > low + 8192 { + val middle := low + (high - low) / 2; + val found := page_after(bytes, serial, audio_at, middle, high) else { high = middle; continue; }; + if found.granule <= granule { + low = found.body + found.length; + after = low; + } else { + high = middle; + } + } + var at := after; + while at < bytes.length { + val next := page_at(bytes, at) else (_) { break; }; + break if next.serial == serial && (next.granule == no_granule || next.granule > granule); + at = next.body + next.length; + if next.serial == serial { + after = at; + } + } + return after; +} + +# The first page of a stream at or after a place, before another, and not +# before its audio, whose granule position says where it is. +def page_after(bytes: span, serial: u32, audio_at: u64, from: u64, before: u64): maybe { + var at := from; + while at + 27 <= before { + if bytes[at] == 'O' && bytes[at + 1] == 'g' && bytes[at + 2] == 'g' && bytes[at + 3] == 'S' { + if page_at(bytes, at) is value(found) { + return found if found.serial == serial && found.granule != no_granule && found.at >= audio_at; + at = found.body + found.length; + continue; + } + } + at++; + } + return nothing {}; +} + +#! The granule position of a stream's last page, or 0 where none is found among +#! the last 64 KiB. +pub 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; +} + +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/opus/celt.sakura b/audio/opus/celt.sakura new file mode 100644 index 0000000..61997a8 --- /dev/null +++ b/audio/opus/celt.sakura @@ -0,0 +1,585 @@ +#! Contains CELT's decoder, which Opus codes music with, and the bands above +#! 8 kHz of its hybrid frames, as RFC 6716's section 4.3 has it and libopus's +#! float build decodes it: a frame's band energies read coarse, then fine, its +#! bits allocated, its bands' shapes read and scaled by their energies, an +#! inverse MDCT of one long block or several short ones overlapped with the +#! frame before, then its pitch post-filter and de-emphasis. +#! +#! A frame that's lost, or empty, decodes as silence, its last frame's end +#! fading out through the overlap: libopus's concealment, which carries on the +#! pitch of what came before, isn't done. + +import std::math; +module malunal::audio::opus; + + +# The frames of 2.5 ms, of a block, and of the overlap between blocks. +const short_size: u64 = 120; +const celt_overlap: u64 = 120; +# How much of each channel's decoded signal is kept: enough for the post-filter's longest period. +const decode_buffer: u64 = 2048; +const band_count: u64 = 21; +const min_period: i32 = 15; +const preemph_coef: f32 = 0.85000610; + +const tapset_icdf: u8[3] = [2, 1, 0]; +const spread_icdf: u8[4] = [25, 23, 2, 0]; +const trim_icdf: u8[11] = [126, 124, 119, 109, 87, 41, 19, 9, 4, 2, 0]; +const small_energy_icdf: u8[3] = [2, 1, 0]; + +# Each band's change of time and frequency resolution: of each LM, as the +# frame isn't and is transient, each choice of select and of its flag. +const tf_select_table: i8[32] = [ + 0, -1, 0, -1, 0, -1, 0, -1, + 0, -1, 0, -2, 1, 0, 1, -1, + 0, -2, 0, -3, 2, 0, 1, -1, + 0, -2, 0, -3, 3, 0, 1, -1, +]; + +# The coarse energy's prediction from the frame before, and from the band +# below, of each LM. +const pred_coef: f32[4] = [0.8984375, 0.796875, 0.6484375, 0.5]; +const beta_coef: f32[4] = [0.920013427734375, 0.67999267578125, 0.3699951171875, 0.20001220703125]; +const beta_intra: f32 = 0.149993896484375; + +# The post-filter's taps, of each tapset. +const comb_gains: f32[9] = [ + 0.3066406250, 0.2170410156, 0.1296386719, + 0.4638671875, 0.2680664062, 0.0, + 0.7998046875, 0.1000976562, 0.0, +]; + +# CELT's decoder of one stream, of one or two channels. +struct celt_decoder { + var channels: i32; # Those it gives. + var stream_channels: i32; # Those the frames have. + var start: i32; # The first band decoded: 17 in hybrid frames. + var end: i32; # And past the last, by the bandwidth. + var disable_inv: bool; + var rng: u32; # The last frame's final range, the next's noise seed. + var postfilter_period: i32; + var postfilter_period_old: i32; + var postfilter_gain: f32; + var postfilter_gain_old: f32; + var postfilter_tapset: i32; + var postfilter_tapset_old: i32; + var preemph_mem: f32[2]; + var memory: vector; # Each channel's last `decode_buffer` frames and an overlap. + var old_band_e: f32[42]; + var old_log_e: f32[42]; + var old_log_e2: f32[42]; + var background_log_e: f32[42]; + var shapes: vector; # Each channel's bands' shapes. + var freq: vector; # A channel's spectrum, and another's. + var norm: vector; # The folding sources. + var bands: band_ctx; +} + +def celt_decoder::new(channels: i32): celt_decoder { + var made := celt_decoder{ + channels = channels, stream_channels = channels, end = band_count as i32, disable_inv = channels == 1, + memory = vector::::new(), shapes = vector::::new(), freq = vector::::new(), + norm = vector::::new(), + bands = band_ctx{ pulses = vector::::new(), swap = vector::::new() }, + }; + made.memory.resize(2 * (decode_buffer + celt_overlap)); + made.shapes.resize(2 * 960); + made.freq.resize(2 * 960); + made.norm.resize(2 * 8 * 100); + made.bands.pulses.resize(176); + made.bands.swap.resize(176); + made.reset(); + return made; +} + +# Forgets every frame before, as a stream's start does. +def celt_decoder::reset(&mut this): void { + this.rng = 0; + this.postfilter_period = 0; + this.postfilter_period_old = 0; + this.postfilter_gain = 0; + this.postfilter_gain_old = 0; + this.postfilter_tapset = 0; + this.postfilter_tapset_old = 0; + this.preemph_mem = [0, 0]; + for i in 0..this.memory.length { + this.memory[i] = 0; + } + for i in 0..42 { + this.old_band_e[i] = 0; + this.old_log_e[i] = -28; + this.old_log_e2[i] = -28; + this.background_log_e[i] = 0; + } +} + +# Where a channel's decoded signal begins in `memory`. +def celt_decoder::channel_at(&this, c: i32): u64 { + return c as u64 * (decode_buffer + celt_overlap); +} + +# Decodes a frame. +# @param rd The frame's range decoder, from its start or where SILK left it. +# @param len The frame's bytes, 0 or 1 for a frame lost or empty. +# @param pcm Where its frames go, `channels` floats each. +# @param frame_size Its frames: 120, 240, 480, or 960. +# @returns Its frames. +def celt_decoder::decode(&mut this, rd: &mut range_decoder, len: i32, pcm: slice, frame_size: i32): i32 { + var lm: i32 = 0; + while lm <= 3 && (short_size as i32) << lm as u32 != frame_size { + lm++; + } + val m: i32 = 1 << lm as u32; + val n := frame_size; + val cc := this.channels; + val c_count := this.stream_channels; + val start := this.start; + val end := this.end; + val eff_end := math::min(end, band_count as i32); + + if len <= 1 { + this.decode_silent(n, lm, pcm); + return frame_size; + } + + if c_count == 1 { + for i in 0..band_count { + this.old_band_e[i] = math::max(this.old_band_e[i], this.old_band_e[band_count + i]); + } + } + var total_bits := len * 8; + var tell := rd.tell(); + var silence := false; + if tell >= total_bits { + silence = true; + } else if tell == 1 { + silence = rd.bit_logp(15); + } + if silence { + # As though every bit was read. + tell = len * 8; + rd.nbits_total += tell - rd.tell(); + } + + var postfilter_gain: f32 = 0; + var postfilter_pitch: i32 = 0; + var postfilter_tapset: i32 = 0; + if start == 0 && tell + 16 <= total_bits { + if rd.bit_logp(1) { + val octave := rd.uint(6) as i32; + postfilter_pitch = (16 << octave as u32) + rd.bits((4 + octave) as u32) as i32 - 1; + val qg := rd.bits(3) as i32; + if rd.tell() + 2 <= total_bits { + postfilter_tapset = rd.icdf(tapset_icdf[0:3], 2); + } + postfilter_gain = 0.09375 as f32 * (qg + 1) as f32; + } + tell = rd.tell(); + } + var transient := false; + if lm > 0 && tell + 3 <= total_bits { + transient = rd.bit_logp(3); + tell = rd.tell(); + } + val intra := tell + 3 <= total_bits ? rd.bit_logp(3) : false; + + this.unquant_coarse_energy(start, end, intra, rd, c_count, lm); + var tf_res: i32[21]; + tf_decode(start, end, transient, &mut tf_res, lm, rd); + tell = rd.tell(); + var spread := spread_normal; + if tell + 4 <= total_bits { + spread = rd.icdf(spread_icdf[0:4], 5); + } + var caps: i32[21]; + init_caps(&mut caps, lm, c_count); + + # Each band's boost. + var offsets: i32[21]; + var dynalloc_logp: i32 = 6; + total_bits <<= bitres as u32; + tell = rd.tell_frac(); + for i in start..end { + val width := c_count * band_width(i) << lm as u32; + val quanta := math::min(width << bitres as u32, math::max(6 << bitres as u32, width)); + var loop_logp := dynalloc_logp; + var boost: i32 = 0; + while tell + (loop_logp << bitres as u32) < total_bits && boost < caps[i as u64] { + val flag := rd.bit_logp(loop_logp as u32); + tell = rd.tell_frac(); + break if !flag; + boost += quanta; + total_bits -= quanta; + loop_logp = 1; + } + offsets[i as u64] = boost; + if boost > 0 { + dynalloc_logp = math::max(2, dynalloc_logp - 1); + } + } + val alloc_trim := tell + (6 << bitres as u32) <= total_bits ? rd.icdf(trim_icdf[0:11], 7) : 5; + var bits := ((len * 8) << bitres as u32) - rd.tell_frac() - 1; + val anti_collapse_rsv: i32 = transient && lm >= 2 && bits >= (lm + 2) << bitres as u32 ? 1 << bitres as u32 : 0; + bits -= anti_collapse_rsv; + var pulses: i32[21]; + var fine: i32[21]; + var priority: i32[21]; + val shared := compute_allocation(start, end, &offsets, &caps, alloc_trim, bits, &mut pulses, &mut fine, &mut priority, c_count, lm, rd); + this.unquant_fine_energy(start, end, &fine, rd, c_count); + + # What was decoded moves back a frame. + for c in 0..cc { + val at := this.channel_at(c); + val keep := decode_buffer - n as u64 + celt_overlap; + for i in 0..keep { + this.memory[at + i] = this.memory[at + n as u64 + i]; + } + } + + var masks: u8[42]; + val shapes := slice::::over(this.shapes.data, (c_count * n) as u64); + quant_all_bands( + start, end, shapes, c_count, n, &mut masks, &pulses, transient, spread, shared.dual, shared.intensity, + &tf_res, len * (8 << bitres as u32) - anti_collapse_rsv, shared.balance, rd, lm, shared.coded, &mut this.rng, + this.disable_inv, &mut this.bands, slice::::over(this.norm.data, this.norm.length), + ); + var anti_collapse_on := false; + if anti_collapse_rsv > 0 { + anti_collapse_on = rd.bits(1) != 0; + } + this.unquant_energy_finalise(start, end, &fine, &priority, len * 8 - rd.tell(), rd, c_count); + if anti_collapse_on { + anti_collapse(shapes, &masks, lm, c_count, n, start, end, &this.old_band_e, &this.old_log_e, &this.old_log_e2, &pulses, this.rng); + } + if silence { + for i in 0..(c_count as u64 * band_count) { + this.old_band_e[i] = -28; + } + } + this.synthesis(shapes, start, eff_end, c_count, cc, transient, lm, silence); + this.post_filter(n, lm, postfilter_pitch, postfilter_gain, postfilter_tapset); + + if c_count == 1 { + for i in 0..band_count { + this.old_band_e[band_count + i] = this.old_band_e[i]; + } + } + if !transient { + for i in 0..42 { + this.old_log_e2[i] = this.old_log_e[i]; + this.old_log_e[i] = this.old_band_e[i]; + } + } else { + for i in 0..42 { + this.old_log_e[i] = math::min(this.old_log_e[i], this.old_band_e[i]); + } + } + val increase := math::min(160, m) as f32 * 0.001; + for i in 0..42 { + this.background_log_e[i] = math::min(this.background_log_e[i] + increase, this.old_band_e[i]); + } + for c in 0..2 { + for i in 0..start { + this.old_band_e[(c * 21 + i) as u64] = 0; + this.old_log_e[(c * 21 + i) as u64] = -28; + this.old_log_e2[(c * 21 + i) as u64] = -28; + } + for i in end..21 { + this.old_band_e[(c * 21 + i) as u64] = 0; + this.old_log_e[(c * 21 + i) as u64] = -28; + this.old_log_e2[(c * 21 + i) as u64] = -28; + } + } + this.rng = rd.rng; + this.deemphasis(n, pcm); + return frame_size; +} + +# A frame lost or empty, as silence: no bands, the last frame's end fading out +# through the overlap and the post-filter. +def celt_decoder::decode_silent(&mut this, n: i32, lm: i32, pcm: slice): void { + for c in 0..this.channels { + val at := this.channel_at(c); + val keep := decode_buffer - n as u64 + celt_overlap; + for i in 0..keep { + this.memory[at + i] = this.memory[at + n as u64 + i]; + } + } + for i in 0..42 { + this.old_band_e[i] = -28; + } + val shapes := slice::::over(this.shapes.data, (this.stream_channels * n) as u64); + this.synthesis(shapes, 0, 0, this.stream_channels, this.channels, false, lm, true); + this.post_filter(n, lm, 0, 0, 0); + this.deemphasis(n, pcm); +} + +# Reads each band's energy coarsely: its difference from what's predicted, of +# the frame before and the band below, by a Laplace-like distribution. +def celt_decoder::unquant_coarse_energy(&mut this, start: i32, end: i32, intra: bool, rd: &mut range_decoder, channels: i32, lm: i32): void { + val model := (lm * 84 + (intra ? 42 : 0)) as u64; + var prev: f32[2] = [0, 0]; + val coef: f32 = intra ? 0 : pred_coef[lm as u64]; + val beta: f32 = intra ? beta_intra : beta_coef[lm as u64]; + val budget := rd.storage as i32 * 8; + for i in start..end { + for c in 0..channels { + val tell := rd.tell(); + var qi: i32 = -1; + if budget - tell >= 15 { + val pi := (2 * math::min(i, 20)) as u64; + qi = laplace_decode(rd, (e_prob_model[model + pi] as u32) << 7, (e_prob_model[model + pi + 1] as i32) << 6); + } else if budget - tell >= 2 { + qi = rd.icdf(small_energy_icdf[0:3], 2); + qi = (qi >> 1) ^ -(qi & 1); + } else if budget - tell >= 1 { + qi = rd.bit_logp(1) ? -1 : 0; + } + val q := qi as f32; + val at := (i + c * 21) as u64; + this.old_band_e[at] = math::max(-9 as f32, this.old_band_e[at]); + val tmp := coef * this.old_band_e[at] + prev[c as u64] + q; + this.old_band_e[at] = tmp; + prev[c as u64] = prev[c as u64] + q - beta * q; + } + } +} + +# Reads each band's finer energy, as raw bits. +def celt_decoder::unquant_fine_energy(&mut this, start: i32, end: i32, fine: &i32[21], rd: &mut range_decoder, channels: i32): void { + for i in start..end { + continue if fine[i as u64] <= 0; + for c in 0..channels { + val q2 := rd.bits(fine[i as u64] as u32); + val offset := (q2 as f32 + 0.5) * (1 << (14 - fine[i as u64]) as u32) as f32 * (1 as f32 / 16384) - 0.5; + this.old_band_e[(i + c * 21) as u64] += offset; + } + } +} + +# Spends the bits left on a last bit of fine energy, the bands of priority 0 first. +def celt_decoder::unquant_energy_finalise(&mut this, start: i32, end: i32, fine: &i32[21], priority: &i32[21], given_left: i32, rd: &mut range_decoder, channels: i32): void { + var left := given_left; + for prio in 0..2 { + var i := start; + while i < end && left >= channels { + if fine[i as u64] < max_fine_bits && priority[i as u64] == prio { + for c in 0..channels { + val q2 := rd.bits(1); + val offset := (q2 as f32 - 0.5) * (1 << (14 - fine[i as u64] - 1) as u32) as f32 * (1 as f32 / 16384); + this.old_band_e[(i + c * 21) as u64] += offset; + left--; + } + } + i++; + } + } +} + +# A symbol of CELT's Laplace-like distribution of energies. +def laplace_decode(rd: &mut range_decoder, given_fs: u32, decay: i32): i32 { + var value: i32 = 0; + var fs := given_fs; + val fm := rd.decode_bin(15); + var fl: u32 = 0; + if fm >= fs { + value++; + fl = fs; + fs = ((32768 - 32 - fs) * (16384 - decay) as u32 >> 15) + 1; + # The decaying part. + while fs > 1 && fm >= fl + 2 * fs { + fs *= 2; + fl += fs; + fs = ((fs - 2) * decay as u32) >> 15; + fs += 1; + value++; + } + # Past that, every value is as likely. + if fs <= 1 { + val di := (fm - fl) >> 1; + value += di as i32; + fl += 2 * di; + } + if fm < fl + fs { + value = -value; + } else { + fl += fs; + } + } + rd.update(fl, math::min(fl + fs, 32768 as u32), 32768); + return value; +} + +# Reads each band's change of time and frequency resolution. +def tf_decode(start: i32, end: i32, transient: bool, tf_res: &mut i32[21], lm: i32, rd: &mut range_decoder): void { + var budget := rd.storage as i32 * 8; + var tell := rd.tell(); + var logp: i32 = transient ? 2 : 4; + val select_rsv := lm > 0 && tell + logp + 1 <= budget; + if select_rsv { + budget--; + } + var changed: i32 = 0; + var curr: i32 = 0; + for i in start..end { + if tell + logp <= budget { + if rd.bit_logp(logp as u32) { + curr ^= 1; + } + tell = rd.tell(); + changed |= curr; + } + tf_res[i as u64] = curr; + logp = transient ? 4 : 5; + } + val row := (lm * 8 + (transient ? 4 : 0)) as u64; + var select: i32 = 0; + if select_rsv && tf_select_table[row + changed as u64] != tf_select_table[row + 2 + changed as u64] { + select = rd.bit_logp(1) ? 1 : 0; + } + for i in start..end { + tf_res[i as u64] = tf_select_table[row + (2 * select + tf_res[i as u64]) as u64] as i32; + } +} + +# Each channel's bands, scaled by their energies, through the inverse MDCT +# into what's decoded: a long block, or `m` short ones; a stream of one channel +# heard on two, or of two mixed to one. +def celt_decoder::synthesis(&mut this, shapes: slice, start: i32, eff_end: i32, c_count: i32, cc: i32, transient: bool, lm: i32, silence: bool): void { + val m: i32 = 1 << lm as u32; + val n := (short_size as i32) << lm as u32; + val blocks: i32 = transient ? m : 1; + val nb: i32 = transient ? short_size as i32 : n; + val shift: i32 = transient ? 3 : 3 - lm; + val freq := slice::::over(this.freq.data, n as u64); + val freq2 := slice::::over(this.freq.data + 960, n as u64); + if cc == 2 && c_count == 1 { + denormalise_bands(shapes, freq, &this.old_band_e, 0, start, eff_end, m, silence); + for i in 0..n { + freq2[i as u64] = freq[i as u64]; + } + this.blocks_to(0, freq2, blocks, nb, n, shift); + this.blocks_to(1, freq, blocks, nb, n, shift); + } else if cc == 1 && c_count == 2 { + denormalise_bands(shapes, freq, &this.old_band_e, 0, start, eff_end, m, silence); + denormalise_bands(sub(shapes, n as u64, n as u64), freq2, &this.old_band_e, 1, start, eff_end, m, silence); + for i in 0..n { + freq[i as u64] = 0.5 as f32 * freq[i as u64] + 0.5 as f32 * freq2[i as u64]; + } + this.blocks_to(0, freq, blocks, nb, n, shift); + } else { + for c in 0..cc { + denormalise_bands(sub(shapes, (c * n) as u64, n as u64), freq, &this.old_band_e, c, start, eff_end, m, silence); + this.blocks_to(c, freq, blocks, nb, n, shift); + } + } +} + +# A channel's spectrum through the inverse MDCT, block by block. +def celt_decoder::blocks_to(&mut this, c: i32, freq: slice, blocks: i32, nb: i32, n: i32, shift: i32): void { + val out_at := this.channel_at(c) + decode_buffer - n as u64; + for b in 0..blocks { + val at := out_at + (nb * b) as u64; + imdct(sub(freq, b as u64, (n - b) as u64), blocks, slice::::over(this.memory.data + at, nb as u64 + celt_overlap), shift); + } +} + +# The pitch post-filter on each channel's frame: the last frame's filter faded +# into the frame's over its first block's overlap. +def celt_decoder::post_filter(&mut this, n: i32, lm: i32, pitch: i32, gain: f32, tapset: i32): void { + for c in 0..this.channels { + this.postfilter_period = math::max(this.postfilter_period, min_period); + this.postfilter_period_old = math::max(this.postfilter_period_old, min_period); + val at := this.channel_at(c) + decode_buffer - n as u64; + comb_filter( + &mut this.memory, at, this.postfilter_period_old, this.postfilter_period, short_size as i32, + this.postfilter_gain_old, this.postfilter_gain, this.postfilter_tapset_old, this.postfilter_tapset, + ); + if lm != 0 { + comb_filter( + &mut this.memory, at + short_size, this.postfilter_period, pitch, n - short_size as i32, + this.postfilter_gain, gain, this.postfilter_tapset, tapset, + ); + } + } + this.postfilter_period_old = this.postfilter_period; + this.postfilter_gain_old = this.postfilter_gain; + this.postfilter_tapset_old = this.postfilter_tapset; + this.postfilter_period = pitch; + this.postfilter_gain = gain; + this.postfilter_tapset = tapset; + if lm != 0 { + this.postfilter_period_old = this.postfilter_period; + this.postfilter_gain_old = this.postfilter_gain; + this.postfilter_tapset_old = this.postfilter_tapset; + } +} + +# A comb filter, in place, of a period's three taps either side, from one +# filter to another over the overlap. +def comb_filter(x: &mut vector, at: u64, given_t0: i32, given_t1: i32, n: i32, g0: f32, g1: f32, tapset0: i32, tapset1: i32): void { + return if g0 == 0 && g1 == 0; + val t0 := math::max(given_t0, min_period) as u64; + val t1 := math::max(given_t1, min_period) as u64; + val g00 := g0 * comb_gains[(tapset0 * 3) as u64]; + val g01 := g0 * comb_gains[(tapset0 * 3 + 1) as u64]; + val g02 := g0 * comb_gains[(tapset0 * 3 + 2) as u64]; + val g10 := g1 * comb_gains[(tapset1 * 3) as u64]; + val g11 := g1 * comb_gains[(tapset1 * 3 + 1) as u64]; + val g12 := g1 * comb_gains[(tapset1 * 3 + 2) as u64]; + var x1 := x[at - t1 + 1]; + var x2 := x[at - t1]; + var x3 := x[at - t1 - 1]; + var x4 := x[at - t1 - 2]; + var overlap := celt_overlap; + if g0 == g1 && t0 == t1 && tapset0 == tapset1 { + overlap = 0; + } + for i in 0..overlap { + val p := at + i; + val x0 := x[p - t1 + 2]; + val f := window120[i] * window120[i]; + x[p] = x[p] + + ((1 as f32 - f) * g00) * x[p - t0] + + ((1 as f32 - f) * g01) * (x[p - t0 + 1] + x[p - t0 - 1]) + + ((1 as f32 - f) * g02) * (x[p - t0 + 2] + x[p - t0 - 2]) + + (f * g10) * x2 + + (f * g11) * (x1 + x3) + + (f * g12) * (x0 + x4); + x4 = x3; + x3 = x2; + x2 = x1; + x1 = x0; + } + return if g1 == 0; + # The rest, of one filter. + val from := at + overlap; + x4 = x[from - t1 - 2]; + x3 = x[from - t1 - 1]; + x2 = x[from - t1]; + x1 = x[from - t1 + 1]; + for i in 0..(n as u64 - overlap) { + val p := from + i; + val x0 := x[p - t1 + 2]; + x[p] = x[p] + g10 * x2 + g11 * (x1 + x3) + g12 * (x0 + x4); + x4 = x3; + x3 = x2; + x2 = x1; + x1 = x0; + } +} + +# The frame's end undone of its pre-emphasis, into the output. +def celt_decoder::deemphasis(&mut this, n: i32, pcm: slice): void { + val cc := this.channels; + for c in 0..cc { + val at := this.channel_at(c) + decode_buffer - n as u64; + var mem := this.preemph_mem[c as u64]; + for j in 0..n { + val tmp := this.memory[at + j as u64] + 1e-30 + mem; + mem = preemph_coef * tmp; + pcm[(j * cc + c) as u64] = tmp * (1 as f32 / 32768); + } + this.preemph_mem[c as u64] = mem; + } +} diff --git a/audio/opus/celt_alloc.sakura b/audio/opus/celt_alloc.sakura new file mode 100644 index 0000000..ee637dd --- /dev/null +++ b/audio/opus/celt_alloc.sakura @@ -0,0 +1,352 @@ +#! Contains CELT's bit allocation, as RFC 6716's section 4.3.3 has it: each +#! band's most bits, its boosts read, then the bits of a frame shared among its +#! bands by interpolating between the allocation vectors, the bands at its top +#! skipped where they're said to be, intensity and dual stereo read, and each +#! band's bits split between its fine energy and its pulses. + +import std::math; +module malunal::audio::opus; + + +# The steps the interpolation between two allocation vectors is found in. +const alloc_steps: i32 = 6; +# The most bits a band's fine energy is given. +const max_fine_bits: i32 = 8; +# How far a band's fine energy's bits are offset from its fair share. +const fine_offset: i32 = 21; + +# The bits, in eighths, of naming one of a count of bands, for intensity stereo. +const log2_frac_table: u8[24] = [0, 8, 13, 16, 19, 21, 23, 24, 26, 27, 28, 29, 30, 31, 32, 32, 33, 34, 34, 35, 36, 36, 37, 37]; + +# The width of a band, in bins of a 2.5 ms block. +def band_width(band: i32): i32 { + return eband5ms[(band + 1) as u64] as i32 - eband5ms[band as u64] as i32; +} + +# Where a band begins, in bins of a 2.5 ms block. +def band_start(band: i32): i32 { + return eband5ms[band as u64] as i32; +} + +# Each band's most bits, in eighths, for a frame size and channel count. +def init_caps(caps: &mut i32[21], lm: i32, channels: i32): void { + for i in 0..21 { + val n := band_width(i as i32) << lm as u32; + caps[i] = (cache_caps50[(21 * (2 * lm + channels - 1) + i as i32) as u64] as i32 + 64) * channels * n >> 2; + } +} + +# The count of pulses a pulse cache's index stands for. +def get_pulses(i: i32): i32 { + return i < 8 ? i : (8 + (i & 7)) << ((i >> 3) - 1) as u32; +} + +# Where a band's pulse cache begins, for an LM, which may be -1. +def cache_at(band: i32, lm: i32): u64 { + return cache_index50[((lm + 1) * 21 + band) as u64] as u64; +} + +# The most pulses a band's bits buy. +def bits2pulses(band: i32, lm: i32, given: i32): i32 { + val cache := cache_at(band, lm); + var lo: i32 = 0; + var hi := cache_bits50[cache] as i32; + val bits := given - 1; + for _ in 0..6 { + val mid := (lo + hi + 1) >> 1; + if cache_bits50[cache + mid as u64] as i32 >= bits { + hi = mid; + } else { + lo = mid; + } + } + val below: i32 = lo == 0 ? -1 : cache_bits50[cache + lo as u64] as i32; + return bits - below <= cache_bits50[cache + hi as u64] as i32 - bits ? lo : hi; +} + +# The bits a count of pulses costs a band. +def pulses2bits(band: i32, lm: i32, pulses: i32): i32 { + return 0 if pulses == 0; + return cache_bits50[cache_at(band, lm) + pulses as u64] as i32 + 1; +} + +# What the allocation decided: how many bands are coded, where intensity +# stereo begins, whether dual stereo is on, and the bits left over. +struct allocation { + var coded: i32; + var intensity: i32; + var dual: bool; + var balance: i32; +} + +# Shares a frame's bits among its bands. +# @param start, end The bands coded. +# @param offsets Each band's boost, in eighths of a bit. +# @param caps Each band's most bits. +# @param trim The allocation's tilt, from 0 to 10. +# @param total The bits to share, in eighths. +# @param pulses Each band's bits for its pulses, in eighths, given. +# @param fine Each band's fine energy's bits, given. +# @param priority Whether each band is first given a bit of what's left, given. +def compute_allocation( + start: i32, end: i32, offsets: &i32[21], caps: &i32[21], trim: i32, given_total: i32, + pulses: &mut i32[21], fine: &mut i32[21], priority: &mut i32[21], channels: i32, lm: i32, + rd: &mut range_decoder, +): allocation { + var total := given_total > 0 ? given_total : 0; + var skip_start := start; + val skip_rsv: i32 = total >= 1 << bitres as u32 ? 1 << bitres as u32 : 0; + total -= skip_rsv; + var intensity_rsv: i32 = 0; + var dual_rsv: i32 = 0; + if channels == 2 { + intensity_rsv = log2_frac_table[(end - start) as u64] as i32; + if intensity_rsv > total { + intensity_rsv = 0; + } else { + total -= intensity_rsv; + dual_rsv = total >= 1 << bitres as u32 ? 1 << bitres as u32 : 0; + total -= dual_rsv; + } + } + + var bits1: i32[21]; + var bits2: i32[21]; + var thresh: i32[21]; + var trim_offset: i32[21]; + for j in start..end { + val width := band_width(j); + thresh[j as u64] = math::max(channels << bitres as u32, (3 * width << lm as u32 << bitres as u32) >> 4); + trim_offset[j as u64] = channels * width * (trim - 5 - lm) * (end - j - 1) * (1 << (lm + bitres) as u32) >> 6; + if width << lm as u32 == 1 { + trim_offset[j as u64] -= channels << bitres as u32; + } + } + var lo: i32 = 1; + var hi: i32 = 10; + while lo <= hi { + var done := false; + var psum: i32 = 0; + val mid := (lo + hi) >> 1; + var j := end; + while j > start { + j--; + var bitsj := channels * band_width(j) * band_allocation[(mid * 21 + j) as u64] as i32 << lm as u32 >> 2; + if bitsj > 0 { + bitsj = math::max(0, bitsj + trim_offset[j as u64]); + } + bitsj += offsets[j as u64]; + if bitsj >= thresh[j as u64] || done { + done = true; + psum += math::min(bitsj, caps[j as u64]); + } else if bitsj >= channels << bitres as u32 { + psum += channels << bitres as u32; + } + } + if psum > total { + hi = mid - 1; + } else { + lo = mid + 1; + } + } + hi = lo; + lo--; + for j in start..end { + val width := band_width(j); + var b1 := channels * width * band_allocation[(lo * 21 + j) as u64] as i32 << lm as u32 >> 2; + var b2 := hi >= 11 ? caps[j as u64] : channels * width * band_allocation[(hi * 21 + j) as u64] as i32 << lm as u32 >> 2; + if b1 > 0 { + b1 = math::max(0, b1 + trim_offset[j as u64]); + } + if b2 > 0 { + b2 = math::max(0, b2 + trim_offset[j as u64]); + } + if lo > 0 { + b1 += offsets[j as u64]; + } + b2 += offsets[j as u64]; + if offsets[j as u64] > 0 { + skip_start = j; + } + bits1[j as u64] = b1; + bits2[j as u64] = math::max(0, b2 - b1); + } + return interp_bits2pulses( + start, end, skip_start, &bits1, &bits2, &thresh, caps, total, skip_rsv, intensity_rsv, dual_rsv, + pulses, fine, priority, channels, lm, rd, + ); +} + +# Interpolates between two allocations, skips bands, and splits each band's +# bits between its fine energy and its pulses. +def interp_bits2pulses( + start: i32, end: i32, skip_start: i32, bits1: &i32[21], bits2: &i32[21], thresh: &i32[21], + caps: &i32[21], given_total: i32, skip_rsv: i32, given_intensity_rsv: i32, given_dual_rsv: i32, + bits: &mut i32[21], ebits: &mut i32[21], priority: &mut i32[21], channels: i32, lm: i32, + rd: &mut range_decoder, +): allocation { + var total := given_total; + var intensity_rsv := given_intensity_rsv; + var dual_rsv := given_dual_rsv; + val alloc_floor := channels << bitres as u32; + val stereo: i32 = channels > 1 ? 1 : 0; + val log_m := lm << bitres as u32; + var lo: i32 = 0; + var hi: i32 = 1 << alloc_steps as u32; + for _ in 0..alloc_steps { + val mid := (lo + hi) >> 1; + var psum: i32 = 0; + var done := false; + var j := end; + while j > start { + j--; + val tmp := bits1[j as u64] + (mid * bits2[j as u64] >> alloc_steps as u32); + if tmp >= thresh[j as u64] || done { + done = true; + psum += math::min(tmp, caps[j as u64]); + } else if tmp >= alloc_floor { + psum += alloc_floor; + } + } + if psum > total { + hi = mid; + } else { + lo = mid; + } + } + var psum: i32 = 0; + var done := false; + var j := end; + while j > start { + j--; + var tmp := bits1[j as u64] + (lo * bits2[j as u64] >> alloc_steps as u32); + if tmp < thresh[j as u64] && !done { + tmp = tmp >= alloc_floor ? alloc_floor : 0; + } else { + done = true; + } + tmp = math::min(tmp, caps[j as u64]); + bits[j as u64] = tmp; + psum += tmp; + } + + # Which bands are skipped, from the top down. + var coded := end; + while true { + val k := coded - 1; + if k <= skip_start { + # The bit kept to end skipping is given back. + total += skip_rsv; + break; + } + var left := total - psum; + val span := band_start(coded) - band_start(start); + val percoeff := left / span; + left -= span * percoeff; + val rem := math::max(left - (band_start(k) - band_start(start)), 0); + val width := band_start(coded) - band_start(k); + var band_bits := bits[k as u64] + percoeff * width + rem; + if band_bits >= math::max(thresh[k as u64], alloc_floor + (1 << bitres as u32)) { + break if rd.bit_logp(1); + # A bit was spent saying the band is skipped. + psum += 1 << bitres as u32; + band_bits -= 1 << bitres as u32; + } + psum -= bits[k as u64] + intensity_rsv; + if intensity_rsv > 0 { + intensity_rsv = log2_frac_table[(k - start) as u64] as i32; + } + psum += intensity_rsv; + if band_bits >= alloc_floor { + psum += alloc_floor; + bits[k as u64] = alloc_floor; + } else { + bits[k as u64] = 0; + } + coded--; + } + + var made := allocation{ coded = coded }; + if intensity_rsv > 0 { + made.intensity = start + rd.uint((coded + 1 - start) as u32) as i32; + } + if made.intensity <= start { + total += dual_rsv; + dual_rsv = 0; + } + if dual_rsv > 0 { + made.dual = rd.bit_logp(1); + } + + # What's left, shared by width. + var left := total - psum; + val span := band_start(coded) - band_start(start); + val percoeff := left / span; + left -= span * percoeff; + for b in start..coded { + bits[b as u64] += percoeff * band_width(b); + } + for b in start..coded { + val tmp := math::min(left, band_width(b)); + bits[b as u64] += tmp; + left -= tmp; + } + + var balance: i32 = 0; + var b := start; + while b < coded { + val n0 := band_width(b); + val n := n0 << lm as u32; + val bit := bits[b as u64] + balance; + var excess: i32 = 0; + if n > 1 { + excess = math::max(bit - caps[b as u64], 0); + bits[b as u64] = bit - excess; + # The extra degree of freedom of stereo. + val den := channels * n + (channels == 2 && n > 2 && !made.dual && b < made.intensity ? 1 : 0); + val nclogn := den * (log_n400[b as u64] as i32 + log_m); + var offset := (nclogn >> 1) - den * fine_offset; + if n == 2 { + offset += den << bitres as u32 >> 2; + } + if bits[b as u64] + offset < den * 2 << bitres as u32 { + offset += nclogn >> 2; + } else if bits[b as u64] + offset < den * 3 << bitres as u32 { + offset += nclogn >> 3; + } + var e := math::max(0, bits[b as u64] + offset + (den << (bitres - 1) as u32)); + e = (e / den) >> bitres as u32; + if channels * e > bits[b as u64] >> bitres as u32 { + e = bits[b as u64] >> stereo as u32 >> bitres as u32; + } + e = math::min(e, max_fine_bits); + ebits[b as u64] = e; + priority[b as u64] = e * (den << bitres as u32) >= bits[b as u64] + offset ? 1 : 0; + bits[b as u64] -= channels * e << bitres as u32; + } else { + # A band of one bin spends all on fine energy, but a sign. + excess = math::max(0, bit - (channels << bitres as u32)); + bits[b as u64] = bit - excess; + ebits[b as u64] = 0; + priority[b as u64] = 1; + } + if excess > 0 { + val extra_fine := math::min(excess >> (stereo + bitres) as u32, max_fine_bits - ebits[b as u64]); + ebits[b as u64] += extra_fine; + val extra_bits := extra_fine * channels << bitres as u32; + priority[b as u64] = extra_bits >= excess - balance ? 1 : 0; + excess -= extra_bits; + } + balance = excess; + b++; + } + made.balance = balance; + # Skipped bands spend all theirs on fine energy. + while b < end { + ebits[b as u64] = bits[b as u64] >> stereo as u32 >> bitres as u32; + bits[b as u64] = 0; + priority[b as u64] = ebits[b as u64] < 1 ? 1 : 0; + b++; + } + return made; +} diff --git a/audio/opus/celt_bands.sakura b/audio/opus/celt_bands.sakura new file mode 100644 index 0000000..94ce0d6 --- /dev/null +++ b/audio/opus/celt_bands.sakura @@ -0,0 +1,934 @@ +#! Contains CELT's bands decoded, as RFC 6716's section 4.3.4 has it: each +#! band's shape, a unit vector, read as pulses of a pyramid vector quantizer, +#! split in halves by angles where it has more bits than one codeword holds, +#! spread by rotations, and folded from the bands below where it has none; +#! stereo coded as mid and side, or dual, or intensity; the time and frequency +#! of short blocks traded by Haar's transform; and bands collapsed to silence by +#! a transient filled with noise again. + +import std::math; +module malunal::audio::opus; + + +const spread_none: i32 = 0; +const spread_light: i32 = 1; +const spread_normal: i32 = 2; +const spread_aggressive: i32 = 3; +const qtheta_offset: i32 = 4; +const qtheta_offset_twophase: i32 = 16; +const pi_f: f32 = 3.141592653; + +# Where each row of `pvq_u_data` begins. +const pvq_u_rows: u16[15] = [0, 176, 351, 525, 698, 870, 1041, 1131, 1178, 1207, 1226, 1240, 1248, 1254, 1257]; + +# The order the blocks of a band are taken in, from Hadamard's natural order, +# for 2, 4, 8, and 16 blocks. +const ordery_table: u8[30] = [ + 1, 0, + 3, 0, 2, 1, + 7, 0, 4, 3, 6, 1, 5, 2, + 15, 0, 8, 7, 12, 3, 11, 4, 14, 1, 9, 6, 13, 2, 10, 5, +]; + +const bit_interleave_table: u8[16] = [0, 1, 1, 1, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3]; +const bit_deinterleave_table: u8[16] = [0x00, 0x03, 0x0C, 0x0F, 0x30, 0x33, 0x3C, 0x3F, 0xC0, 0xC3, 0xCC, 0xCF, 0xF0, 0xF3, 0xFC, 0xFF]; +const exp2_table8: i16[8] = [16384, 17866, 19483, 21247, 23170, 25267, 27554, 30048]; +const spread_factor: i32[3] = [15, 10, 5]; + +# A part of a slice. +def sub(s: slice, at: u64, length: u64): slice { + return slice::::over(s.data + at, length); +} + +# No slice, as a band that folds from nothing has. +def no_slice(): slice { + return slice::::blank(); +} + +# U(N, K) of the table's row and column. +def pvq_row(row: i32, column: i32): u32 { + return pvq_u_data[(pvq_u_rows[row as u64] as i32 + column) as u64]; +} + +def pvq_u(n: i32, k: i32): u64 { + return pvq_row(math::min(n, k), math::max(n, k)) as u64; +} + +# How many vectors of N dimensions K pulses make. +def pvq_v(n: i32, k: i32): u32 { + return (pvq_u(n, k) + pvq_u(n, k + 1)) as u32; +} + +# The pulse vector an index names, and its squared length. +def cwrsi(dims: i32, pulses: i32, index: u32, y: slice): f32 { + var n := dims; + var k := pulses; + var i := index; + var yy: f32 = 0; + var at: u64 = 0; + while n > 2 { + var value: i32 = 0; + if k >= n { + # Many pulses: those of this dimension, and their sign. + var p := pvq_row(n, k + 1); + val negative := i >= p; + if negative { + i -= p; + } + val before := k; + val q := pvq_row(n, n); + if q > i { + k = n; + while true { + k--; + p = pvq_row(k, n); + break if p <= i; + } + } else { + p = pvq_row(n, k); + while p > i { + k--; + p = pvq_row(n, k); + } + } + i -= p; + value = negative ? k - before : before - k; + } else { + # Many dimensions: whether this one has pulses at all. + var p := pvq_row(k, n); + val q := pvq_row(k + 1, n); + if p <= i && i < q { + i -= p; + } else { + val negative := i >= q; + if negative { + i -= q; + } + val before := k; + while true { + k--; + p = pvq_row(k, n); + break if p <= i; + } + i -= p; + value = negative ? k - before : before - k; + } + } + y[at] = value; + at++; + yy += value as f32 * value as f32; + n--; + } + # Two dimensions. + val p := (2 * k + 1) as u32; + val negative := i >= p; + if negative { + i -= p; + } + val before := k; + k = ((i + 1) >> 1) as i32; + if k != 0 { + i -= (2 * k - 1) as u32; + } + var value := negative ? k - before : before - k; + y[at] = value; + yy += value as f32 * value as f32; + # One. + value = i != 0 ? -k : k; + y[at + 1] = value; + yy += value as f32 * value as f32; + return yy; +} + +def celt_cos_norm(x: f32): f32 { + return math::cos(((0.5 as f32 * pi_f) * x) as f64) as f32; +} + +def celt_rsqrt(x: f32): f32 { + return 1 as f32 / (math::sqrt(x as f64) as f32); +} + +# A band's shape spread, or gathered, by rotations, so its pulses aren't all +# heard as tones. +def exp_rotation(x: slice, given_length: i32, direction: i32, stride: i32, pulses: i32, spread: i32): void { + return if 2 * pulses >= given_length || spread == spread_none; + val factor := spread_factor[(spread - 1) as u64]; + val gain := (given_length as f32) / ((given_length + factor * pulses) as f32); + val theta := 0.5 as f32 * (gain * gain); + val c := celt_cos_norm(theta); + val s := celt_cos_norm(1 as f32 - theta); + var stride2: i32 = 0; + if given_length >= 8 * stride { + stride2 = 1; + while (stride2 * stride2 + stride2) * stride + (stride >> 2) < given_length { + stride2++; + } + } + val length := given_length / stride; + for i in 0..stride { + val part := sub(x, (i * length) as u64, length as u64); + if direction < 0 { + if stride2 != 0 { + exp_rotation1(part, length, stride2, s, c); + } + exp_rotation1(part, length, 1, c, s); + } else { + exp_rotation1(part, length, 1, c, -s); + if stride2 != 0 { + exp_rotation1(part, length, stride2, s, -c); + } + } + } +} + +def exp_rotation1(x: slice, length: i32, stride: i32, c: f32, s: f32): void { + val ms := -s; + for i in 0..length - stride { + val x1 := x[i as u64]; + val x2 := x[(i + stride) as u64]; + x[(i + stride) as u64] = c * x2 + s * x1; + x[i as u64] = c * x1 + ms * x2; + } + var i := length - 2 * stride - 1; + while i >= 0 { + val x1 := x[i as u64]; + val x2 := x[(i + stride) as u64]; + x[(i + stride) as u64] = c * x2 + s * x1; + x[i as u64] = c * x1 + ms * x2; + i--; + } +} + +# Reads a band's pulses, and makes its shape of them: scaled to a length of +# `gain`, then spread. +# @returns Which of its blocks have pulses, a bit each. +def alg_unquant(x: slice, n: i32, k: i32, spread: i32, blocks: i32, rd: &mut range_decoder, gain: f32, iy: slice): u32 { + val ryy := cwrsi(n, k, rd.uint(pvq_v(n, k)), iy); + val g := celt_rsqrt(ryy) * gain; + for i in 0..n { + x[i as u64] = g * iy[i as u64] as f32; + } + exp_rotation(x, n, -1, blocks, k, spread); + return 1 if blocks <= 1; + val n0 := n / blocks; + var mask: u32 = 0; + for b in 0..blocks { + var any: i32 = 0; + for j in 0..n0 { + any |= iy[(b * n0 + j) as u64]; + } + if any != 0 { + mask |= 1 << b as u32; + } + } + return mask; +} + +# Scales a vector to a length. +def renormalise_vector(x: slice, n: i32, gain: f32): void { + var e: f32 = 1e-15; + for i in 0..n { + e += x[i as u64] * x[i as u64]; + } + val g := celt_rsqrt(e) * gain; + for i in 0..n { + x[i as u64] = g * x[i as u64]; + } +} + +def lcg_rand(seed: u32): u32 { + return math::wrapping_add(math::wrapping_mul(1664525 as u32, seed), 1013904223 as u32); +} + +# A cosine, the same on every machine, as the bits theta splits depend on it. +def bitexact_cos(x: i32): i32 { + val x2 := (4096 + x * x) >> 13; + val y := (32767 - x2) + frac_mul16(x2, -7651 + frac_mul16(x2, 8277 + frac_mul16(-626, x2))); + return 1 + y; +} + +def bitexact_log2tan(given_sin: i32, given_cos: i32): i32 { + val lc := ilog(given_cos as u32); + val ls := ilog(given_sin as u32); + val icos := given_cos << (15 - lc) as u32; + val isin := given_sin << (15 - ls) as u32; + return (ls - lc) * (1 << 11) + frac_mul16(isin, frac_mul16(isin, -2597) + 7932) - frac_mul16(icos, frac_mul16(icos, -2597) + 7932); +} + +# Two 16-bit numbers multiplied in Q15, rounded. +def frac_mul16(a: i32, b: i32): i32 { + return (16384 + (a as i16 as i32) * (b as i16 as i32)) >> 15; +} + +def isqrt32(given: u32): u32 { + var value := given; + var g: u32 = 0; + var shift := (ilog(value) - 1) >> 1; + var b: u32 = 1 << shift as u32; + while true { + val t := ((g << 1) + b) << shift as u32; + if t <= value { + g += b; + value -= t; + } + b >>= 1; + shift--; + break if shift < 0; + } + return g; +} + +# Haar's transform of interleaved blocks, which is its own inverse. +def haar1(x: slice, given_n0: i32, stride: i32): void { + val n0 := given_n0 >> 1; + for i in 0..stride { + for j in 0..n0 { + val a := (stride * 2 * j + i) as u64; + val b := (stride * (2 * j + 1) + i) as u64; + val tmp1 := 0.70710678 as f32 * x[a]; + val tmp2 := 0.70710678 as f32 * x[b]; + x[a] = tmp1 + tmp2; + x[b] = tmp1 - tmp2; + } + } +} + +def deinterleave_hadamard(x: slice, n0: i32, stride: i32, hadamard: bool, tmp: slice): void { + val n := n0 * stride; + for i in 0..stride { + val to := hadamard ? ordery_table[(stride - 2 + i) as u64] as i32 : i; + for j in 0..n0 { + tmp[(to * n0 + j) as u64] = x[(j * stride + i) as u64]; + } + } + for i in 0..n { + x[i as u64] = tmp[i as u64]; + } +} + +def interleave_hadamard(x: slice, n0: i32, stride: i32, hadamard: bool, tmp: slice): void { + val n := n0 * stride; + for i in 0..stride { + val from := hadamard ? ordery_table[(stride - 2 + i) as u64] as i32 : i; + for j in 0..n0 { + tmp[(j * stride + i) as u64] = x[(from * n0 + j) as u64]; + } + } + for i in 0..n { + x[i as u64] = tmp[i as u64]; + } +} + +# How finely a split's angle is read. +def compute_qn(n: i32, b: i32, offset: i32, pulse_cap: i32, stereo: bool): i32 { + var n2 := 2 * n - 1; + if stereo && n == 2 { + n2--; + } + var qb := (b + n2 * offset) / n2; + qb = math::min(b - pulse_cap - (4 << bitres as u32), qb); + qb = math::min(8 << bitres as u32, qb); + return 1 if qb < (1 << bitres as u32 >> 1); + val qn := exp2_table8[(qb & 0x7) as u64] as i32 >> (14 - (qb >> bitres as u32)) as u32; + return (qn + 1) >> 1 << 1; +} + +# What every band shares as they're read. +struct band_ctx { + var band: i32; + var lm: i32; # The frame's. + var intensity: i32; + var spread: i32; + var tf_change: i32; + var remaining_bits: i32; + var seed: u32; + var disable_inv: bool; + var avoid_split_noise: bool; + var pulses: vector; # A band's pulses, as they're read. + var swap: vector; # Room to reorder a band. +} + +# How a split divides its bits and gains. +struct split_ctx { + var inv: bool; + var imid: i32; + var iside: i32; + var delta: i32; + var itheta: i32; + var qalloc: i32; +} + +# Reads the angle splitting a band in halves, or a stereo band in mid and side. +def compute_theta(ctx: &mut band_ctx, rd: &mut range_decoder, n: i32, b: &mut i32, blocks: i32, blocks0: i32, lm: i32, stereo: bool, fill: &mut i32): split_ctx { + val pulse_cap := log_n400[ctx.band as u64] as i32 + lm * (1 << bitres as u32); + val offset := (pulse_cap >> 1) - (stereo && n == 2 ? qtheta_offset_twophase : qtheta_offset); + var qn := compute_qn(n, b, offset, pulse_cap, stereo); + if stereo && ctx.band >= ctx.intensity { + qn = 1; + } + val tell := rd.tell_frac(); + var itheta: i32 = 0; + var inv := false; + if qn != 1 { + if stereo && n > 2 { + # A step: likelier up to half. + val p0: i32 = 3; + val x0 := qn / 2; + val ft := p0 * (x0 + 1) + x0; + val fs := rd.decode(ft as u32) as i32; + val x := fs < (x0 + 1) * p0 ? fs / p0 : x0 + 1 + (fs - (x0 + 1) * p0); + val low := x <= x0 ? p0 * x : (x - 1 - x0) + (x0 + 1) * p0; + val high := x <= x0 ? p0 * (x + 1) : (x - x0) + (x0 + 1) * p0; + rd.update(low as u32, high as u32, ft as u32); + itheta = x; + } else if blocks0 > 1 || stereo { + itheta = rd.uint((qn + 1) as u32) as i32; + } else { + # A triangle. + val ft := ((qn >> 1) + 1) * ((qn >> 1) + 1); + val fm := rd.decode(ft as u32) as i32; + var fs: i32 = 0; + var fl: i32 = 0; + if fm < ((qn >> 1) * ((qn >> 1) + 1) >> 1) { + itheta = (isqrt32((8 * fm + 1) as u32) as i32 - 1) >> 1; + fs = itheta + 1; + fl = itheta * (itheta + 1) >> 1; + } else { + itheta = (2 * (qn + 1) - isqrt32((8 * (ft - fm - 1) + 1) as u32) as i32) >> 1; + fs = qn + 1 - itheta; + fl = ft - ((qn + 1 - itheta) * (qn + 2 - itheta) >> 1); + } + rd.update(fl as u32, (fl + fs) as u32, ft as u32); + } + itheta = itheta * 16384 / qn; + } else if stereo { + if b > 2 << bitres as u32 && ctx.remaining_bits > 2 << bitres as u32 { + inv = rd.bit_logp(2); + } + if ctx.disable_inv { + inv = false; + } + itheta = 0; + } + val qalloc := rd.tell_frac() - tell; + b -= qalloc; + + var made := split_ctx{ inv = inv, itheta = itheta, qalloc = qalloc }; + if itheta == 0 { + made.imid = 32767; + made.iside = 0; + fill &= (1 << blocks as u32) - 1; + made.delta = -16384; + } else if itheta == 16384 { + made.imid = 0; + made.iside = 32767; + fill &= ((1 << blocks as u32) - 1) << blocks as u32; + made.delta = 16384; + } else { + made.imid = bitexact_cos(itheta); + made.iside = bitexact_cos(16384 - itheta); + made.delta = frac_mul16((n - 1) << 7, bitexact_log2tan(made.iside, made.imid)); + } + return made; +} + +# A band of one bin: a sign each channel. +def quant_band_n1(ctx: &mut band_ctx, rd: &mut range_decoder, x: slice, y: slice, lowband_out: slice): u32 { + val stereo := y.length > 0; + for c in 0..(stereo ? 2 : 1) { + var negative := false; + if ctx.remaining_bits >= 1 << bitres as u32 { + negative = rd.bits(1) != 0; + ctx.remaining_bits -= 1 << bitres as u32; + } + val to := c == 0 ? x : y; + to[0] = negative ? -1 as f32 : 1 as f32; + } + if lowband_out.length > 0 { + lowband_out[0] = x[0]; + } + return 1; +} + +# A mono partition: split in halves while it has more bits than a codeword +# holds, else read as pulses, or folded where it has none. +def quant_partition(ctx: &mut band_ctx, rd: &mut range_decoder, x: slice, given_n: i32, given_b: i32, given_blocks: i32, lowband: slice, given_lm: i32, gain: f32, given_fill: i32): u32 { + var n := given_n; + var b := given_b; + var blocks := given_blocks; + var lm := given_lm; + var fill := given_fill; + val blocks0 := blocks; + val i := ctx.band; + var cm: u32 = 0; + val cache := cache_at(i, lm); + if lm != -1 && b > cache_bits50[cache + cache_bits50[cache] as u64] as i32 + 12 && n > 2 { + n >>= 1; + val y := sub(x, n as u64, n as u64); + lm -= 1; + if blocks == 1 { + fill = (fill & 1) | (fill << 1); + } + blocks = (blocks + 1) >> 1; + val split := compute_theta(ctx, rd, n, &mut b, blocks, blocks0, lm, false, &mut fill); + var delta := split.delta; + val mid := (1 as f32 / 32768) * split.imid as f32; + val side := (1 as f32 / 32768) * split.iside as f32; + # Low-energy blocks are given more bits than they'd deserve. + if blocks0 > 1 && (split.itheta & 0x3fff) != 0 { + if split.itheta > 8192 { + delta -= delta >> (4 - lm) as u32; + } else { + delta = math::min(0, delta + (n << bitres as u32 >> (5 - lm) as u32)); + } + } + var mbits := math::max(0, math::min(b, (b - delta) / 2)); + var sbits := b - mbits; + ctx.remaining_bits -= split.qalloc; + val next_lowband2 := lowband.length > 0 ? sub(lowband, n as u64, n as u64) : no_slice(); + var rebalance := ctx.remaining_bits; + if mbits >= sbits { + cm = quant_partition(ctx, rd, x, n, mbits, blocks, lowband, lm, gain * mid, fill); + rebalance = mbits - (rebalance - ctx.remaining_bits); + if rebalance > 3 << bitres as u32 && split.itheta != 0 { + sbits += rebalance - (3 << bitres as u32); + } + cm |= quant_partition(ctx, rd, y, n, sbits, blocks, next_lowband2, lm, gain * side, fill >> blocks as u32) << (blocks0 >> 1) as u32; + } else { + cm = quant_partition(ctx, rd, y, n, sbits, blocks, next_lowband2, lm, gain * side, fill >> blocks as u32) << (blocks0 >> 1) as u32; + rebalance = sbits - (rebalance - ctx.remaining_bits); + if rebalance > 3 << bitres as u32 && split.itheta != 16384 { + mbits += rebalance - (3 << bitres as u32); + } + cm |= quant_partition(ctx, rd, x, n, mbits, blocks, lowband, lm, gain * mid, fill); + } + return cm; + } + + var q := bits2pulses(i, lm, b); + var curr_bits := pulses2bits(i, lm, q); + ctx.remaining_bits -= curr_bits; + # Never past the budget. + while ctx.remaining_bits < 0 && q > 0 { + ctx.remaining_bits += curr_bits; + q--; + curr_bits = pulses2bits(i, lm, q); + ctx.remaining_bits -= curr_bits; + } + if q != 0 { + val iy := slice::::over(ctx.pulses.data, n as u64); + return alg_unquant(x, n, get_pulses(q), ctx.spread, blocks, rd, gain, iy); + } + # No pulses: noise, or what's folded from below. + val cm_mask := ((1u << blocks as u64) - 1) as u32; + fill &= cm_mask as i32; + if fill == 0 { + for j in 0..n { + x[j as u64] = 0; + } + return 0; + } + if lowband.length == 0 { + for j in 0..n { + ctx.seed = lcg_rand(ctx.seed); + # The seed's top 12 bits, signed. + val top := (ctx.seed >> 20) as i32; + x[j as u64] = (top >= 2048 ? top - 4096 : top) as f32; + } + cm = cm_mask; + } else { + for j in 0..n { + ctx.seed = lcg_rand(ctx.seed); + # About 48 dB below folding's usual level. + val tmp: f32 = (ctx.seed & 0x8000) != 0 ? 1 as f32 / 256 : -1 as f32 / 256; + x[j as u64] = lowband[j as u64] + tmp; + } + cm = fill as u32; + } + renormalise_vector(x, n, gain); + return cm; +} + +# A mono band: its time and frequency traded as the frame says, then read. +def quant_band(ctx: &mut band_ctx, rd: &mut range_decoder, x: slice, n: i32, b: i32, given_blocks: i32, given_lowband: slice, lm: i32, lowband_out: slice, gain: f32, lowband_scratch: slice, given_fill: i32): u32 { + val n0 := n; + var n_b := n; + var blocks := given_blocks; + var blocks0 := blocks; + var lowband := given_lowband; + var fill := given_fill; + var time_divide: i32 = 0; + var recombine: i32 = 0; + val long_blocks := blocks0 == 1; + var tf_change := ctx.tf_change; + n_b = n_b / blocks; + + return quant_band_n1(ctx, rd, x, no_slice(), lowband_out) if n == 1; + if tf_change > 0 { + recombine = tf_change; + } + if lowband_scratch.length > 0 && lowband.length > 0 && (recombine != 0 || ((n_b & 1) == 0 && tf_change < 0) || blocks0 > 1) { + for j in 0..n { + lowband_scratch[j as u64] = lowband[j as u64]; + } + lowband = sub(lowband_scratch, 0, n as u64); + } + for k in 0..recombine { + if lowband.length > 0 { + haar1(lowband, n >> k as u32, 1 << k as u32); + } + fill = bit_interleave_table[(fill & 0xF) as u64] as i32 | (bit_interleave_table[(fill >> 4) as u64] as i32) << 2; + } + blocks >>= recombine as u32; + n_b <<= recombine as u32; + + # More time resolution. + while (n_b & 1) == 0 && tf_change < 0 { + if lowband.length > 0 { + haar1(lowband, n_b, blocks); + } + fill |= fill << blocks as u32; + blocks <<= 1; + n_b >>= 1; + time_divide++; + tf_change++; + } + blocks0 = blocks; + val n_b0 := n_b; + val swap := slice::::over(ctx.swap.data, n as u64); + + # The blocks in time's order, rather than frequency's. + if blocks0 > 1 && lowband.length > 0 { + deinterleave_hadamard(lowband, n_b >> recombine as u32, blocks0 << recombine as u32, long_blocks, swap); + } + var cm := quant_partition(ctx, rd, x, n, b, blocks, lowband, lm, gain, fill); + + if blocks0 > 1 { + interleave_hadamard(x, n_b >> recombine as u32, blocks0 << recombine as u32, long_blocks, swap); + } + n_b = n_b0; + blocks = blocks0; + for _ in 0..time_divide { + blocks >>= 1; + n_b <<= 1; + cm |= cm >> blocks as u32; + haar1(x, n_b, blocks); + } + for k in 0..recombine { + cm = bit_deinterleave_table[cm as u64] as u32; + haar1(x, n0 >> k as u32, 1 << k as u32); + } + blocks <<= recombine as u32; + # Scaled, to be folded from. + if lowband_out.length > 0 { + val scale := math::sqrt(n0 as f64) as f32; + for j in 0..n0 { + lowband_out[j as u64] = scale * x[j as u64]; + } + } + return cm & ((1u << blocks as u64) - 1) as u32; +} + +# A stereo band, as mid and side. +def quant_band_stereo(ctx: &mut band_ctx, rd: &mut range_decoder, x: slice, y: slice, n: i32, given_b: i32, blocks: i32, lowband: slice, lm: i32, lowband_out: slice, lowband_scratch: slice, given_fill: i32): u32 { + var b := given_b; + var fill := given_fill; + return quant_band_n1(ctx, rd, x, y, lowband_out) if n == 1; + val orig_fill := fill; + val split := compute_theta(ctx, rd, n, &mut b, blocks, blocks, lm, true, &mut fill); + val mid := (1 as f32 / 32768) * split.imid as f32; + val side := (1 as f32 / 32768) * split.iside as f32; + var cm: u32 = 0; + if n == 2 { + # Mid and side are orthogonal, so the side is a sign. + var mbits := b; + var sbits: i32 = 0; + if split.itheta != 0 && split.itheta != 16384 { + sbits = 1 << bitres as u32; + } + mbits -= sbits; + val swapped := split.itheta > 8192; + ctx.remaining_bits -= split.qalloc + sbits; + val x2 := swapped ? y : x; + val y2 := swapped ? x : y; + var sign: i32 = 0; + if sbits != 0 { + sign = rd.bits(1) as i32; + } + sign = 1 - 2 * sign; + cm = quant_band(ctx, rd, x2, n, mbits, blocks, lowband, lm, lowband_out, 1, lowband_scratch, orig_fill); + y2[0] = -sign as f32 * x2[1]; + y2[1] = sign as f32 * x2[0]; + x[0] = mid * x[0]; + x[1] = mid * x[1]; + y[0] = side * y[0]; + y[1] = side * y[1]; + var tmp := x[0]; + x[0] = tmp - y[0]; + y[0] = tmp + y[0]; + tmp = x[1]; + x[1] = tmp - y[1]; + y[1] = tmp + y[1]; + } else { + var mbits := math::max(0, math::min(b, (b - split.delta) / 2)); + var sbits := b - mbits; + ctx.remaining_bits -= split.qalloc; + var rebalance := ctx.remaining_bits; + if mbits >= sbits { + # The mid isn't scaled, as it's folded from later. + cm = quant_band(ctx, rd, x, n, mbits, blocks, lowband, lm, lowband_out, 1, lowband_scratch, fill); + rebalance = mbits - (rebalance - ctx.remaining_bits); + if rebalance > 3 << bitres as u32 && split.itheta != 0 { + sbits += rebalance - (3 << bitres as u32); + } + cm |= quant_band(ctx, rd, y, n, sbits, blocks, no_slice(), lm, no_slice(), side, no_slice(), fill >> blocks as u32); + } else { + cm = quant_band(ctx, rd, y, n, sbits, blocks, no_slice(), lm, no_slice(), side, no_slice(), fill >> blocks as u32); + rebalance = sbits - (rebalance - ctx.remaining_bits); + if rebalance > 3 << bitres as u32 && split.itheta != 16384 { + mbits += rebalance - (3 << bitres as u32); + } + cm |= quant_band(ctx, rd, x, n, mbits, blocks, lowband, lm, lowband_out, 1, lowband_scratch, fill); + } + } + if n != 2 { + stereo_merge(x, y, mid, n); + } + if split.inv { + for j in 0..n { + y[j as u64] = -y[j as u64]; + } + } + return cm; +} + +# Mid and side back to left and right, each scaled to a unit length. +def stereo_merge(x: slice, y: slice, mid: f32, n: i32): void { + var xp: f32 = 0; + var side: f32 = 0; + for j in 0..n { + xp += y[j as u64] * x[j as u64]; + side += y[j as u64] * y[j as u64]; + } + xp = mid * xp; + val el := mid * mid + side - 2 * xp; + val er := mid * mid + side + 2 * xp; + if er < 6e-4 || el < 6e-4 { + for j in 0..n { + y[j as u64] = x[j as u64]; + } + return; + } + val lgain := celt_rsqrt(el); + val rgain := celt_rsqrt(er); + for j in 0..n { + val l := mid * x[j as u64]; + val r := y[j as u64]; + x[j as u64] = lgain * (l - r); + y[j as u64] = rgain * (l + r); + } +} + +# Every band of a frame read, each channel's shape into its part of `x`. +# @param x The bands' shapes, the second channel's `n` after the first's. +# @param n The frame's bins a channel. +# @param masks Which blocks of each band and channel have pulses, given. +# @param pulses Each band's bits, as the allocation gave them. +# @param tf_res Each band's change of time and frequency. +# @param total_bits The frame's bits, in eighths, less the anti-collapse bit. +# @param balance The allocation's leftover. +# @param seed The noise's seed, which goes on to the next frame. +# @param norm Room for each channel's folding source. +def quant_all_bands( + start: i32, end: i32, x: slice, channels: i32, n: i32, masks: &mut u8[42], pulses: &i32[21], + short_blocks: bool, spread: i32, given_dual: bool, intensity: i32, tf_res: &i32[21], total_bits: i32, + given_balance: i32, rd: &mut range_decoder, lm: i32, coded: i32, seed: &mut u32, disable_inv: bool, + ctx: &mut band_ctx, norm_room: slice, +): void { + val m: i32 = 1 << lm as u32; + val blocks: i32 = short_blocks ? m : 1; + var dual := given_dual; + var balance := given_balance; + val norm_offset := m * band_start(start); + val norm_length := (m * band_start(20) - norm_offset) as u64; + val norm := sub(norm_room, 0, norm_length); + val norm2 := sub(norm_room, norm_length, norm_length); + var lowband_scratch := sub(x, (m * band_start(20)) as u64, (m * band_width(20)) as u64); + var lowband_offset: i32 = 0; + var update_lowband := true; + ctx.intensity = intensity; + ctx.seed = seed; + ctx.spread = spread; + ctx.disable_inv = disable_inv; + ctx.lm = lm; + ctx.avoid_split_noise = blocks > 1; + for i in start..end { + ctx.band = i; + val last := i == end - 1; + val xb := sub(x, (m * band_start(i)) as u64, (m * band_width(i)) as u64); + val yb := channels == 2 ? sub(x, (n + m * band_start(i)) as u64, (m * band_width(i)) as u64) : no_slice(); + val width := m * band_width(i); + val tell := rd.tell_frac(); + if i != start { + balance -= tell; + } + val remaining := total_bits - tell - 1; + ctx.remaining_bits = remaining; + var b: i32 = 0; + if i <= coded - 1 { + val curr_balance := balance / math::min(3, coded - i); + b = math::max(0, math::min(16383, math::min(remaining + 1, pulses[i as u64] + curr_balance))); + } + if m * band_start(i) - width >= m * band_start(start) || i == start + 1 { + if update_lowband || lowband_offset == 0 { + lowband_offset = i; + } + } + if i == start + 1 { + special_hybrid_folding(norm, norm2, start, m, dual); + } + ctx.tf_change = tf_res[i as u64]; + if last { + lowband_scratch = no_slice(); + } + var effective_lowband: i32 = -1; + var x_cm: u32 = 0; + var y_cm: u32 = 0; + if lowband_offset != 0 && (spread != spread_aggressive || blocks > 1 || ctx.tf_change < 0) { + # Folding never repeats what's within one band. + effective_lowband = math::max(0, m * band_start(lowband_offset) - norm_offset - width); + var fold_start := lowband_offset; + while true { + fold_start--; + break if m * band_start(fold_start) <= effective_lowband + norm_offset; + } + var fold_end := lowband_offset - 1; + while true { + fold_end++; + break if fold_end >= i || m * band_start(fold_end) >= effective_lowband + norm_offset + width; + } + var fold_i := fold_start; + while true { + x_cm |= masks[(fold_i * channels) as u64] as u32; + y_cm |= masks[(fold_i * channels + channels - 1) as u64] as u32; + fold_i++; + break if fold_i >= fold_end; + } + } else { + x_cm = ((1u << blocks as u64) - 1) as u32; + y_cm = x_cm; + } + if dual && i == intensity { + # Dual stereo ends where intensity begins. + dual = false; + for j in 0..m * band_start(i) - norm_offset { + norm[j as u64] = 0.5 as f32 * (norm[j as u64] + norm2[j as u64]); + } + } + val fold_x := effective_lowband != -1 ? sub(norm, effective_lowband as u64, width as u64) : no_slice(); + val out_x := last ? no_slice() : sub(norm, (m * band_start(i) - norm_offset) as u64, width as u64); + if dual { + val fold_y := effective_lowband != -1 ? sub(norm2, effective_lowband as u64, width as u64) : no_slice(); + val out_y := last ? no_slice() : sub(norm2, (m * band_start(i) - norm_offset) as u64, width as u64); + x_cm = quant_band(ctx, rd, xb, width, b / 2, blocks, fold_x, lm, out_x, 1, lowband_scratch, x_cm as i32); + y_cm = quant_band(ctx, rd, yb, width, b / 2, blocks, fold_y, lm, out_y, 1, lowband_scratch, y_cm as i32); + } else { + if channels == 2 { + x_cm = quant_band_stereo(ctx, rd, xb, yb, width, b, blocks, fold_x, lm, out_x, lowband_scratch, (x_cm | y_cm) as i32); + } else { + x_cm = quant_band(ctx, rd, xb, width, b, blocks, fold_x, lm, out_x, 1, lowband_scratch, (x_cm | y_cm) as i32); + } + y_cm = x_cm; + } + masks[(i * channels) as u64] = x_cm as u8; + masks[(i * channels + channels - 1) as u64] = y_cm as u8; + balance += pulses[i as u64] + tell; + # Folding moves on only while bands have a bit a bin. + update_lowband = b > width << bitres as u32; + ctx.avoid_split_noise = false; + } + seed = ctx.seed; +} + +# The first band's folding source copied on, so the second can fold, as a +# hybrid frame's first band is too narrow to. +def special_hybrid_folding(norm: slice, norm2: slice, start: i32, m: i32, dual: bool): void { + val n1 := m * band_width(start); + val n2 := m * band_width(start + 1); + for j in 0..n2 - n1 { + norm[(n1 + j) as u64] = norm[(2 * n1 - n2 + j) as u64]; + } + if dual { + for j in 0..n2 - n1 { + norm2[(n1 + j) as u64] = norm2[(2 * n1 - n2 + j) as u64]; + } + } +} + +# Blocks of a transient left with no pulses filled with noise, so its energy +# doesn't collapse. +def anti_collapse(x: slice, masks: &u8[42], lm: i32, channels: i32, size: i32, start: i32, end: i32, log_e: &f32[42], prev1_log_e: &f32[42], prev2_log_e: &f32[42], pulses: &i32[21], given_seed: u32): void { + var seed := given_seed; + for i in start..end { + val n0 := band_width(i); + val depth := ((1 + pulses[i as u64]) / n0) >> lm as u32; + val thresh := 0.5 as f32 * (math::exp(0.6931471805599453094 * (-0.125 as f32 * depth as f32) as f64) as f32); + val sqrt_1 := celt_rsqrt((n0 << lm as u32) as f32); + for c in 0..channels { + var prev1 := prev1_log_e[(c * 21 + i) as u64]; + var prev2 := prev2_log_e[(c * 21 + i) as u64]; + if channels == 1 { + prev1 = math::max(prev1, prev1_log_e[(21 + i) as u64]); + prev2 = math::max(prev2, prev2_log_e[(21 + i) as u64]); + } + var ediff := log_e[(c * 21 + i) as u64] - math::min(prev1, prev2); + ediff = math::max(0 as f32, ediff); + var r := 2 as f32 * (math::exp(0.6931471805599453094 * (-ediff) as f64) as f32); + if lm == 3 { + r *= 1.41421356; + } + r = math::min(thresh, r); + r = r * sqrt_1; + val band := sub(x, (c * size + (band_start(i) << lm as u32)) as u64, (n0 << lm as u32) as u64); + var renormalize := false; + for k in 0..1 << lm as u32 { + if (masks[(i * channels + c) as u64] as u32 & (1 << k as u32)) == 0 { + for j in 0..n0 { + seed = lcg_rand(seed); + band[((j << lm as u32) + k) as u64] = (seed & 0x8000) != 0 ? r : -r; + } + renormalize = true; + } + } + if renormalize { + renormalise_vector(band, n0 << lm as u32, 1); + } + } + } +} + +# A channel's shapes scaled by their bands' energies, to its spectrum. +def denormalise_bands(x: slice, freq: slice, energies: &f32[42], channel: i32, given_start: i32, given_end: i32, m: i32, silence: bool): void { + var start := given_start; + var end := given_end; + val n := m * short_size as i32; + var bound := m * band_start(end); + if silence { + bound = 0; + start = 0; + end = 0; + } + for i in 0..m * band_start(start) { + freq[i as u64] = 0; + } + for i in start..end { + val lg := energies[(channel * 21 + i) as u64] + e_means[i as u64]; + val g := math::exp(0.6931471805599453094 * math::min(32 as f32, lg) as f64) as f32; + for j in m * band_start(i)..m * band_start(i + 1) { + freq[j as u64] = x[j as u64] * g; + } + } + for i in bound..n { + freq[i as u64] = 0; + } +} diff --git a/audio/opus/celt_mdct.sakura b/audio/opus/celt_mdct.sakura new file mode 100644 index 0000000..730368e --- /dev/null +++ b/audio/opus/celt_mdct.sakura @@ -0,0 +1,315 @@ +#! Contains CELT's inverse MDCT, of 1920 points halved up to three times: a +#! rotation, an FFT of a quarter as many complex points, of KISS FFT's radices +#! 5, 3, 4, and 2, another rotation, and the window's mirroring with the block +#! before, as libopus's float build does them. + +module malunal::audio::opus; + + +# Each FFT's radices and the stages' lengths after them, as libopus factors +# 480, 240, 120, and 60, ended by a length of 1. +const fft_factors: i16[40] = [ + 5, 96, 3, 32, 4, 8, 2, 4, 4, 1, + 5, 48, 3, 16, 4, 4, 4, 1, 0, 0, + 5, 24, 3, 8, 2, 4, 4, 1, 0, 0, + 5, 12, 3, 4, 4, 1, 0, 0, 0, 0, +]; + +# Where an FFT puts each input, by how many times 480 is halved. +def fft_bitrev(shift: i32, i: u64): u64 { + return match shift { + 0 => fft_bitrev480[i] as u64, + 1 => fft_bitrev240[i] as u64, + 2 => fft_bitrev120[i] as u64, + else => fft_bitrev60[i] as u64, + }; +} + +# An FFT of 480 points halved `shift` times, in place over complex values, +# each real then imaginary, its input already in its bit-reversed order. +def fft_impl(shift: i32, f: slice): void { + val factors := (shift * 10) as u64; + val twiddle_shift := shift; + var fstride: i32[8]; + fstride[0] = 1; + var stages: u64 = 0; + while true { + val p := fft_factors[factors + 2 * stages] as i32; + val m := fft_factors[factors + 2 * stages + 1] as i32; + fstride[stages + 1] = fstride[stages] * p; + stages++; + break if m == 1; + } + var m := fft_factors[factors + 2 * stages - 1] as i32; + var i := stages as i32 - 1; + while i >= 0 { + val m2: i32 = i != 0 ? fft_factors[factors + 2 * i as u64 - 1] as i32 : 1; + val n := fstride[i as u64]; + val stride := fstride[i as u64] << twiddle_shift as u32; + match fft_factors[factors + 2 * i as u64] { + 2 => bfly2(f, n); + 4 => bfly4(f, stride, m, n, m2); + 3 => bfly3(f, stride, m, n, m2); + else => bfly5(f, stride, m, n, m2); + } + m = m2; + i--; + } +} + +def tw_re(k: i32): f32 { + return fft_twiddles[(2 * k) as u64]; +} + +def tw_im(k: i32): f32 { + return fft_twiddles[(2 * k + 1) as u64]; +} + +# Radix 2, after a radix 4, so of 4 at a time. +def bfly2(f: slice, n: i32): void { + val tw: f32 = 0.7071067812; + for i in 0..n { + val a := (16 * i) as u64; + val b := a + 8; + # 0 + var tr := f[b]; + var ti := f[b + 1]; + f[b] = f[a] - tr; + f[b + 1] = f[a + 1] - ti; + f[a] += tr; + f[a + 1] += ti; + # 1 + tr = (f[b + 2] + f[b + 3]) * tw; + ti = (f[b + 3] - f[b + 2]) * tw; + f[b + 2] = f[a + 2] - tr; + f[b + 3] = f[a + 3] - ti; + f[a + 2] += tr; + f[a + 3] += ti; + # 2 + tr = f[b + 5]; + ti = -f[b + 4]; + f[b + 4] = f[a + 4] - tr; + f[b + 5] = f[a + 5] - ti; + f[a + 4] += tr; + f[a + 5] += ti; + # 3 + tr = (f[b + 7] - f[b + 6]) * tw; + ti = -(f[b + 7] + f[b + 6]) * tw; + f[b + 6] = f[a + 6] - tr; + f[b + 7] = f[a + 7] - ti; + f[a + 6] += tr; + f[a + 7] += ti; + } +} + +def bfly4(f: slice, fstride: i32, m: i32, n: i32, mm: i32): void { + if m == 1 { + for i in 0..n { + val o := (8 * i) as u64; + val s0r := f[o] - f[o + 4]; + val s0i := f[o + 1] - f[o + 5]; + f[o] += f[o + 4]; + f[o + 1] += f[o + 5]; + var s1r := f[o + 2] + f[o + 6]; + var s1i := f[o + 3] + f[o + 7]; + f[o + 4] = f[o] - s1r; + f[o + 5] = f[o + 1] - s1i; + f[o] += s1r; + f[o + 1] += s1i; + s1r = f[o + 2] - f[o + 6]; + s1i = f[o + 3] - f[o + 7]; + f[o + 2] = s0r + s1i; + f[o + 3] = s0i - s1r; + f[o + 6] = s0r - s1i; + f[o + 7] = s0i + s1r; + } + return; + } + val m2 := 2 * m; + val m3 := 3 * m; + for i in 0..n { + for j in 0..m { + val o := (2 * (i * mm + j)) as u64; + val a := o + (2 * m) as u64; + val b := o + (2 * m2) as u64; + val c := o + (2 * m3) as u64; + val t1 := j * fstride; + val t2 := 2 * j * fstride; + val t3 := 3 * j * fstride; + val s0r := f[a] * tw_re(t1) - f[a + 1] * tw_im(t1); + val s0i := f[a] * tw_im(t1) + f[a + 1] * tw_re(t1); + val s1r := f[b] * tw_re(t2) - f[b + 1] * tw_im(t2); + val s1i := f[b] * tw_im(t2) + f[b + 1] * tw_re(t2); + val s2r := f[c] * tw_re(t3) - f[c + 1] * tw_im(t3); + val s2i := f[c] * tw_im(t3) + f[c + 1] * tw_re(t3); + val s5r := f[o] - s1r; + val s5i := f[o + 1] - s1i; + f[o] += s1r; + f[o + 1] += s1i; + val s3r := s0r + s2r; + val s3i := s0i + s2i; + val s4r := s0r - s2r; + val s4i := s0i - s2i; + f[b] = f[o] - s3r; + f[b + 1] = f[o + 1] - s3i; + f[o] += s3r; + f[o + 1] += s3i; + f[a] = s5r + s4i; + f[a + 1] = s5i - s4r; + f[c] = s5r - s4i; + f[c + 1] = s5i + s4r; + } + } +} + +def bfly3(f: slice, fstride: i32, m: i32, n: i32, mm: i32): void { + val epi3i := tw_im(fstride * m); + for i in 0..n { + for j in 0..m { + val o := (2 * (i * mm + j)) as u64; + val a := o + (2 * m) as u64; + val b := o + (4 * m) as u64; + val t1 := j * fstride; + val t2 := 2 * j * fstride; + val s1r := f[a] * tw_re(t1) - f[a + 1] * tw_im(t1); + val s1i := f[a] * tw_im(t1) + f[a + 1] * tw_re(t1); + val s2r := f[b] * tw_re(t2) - f[b + 1] * tw_im(t2); + val s2i := f[b] * tw_im(t2) + f[b + 1] * tw_re(t2); + val s3r := s1r + s2r; + val s3i := s1i + s2i; + var s0r := s1r - s2r; + var s0i := s1i - s2i; + f[a] = f[o] - s3r * 0.5; + f[a + 1] = f[o + 1] - s3i * 0.5; + s0r *= epi3i; + s0i *= epi3i; + f[o] += s3r; + f[o + 1] += s3i; + f[b] = f[a] + s0i; + f[b + 1] = f[a + 1] - s0r; + f[a] = f[a] - s0i; + f[a + 1] = f[a + 1] + s0r; + } + } +} + +def bfly5(f: slice, fstride: i32, m: i32, n: i32, mm: i32): void { + val yar := tw_re(fstride * m); + val yai := tw_im(fstride * m); + val ybr := tw_re(fstride * 2 * m); + val ybi := tw_im(fstride * 2 * m); + for i in 0..n { + for u in 0..m { + val f0 := (2 * (i * mm + u)) as u64; + val f1 := f0 + (2 * m) as u64; + val f2 := f0 + (4 * m) as u64; + val f3 := f0 + (6 * m) as u64; + val f4 := f0 + (8 * m) as u64; + val s0r := f[f0]; + val s0i := f[f0 + 1]; + val k1 := u * fstride; + val k2 := 2 * u * fstride; + val k3 := 3 * u * fstride; + val k4 := 4 * u * fstride; + val s1r := f[f1] * tw_re(k1) - f[f1 + 1] * tw_im(k1); + val s1i := f[f1] * tw_im(k1) + f[f1 + 1] * tw_re(k1); + val s2r := f[f2] * tw_re(k2) - f[f2 + 1] * tw_im(k2); + val s2i := f[f2] * tw_im(k2) + f[f2 + 1] * tw_re(k2); + val s3r := f[f3] * tw_re(k3) - f[f3 + 1] * tw_im(k3); + val s3i := f[f3] * tw_im(k3) + f[f3 + 1] * tw_re(k3); + val s4r := f[f4] * tw_re(k4) - f[f4 + 1] * tw_im(k4); + val s4i := f[f4] * tw_im(k4) + f[f4 + 1] * tw_re(k4); + val s7r := s1r + s4r; + val s7i := s1i + s4i; + val s10r := s1r - s4r; + val s10i := s1i - s4i; + val s8r := s2r + s3r; + val s8i := s2i + s3i; + val s9r := s2r - s3r; + val s9i := s2i - s3i; + f[f0] = f[f0] + (s7r + s8r); + f[f0 + 1] = f[f0 + 1] + (s7i + s8i); + val s5r := s0r + (s7r * yar + s8r * ybr); + val s5i := s0i + (s7i * yar + s8i * ybr); + val s6r := s10i * yai + s9i * ybi; + val s6i := -(s10r * yai + s9r * ybi); + f[f1] = s5r - s6r; + f[f1 + 1] = s5i - s6i; + f[f4] = s5r + s6r; + f[f4 + 1] = s5i + s6i; + val s11r := s0r + (s7r * ybr + s8r * yar); + val s11i := s0i + (s7i * ybr + s8i * yar); + val s12r := s9i * yai - s10i * ybi; + val s12i := s10r * ybi - s9r * yai; + f[f2] = s11r + s12r; + f[f2 + 1] = s11i + s12i; + f[f3] = s11r - s12r; + f[f3 + 1] = s11i - s12i; + } + } +} + +# The inverse MDCT of a block's spectrum, taken every `stride` bins from +# `input`, into `out`: its first `overlap` values mixed with the block before's +# end, which they hold, and the rest written. +# @param shift How many times 1920 is halved: the MDCT is of 1920 >> shift. +def imdct(input: slice, stride: i32, out: slice, shift: i32): void { + var n: i32 = 1920; + var trig: u64 = 0; + for _ in 0..shift { + n >>= 1; + trig += n as u64; + } + val n2 := n >> 1; + val n4 := n >> 2; + val half := (celt_overlap / 2) as u64; + + # Rotated, into the FFT's order, real and imaginary swapped. + for i in 0..n4 { + val rev := fft_bitrev(shift, i as u64); + val x1 := input[(2 * stride * i) as u64]; + val x2 := input[(stride * (n2 - 1) - 2 * stride * i) as u64]; + val t0 := mdct_twiddles960[trig + i as u64]; + val t1 := mdct_twiddles960[trig + (n4 + i) as u64]; + val yr := x2 * t0 + x1 * t1; + val yi := x1 * t0 - x2 * t1; + out[half + 2 * rev + 1] = yr; + out[half + 2 * rev] = yi; + } + fft_impl(shift, slice::::over(out.data + half, n2 as u64)); + + # Rotated again, from both ends at once. + var y0 := half; + var y1 := half + (n2 - 2) as u64; + for i in 0..(n4 + 1) >> 1 { + var re := out[y0 + 1]; + var im := out[y0]; + var t0 := mdct_twiddles960[trig + i as u64]; + var t1 := mdct_twiddles960[trig + (n4 + i) as u64]; + var yr := re * t0 + im * t1; + var yi := re * t1 - im * t0; + re = out[y1 + 1]; + im = out[y1]; + out[y0] = yr; + out[y1 + 1] = yi; + t0 = mdct_twiddles960[trig + (n4 - i - 1) as u64]; + t1 = mdct_twiddles960[trig + (n2 - i - 1) as u64]; + yr = re * t0 + im * t1; + yi = re * t1 - im * t0; + out[y1] = yr; + out[y0 + 1] = yi; + y0 += 2; + y1 -= 2; + } + + # Mirrored on both sides, for the time-domain aliasing to cancel. + for i in 0..half { + val a := celt_overlap - 1 - i; + val x1 := out[a]; + val x2 := out[i]; + val w1 := window120[i]; + val w2 := window120[a]; + out[i] = w2 * x2 - w1 * x1; + out[a] = w1 * x2 + w2 * x1; + } +} diff --git a/audio/opus/celt_tables.sakura b/audio/opus/celt_tables.sakura new file mode 100644 index 0000000..0ca53ea --- /dev/null +++ b/audio/opus/celt_tables.sakura @@ -0,0 +1,732 @@ +#! Contains the tables CELT is decoded by, of its one mode, 48 kHz in frames of +#! up to 960: its bands, its allocation vectors and pulse cache, its window, its +#! FFT's and MDCT's twiddles, the models of its coarse energy, and the sizes of +#! its pulse vectors, each as libopus keeps them, generated from its sources. +#! +#! libopus is Copyright 2001-2023 Xiph.Org, Skype Limited, Octasic, Jean-Marc +#! Valin, Timothy B. Terriberry, CSIRO, Gregory Maxwell, Mark Borgerding, Erik +#! de Castro Lopo, Mozilla, and Amazon, under the 3-clause BSD license; see +#! `opus.sakura`. + +module malunal::audio::opus; + +# Where each of the 21 bands begins, in bins of a 2.5 ms block, and the end. +const eband5ms: i16[22] = [ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, + 34, 40, 48, 60, 78, 100, +]; + +# The 11 allocation vectors, each a band's bits, in 32nds of a bit a bin. +const band_allocation: u8[231] = [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 90, 80, 75, 69, 63, 56, 49, 40, 34, 29, 20, 18, 10, 0, 0, 0, 0, 0, 0, 0, 0, + 110, 100, 90, 84, 78, 71, 65, 58, 51, 45, 39, 32, 26, 20, 12, 0, 0, 0, 0, 0, 0, + 118, 110, 103, 93, 86, 80, 75, 70, 65, 59, 53, 47, 40, 31, 23, 15, 4, 0, 0, 0, 0, + 126, 119, 112, 104, 95, 89, 83, 78, 72, 66, 60, 54, 47, 39, 32, 25, 17, 12, 1, 0, 0, + 134, 127, 120, 114, 103, 97, 91, 85, 78, 72, 66, 60, 54, 47, 41, 35, 29, 23, 16, 10, 1, + 144, 137, 130, 124, 113, 107, 101, 95, 88, 82, 76, 70, 64, 57, 51, 45, 39, 33, 26, 15, 1, + 152, 145, 138, 132, 123, 117, 111, 105, 98, 92, 86, 80, 74, 67, 61, 55, 49, 43, 36, 20, 1, + 162, 155, 148, 142, 133, 127, 121, 115, 108, 102, 96, 90, 84, 77, 71, 65, 59, 53, 46, 30, 1, + 172, 165, 158, 152, 143, 137, 131, 125, 118, 112, 106, 100, 94, 87, 81, 75, 69, 63, 56, 45, 20, + 200, 200, 200, 200, 200, 200, 200, 200, 198, 193, 188, 183, 178, 173, 168, 163, 158, 153, 148, 129, 104, +]; + +# Each band's width's log, in eighths of a bit. +const log_n400: i16[21] = [ + 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8, 8, 16, 16, 16, 21, + 21, 24, 29, 34, 36, +]; + +# Where each band's pulse cache begins, for each LM from -1 to 3. +const cache_index50: i16[105] = [ + -1, -1, -1, -1, -1, -1, -1, -1, 0, 0, 0, 0, 41, 41, 41, 82, 82, 123, 164, 200, 222, + 0, 0, 0, 0, 0, 0, 0, 0, 41, 41, 41, 41, 123, 123, 123, 164, 164, 240, 266, 283, 295, + 41, 41, 41, 41, 41, 41, 41, 41, 123, 123, 123, 123, 240, 240, 240, 266, 266, 305, 318, 328, 336, + 123, 123, 123, 123, 123, 123, 123, 123, 240, 240, 240, 240, 305, 305, 305, 318, 318, 343, 351, 358, 364, + 240, 240, 240, 240, 240, 240, 240, 240, 305, 305, 305, 305, 343, 343, 343, 351, 351, 370, 376, 382, 387, +]; + +# The bits each count of pulses costs, less one, after a count of entries. +const cache_bits50: u8[392] = [ + 40, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 40, 15, 23, 28, 31, 34, 36, + 38, 39, 41, 42, 43, 44, 45, 46, 47, 47, 49, 50, 51, 52, 53, 54, + 55, 55, 57, 58, 59, 60, 61, 62, 63, 63, 65, 66, 67, 68, 69, 70, + 71, 71, 40, 20, 33, 41, 48, 53, 57, 61, 64, 66, 69, 71, 73, 75, + 76, 78, 80, 82, 85, 87, 89, 91, 92, 94, 96, 98, 101, 103, 105, 107, + 108, 110, 112, 114, 117, 119, 121, 123, 124, 126, 128, 40, 23, 39, 51, 60, + 67, 73, 79, 83, 87, 91, 94, 97, 100, 102, 105, 107, 111, 115, 118, 121, + 124, 126, 129, 131, 135, 139, 142, 145, 148, 150, 153, 155, 159, 163, 166, 169, + 172, 174, 177, 179, 35, 28, 49, 65, 78, 89, 99, 107, 114, 120, 126, 132, + 136, 141, 145, 149, 153, 159, 165, 171, 176, 180, 185, 189, 192, 199, 205, 211, + 216, 220, 225, 229, 232, 239, 245, 251, 21, 33, 58, 79, 97, 112, 125, 137, + 148, 157, 166, 174, 182, 189, 195, 201, 207, 217, 227, 235, 243, 251, 17, 35, + 63, 86, 106, 123, 139, 152, 165, 177, 187, 197, 206, 214, 222, 230, 237, 250, + 25, 31, 55, 75, 91, 105, 117, 128, 138, 146, 154, 161, 168, 174, 180, 185, + 190, 200, 208, 215, 222, 229, 235, 240, 245, 255, 16, 36, 65, 89, 110, 128, + 144, 159, 173, 185, 196, 207, 217, 226, 234, 242, 250, 11, 41, 74, 103, 128, + 151, 172, 191, 209, 225, 241, 255, 9, 43, 79, 110, 138, 163, 186, 207, 227, + 246, 12, 39, 71, 99, 123, 144, 164, 182, 198, 214, 228, 241, 253, 9, 44, + 81, 113, 142, 168, 192, 214, 235, 255, 7, 49, 90, 127, 160, 191, 220, 247, + 6, 51, 95, 134, 170, 203, 234, 7, 47, 87, 123, 155, 184, 212, 237, 6, + 52, 97, 137, 174, 208, 240, 5, 57, 106, 151, 192, 231, 5, 59, 111, 158, + 202, 243, 5, 55, 103, 147, 187, 224, 5, 60, 113, 161, 206, 248, 4, 65, + 122, 175, 224, 4, 67, 127, 182, 234, +]; + +# Each band's most bits, for each LM and channel count. +const cache_caps50: u8[168] = [ + 224, 224, 224, 224, 224, 224, 224, 224, 160, 160, 160, 160, 185, 185, 185, 178, 178, 168, 134, 61, 37, + 224, 224, 224, 224, 224, 224, 224, 224, 240, 240, 240, 240, 207, 207, 207, 198, 198, 183, 144, 66, 40, + 160, 160, 160, 160, 160, 160, 160, 160, 185, 185, 185, 185, 193, 193, 193, 183, 183, 172, 138, 64, 38, + 240, 240, 240, 240, 240, 240, 240, 240, 207, 207, 207, 207, 204, 204, 204, 193, 193, 180, 143, 66, 40, + 185, 185, 185, 185, 185, 185, 185, 185, 193, 193, 193, 193, 193, 193, 193, 183, 183, 172, 138, 65, 39, + 207, 207, 207, 207, 207, 207, 207, 207, 204, 204, 204, 204, 201, 201, 201, 188, 188, 176, 141, 66, 40, + 193, 193, 193, 193, 193, 193, 193, 193, 193, 193, 193, 193, 194, 194, 194, 184, 184, 173, 139, 65, 39, + 204, 204, 204, 204, 204, 204, 204, 204, 201, 201, 201, 201, 198, 198, 198, 187, 187, 175, 140, 66, 40, +]; + +# The overlap's window: its rising half, then falling. +const window120: f32[120] = [ + 6.7286966e-5, 0.00060551348, 0.001681597, 0.0032947962, 0.0054439943, 0.0081276923, 0.011344001, 0.015090633, + 0.019364886, 0.024163635, 0.029483315, 0.035319905, 0.041668911, 0.048525347, 0.055883718, 0.063737999, + 0.072081616, 0.080907428, 0.090207705, 0.099974111, 0.11019769, 0.12086883, 0.13197729, 0.14351214, + 0.15546177, 0.16781389, 0.1805555, 0.1936729, 0.20715171, 0.22097682, 0.23513243, 0.24960208, + 0.2643686, 0.27941419, 0.2947204, 0.31026818, 0.32603788, 0.34200931, 0.35816177, 0.37447407, + 0.39092462, 0.40749142, 0.42415215, 0.44088423, 0.45766484, 0.47447104, 0.49127978, 0.50806798, + 0.52481261, 0.54149077, 0.55807973, 0.57455701, 0.59090049, 0.60708841, 0.62309951, 0.63891306, + 0.65450896, 0.66986776, 0.68497077, 0.6998001, 0.71433873, 0.72857055, 0.74248043, 0.75605424, + 0.76927895, 0.78214257, 0.7946343, 0.80674445, 0.81846456, 0.82978733, 0.84070669, 0.85121779, + 0.86131698, 0.87100183, 0.88027111, 0.88912479, 0.89756398, 0.90559094, 0.91320904, 0.9204227, + 0.92723738, 0.93365955, 0.93969656, 0.94535671, 0.95064907, 0.95558353, 0.96017067, 0.96442171, + 0.96834849, 0.97196334, 0.97527906, 0.97830883, 0.98106616, 0.9835648, 0.98581869, 0.98784191, + 0.98964856, 0.99125274, 0.99266849, 0.99390969, 0.99499004, 0.99592297, 0.99672162, 0.99739874, + 0.99796667, 0.99843728, 0.99882195, 0.99913147, 0.99937606, 0.99956527, 0.99970802, 0.99981248, + 0.99988613, 0.99993565, 0.99996697, 0.99998518, 0.99999457, 0.99999859, 0.99999982, 1.0, +]; + +# The FFT's twiddles, of 480 points, each real then imaginary. +const fft_twiddles: f32[960] = [ + 1.0, -0.0, 0.99991433, -0.013089596, 0.99965732, -0.026176948, 0.99922904, -0.039259816, + 0.99862953, -0.052335956, 0.99785892, -0.065403129, 0.99691733, -0.078459096, 0.99580493, -0.091501619, + 0.9945219, -0.10452846, 0.99306846, -0.1175374, 0.99144486, -0.13052619, 0.98965139, -0.14349262, + 0.98768834, -0.15643447, 0.98555606, -0.1693495, 0.98325491, -0.18223553, 0.98078528, -0.19509032, + 0.9781476, -0.20791169, 0.97534232, -0.22069744, 0.97236992, -0.23344536, 0.96923091, -0.24615329, + 0.96592583, -0.25881905, 0.96245524, -0.27144045, 0.95881973, -0.28401534, 0.95501994, -0.29654157, + 0.95105652, -0.30901699, 0.94693013, -0.32143947, 0.94264149, -0.33380686, 0.93819134, -0.34611706, + 0.93358043, -0.35836795, 0.92880955, -0.37055744, 0.92387953, -0.38268343, 0.91879121, -0.39474386, + 0.91354546, -0.40673664, 0.90814317, -0.41865974, 0.90258528, -0.4305111, 0.89687274, -0.44228869, + 0.89100652, -0.4539905, 0.88498764, -0.46561452, 0.87881711, -0.47715876, 0.87249601, -0.48862124, + 0.8660254, -0.5, 0.85940641, -0.51129309, 0.85264016, -0.52249856, 0.84572782, -0.53361452, + 0.83867057, -0.54463904, 0.83146961, -0.55557023, 0.82412619, -0.56640624, 0.81664156, -0.57714519, + 0.80901699, -0.58778525, 0.80125381, -0.5983246, 0.79335334, -0.60876143, 0.78531693, -0.61909395, + 0.77714596, -0.62932039, 0.76884183, -0.639439, 0.76040597, -0.64944805, 0.75183981, -0.65934582, + 0.74314483, -0.66913061, 0.73432251, -0.67880075, 0.72537437, -0.68835458, 0.71630194, -0.69779046, + 0.70710678, -0.70710678, 0.69779046, -0.71630194, 0.68835458, -0.72537437, 0.67880075, -0.73432251, + 0.66913061, -0.74314483, 0.65934582, -0.75183981, 0.64944805, -0.76040597, 0.639439, -0.76884183, + 0.62932039, -0.77714596, 0.61909395, -0.78531693, 0.60876143, -0.79335334, 0.5983246, -0.80125381, + 0.58778525, -0.80901699, 0.57714519, -0.81664156, 0.56640624, -0.82412619, 0.55557023, -0.83146961, + 0.54463904, -0.83867057, 0.53361452, -0.84572782, 0.52249856, -0.85264016, 0.51129309, -0.85940641, + 0.5, -0.8660254, 0.48862124, -0.87249601, 0.47715876, -0.87881711, 0.46561452, -0.88498764, + 0.4539905, -0.89100652, 0.44228869, -0.89687274, 0.4305111, -0.90258528, 0.41865974, -0.90814317, + 0.40673664, -0.91354546, 0.39474386, -0.91879121, 0.38268343, -0.92387953, 0.37055744, -0.92880955, + 0.35836795, -0.93358043, 0.34611706, -0.93819134, 0.33380686, -0.94264149, 0.32143947, -0.94693013, + 0.30901699, -0.95105652, 0.29654157, -0.95501994, 0.28401534, -0.95881973, 0.27144045, -0.96245524, + 0.25881905, -0.96592583, 0.24615329, -0.96923091, 0.23344536, -0.97236992, 0.22069744, -0.97534232, + 0.20791169, -0.9781476, 0.19509032, -0.98078528, 0.18223553, -0.98325491, 0.1693495, -0.98555606, + 0.15643447, -0.98768834, 0.14349262, -0.98965139, 0.13052619, -0.99144486, 0.1175374, -0.99306846, + 0.10452846, -0.9945219, 0.091501619, -0.99580493, 0.078459096, -0.99691733, 0.065403129, -0.99785892, + 0.052335956, -0.99862953, 0.039259816, -0.99922904, 0.026176948, -0.99965732, 0.013089596, -0.99991433, + 6.1230318e-17, -1.0, -0.013089596, -0.99991433, -0.026176948, -0.99965732, -0.039259816, -0.99922904, + -0.052335956, -0.99862953, -0.065403129, -0.99785892, -0.078459096, -0.99691733, -0.091501619, -0.99580493, + -0.10452846, -0.9945219, -0.1175374, -0.99306846, -0.13052619, -0.99144486, -0.14349262, -0.98965139, + -0.15643447, -0.98768834, -0.1693495, -0.98555606, -0.18223553, -0.98325491, -0.19509032, -0.98078528, + -0.20791169, -0.9781476, -0.22069744, -0.97534232, -0.23344536, -0.97236992, -0.24615329, -0.96923091, + -0.25881905, -0.96592583, -0.27144045, -0.96245524, -0.28401534, -0.95881973, -0.29654157, -0.95501994, + -0.30901699, -0.95105652, -0.32143947, -0.94693013, -0.33380686, -0.94264149, -0.34611706, -0.93819134, + -0.35836795, -0.93358043, -0.37055744, -0.92880955, -0.38268343, -0.92387953, -0.39474386, -0.91879121, + -0.40673664, -0.91354546, -0.41865974, -0.90814317, -0.4305111, -0.90258528, -0.44228869, -0.89687274, + -0.4539905, -0.89100652, -0.46561452, -0.88498764, -0.47715876, -0.87881711, -0.48862124, -0.87249601, + -0.5, -0.8660254, -0.51129309, -0.85940641, -0.52249856, -0.85264016, -0.53361452, -0.84572782, + -0.54463904, -0.83867057, -0.55557023, -0.83146961, -0.56640624, -0.82412619, -0.57714519, -0.81664156, + -0.58778525, -0.80901699, -0.5983246, -0.80125381, -0.60876143, -0.79335334, -0.61909395, -0.78531693, + -0.62932039, -0.77714596, -0.639439, -0.76884183, -0.64944805, -0.76040597, -0.65934582, -0.75183981, + -0.66913061, -0.74314483, -0.67880075, -0.73432251, -0.68835458, -0.72537437, -0.69779046, -0.71630194, + -0.70710678, -0.70710678, -0.71630194, -0.69779046, -0.72537437, -0.68835458, -0.73432251, -0.67880075, + -0.74314483, -0.66913061, -0.75183981, -0.65934582, -0.76040597, -0.64944805, -0.76884183, -0.639439, + -0.77714596, -0.62932039, -0.78531693, -0.61909395, -0.79335334, -0.60876143, -0.80125381, -0.5983246, + -0.80901699, -0.58778525, -0.81664156, -0.57714519, -0.82412619, -0.56640624, -0.83146961, -0.55557023, + -0.83867057, -0.54463904, -0.84572782, -0.53361452, -0.85264016, -0.52249856, -0.85940641, -0.51129309, + -0.8660254, -0.5, -0.87249601, -0.48862124, -0.87881711, -0.47715876, -0.88498764, -0.46561452, + -0.89100652, -0.4539905, -0.89687274, -0.44228869, -0.90258528, -0.4305111, -0.90814317, -0.41865974, + -0.91354546, -0.40673664, -0.91879121, -0.39474386, -0.92387953, -0.38268343, -0.92880955, -0.37055744, + -0.93358043, -0.35836795, -0.93819134, -0.34611706, -0.94264149, -0.33380686, -0.94693013, -0.32143947, + -0.95105652, -0.30901699, -0.95501994, -0.29654157, -0.95881973, -0.28401534, -0.96245524, -0.27144045, + -0.96592583, -0.25881905, -0.96923091, -0.24615329, -0.97236992, -0.23344536, -0.97534232, -0.22069744, + -0.9781476, -0.20791169, -0.98078528, -0.19509032, -0.98325491, -0.18223553, -0.98555606, -0.1693495, + -0.98768834, -0.15643447, -0.98965139, -0.14349262, -0.99144486, -0.13052619, -0.99306846, -0.1175374, + -0.9945219, -0.10452846, -0.99580493, -0.091501619, -0.99691733, -0.078459096, -0.99785892, -0.065403129, + -0.99862953, -0.052335956, -0.99922904, -0.039259816, -0.99965732, -0.026176948, -0.99991433, -0.013089596, + -1.0, -1.2246064e-16, -0.99991433, 0.013089596, -0.99965732, 0.026176948, -0.99922904, 0.039259816, + -0.99862953, 0.052335956, -0.99785892, 0.065403129, -0.99691733, 0.078459096, -0.99580493, 0.091501619, + -0.9945219, 0.10452846, -0.99306846, 0.1175374, -0.99144486, 0.13052619, -0.98965139, 0.14349262, + -0.98768834, 0.15643447, -0.98555606, 0.1693495, -0.98325491, 0.18223553, -0.98078528, 0.19509032, + -0.9781476, 0.20791169, -0.97534232, 0.22069744, -0.97236992, 0.23344536, -0.96923091, 0.24615329, + -0.96592583, 0.25881905, -0.96245524, 0.27144045, -0.95881973, 0.28401534, -0.95501994, 0.29654157, + -0.95105652, 0.30901699, -0.94693013, 0.32143947, -0.94264149, 0.33380686, -0.93819134, 0.34611706, + -0.93358043, 0.35836795, -0.92880955, 0.37055744, -0.92387953, 0.38268343, -0.91879121, 0.39474386, + -0.91354546, 0.40673664, -0.90814317, 0.41865974, -0.90258528, 0.4305111, -0.89687274, 0.44228869, + -0.89100652, 0.4539905, -0.88498764, 0.46561452, -0.87881711, 0.47715876, -0.87249601, 0.48862124, + -0.8660254, 0.5, -0.85940641, 0.51129309, -0.85264016, 0.52249856, -0.84572782, 0.53361452, + -0.83867057, 0.54463904, -0.83146961, 0.55557023, -0.82412619, 0.56640624, -0.81664156, 0.57714519, + -0.80901699, 0.58778525, -0.80125381, 0.5983246, -0.79335334, 0.60876143, -0.78531693, 0.61909395, + -0.77714596, 0.62932039, -0.76884183, 0.639439, -0.76040597, 0.64944805, -0.75183981, 0.65934582, + -0.74314483, 0.66913061, -0.73432251, 0.67880075, -0.72537437, 0.68835458, -0.71630194, 0.69779046, + -0.70710678, 0.70710678, -0.69779046, 0.71630194, -0.68835458, 0.72537437, -0.67880075, 0.73432251, + -0.66913061, 0.74314483, -0.65934582, 0.75183981, -0.64944805, 0.76040597, -0.639439, 0.76884183, + -0.62932039, 0.77714596, -0.61909395, 0.78531693, -0.60876143, 0.79335334, -0.5983246, 0.80125381, + -0.58778525, 0.80901699, -0.57714519, 0.81664156, -0.56640624, 0.82412619, -0.55557023, 0.83146961, + -0.54463904, 0.83867057, -0.53361452, 0.84572782, -0.52249856, 0.85264016, -0.51129309, 0.85940641, + -0.5, 0.8660254, -0.48862124, 0.87249601, -0.47715876, 0.87881711, -0.46561452, 0.88498764, + -0.4539905, 0.89100652, -0.44228869, 0.89687274, -0.4305111, 0.90258528, -0.41865974, 0.90814317, + -0.40673664, 0.91354546, -0.39474386, 0.91879121, -0.38268343, 0.92387953, -0.37055744, 0.92880955, + -0.35836795, 0.93358043, -0.34611706, 0.93819134, -0.33380686, 0.94264149, -0.32143947, 0.94693013, + -0.30901699, 0.95105652, -0.29654157, 0.95501994, -0.28401534, 0.95881973, -0.27144045, 0.96245524, + -0.25881905, 0.96592583, -0.24615329, 0.96923091, -0.23344536, 0.97236992, -0.22069744, 0.97534232, + -0.20791169, 0.9781476, -0.19509032, 0.98078528, -0.18223553, 0.98325491, -0.1693495, 0.98555606, + -0.15643447, 0.98768834, -0.14349262, 0.98965139, -0.13052619, 0.99144486, -0.1175374, 0.99306846, + -0.10452846, 0.9945219, -0.091501619, 0.99580493, -0.078459096, 0.99691733, -0.065403129, 0.99785892, + -0.052335956, 0.99862953, -0.039259816, 0.99922904, -0.026176948, 0.99965732, -0.013089596, 0.99991433, + -1.8369095e-16, 1.0, 0.013089596, 0.99991433, 0.026176948, 0.99965732, 0.039259816, 0.99922904, + 0.052335956, 0.99862953, 0.065403129, 0.99785892, 0.078459096, 0.99691733, 0.091501619, 0.99580493, + 0.10452846, 0.9945219, 0.1175374, 0.99306846, 0.13052619, 0.99144486, 0.14349262, 0.98965139, + 0.15643447, 0.98768834, 0.1693495, 0.98555606, 0.18223553, 0.98325491, 0.19509032, 0.98078528, + 0.20791169, 0.9781476, 0.22069744, 0.97534232, 0.23344536, 0.97236992, 0.24615329, 0.96923091, + 0.25881905, 0.96592583, 0.27144045, 0.96245524, 0.28401534, 0.95881973, 0.29654157, 0.95501994, + 0.30901699, 0.95105652, 0.32143947, 0.94693013, 0.33380686, 0.94264149, 0.34611706, 0.93819134, + 0.35836795, 0.93358043, 0.37055744, 0.92880955, 0.38268343, 0.92387953, 0.39474386, 0.91879121, + 0.40673664, 0.91354546, 0.41865974, 0.90814317, 0.4305111, 0.90258528, 0.44228869, 0.89687274, + 0.4539905, 0.89100652, 0.46561452, 0.88498764, 0.47715876, 0.87881711, 0.48862124, 0.87249601, + 0.5, 0.8660254, 0.51129309, 0.85940641, 0.52249856, 0.85264016, 0.53361452, 0.84572782, + 0.54463904, 0.83867057, 0.55557023, 0.83146961, 0.56640624, 0.82412619, 0.57714519, 0.81664156, + 0.58778525, 0.80901699, 0.5983246, 0.80125381, 0.60876143, 0.79335334, 0.61909395, 0.78531693, + 0.62932039, 0.77714596, 0.639439, 0.76884183, 0.64944805, 0.76040597, 0.65934582, 0.75183981, + 0.66913061, 0.74314483, 0.67880075, 0.73432251, 0.68835458, 0.72537437, 0.69779046, 0.71630194, + 0.70710678, 0.70710678, 0.71630194, 0.69779046, 0.72537437, 0.68835458, 0.73432251, 0.67880075, + 0.74314483, 0.66913061, 0.75183981, 0.65934582, 0.76040597, 0.64944805, 0.76884183, 0.639439, + 0.77714596, 0.62932039, 0.78531693, 0.61909395, 0.79335334, 0.60876143, 0.80125381, 0.5983246, + 0.80901699, 0.58778525, 0.81664156, 0.57714519, 0.82412619, 0.56640624, 0.83146961, 0.55557023, + 0.83867057, 0.54463904, 0.84572782, 0.53361452, 0.85264016, 0.52249856, 0.85940641, 0.51129309, + 0.8660254, 0.5, 0.87249601, 0.48862124, 0.87881711, 0.47715876, 0.88498764, 0.46561452, + 0.89100652, 0.4539905, 0.89687274, 0.44228869, 0.90258528, 0.4305111, 0.90814317, 0.41865974, + 0.91354546, 0.40673664, 0.91879121, 0.39474386, 0.92387953, 0.38268343, 0.92880955, 0.37055744, + 0.93358043, 0.35836795, 0.93819134, 0.34611706, 0.94264149, 0.33380686, 0.94693013, 0.32143947, + 0.95105652, 0.30901699, 0.95501994, 0.29654157, 0.95881973, 0.28401534, 0.96245524, 0.27144045, + 0.96592583, 0.25881905, 0.96923091, 0.24615329, 0.97236992, 0.23344536, 0.97534232, 0.22069744, + 0.9781476, 0.20791169, 0.98078528, 0.19509032, 0.98325491, 0.18223553, 0.98555606, 0.1693495, + 0.98768834, 0.15643447, 0.98965139, 0.14349262, 0.99144486, 0.13052619, 0.99306846, 0.1175374, + 0.9945219, 0.10452846, 0.99580493, 0.091501619, 0.99691733, 0.078459096, 0.99785892, 0.065403129, + 0.99862953, 0.052335956, 0.99922904, 0.039259816, 0.99965732, 0.026176948, 0.99991433, 0.013089596, +]; + +# Where each of the FFT's inputs goes, of 480 points. +const fft_bitrev480: i16[480] = [ + 0, 96, 192, 288, 384, 32, 128, 224, 320, 416, 64, 160, 256, 352, 448, 8, + 104, 200, 296, 392, 40, 136, 232, 328, 424, 72, 168, 264, 360, 456, 16, 112, + 208, 304, 400, 48, 144, 240, 336, 432, 80, 176, 272, 368, 464, 24, 120, 216, + 312, 408, 56, 152, 248, 344, 440, 88, 184, 280, 376, 472, 4, 100, 196, 292, + 388, 36, 132, 228, 324, 420, 68, 164, 260, 356, 452, 12, 108, 204, 300, 396, + 44, 140, 236, 332, 428, 76, 172, 268, 364, 460, 20, 116, 212, 308, 404, 52, + 148, 244, 340, 436, 84, 180, 276, 372, 468, 28, 124, 220, 316, 412, 60, 156, + 252, 348, 444, 92, 188, 284, 380, 476, 1, 97, 193, 289, 385, 33, 129, 225, + 321, 417, 65, 161, 257, 353, 449, 9, 105, 201, 297, 393, 41, 137, 233, 329, + 425, 73, 169, 265, 361, 457, 17, 113, 209, 305, 401, 49, 145, 241, 337, 433, + 81, 177, 273, 369, 465, 25, 121, 217, 313, 409, 57, 153, 249, 345, 441, 89, + 185, 281, 377, 473, 5, 101, 197, 293, 389, 37, 133, 229, 325, 421, 69, 165, + 261, 357, 453, 13, 109, 205, 301, 397, 45, 141, 237, 333, 429, 77, 173, 269, + 365, 461, 21, 117, 213, 309, 405, 53, 149, 245, 341, 437, 85, 181, 277, 373, + 469, 29, 125, 221, 317, 413, 61, 157, 253, 349, 445, 93, 189, 285, 381, 477, + 2, 98, 194, 290, 386, 34, 130, 226, 322, 418, 66, 162, 258, 354, 450, 10, + 106, 202, 298, 394, 42, 138, 234, 330, 426, 74, 170, 266, 362, 458, 18, 114, + 210, 306, 402, 50, 146, 242, 338, 434, 82, 178, 274, 370, 466, 26, 122, 218, + 314, 410, 58, 154, 250, 346, 442, 90, 186, 282, 378, 474, 6, 102, 198, 294, + 390, 38, 134, 230, 326, 422, 70, 166, 262, 358, 454, 14, 110, 206, 302, 398, + 46, 142, 238, 334, 430, 78, 174, 270, 366, 462, 22, 118, 214, 310, 406, 54, + 150, 246, 342, 438, 86, 182, 278, 374, 470, 30, 126, 222, 318, 414, 62, 158, + 254, 350, 446, 94, 190, 286, 382, 478, 3, 99, 195, 291, 387, 35, 131, 227, + 323, 419, 67, 163, 259, 355, 451, 11, 107, 203, 299, 395, 43, 139, 235, 331, + 427, 75, 171, 267, 363, 459, 19, 115, 211, 307, 403, 51, 147, 243, 339, 435, + 83, 179, 275, 371, 467, 27, 123, 219, 315, 411, 59, 155, 251, 347, 443, 91, + 187, 283, 379, 475, 7, 103, 199, 295, 391, 39, 135, 231, 327, 423, 71, 167, + 263, 359, 455, 15, 111, 207, 303, 399, 47, 143, 239, 335, 431, 79, 175, 271, + 367, 463, 23, 119, 215, 311, 407, 55, 151, 247, 343, 439, 87, 183, 279, 375, + 471, 31, 127, 223, 319, 415, 63, 159, 255, 351, 447, 95, 191, 287, 383, 479, +]; + +# Of 240. +const fft_bitrev240: i16[240] = [ + 0, 48, 96, 144, 192, 16, 64, 112, 160, 208, 32, 80, 128, 176, 224, 4, + 52, 100, 148, 196, 20, 68, 116, 164, 212, 36, 84, 132, 180, 228, 8, 56, + 104, 152, 200, 24, 72, 120, 168, 216, 40, 88, 136, 184, 232, 12, 60, 108, + 156, 204, 28, 76, 124, 172, 220, 44, 92, 140, 188, 236, 1, 49, 97, 145, + 193, 17, 65, 113, 161, 209, 33, 81, 129, 177, 225, 5, 53, 101, 149, 197, + 21, 69, 117, 165, 213, 37, 85, 133, 181, 229, 9, 57, 105, 153, 201, 25, + 73, 121, 169, 217, 41, 89, 137, 185, 233, 13, 61, 109, 157, 205, 29, 77, + 125, 173, 221, 45, 93, 141, 189, 237, 2, 50, 98, 146, 194, 18, 66, 114, + 162, 210, 34, 82, 130, 178, 226, 6, 54, 102, 150, 198, 22, 70, 118, 166, + 214, 38, 86, 134, 182, 230, 10, 58, 106, 154, 202, 26, 74, 122, 170, 218, + 42, 90, 138, 186, 234, 14, 62, 110, 158, 206, 30, 78, 126, 174, 222, 46, + 94, 142, 190, 238, 3, 51, 99, 147, 195, 19, 67, 115, 163, 211, 35, 83, + 131, 179, 227, 7, 55, 103, 151, 199, 23, 71, 119, 167, 215, 39, 87, 135, + 183, 231, 11, 59, 107, 155, 203, 27, 75, 123, 171, 219, 43, 91, 139, 187, + 235, 15, 63, 111, 159, 207, 31, 79, 127, 175, 223, 47, 95, 143, 191, 239, +]; + +# Of 120. +const fft_bitrev120: i16[120] = [ + 0, 24, 48, 72, 96, 8, 32, 56, 80, 104, 16, 40, 64, 88, 112, 4, + 28, 52, 76, 100, 12, 36, 60, 84, 108, 20, 44, 68, 92, 116, 1, 25, + 49, 73, 97, 9, 33, 57, 81, 105, 17, 41, 65, 89, 113, 5, 29, 53, + 77, 101, 13, 37, 61, 85, 109, 21, 45, 69, 93, 117, 2, 26, 50, 74, + 98, 10, 34, 58, 82, 106, 18, 42, 66, 90, 114, 6, 30, 54, 78, 102, + 14, 38, 62, 86, 110, 22, 46, 70, 94, 118, 3, 27, 51, 75, 99, 11, + 35, 59, 83, 107, 19, 43, 67, 91, 115, 7, 31, 55, 79, 103, 15, 39, + 63, 87, 111, 23, 47, 71, 95, 119, +]; + +# Of 60. +const fft_bitrev60: i16[60] = [ + 0, 12, 24, 36, 48, 4, 16, 28, 40, 52, 8, 20, 32, 44, 56, 1, + 13, 25, 37, 49, 5, 17, 29, 41, 53, 9, 21, 33, 45, 57, 2, 14, + 26, 38, 50, 6, 18, 30, 42, 54, 10, 22, 34, 46, 58, 3, 15, 27, + 39, 51, 7, 19, 31, 43, 55, 11, 23, 35, 47, 59, +]; + +# The MDCT's twiddles, for each size from 1920 down, halving. +const mdct_twiddles960: f32[1800] = [ + 0.99999994, 0.99999321, 0.9999758, 0.99994773, 0.99990886, 0.99985933, 0.99979913, 0.9997282, + 0.99964654, 0.99955416, 0.9994511, 0.99933738, 0.99921292, 0.99907774, 0.99893188, 0.9987753, + 0.99860805, 0.99843007, 0.99824142, 0.99804211, 0.99783206, 0.9976114, 0.99737996, 0.9971379, + 0.99688518, 0.99662173, 0.99634761, 0.99606287, 0.99576741, 0.99546129, 0.99514455, 0.99481714, + 0.99447906, 0.99413031, 0.99377096, 0.99340093, 0.9930203, 0.99262899, 0.99222708, 0.99181455, + 0.99139136, 0.99095762, 0.99051321, 0.99005818, 0.98959261, 0.98911643, 0.98862964, 0.98813224, + 0.98762429, 0.98710573, 0.98657662, 0.98603696, 0.98548669, 0.98492593, 0.98435456, 0.9837727, + 0.98318028, 0.98257732, 0.98196387, 0.98133987, 0.98070538, 0.9800604, 0.97940493, 0.9787389, + 0.97806245, 0.97737551, 0.97667813, 0.97597027, 0.97525197, 0.97452319, 0.97378403, 0.97303438, + 0.97227436, 0.97150391, 0.97072303, 0.96993178, 0.96913016, 0.9683181, 0.96749574, 0.966663, + 0.9658199, 0.96496642, 0.96410263, 0.96322852, 0.96234411, 0.96144938, 0.96054435, 0.95962906, + 0.95870346, 0.95776761, 0.9568215, 0.95586514, 0.95489854, 0.95392174, 0.95293468, 0.95193744, + 0.95093, 0.94991243, 0.94888461, 0.94784665, 0.94679856, 0.94574034, 0.94467193, 0.94359344, + 0.94250488, 0.94140619, 0.94029742, 0.93917859, 0.93804967, 0.93691075, 0.93576175, 0.93460274, + 0.93343377, 0.93225473, 0.93106574, 0.92986679, 0.92865789, 0.92743903, 0.92621022, 0.92497152, + 0.92372292, 0.92246443, 0.92119598, 0.91991776, 0.91862965, 0.9173317, 0.91602397, 0.91470635, + 0.91337901, 0.91204184, 0.9106949, 0.90933824, 0.90797186, 0.90659571, 0.90520984, 0.90381432, + 0.90240908, 0.90099424, 0.89956969, 0.89813554, 0.89669174, 0.89523834, 0.8937754, 0.89230281, + 0.89082074, 0.88932908, 0.88782793, 0.88631725, 0.8847971, 0.88326746, 0.88172835, 0.88017982, + 0.87862182, 0.87705445, 0.87547767, 0.87389153, 0.87229604, 0.87069118, 0.86907703, 0.86745358, + 0.86582077, 0.86417878, 0.86252749, 0.8608669, 0.8591972, 0.85751826, 0.85583007, 0.85413277, + 0.85242635, 0.85071075, 0.84898609, 0.84725231, 0.84550947, 0.84375757, 0.84199661, 0.84022665, + 0.83844769, 0.83665979, 0.83486289, 0.83305705, 0.83124226, 0.8294186, 0.82758605, 0.82574469, + 0.82389444, 0.82203537, 0.82016748, 0.81829083, 0.81640542, 0.81451124, 0.81260836, 0.81069672, + 0.8087765, 0.80684757, 0.80490994, 0.80296379, 0.801009, 0.79904562, 0.79707366, 0.79509324, + 0.79310423, 0.79110676, 0.78910083, 0.78708643, 0.78506362, 0.78303236, 0.78099275, 0.77894479, + 0.77688843, 0.77482378, 0.77275085, 0.77066964, 0.7685802, 0.76648247, 0.76437658, 0.76226246, + 0.76014024, 0.75800985, 0.7558713, 0.75372469, 0.75157005, 0.74940729, 0.74723655, 0.74505776, + 0.74287105, 0.74067634, 0.73847371, 0.73626316, 0.73404479, 0.7318185, 0.72958434, 0.72734243, + 0.72509271, 0.72283524, 0.72057003, 0.71829706, 0.71601641, 0.71372813, 0.71143216, 0.70912862, + 0.70681745, 0.70449871, 0.70217246, 0.69983864, 0.69749737, 0.69514859, 0.69279242, 0.69042879, + 0.68805778, 0.68567938, 0.68329364, 0.68090063, 0.67850029, 0.67609268, 0.67367786, 0.67125577, + 0.66882652, 0.66639012, 0.66394657, 0.66149592, 0.65903819, 0.65657341, 0.65410155, 0.65162271, + 0.6491369, 0.64664418, 0.64414448, 0.64163786, 0.63912445, 0.63660413, 0.63407701, 0.6315431, + 0.62900239, 0.62645501, 0.62390089, 0.6213401, 0.61877263, 0.61619854, 0.6136179, 0.61103064, + 0.60843682, 0.60583651, 0.6032297, 0.60061646, 0.59799677, 0.59537065, 0.59273821, 0.59009939, + 0.58745426, 0.58480281, 0.58214509, 0.57948118, 0.57681108, 0.57413477, 0.57145232, 0.56876373, + 0.56606907, 0.56336832, 0.56066155, 0.55794877, 0.55523002, 0.55250537, 0.54977477, 0.54703826, + 0.54429591, 0.54154772, 0.53879374, 0.53603399, 0.53326851, 0.53049731, 0.52772039, 0.52493787, + 0.52214974, 0.51935595, 0.51655668, 0.5137518, 0.51094145, 0.50812566, 0.5053044, 0.50247771, + 0.49964568, 0.49680826, 0.49396557, 0.49111754, 0.48826426, 0.48540577, 0.48254207, 0.47967321, + 0.47679919, 0.47392011, 0.4710359, 0.46814668, 0.46525243, 0.46235323, 0.45944905, 0.45653993, + 0.45362595, 0.45070711, 0.44778344, 0.44485497, 0.44192174, 0.4389838, 0.43604112, 0.43309379, + 0.43014181, 0.42718524, 0.42422408, 0.42125839, 0.4182882, 0.41531351, 0.41233435, 0.40935081, + 0.40636289, 0.40337059, 0.400374, 0.39737311, 0.39436796, 0.39135858, 0.388345, 0.38532731, + 0.38230544, 0.37927949, 0.37624949, 0.37321547, 0.37017745, 0.36713544, 0.36408952, 0.3610397, + 0.357986, 0.35492846, 0.35186714, 0.34880206, 0.34573323, 0.3426607, 0.33958447, 0.33650464, + 0.3334212, 0.33033419, 0.32724363, 0.32414958, 0.32105204, 0.31795108, 0.31484672, 0.31173897, + 0.3086279, 0.3055135, 0.30239585, 0.29927495, 0.29615086, 0.29302359, 0.28989318, 0.28675964, + 0.28362307, 0.28048345, 0.27734083, 0.27419522, 0.2710467, 0.26789525, 0.26474094, 0.26158381, + 0.25842386, 0.25526115, 0.2520957, 0.24892756, 0.24575676, 0.24258332, 0.23940729, 0.23622867, + 0.23304754, 0.22986393, 0.22667783, 0.22348931, 0.22029841, 0.21710514, 0.21390954, 0.21071166, + 0.20751151, 0.20430915, 0.2011046, 0.1978979, 0.19468907, 0.19147816, 0.18826519, 0.18505022, + 0.18183327, 0.17861435, 0.17539354, 0.17217083, 0.1689463, 0.16571994, 0.16249183, 0.15926196, + 0.15603039, 0.15279715, 0.14956227, 0.14632578, 0.14308774, 0.13984816, 0.13660708, 0.13336454, + 0.13012058, 0.12687522, 0.1236285, 0.12038045, 0.11713112, 0.11388054, 0.11062872, 0.10737573, + 0.1041216, 0.10086634, 0.097609997, 0.094352618, 0.091094226, 0.087834857, 0.08457455, 0.081313334, + 0.078051247, 0.074788325, 0.071524605, 0.068260118, 0.064994894, 0.06172898, 0.058462404, 0.055195201, + 0.05192741, 0.04865906, 0.045390189, 0.042120833, 0.038851023, 0.035580799, 0.032310195, 0.029039243, + 0.025767982, 0.022496443, 0.019224664, 0.01595268, 0.012680525, 0.0094082337, 0.0061358409, 0.0028633832, + -0.00040910527, -0.0036815894, -0.0069540343, -0.010226404, -0.013498665, -0.016770782, -0.020042717, -0.023314439, + -0.026585912, -0.029857099, -0.033127967, -0.036398482, -0.039668605, -0.042938303, -0.04620754, -0.049476285, + -0.052744497, -0.056012146, -0.059279196, -0.062545612, -0.065811358, -0.069076397, -0.072340697, -0.075604223, + -0.078866936, -0.082128808, -0.0853898, -0.088649876, -0.091909006, -0.095167145, -0.098424271, -0.10168034, + -0.10493532, -0.10818918, -0.11144188, -0.11469338, -0.11794366, -0.12119267, -0.12444039, -0.12768677, + -0.13093179, -0.1341754, -0.13741758, -0.14065829, -0.14389749, -0.14713514, -0.15037122, -0.1536057, + -0.15683852, -0.16006967, -0.1632991, -0.16652679, -0.16975269, -0.17297678, -0.176199, -0.17941935, + -0.18263777, -0.18585424, -0.1890687, -0.19228116, -0.19549155, -0.19869985, -0.20190603, -0.20511003, + -0.20831184, -0.21151142, -0.21470875, -0.21790376, -0.22109644, -0.22428675, -0.22747467, -0.23066014, + -0.23384315, -0.23702365, -0.24020162, -0.24337701, -0.2465498, -0.24971995, -0.2528874, -0.25605217, + -0.25921419, -0.26237345, -0.26552987, -0.26868346, -0.27183419, -0.27498198, -0.27812684, -0.28126872, + -0.28440759, -0.28754342, -0.29067615, -0.29380578, -0.29693225, -0.30005556, -0.30317566, -0.3062925, + -0.30940607, -0.3125163, -0.31562322, -0.31872672, -0.32182685, -0.32492352, -0.3280167, -0.33110636, + -0.33419248, -0.33727503, -0.34035397, -0.34342924, -0.34650084, -0.34956875, -0.35263291, -0.35569328, + -0.35874987, -0.36180258, -0.36485144, -0.36789638, -0.37093741, -0.37397444, -0.37700745, -0.38003644, + -0.38306138, -0.3860822, -0.38909888, -0.39211139, -0.39511973, -0.3981238, -0.40112361, -0.40411916, + -0.40711036, -0.41009718, -0.41307965, -0.41605768, -0.41903123, -0.42200032, -0.42496487, -0.4279249, + -0.43088034, -0.43383113, -0.43677729, -0.43971881, -0.44265559, -0.44558764, -0.44851488, -0.45143735, + -0.454355, -0.45726776, -0.46017563, -0.46307856, -0.46597654, -0.46886954, -0.4717575, -0.47464043, + -0.47751826, -0.480391, -0.48325855, -0.48612097, -0.48897815, -0.49183011, -0.4946768, -0.49751821, + -0.50035429, -0.50318497, -0.50601029, -0.50883019, -0.51164466, -0.51445359, -0.51725709, -0.520055, + -0.52284735, -0.52563411, -0.5284152, -0.53119069, -0.53396046, -0.53672451, -0.53948283, -0.54223537, + -0.54498214, -0.547723, -0.55045801, -0.55318713, -0.55591035, -0.55862761, -0.5613389, -0.56404412, + -0.56674337, -0.56943649, -0.57212353, -0.57480448, -0.57747924, -0.5801478, -0.58281022, -0.58546633, + -0.58811617, -0.59075975, -0.59339696, -0.59602785, -0.59865236, -0.60127044, -0.60388207, -0.60648727, + -0.60908598, -0.61167812, -0.61426371, -0.61684275, -0.61941516, -0.62198097, -0.62454009, -0.62709254, + -0.62963831, -0.63217729, -0.63470948, -0.63723493, -0.63975352, -0.64226526, -0.64477009, -0.64726806, + -0.64975911, -0.65224314, -0.65472025, -0.65719032, -0.65965337, -0.66210932, -0.66455823, -0.667, + -0.66943461, -0.67186207, -0.67428231, -0.67669535, -0.67910111, -0.68149966, -0.68389088, -0.68627477, + -0.68865126, -0.69102043, -0.6933822, -0.69573659, -0.69808346, -0.70042288, -0.7027548, -0.7050792, + -0.70739603, -0.70970529, -0.71200693, -0.71430099, -0.71658736, -0.71886611, -0.72113711, -0.72340041, + -0.72565591, -0.72790372, -0.73014367, -0.73237586, -0.73460019, -0.73681659, -0.73902518, -0.74122584, + -0.74341851, -0.74560326, -0.74778003, -0.7499488, -0.75210953, -0.75426215, -0.75640678, -0.75854325, + -0.76067162, -0.76279181, -0.7649039, -0.76700771, -0.76910341, -0.77119076, -0.77326995, -0.7753408, + -0.77740335, -0.77945763, -0.7815035, -0.78354102, -0.78557014, -0.78759086, -0.78960317, -0.79160696, + -0.79360235, -0.79558921, -0.79756755, -0.7995373, -0.80149853, -0.80345118, -0.80539525, -0.80733067, + -0.80925739, -0.81117553, -0.8130849, -0.81498563, -0.8168776, -0.81876087, -0.82063532, -0.822501, + -0.82435787, -0.82620591, -0.82804507, -0.82987541, -0.83169687, -0.83350939, -0.83531296, -0.83710766, + -0.83889335, -0.84067005, -0.84243774, -0.84419644, -0.84594607, -0.84768665, -0.84941816, -0.85114056, + -0.85285389, -0.85455805, -0.85625303, -0.85793889, -0.8596155, -0.86128294, -0.86294121, -0.86459017, + -0.86622989, -0.86786032, -0.8694815, -0.87109333, -0.87269586, -0.87428904, -0.87587279, -0.87744725, + -0.87901229, -0.88056785, -0.88211405, -0.88365078, -0.88517809, -0.88669586, -0.88820416, -0.88970292, + -0.8911922, -0.89267188, -0.89414203, -0.89560264, -0.8970536, -0.89849502, -0.89992678, -0.90134889, + -0.90276134, -0.90416414, -0.90555727, -0.9069407, -0.90831441, -0.90967834, -0.91103262, -0.91237706, + -0.91371179, -0.91503674, -0.91635185, -0.91765714, -0.91895264, -0.92023826, -0.92151409, -0.92277998, + -0.92403603, -0.92528218, -0.92651838, -0.92774469, -0.9289611, -0.9301675, -0.931364, -0.93255049, + -0.93372697, -0.93489349, -0.93604994, -0.93719643, -0.93833286, -0.93945926, -0.9405756, -0.9416818, + -0.94277799, -0.94386405, -0.94494003, -0.94600588, -0.94706154, -0.94810712, -0.94914252, -0.95016778, + -0.95118284, -0.95218778, -0.95318246, -0.95416695, -0.95514119, -0.95610523, -0.95705903, -0.95800257, + -0.95893586, -0.95985889, -0.96077162, -0.96167403, -0.9625662, -0.96344805, -0.96431959, -0.96518075, + -0.96603161, -0.96687216, -0.96770233, -0.96852213, -0.96933156, -0.97013056, -0.97091925, -0.97169751, + -0.97246534, -0.97322279, -0.97396982, -0.97470641, -0.97543252, -0.97614825, -0.97685349, -0.97754824, + -0.97823256, -0.97890645, -0.97956979, -0.98022264, -0.980865, -0.98149687, -0.98211825, -0.98272908, + -0.98332942, -0.98391914, -0.98449844, -0.98506713, -0.98562527, -0.98617285, -0.98670989, -0.98723638, + -0.98775226, -0.98825759, -0.98875231, -0.98923647, -0.98971003, -0.99017298, -0.99062532, -0.99106705, + -0.99149817, -0.99191868, -0.99232858, -0.99272782, -0.99311644, -0.99349445, -0.99386179, -0.99421853, + -0.99456459, -0.99489999, -0.99522477, -0.99553883, -0.99584228, -0.99613506, -0.99641716, -0.9966886, + -0.99694937, -0.99719942, -0.99743885, -0.99766755, -0.99788558, -0.99809295, -0.99828959, -0.99847561, + -0.99865085, -0.99881548, -0.99896932, -0.99911255, -0.99924499, -0.99936682, -0.99947786, -0.9995783, + -0.99966794, -0.99974692, -0.99981517, -0.99987274, -0.99991959, -0.99995571, -0.99998116, -0.99999589, + 0.99999964, 0.99997288, 0.99990326, 0.99979085, 0.99963558, 0.99943751, 0.99919659, 0.99891287, + 0.99858636, 0.99821711, 0.99780506, 0.99735034, 0.99685282, 0.99631262, 0.99572974, 0.99510419, + 0.99443603, 0.9937253, 0.99297196, 0.99217612, 0.99133772, 0.99045694, 0.98953366, 0.98856801, + 0.98756003, 0.98650974, 0.98541719, 0.98428243, 0.98310548, 0.98188645, 0.98062533, 0.97932225, + 0.97797716, 0.97659022, 0.97516143, 0.97369087, 0.97217858, 0.97062469, 0.96902919, 0.96739221, + 0.96571374, 0.96399397, 0.96223283, 0.9604305, 0.95858705, 0.95670253, 0.954777, 0.95281059, + 0.9508034, 0.94875544, 0.94666684, 0.9445377, 0.94236809, 0.94015813, 0.93790787, 0.93561745, + 0.93328691, 0.93091643, 0.92850608, 0.92605597, 0.92356616, 0.92103678, 0.91846794, 0.91585976, + 0.91321236, 0.91052586, 0.90780038, 0.90503591, 0.90223277, 0.89939094, 0.8965106, 0.89359182, + 0.89063478, 0.88763964, 0.88460642, 0.88153529, 0.87842643, 0.87527996, 0.87209594, 0.86887461, + 0.86561602, 0.86232042, 0.85898781, 0.85561842, 0.85221243, 0.84876984, 0.84529096, 0.84177583, + 0.83822471, 0.83463764, 0.83101481, 0.8273564, 0.82366252, 0.81993335, 0.81616908, 0.81236988, + 0.80853581, 0.80466717, 0.80076402, 0.7968266, 0.79285502, 0.78884947, 0.78481019, 0.78073722, + 0.77663082, 0.77249116, 0.76831841, 0.76411277, 0.75987434, 0.75560343, 0.7513001, 0.74696463, + 0.7425971, 0.7381978, 0.73376691, 0.72930455, 0.72481096, 0.72028631, 0.71573079, 0.71114463, + 0.70652801, 0.70188117, 0.69720417, 0.69249737, 0.68776089, 0.68299496, 0.67819971, 0.67337549, + 0.66852236, 0.66364062, 0.65873051, 0.65379208, 0.64882571, 0.64383155, 0.63880974, 0.63376063, + 0.62868434, 0.62358117, 0.61845124, 0.61329484, 0.60811216, 0.60290343, 0.59766883, 0.59240872, + 0.58712316, 0.5818125, 0.57647687, 0.57111657, 0.56573176, 0.56032276, 0.5548898, 0.54943299, + 0.5439527, 0.53844911, 0.53292239, 0.5273729, 0.52180082, 0.51620632, 0.51058978, 0.50495136, + 0.4992913, 0.49360985, 0.48790723, 0.48218375, 0.4764396, 0.47067502, 0.4648903, 0.45908567, + 0.45326138, 0.44741765, 0.44155475, 0.43567297, 0.4297725, 0.42385364, 0.4179166, 0.41196167, + 0.40598908, 0.39999911, 0.39399201, 0.38796803, 0.38192743, 0.37587047, 0.36979741, 0.3637085, + 0.35760403, 0.35148421, 0.34534934, 0.33919969, 0.33303553, 0.32685706, 0.32066461, 0.31445843, + 0.30823877, 0.30200592, 0.29576012, 0.28950164, 0.28323078, 0.2769478, 0.27065292, 0.26434645, + 0.25802869, 0.25169984, 0.24536023, 0.2390101, 0.23264973, 0.22627939, 0.21989937, 0.21350993, + 0.20711134, 0.20070387, 0.19428782, 0.18786344, 0.18143101, 0.1749908, 0.1685431, 0.16208819, + 0.15562633, 0.14915779, 0.14268288, 0.13620184, 0.12971498, 0.12322257, 0.11672486, 0.11022217, + 0.10371475, 0.097202882, 0.090686858, 0.084166944, 0.077643424, 0.071116582, 0.064586692, 0.058054037, + 0.051518895, 0.044981543, 0.038442269, 0.031901345, 0.025359053, 0.018815678, 0.012271495, 0.0057267868, + -0.00081816671, -0.0073630852, -0.013907688, -0.020451695, -0.026994826, -0.033536803, -0.04007734, -0.046616159, + -0.053152986, -0.059687532, -0.066219524, -0.072748676, -0.079274714, -0.085797355, -0.092316322, -0.098831341, + -0.10534211, -0.11184838, -0.11834986, -0.12484626, -0.13133731, -0.13782275, -0.14430228, -0.15077563, + -0.15724251, -0.16370267, -0.17015581, -0.17660165, -0.18303993, -0.18947038, -0.19589271, -0.20230664, + -0.20871192, -0.21510825, -0.22149536, -0.22787298, -0.23424086, -0.24059868, -0.24694622, -0.25328314, + -0.25960925, -0.26592422, -0.27222782, -0.27851975, -0.28479972, -0.29106751, -0.29732284, -0.30356544, + -0.30979502, -0.31601134, -0.32221413, -0.32840309, -0.33457801, -0.34073856, -0.34688455, -0.35301566, + -0.35913166, -0.36523229, -0.37131724, -0.3773863, -0.38343921, -0.38947567, -0.39549544, -0.40149832, + -0.40748394, -0.41345215, -0.41940263, -0.42533514, -0.43124944, -0.43714526, -0.44302234, -0.44888046, + -0.45471936, -0.46053877, -0.46633846, -0.47211814, -0.47787762, -0.48361665, -0.48933494, -0.49503228, + -0.5007084, -0.50636309, -0.51199609, -0.51760709, -0.52319598, -0.52876246, -0.53430629, -0.53982723, + -0.54532504, -0.55079949, -0.55625033, -0.5616774, -0.56708032, -0.57245898, -0.57781315, -0.58314258, + -0.58844697, -0.59372622, -0.59897995, -0.60420811, -0.60941035, -0.61458647, -0.61973625, -0.62485951, + -0.62995601, -0.63502556, -0.64006782, -0.64508271, -0.65007001, -0.65502942, -0.65996075, -0.66486382, + -0.66973841, -0.67458433, -0.67940134, -0.68418926, -0.68894786, -0.69367695, -0.6983763, -0.70304573, + -0.70768511, -0.7122941, -0.71687263, -0.72142041, -0.72593731, -0.73042315, -0.73487765, -0.73930067, + -0.74369204, -0.74805158, -0.752379, -0.75667429, -0.76093709, -0.7651673, -0.76936477, -0.77352923, + -0.77766061, -0.78175867, -0.78582323, -0.78985411, -0.79385114, -0.79781419, -0.80174309, -0.8056376, + -0.80949765, -0.81332302, -0.81711352, -0.82086903, -0.82458937, -0.82827437, -0.8319239, -0.83553779, + -0.83911592, -0.84265804, -0.84616417, -0.84963393, -0.8530674, -0.85646427, -0.85982448, -0.8631478, + -0.86643422, -0.8696835, -0.87289548, -0.87607014, -0.87920725, -0.88230664, -0.88536829, -0.88839203, + -0.89137769, -0.89432514, -0.89723432, -0.90010506, -0.90293723, -0.90573072, -0.90848541, -0.91120118, + -0.91387796, -0.91651553, -0.91911387, -0.92167282, -0.92419231, -0.92667222, -0.92911243, -0.93151283, + -0.93387336, -0.93619382, -0.93847424, -0.94071442, -0.94291431, -0.94507378, -0.94719279, -0.94927126, + -0.95130903, -0.95330608, -0.95526224, -0.95717752, -0.95905179, -0.96088499, -0.962677, -0.96442777, + -0.96613729, -0.96780539, -0.969432, -0.97101706, -0.97256058, -0.97406244, -0.97552258, -0.97694093, + -0.97831738, -0.97965199, -0.98094457, -0.98219514, -0.98340368, -0.98457009, -0.98569429, -0.98677629, + -0.98781598, -0.9888134, -0.98976845, -0.99068111, -0.99155134, -0.99237907, -0.9931643, -0.99390697, + -0.99460709, -0.99526459, -0.99587947, -0.99645168, -0.9969812, -0.99746799, -0.99791211, -0.99831343, + -0.99867201, -0.99898779, -0.99926084, -0.99949104, -0.99967843, -0.99982297, -0.99992472, -0.99998361, + 0.99999869, 0.99989158, 0.99961317, 0.99916345, 0.99854255, 0.99775058, 0.99678761, 0.99565387, + 0.99434954, 0.9928748, 0.99122995, 0.98941529, 0.98743105, 0.98527765, 0.9829554, 0.98046476, + 0.97780609, 0.97497988, 0.97198665, 0.96882683, 0.96550101, 0.96200979, 0.95835376, 0.95453346, + 0.9505496, 0.94640291, 0.94209403, 0.93762374, 0.93299282, 0.92820197, 0.92325211, 0.91814411, + 0.91287869, 0.90745693, 0.90187967, 0.89614785, 0.89026248, 0.88422459, 0.87803519, 0.87169534, + 0.86520612, 0.85856867, 0.85178405, 0.84485358, 0.83777827, 0.83055943, 0.82319832, 0.81569612, + 0.80805415, 0.80027372, 0.79235619, 0.78430289, 0.77611518, 0.76779449, 0.75934225, 0.75075996, + 0.74204898, 0.7332108, 0.7242471, 0.71515924, 0.70594883, 0.69661748, 0.68716675, 0.6775983, + 0.66791373, 0.65811473, 0.64820296, 0.63818014, 0.62804794, 0.6178081, 0.60746247, 0.59701276, + 0.58646071, 0.57580817, 0.56505698, 0.55420899, 0.543266, 0.53222996, 0.52110273, 0.50988621, + 0.49858227, 0.48719296, 0.47572014, 0.46416581, 0.45253196, 0.44082057, 0.42903364, 0.41717321, + 0.40524128, 0.39323992, 0.3811712, 0.36903715, 0.35683987, 0.34458145, 0.33226398, 0.31988961, + 0.3074604, 0.2949785, 0.28244606, 0.26986524, 0.25723818, 0.24456702, 0.23185398, 0.21910121, + 0.20631088, 0.19348522, 0.18062639, 0.16773662, 0.15481812, 0.14187308, 0.12890373, 0.1159123, + 0.102901, 0.089872077, 0.07682775, 0.063770257, 0.050701842, 0.037624735, 0.024541186, 0.011453429, + -0.0016362892, -0.014725727, -0.027812643, -0.040894791, -0.053969935, -0.067035832, -0.08009024, -0.093130924, + -0.10615565, -0.11916219, -0.13214831, -0.14511178, -0.1580504, -0.17096193, -0.18384418, -0.19669491, + -0.20951195, -0.22229309, -0.23503613, -0.24773891, -0.26039925, -0.27301496, -0.28558388, -0.29810387, + -0.3105728, -0.32298848, -0.33534884, -0.34765175, -0.35989508, -0.37207675, -0.38419467, -0.39624676, + -0.40823093, -0.42014518, -0.43198743, -0.44375566, -0.45544785, -0.467062, -0.47859612, -0.49004826, + -0.50141639, -0.51269865, -0.52389306, -0.53499764, -0.54601061, -0.55693001, -0.56775403, -0.57848072, + -0.58910829, -0.59963489, -0.61005878, -0.62037814, -0.63059121, -0.64069623, -0.65069145, -0.66057515, + -0.67034572, -0.68000144, -0.68954057, -0.69896162, -0.70826286, -0.71744281, -0.72649974, -0.73543227, + -0.74423873, -0.75291771, -0.76146764, -0.76988715, -0.7781747, -0.78632891, -0.79434842, -0.80223179, + -0.80997771, -0.81758487, -0.8250519, -0.83237761, -0.83956063, -0.84659988, -0.85349399, -0.86024189, + -0.86684239, -0.87329435, -0.87959671, -0.88574833, -0.89174819, -0.89759529, -0.90328854, -0.90882701, + -0.91420978, -0.91943592, -0.92450452, -0.92941469, -0.9341656, -0.93875647, -0.94318646, -0.94745487, + -0.95156091, -0.95550388, -0.95928317, -0.96289814, -0.96634805, -0.96963239, -0.9727506, -0.97570217, + -0.97848648, -0.98110318, -0.9835518, -0.98583186, -0.98794299, -0.98988485, -0.99165714, -0.99325943, + -0.99469161, -0.99595332, -0.99704438, -0.99796462, -0.99871385, -0.99929196, -0.99969882, -0.99993443, + 0.99999464, 0.99956632, 0.9984529, 0.99665523, 0.99417448, 0.99101239, 0.98717111, 0.98265326, + 0.97746199, 0.97160077, 0.96507365, 0.95788515, 0.95004016, 0.94154406, 0.93240267, 0.92262226, + 0.91220951, 0.90117162, 0.88951606, 0.87725091, 0.86438453, 0.85092574, 0.83688372, 0.82226819, + 0.80708915, 0.79135692, 0.77508235, 0.75827658, 0.74095112, 0.72311783, 0.70478898, 0.6859771, + 0.66669506, 0.64695615, 0.62677377, 0.60616189, 0.58513457, 0.56370622, 0.54189157, 0.51970547, + 0.49716324, 0.47428027, 0.45107225, 0.42755505, 0.40374488, 0.37965798, 0.35531086, 0.33072025, + 0.30590299, 0.28087607, 0.25565663, 0.23026201, 0.20470956, 0.17901683, 0.15320139, 0.12728097, + 0.10127331, 0.075196236, 0.049067631, 0.0229054, -0.0032725304, -0.029448219, -0.055603724, -0.08172112, + -0.10778251, -0.13377003, -0.15966587, -0.18545228, -0.21111161, -0.23662624, -0.26197869, -0.2871516, + -0.31212771, -0.33688989, -0.3614212, -0.38570482, -0.40972409, -0.43346253, -0.45690393, -0.48003218, + -0.50283146, -0.52528608, -0.54738069, -0.5691002, -0.59042966, -0.61135447, -0.63186026, -0.65193301, + -0.67155898, -0.69072473, -0.70941705, -0.72762316, -0.74533063, -0.76252723, -0.77920127, -0.79534131, + -0.81093621, -0.82597536, -0.84044844, -0.8543455, -0.86765707, -0.88037395, -0.89248747, -0.90398932, + -0.91487163, -0.92512697, -0.93474823, -0.94372886, -0.95206273, -0.95974404, -0.96676767, -0.97312868, + -0.97882277, -0.98384601, -0.988195, -0.99186671, -0.99485862, -0.99716878, -0.99879545, -0.99973762, +]; + +# Of each LM, inter then intra, each band's chance of no change and its decay. +const e_prob_model: u8[336] = [ + 72, 127, 65, 129, 66, 128, 65, 128, 64, 128, 62, 128, 64, 128, + 64, 128, 92, 78, 92, 79, 92, 78, 90, 79, 116, 41, 115, 40, + 114, 40, 132, 26, 132, 26, 145, 17, 161, 12, 176, 10, 177, 11, + 24, 179, 48, 138, 54, 135, 54, 132, 53, 134, 56, 133, 55, 132, + 55, 132, 61, 114, 70, 96, 74, 88, 75, 88, 87, 74, 89, 66, + 91, 67, 100, 59, 108, 50, 120, 40, 122, 37, 97, 43, 78, 50, + 83, 78, 84, 81, 88, 75, 86, 74, 87, 71, 90, 73, 93, 74, + 93, 74, 109, 40, 114, 36, 117, 34, 117, 34, 143, 17, 145, 18, + 146, 19, 162, 12, 165, 10, 178, 7, 189, 6, 190, 8, 177, 9, + 23, 178, 54, 115, 63, 102, 66, 98, 69, 99, 74, 89, 71, 91, + 73, 91, 78, 89, 86, 80, 92, 66, 93, 64, 102, 59, 103, 60, + 104, 60, 117, 52, 123, 44, 138, 35, 133, 31, 97, 38, 77, 45, + 61, 90, 93, 60, 105, 42, 107, 41, 110, 45, 116, 38, 113, 38, + 112, 38, 124, 26, 132, 27, 136, 19, 140, 20, 155, 14, 159, 16, + 158, 18, 170, 13, 177, 10, 187, 8, 192, 6, 175, 9, 159, 10, + 21, 178, 59, 110, 71, 86, 75, 85, 84, 83, 91, 66, 88, 73, + 87, 72, 92, 75, 98, 72, 105, 58, 107, 54, 115, 52, 114, 55, + 112, 56, 129, 51, 132, 40, 150, 33, 140, 29, 98, 35, 77, 42, + 42, 121, 96, 66, 108, 43, 111, 40, 117, 44, 123, 32, 120, 36, + 119, 33, 127, 33, 134, 34, 139, 21, 147, 23, 152, 20, 158, 25, + 154, 26, 166, 21, 173, 16, 184, 13, 184, 10, 150, 13, 139, 15, + 22, 178, 63, 114, 74, 82, 84, 83, 92, 82, 103, 62, 96, 72, + 96, 67, 101, 73, 107, 72, 113, 55, 118, 52, 125, 52, 118, 52, + 117, 55, 135, 49, 137, 39, 157, 32, 145, 29, 97, 33, 77, 40, +]; + +# Each band's mean energy, in log2. +const e_means: f32[25] = [ + 6.4375, 6.25, 5.75, 5.3125, 5.0625, 4.8125, 4.5, 4.375, + 4.875, 4.6875, 4.5625, 4.4375, 4.875, 4.625, 4.3125, 4.5, + 4.375, 4.625, 4.75, 4.4375, 3.75, 3.75, 3.75, 3.75, + 3.75, +]; + +# U(N, K), the counts of pulse vectors, by rows, as `pvq_u_rows` says where. +const pvq_u_data: u32[1272] = [ + 1, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 3, 5, 7, 9, 11, 13, 15, + 17, 19, 21, 23, 25, 27, 29, 31, + 33, 35, 37, 39, 41, 43, 45, 47, + 49, 51, 53, 55, 57, 59, 61, 63, + 65, 67, 69, 71, 73, 75, 77, 79, + 81, 83, 85, 87, 89, 91, 93, 95, + 97, 99, 101, 103, 105, 107, 109, 111, + 113, 115, 117, 119, 121, 123, 125, 127, + 129, 131, 133, 135, 137, 139, 141, 143, + 145, 147, 149, 151, 153, 155, 157, 159, + 161, 163, 165, 167, 169, 171, 173, 175, + 177, 179, 181, 183, 185, 187, 189, 191, + 193, 195, 197, 199, 201, 203, 205, 207, + 209, 211, 213, 215, 217, 219, 221, 223, + 225, 227, 229, 231, 233, 235, 237, 239, + 241, 243, 245, 247, 249, 251, 253, 255, + 257, 259, 261, 263, 265, 267, 269, 271, + 273, 275, 277, 279, 281, 283, 285, 287, + 289, 291, 293, 295, 297, 299, 301, 303, + 305, 307, 309, 311, 313, 315, 317, 319, + 321, 323, 325, 327, 329, 331, 333, 335, + 337, 339, 341, 343, 345, 347, 349, 351, + 13, 25, 41, 61, 85, 113, 145, 181, + 221, 265, 313, 365, 421, 481, 545, 613, + 685, 761, 841, 925, 1013, 1105, 1201, 1301, + 1405, 1513, 1625, 1741, 1861, 1985, 2113, 2245, + 2381, 2521, 2665, 2813, 2965, 3121, 3281, 3445, + 3613, 3785, 3961, 4141, 4325, 4513, 4705, 4901, + 5101, 5305, 5513, 5725, 5941, 6161, 6385, 6613, + 6845, 7081, 7321, 7565, 7813, 8065, 8321, 8581, + 8845, 9113, 9385, 9661, 9941, 10225, 10513, 10805, + 11101, 11401, 11705, 12013, 12325, 12641, 12961, 13285, + 13613, 13945, 14281, 14621, 14965, 15313, 15665, 16021, + 16381, 16745, 17113, 17485, 17861, 18241, 18625, 19013, + 19405, 19801, 20201, 20605, 21013, 21425, 21841, 22261, + 22685, 23113, 23545, 23981, 24421, 24865, 25313, 25765, + 26221, 26681, 27145, 27613, 28085, 28561, 29041, 29525, + 30013, 30505, 31001, 31501, 32005, 32513, 33025, 33541, + 34061, 34585, 35113, 35645, 36181, 36721, 37265, 37813, + 38365, 38921, 39481, 40045, 40613, 41185, 41761, 42341, + 42925, 43513, 44105, 44701, 45301, 45905, 46513, 47125, + 47741, 48361, 48985, 49613, 50245, 50881, 51521, 52165, + 52813, 53465, 54121, 54781, 55445, 56113, 56785, 57461, + 58141, 58825, 59513, 60205, 60901, 61601, 63, 129, + 231, 377, 575, 833, 1159, 1561, 2047, 2625, + 3303, 4089, 4991, 6017, 7175, 8473, 9919, 11521, + 13287, 15225, 17343, 19649, 22151, 24857, 27775, 30913, + 34279, 37881, 41727, 45825, 50183, 54809, 59711, 64897, + 70375, 76153, 82239, 88641, 95367, 102425, 109823, 117569, + 125671, 134137, 142975, 152193, 161799, 171801, 182207, 193025, + 204263, 215929, 228031, 240577, 253575, 267033, 280959, 295361, + 310247, 325625, 341503, 357889, 374791, 392217, 410175, 428673, + 447719, 467321, 487487, 508225, 529543, 551449, 573951, 597057, + 620775, 645113, 670079, 695681, 721927, 748825, 776383, 804609, + 833511, 863097, 893375, 924353, 956039, 988441, 1021567, 1055425, + 1090023, 1125369, 1161471, 1198337, 1235975, 1274393, 1313599, 1353601, + 1394407, 1436025, 1478463, 1521729, 1565831, 1610777, 1656575, 1703233, + 1750759, 1799161, 1848447, 1898625, 1949703, 2001689, 2054591, 2108417, + 2163175, 2218873, 2275519, 2333121, 2391687, 2451225, 2511743, 2573249, + 2635751, 2699257, 2763775, 2829313, 2895879, 2963481, 3032127, 3101825, + 3172583, 3244409, 3317311, 3391297, 3466375, 3542553, 3619839, 3698241, + 3777767, 3858425, 3940223, 4023169, 4107271, 4192537, 4278975, 4366593, + 4455399, 4545401, 4636607, 4729025, 4822663, 4917529, 5013631, 5110977, + 5209575, 5309433, 5410559, 5512961, 5616647, 5721625, 5827903, 5935489, + 6044391, 6154617, 6266175, 6379073, 6493319, 6608921, 6725887, 6844225, + 6963943, 7085049, 7207551, 321, 681, 1289, 2241, 3649, + 5641, 8361, 11969, 16641, 22569, 29961, 39041, 50049, + 63241, 78889, 97281, 118721, 143529, 172041, 204609, 241601, + 283401, 330409, 383041, 441729, 506921, 579081, 658689, 746241, + 842249, 947241, 1061761, 1186369, 1321641, 1468169, 1626561, 1797441, + 1981449, 2179241, 2391489, 2618881, 2862121, 3121929, 3399041, 3694209, + 4008201, 4341801, 4695809, 5071041, 5468329, 5888521, 6332481, 6801089, + 7295241, 7815849, 8363841, 8940161, 9545769, 10181641, 10848769, 11548161, + 12280841, 13047849, 13850241, 14689089, 15565481, 16480521, 17435329, 18431041, + 19468809, 20549801, 21675201, 22846209, 24064041, 25329929, 26645121, 28010881, + 29428489, 30899241, 32424449, 34005441, 35643561, 37340169, 39096641, 40914369, + 42794761, 44739241, 46749249, 48826241, 50971689, 53187081, 55473921, 57833729, + 60268041, 62778409, 65366401, 68033601, 70781609, 73612041, 76526529, 79526721, + 82614281, 85790889, 89058241, 92418049, 95872041, 99421961, 103069569, 106816641, + 110664969, 114616361, 118672641, 122835649, 127107241, 131489289, 135983681, 140592321, + 145317129, 150160041, 155123009, 160208001, 165417001, 170752009, 176215041, 181808129, + 187533321, 193392681, 199388289, 205522241, 211796649, 218213641, 224775361, 231483969, + 238341641, 245350569, 252512961, 259831041, 267307049, 274943241, 282741889, 290705281, + 298835721, 307135529, 315607041, 324252609, 333074601, 342075401, 351257409, 360623041, + 370174729, 379914921, 389846081, 399970689, 410291241, 420810249, 431530241, 442453761, + 453583369, 464921641, 476471169, 488234561, 500214441, 512413449, 524834241, 537479489, + 550351881, 563454121, 576788929, 590359041, 604167209, 618216201, 632508801, 1683, + 3653, 7183, 13073, 22363, 36365, 56695, 85305, 124515, + 177045, 246047, 335137, 448427, 590557, 766727, 982729, 1244979, + 1560549, 1937199, 2383409, 2908411, 3522221, 4235671, 5060441, 6009091, + 7095093, 8332863, 9737793, 11326283, 13115773, 15124775, 17372905, 19880915, + 22670725, 25765455, 29189457, 32968347, 37129037, 41699767, 46710137, 52191139, + 58175189, 64696159, 71789409, 79491819, 87841821, 96879431, 106646281, 117185651, + 128542501, 140763503, 153897073, 167993403, 183104493, 199284183, 216588185, 235074115, + 254801525, 275831935, 298228865, 322057867, 347386557, 374284647, 402823977, 433078547, + 465124549, 499040399, 534906769, 572806619, 612825229, 655050231, 699571641, 746481891, + 795875861, 847850911, 902506913, 959946283, 1020274013, 1083597703, 1150027593, 1219676595, + 1292660325, 1369097135, 1449108145, 1532817275, 1620351277, 1711839767, 1807415257, 1907213187, + 2011371957, 2120032959, 8989, 19825, 40081, 75517, 134245, 227305, + 369305, 579125, 880685, 1303777, 1884961, 2668525, 3707509, 5064793, + 6814249, 9041957, 11847485, 15345233, 19665841, 24957661, 31388293, 39146185, + 48442297, 59511829, 72616013, 88043969, 106114625, 127178701, 151620757, 179861305, + 212358985, 249612805, 292164445, 340600625, 395555537, 457713341, 527810725, 606639529, + 695049433, 793950709, 904317037, 1027188385, 1163673953, 1314955181, 1482288821, 1667010073, + 1870535785, 2094367717, 48639, 108545, 224143, 433905, 795455, 1392065, + 2340495, 3800305, 5984767, 9173505, 13726991, 20103025, 28875327, 40754369, + 56610575, 77500017, 104692735, 139703809, 184327311, 240673265, 311207743, 398796225, + 506750351, 638878193, 799538175, 993696769, 1226990095, 1505789553, 1837271615, 2229491905, + 265729, 598417, 1256465, 2485825, 4673345, 8405905, 14546705, 24331777, + 39490049, 62390545, 96220561, 145198913, 214828609, 312193553, 446304145, 628496897, + 872893441, 1196924561, 1621925137, 2173806145, 1462563, 3317445, 7059735, 14218905, + 27298155, 50250765, 89129247, 152951073, 254831667, 413442773, 654862247, 1014889769, + 1541911931, 2300409629, 3375210671, 8097453, 18474633, 39753273, 81270333, 158819253, + 298199265, 540279585, 948062325, 1616336765, 45046719, 103274625, 224298231, 464387817, + 921406335, 1759885185, 3248227095, 251595969, 579168825, 1267854873, 2653649025, 1409933619, +]; diff --git a/audio/opus/opus.sakura b/audio/opus/opus.sakura new file mode 100644 index 0000000..62fb240 --- /dev/null +++ b/audio/opus/opus.sakura @@ -0,0 +1,687 @@ +#! Contains `decoder`, which reads an Ogg Opus stream's frames as it's asked +#! for them, so a long one plays without being held decoded, and `decode`, which +#! reads one whole. +#! +#! Opus is decoded as RFC 6716 has it and libopus's float build decodes it, +#! whose decoder this is a port of: each packet's frames are SILK's, of speech, +#! CELT's, of music, or hybrid, of both, SILK's below 8 kHz and CELT's above, +#! and a stream moves between them as it goes, with CELT's redundant frames, or +#! a crossfade, smoothing each change. Everything is decoded at 48 kHz, SILK +#! resampled up from its own rate. A stream of one or two channels, of channel +#! mapping family 0, is read; streams of more aren't. Its pre-skip is cut from +#! its start and its end cut where its last page's granule position says, as +#! RFC 7845 has it, its output gain applied, and its comments read for where +#! it loops, as `audio::loop_of_comments` reads them. A stream is sought by +#! halving its pages, then decoding from half a second before where it's +#! sought, more than the 80 ms Opus asks, so its decoder settles to within a +#! few ten-thousandths of decoding straight through, if not exactly. +#! +#! A lost or empty frame is decoded as silence, rather than concealed as +#! libopus does. + +# libopus, which this decoder is a port of, is: +# +# Copyright 2001-2023 Xiph.Org, Skype Limited, Octasic, +# Jean-Marc Valin, Timothy B. Terriberry, +# CSIRO, Gregory Maxwell, Mark Borgerding, +# Erik de Castro Lopo, Mozilla, Amazon +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# +# - Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# - Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# +# - Neither the name of Internet Society, IETF or IETF Trust, nor the +# names of specific contributors, may be used to endorse or promote +# products derived from this software without specific prior written +# permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER +# OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +import std::math; +import malunal::audio::ogg; +module malunal::audio::opus; + + +# Each frame's mode. +const mode_silk: i32 = 1000; +const mode_hybrid: i32 = 1001; +const mode_celt: i32 = 1002; + +# Each frame's bandwidth: narrow, medium, wide, super-wide, and full. +const band_nb: i32 = 1101; +const band_mb: i32 = 1102; +const band_wb: i32 = 1103; +const band_swb: i32 = 1104; +const band_fb: i32 = 1105; + +# The frames of 20, 10, 5, and 2.5 ms, at 48 kHz. +const f20: i32 = 960; +const f10: i32 = 480; +const f5: i32 = 240; +const f2_5: i32 = 120; + +# The frames decoded before a frame sought, so the decoder settles: half a +# second, as CELT's energies, predicted from the frame before, halve their +# error a frame of 20 ms, and those of 2.5 ms a tenth. +const preroll: u64 = 24000; + +# The most frames a packet decodes to: 120 ms. +const most_packet_frames: u64 = 5760; + +# What decoding frames keeps between them: libopus's `OpusDecoder`. +struct frames_state { + var channels: i32; + var celt: celt_decoder; + var silk: silk_decoder; + var stream_channels: i32; # Of the packet being decoded. + var mode: i32; + var prev_mode: i32; # 0 before any frame. + var bandwidth: i32; + var frame_size: i32; + var prev_redundancy: bool; + var gain: f32; # The stream's output gain, as a multiple. + var silk_pcm: vector; + var transition: vector; + var redundant: vector; +} + +def frames_state::new(channels: i32, gain_q8: i32): frames_state { + var made := frames_state{ + channels = channels, celt = celt_decoder::new(channels), silk = silk_decoder::new(), + silk_pcm = vector::::new(), transition = vector::::new(), redundant = vector::::new(), gain = 1, + }; + if gain_q8 != 0 { + made.gain = math::exp(0.6931471805599453094 * (6.48814081e-4 as f32 * gain_q8 as f32) as f64) as f32; + } + made.silk_pcm.resize(most_packet_frames * 2); + made.transition.resize((f5 * 2) as u64); + made.redundant.resize((f5 * 2) as u64); + made.reset(); + return made; +} + +# Forgets every frame before. +def frames_state::reset(&mut this): void { + this.celt.reset(); + this.silk.reset(); + this.stream_channels = this.channels; + this.mode = 0; + this.prev_mode = 0; + this.bandwidth = 0; + this.frame_size = 120; + this.prev_redundancy = false; +} + +# The frames of a packet, as its first byte, its table of contents, says. +def samples_per_frame(toc: u8): i32 { + if (toc & 0x80) != 0 { + return (48000 << ((toc >> 3) & 3) as u32) / 400; + } + if (toc & 0x60) == 0x60 { + return (toc & 0x08) != 0 ? 960 : 480; + } + val size := ((toc >> 3) & 3) as i32; + return size == 3 ? 2880 : (48000 << size as u32) / 100; +} + +def mode_of(toc: u8): i32 { + return (toc & 0x80) != 0 ? mode_celt : (toc & 0x60) == 0x60 ? mode_hybrid : mode_silk; +} + +def bandwidth_of(toc: u8): i32 { + if (toc & 0x80) != 0 { + val made := band_mb + ((toc >> 5) & 3) as i32; + return made == band_mb ? band_nb : made; + } + if (toc & 0x60) == 0x60 { + return (toc & 0x10) != 0 ? band_fb : band_swb; + } + return band_nb + ((toc >> 5) & 3) as i32; +} + +# A frame's size as a packet codes it: in one byte, or two. +def frame_size_at(data: span, at: u64, sizes: &mut i32[48], index: u64): i32 { + return -1 if at >= data.length; + if data[at] < 252 { + sizes[index] = data[at] as i32; + return 1; + } + return -1 if at + 1 >= data.length; + sizes[index] = 4 * data[at + 1] as i32 + data[at] as i32; + return 2; +} + +# Decodes a packet's frames. +# @returns How many frames it gave, or -1 where it's malformed. +def frames_state::decode_packet(&mut this, data: span, pcm: slice): i32 { + return -1 if data.length == 0; + val toc := data[0]; + val frame_size := samples_per_frame(toc); + var sizes: i32[48]; + var count: i32 = 1; + var at: u64 = 1; + var len := data.length as i32 - 1; + var last_size := len; + match toc & 3 { + 0 => {} + 1 => { + count = 2; + return -1 if (len & 1) != 0; + last_size = len / 2; + sizes[0] = last_size; + } + 2 => { + count = 2; + val bytes := frame_size_at(data, at, &mut sizes, 0); + return -1 if bytes < 0; + len -= bytes; + return -1 if sizes[0] > len; + at += bytes as u64; + last_size = len - sizes[0]; + } + else => { + return -1 if len < 1; + val ch := data[at]; + at++; + count = (ch & 0x3F) as i32; + return -1 if count <= 0 || frame_size * count > 5760; + len--; + if (ch & 0x40) != 0 { + # Padding. + while true { + return -1 if len <= 0; + val p := data[at] as i32; + at++; + len--; + val tmp := p == 255 ? 254 : p; + len -= tmp; + break if p != 255; + } + } + return -1 if len < 0; + if (ch & 0x80) != 0 { + # Of frames of their own sizes. + last_size = len; + for i in 0..count - 1 { + val bytes := frame_size_at(data, at, &mut sizes, i as u64); + return -1 if bytes < 0; + len -= bytes; + return -1 if sizes[i as u64] > len; + at += bytes as u64; + last_size -= bytes + sizes[i as u64]; + } + return -1 if last_size < 0; + } else { + last_size = len / count; + return -1 if last_size * count != len; + for i in 0..count - 1 { + sizes[i as u64] = last_size; + } + } + } + } + return -1 if last_size > 1275; + sizes[(count - 1) as u64] = last_size; + + this.mode = mode_of(toc); + this.bandwidth = bandwidth_of(toc); + this.frame_size = frame_size; + this.stream_channels = (toc & 4) != 0 ? 2 : 1; + var made: i32 = 0; + for i in 0..count { + val size := sizes[i as u64] as u64; + val frame := data[at:size]; + val got := this.decode_frame(frame, true, slice::::over(pcm.data + (made * this.channels) as u64, (frame_size * this.channels) as u64), frame_size); + return -1 if got < 0; + at += size; + made += got; + } + return made; +} + +# A crossfade from one signal to another over 2.5 ms, by the square of CELT's window. +def smooth_fade(from: slice, to: slice, out: slice, channels: i32): void { + for c in 0..channels { + for i in 0..f2_5 { + val w := window120[i as u64] * window120[i as u64]; + val at := (i * channels + c) as u64; + out[at] = w * to[at] + (1 as f32 - w) * from[at]; + } + } +} + +# Decodes a frame, or, where it's lost, conceals one: libopus's +# `opus_decode_frame`. +# @param given The frame, or nothing where `present` is false. +# @param pcm Where its frames go, `channels` floats each. +# @param wanted How many frames it may give. +# @returns How many it gave, or -1 where it's malformed. +def frames_state::decode_frame(&mut this, given: span, given_present: bool, pcm: slice, wanted: i32): i32 { + var frame_size := math::min(wanted, 2880); + var len := given.length as i32; + var present := given_present; + if len <= 1 { + present = false; + frame_size = math::min(frame_size, this.frame_size); + } + var audiosize := frame_size; + var mode := this.prev_redundancy ? mode_celt : this.prev_mode; + var bandwidth: i32 = 0; + var rd := range_decoder::of(given); + if present { + audiosize = this.frame_size; + mode = this.mode; + bandwidth = this.bandwidth; + } else { + if mode == 0 { + for i in 0..(audiosize * this.channels) as u64 { + pcm[i] = 0; + } + return audiosize; + } + # Concealed 20 ms at most at a time. + if audiosize > f20 { + var done: i32 = 0; + while done < audiosize { + val got := this.decode_frame(span::::blank(), false, sub(pcm, (done * this.channels) as u64, ((audiosize - done) * this.channels) as u64), math::min(audiosize - done, f20)); + return got if got < 0; + done += got; + } + return frame_size; + } + if audiosize < f20 { + if audiosize > f10 { + audiosize = f10; + } else if mode != mode_silk && audiosize > f5 && audiosize < f10 { + audiosize = f5; + } + } + } + val channels := this.channels; + + var transition := false; + if present && this.prev_mode > 0 && ((mode == mode_celt && this.prev_mode != mode_celt && !this.prev_redundancy) || (mode != mode_celt && this.prev_mode == mode_celt)) { + transition = true; + } + val transition_pcm := slice::::over(this.transition.data, (f5 * channels) as u64); + if transition && mode == mode_celt { + _ = this.decode_frame(span::::blank(), false, transition_pcm, math::min(f5, audiosize)); + } + return -1 if audiosize > frame_size; + frame_size = audiosize; + + # SILK's frames. + if mode != mode_celt { + if this.prev_mode == mode_celt { + this.silk.reset(); + } + val payload_ms := math::max(10, 1000 * audiosize / 48000); + val internal_rate: i32 = mode == mode_silk && bandwidth == band_nb ? 8000 : mode == mode_silk && bandwidth == band_mb ? 12000 : 16000; + var decoded: i32 = 0; + while decoded < frame_size { + val out := slice::::over(this.silk_pcm.data + (decoded * channels) as u64, ((frame_size - decoded) * channels) as u64); + var got := this.silk.decode(&mut rd, !present, decoded == 0, this.stream_channels, internal_rate, payload_ms, channels, out); + if got < 0 { + return -1 if present; + # Concealment failing isn't fatal. + got = frame_size; + for i in 0..(frame_size * channels) as u64 { + out[i] = 0; + } + } + decoded += got; + } + } + + var start_band: i32 = 0; + var redundancy := false; + var celt_to_silk := false; + var redundancy_bytes: i32 = 0; + if mode != mode_celt && present && rd.tell() + 17 + (mode == mode_hybrid ? 20 : 0) <= 8 * len { + # Whether there's a redundant frame of CELT's, of the band to 8 kHz. + redundancy = mode == mode_hybrid ? rd.bit_logp(12) : true; + if redundancy { + celt_to_silk = rd.bit_logp(1); + redundancy_bytes = mode == mode_hybrid ? rd.uint(256) as i32 + 2 : len - ((rd.tell() + 7) >> 3); + len -= redundancy_bytes; + if len * 8 < rd.tell() { + len = 0; + redundancy_bytes = 0; + redundancy = false; + } + rd.storage -= redundancy_bytes as u32; + } + } + if mode != mode_celt { + start_band = 17; + } + if redundancy { + transition = false; + } + if transition && mode != mode_celt { + _ = this.decode_frame(span::::blank(), false, transition_pcm, math::min(f5, audiosize)); + } + + if bandwidth != 0 { + this.celt.end = bandwidth == band_nb ? 13 : bandwidth == band_mb || bandwidth == band_wb ? 17 : bandwidth == band_swb ? 19 : 21; + } + this.celt.stream_channels = this.stream_channels; + val redundant := slice::::over(this.redundant.data, (f5 * channels) as u64); + if redundancy && celt_to_silk { + this.celt.start = 0; + var own := range_decoder::of(given[len as u64:redundancy_bytes as u64]); + _ = this.celt.decode(&mut own, redundancy_bytes, redundant, f5); + } + this.celt.start = start_band; + + if mode != mode_silk { + val celt_frame_size := math::min(f20, frame_size); + if mode != this.prev_mode && this.prev_mode > 0 && !this.prev_redundancy { + this.celt.reset(); + } + _ = this.celt.decode(&mut rd, present ? len : 0, pcm, celt_frame_size); + } else { + for i in 0..(frame_size * channels) as u64 { + pcm[i] = 0; + } + # Leaving hybrid, CELT fades out by a frame of silence. + if this.prev_mode == mode_hybrid && !(redundancy && celt_to_silk && this.prev_redundancy) { + this.celt.start = 0; + val silence: u8[2] = [0xFF, 0xFF]; + var quiet := range_decoder::of(silence[0:2]); + _ = this.celt.decode(&mut quiet, 2, pcm, f2_5); + } + } + + if mode != mode_celt { + for i in 0..(frame_size * channels) as u64 { + pcm[i] = pcm[i] + (1 as f32 / 32768) * this.silk_pcm[i] as f32; + } + } + + # CELT's redundant frame at a move from SILK to it. + if redundancy && !celt_to_silk { + this.celt.reset(); + this.celt.start = 0; + var own := range_decoder::of(given[len as u64:redundancy_bytes as u64]); + _ = this.celt.decode(&mut own, redundancy_bytes, redundant, f5); + val end := sub(pcm, ((frame_size - f2_5) * channels) as u64, (f2_5 * channels) as u64); + smooth_fade(end, sub(redundant, (f2_5 * channels) as u64, (f2_5 * channels) as u64), end, channels); + } + # And at a move from it to SILK. + if redundancy && celt_to_silk && (this.prev_mode != mode_silk || this.prev_redundancy) { + for i in 0..(f2_5 * channels) as u64 { + pcm[i] = redundant[i]; + } + val rest := sub(pcm, (f2_5 * channels) as u64, (f2_5 * channels) as u64); + smooth_fade(sub(redundant, (f2_5 * channels) as u64, (f2_5 * channels) as u64), rest, rest, channels); + } + if transition { + if audiosize >= f5 { + for i in 0..(f2_5 * channels) as u64 { + pcm[i] = transition_pcm[i]; + } + val rest := sub(pcm, (f2_5 * channels) as u64, (f2_5 * channels) as u64); + smooth_fade(sub(transition_pcm, (f2_5 * channels) as u64, (f2_5 * channels) as u64), rest, rest, channels); + } else { + smooth_fade(transition_pcm, pcm, pcm, channels); + } + } + if this.gain != 1 { + for i in 0..(frame_size * channels) as u64 { + pcm[i] = pcm[i] * this.gain; + } + } + this.prev_mode = mode; + this.prev_redundancy = redundancy && !celt_to_silk; + return audiosize; +} + +#! Reads an Ogg Opus stream's frames as it's asked for them, at 48 kHz. Its +#! bytes must stay where they are while it reads them. +pub struct decoder { + var stream: packets; + var audio_at: u64; # Where the first page of audio begins. + var heard: u32; # The channels: one, or two. + var pre_skip: u64; # The frames decoded first, then cut. + var state: frames_state; + var made: vector; # The frames a packet gave. + 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; # The granule position of the stream's end. + var from: u64; # The granule position a seek asked for, before which what's decoded is cut. + var looped: loop_range; # Where its comments say it loops. +} + +#! Opens an Ogg Opus 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 Opus stream, `malformed` where a header +#! or page is broken, and `unsupported` where it's of a later +#! version, or more than two channels. +pub def decoder::open(bytes: span): result { + # The first stream whose first page begins with Opus'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 := ogg::page_at(bytes, at) else (e) { return e; }; + return audio_error::unrecognized if (first.flags & ogg::first_page) == 0; + if is_opus_head(bytes[first.body:first.length]) { + serial = first.serial; + found = true; + } else { + at = first.body + first.length; + } + } + + var stream := ogg::packets::of(bytes, serial, at); + var next := ogg::packet{}; + var had := stream.next(&mut next) else (e) { return e; }; + return audio_error::malformed if !had || next.data.length < 19; + val head := next.data; + return audio_error::unsupported if (head[8] & 0xF0) != 0; + val channels := head[9] as u32; + return audio_error::malformed if channels == 0; + return audio_error::unsupported if channels > 2 || head[18] != 0; + val pre_skip := head[10] as u64 | (head[11] as u64) << 8; + var gain := head[16] as i32 | (head[17] as i32) << 8; + if gain >= 32768 { + gain -= 65536; + } + + had = stream.next(&mut next) else (e) { return e; }; + return audio_error::malformed if !had || next.data.length < 16 || !has_magic(next.data, "OpusTags"); + val looped := audio::loop_of_comments(next.data[8:next.data.length - 8]); + # Audio begins on a page of its own. + return audio_error::malformed if stream.segment != stream.current.segments; + + var made := decoder{ + stream = move(&mut stream), audio_at = 0, heard = channels, pre_skip = pre_skip, + state = frames_state::new(channels as i32, gain), made = vector::::new(), pending = vector::::new(), + looped = looped, + }; + made.audio_at = made.stream.at; + made.made.resize(most_packet_frames * 2); + made.total = ogg::last_granule(bytes, serial); + return made; +} + +def has_magic(data: span, magic: strview): bool { + return false if data.length < magic.length; + for i in 0..magic.length { + return false if data[i] != magic[i]; + } + return true; +} + +# Whether a packet is Opus's identification header. +def is_opus_head(data: span): bool { + return data.length >= 19 && has_magic(data, "OpusHead"); +} + +#! How many channels the frames read have: one, or two. +pub val decoder::channels: u32 { + get => this.heard; +} + +#! Frames a second: 48000, at which Opus is always decoded. +pub val decoder::rate: u32 { + get => 48000; +} + +#! How many frames the stream has, as its last page says, less its pre-skip, +#! or 0 where it says nothing. +pub val decoder::frames: u64 { + get => this.total > this.pre_skip ? this.total - this.pre_skip : 0; +} + +#! Where the stream says a voice playing it loops, as its comments say. +pub val decoder::loop_points: loop_range { + get => this.looped; +} + +#! 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.heard as u64; + val wanted := into.length / width; + val cut := math::max(this.from, this.pre_skip); + var given: u64 = 0; + while given < wanted { + val held := (this.pending.length - this.taken) / width; + # What the pre-skip, or a seek, passes, once it's known where it is. + if held > 0 && this.timed && this.clock - held < cut { + val before := cut - (this.clock - held); + this.taken += (before < held ? before : held) * width; + continue; + } + 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 := ogg::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.state.decode_packet(next.data, slice::::over(this.made.data, this.made.length)); + return audio_error::malformed if count < 0; + this.pending.extend(span::::over(this.made.data, count as u64 * width)); + this.time(count as u64, 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.state.reset(); + this.pending.clear(); + this.taken = 0; + this.timed = false; + this.clock = 0; + this.from = 0; +} + +#! Reads on from a frame of the stream: from the page halving its pages finds +#! half a second or more before it, the frames between decoded and left out, +#! so the decoder has settled by the frame, to within a few ten-thousandths of +#! what decoding straight through gives. +#! @param frame The frame, past the end where the stream ends there. +#! @returns Nothing, or why the stream couldn't be read. +pub def decoder::seek(&mut this, frame: u64): result { + this.rewind(); + this.from = frame + this.pre_skip; + return if this.from <= preroll; + this.stream.rewind(ogg::resume_at(this.stream.bytes, this.stream.serial, this.audio_at, this.from - preroll)); + return; +} + +# 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.heard as u64; + if !this.timed { + return if granule == ogg::no_granule; + 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 != ogg::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 != ogg::no_granule { + this.clock = granule; + } +} + +#! Reads an Ogg Opus file whole. +#! @param bytes The file's bytes. +#! @returns The sound, at 48 kHz, 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 = 48000, channels = reading.channels, samples = move(samples), loop_points = reading.loop_points }; +} diff --git a/audio/opus/range.sakura b/audio/opus/range.sakura new file mode 100644 index 0000000..f5959a6 --- /dev/null +++ b/audio/opus/range.sakura @@ -0,0 +1,207 @@ +#! Contains the range decoder every Opus frame is coded with, SILK's and CELT's +#! alike, as RFC 6716's section 4.1 has it: symbols of 8 bits read from the +#! frame's start, into a 32-bit range, and raw bits read from its end, which +#! CELT keeps its finest values in. Reading past either end gives zeros. + +module malunal::audio::opus; + + +# The top of the range, and the least it's let fall to before a symbol is read. +const code_top: u32 = 0x80000000; +const code_bot: u32 = 0x800000; +# The bits of the first symbol read that aren't the range's. +const code_extra: u32 = 7; +# The fractions of a bit `tell_frac` counts in: eighths. +const bitres: i32 = 3; + +# A frame's range decoder. +struct range_decoder { + var buf: span; + var storage: u32; # How many bytes the frame has, which raw bits are read back from. + var end_offs: u32; # How many raw bits' bytes were read. + var end_window: u32; # Raw bits read and not yet given. + var nend_bits: i32; + var nbits_total: i32; # The whole bits read, not counting those still in the range. + var offs: u32; # The next symbol's byte. + var rng: u32; # How many values the range holds. + var value: u32; # The top of the range less the value read, less one. + var ext: u32; # What `decode` scaled the range by, for `update`. + var rem: u32; # The last symbol's byte, some of whose bits are yet to be read. + var error: bool; +} + +# A decoder of a frame's bytes. +def range_decoder::of(bytes: span): range_decoder { + var made := range_decoder{ buf = bytes, storage = bytes.length as u32 }; + made.nbits_total = 32 + 1 - ((32 - code_extra as i32) / 8) * 8; + made.rng = 1 << code_extra; + made.rem = made.read_byte(); + made.value = made.rng - 1 - (made.rem >> (8 - code_extra)); + made.normalize(); + return made; +} + +def range_decoder::read_byte(&mut this): u32 { + return 0 if this.offs >= this.storage; + val byte := this.buf[this.offs as u64] as u32; + this.offs++; + return byte; +} + +def range_decoder::read_byte_from_end(&mut this): u32 { + return 0 if this.end_offs >= this.storage; + this.end_offs++; + return this.buf[(this.storage - this.end_offs) as u64] as u32; +} + +# Reads symbols until the range lies wholly in the top one. +def range_decoder::normalize(&mut this): void { + while this.rng <= code_bot { + this.nbits_total += 8; + this.rng <<= 8; + val last := this.rem; + this.rem = this.read_byte(); + val symbol := ((last << 8) | this.rem) >> (8 - code_extra); + this.value = ((((this.value as u64) << 8) + (255 & ~symbol) as u64) & (code_top - 1) as u64) as u32; + } +} + +# The bits read so far, rounded up. +def range_decoder::tell(&this): i32 { + return this.nbits_total - ilog(this.rng); +} + +# The bits read so far in eighths of a bit, rounded up. +def range_decoder::tell_frac(&this): i32 { + val correction: u32[8] = [35733, 38967, 42495, 46340, 50535, 55109, 60097, 65535]; + val whole := this.nbits_total << bitres; + var l := ilog(this.rng); + val r := this.rng >> (l - 16) as u32; + var b := (r >> 12) - 8; + if r > correction[b as u64] { + b++; + } + l = (l << 3) + b as i32; + return whole - l; +} + +# The cumulative frequency of the next symbol, of `total` in all, which +# `update` must follow. +def range_decoder::decode(&mut this, total: u32): u32 { + this.ext = this.rng / total; + val s := this.value / this.ext; + return total - (s + 1 < total ? s + 1 : total); +} + +# As `decode`, of a total of a power of two. +def range_decoder::decode_bin(&mut this, bits: u32): u32 { + this.ext = this.rng >> bits; + val s := this.value / this.ext; + val total: u32 = 1 << bits; + return total - (s + 1 < total ? s + 1 : total); +} + +# Takes the symbol `decode` found, of frequencies from `low` to `high`. +def range_decoder::update(&mut this, low: u32, high: u32, total: u32): void { + val s := this.ext * (total - high); + this.value -= s; + this.rng = low > 0 ? this.ext * (high - low) : this.rng - s; + this.normalize(); +} + +# A bit whose chance of being one is 1 in 2 to the `logp`. +def range_decoder::bit_logp(&mut this, logp: u32): bool { + val r := this.rng; + val d := this.value; + val s := r >> logp; + val one := d < s; + if !one { + this.value = d - s; + } + this.rng = one ? s : r - s; + this.normalize(); + return one; +} + +# A symbol of an inverse cumulative table, of 2 to the `bits` in all. +def range_decoder::icdf(&mut this, table: span, bits: u32): i32 { + var s := this.rng; + val d := this.value; + val r := s >> bits; + var symbol: i32 = -1; + var t: u32 = 0; + while true { + t = s; + symbol++; + s = r * table[symbol as u64] as u32; + break if d >= s; + } + this.value = d - s; + this.rng = t - s; + this.normalize(); + return symbol; +} + +# As `icdf`, of a table of 16-bit values. +def range_decoder::icdf16(&mut this, table: span, bits: u32): i32 { + var s := this.rng; + val d := this.value; + val r := s >> bits; + var symbol: i32 = -1; + var t: u32 = 0; + while true { + t = s; + symbol++; + s = r * table[symbol as u64] as u32; + break if d >= s; + } + this.value = d - s; + this.rng = t - s; + this.normalize(); + return symbol; +} + +# A whole number from 0 to `total` less one, evenly likely: its top 8 bits +# ranged, the rest raw. +def range_decoder::uint(&mut this, total: u32): u32 { + val most := total - 1; + var bits := ilog(most); + if bits > 8 { + bits -= 8; + val top := (most >> bits as u32) + 1; + val s := this.decode(top); + this.update(s, s + 1, top); + val t := (s << bits as u32) | this.bits(bits as u32); + return t if t <= most; + this.error = true; + return most; + } + val s := this.decode(total); + this.update(s, s + 1, total); + return s; +} + +# Raw bits, read back from the frame's end. +def range_decoder::bits(&mut this, count: u32): u32 { + return 0 if count == 0; + var window := this.end_window as u64; + var available := this.nend_bits; + if (available as u32) < count { + while available <= 32 - 8 { + window |= (this.read_byte_from_end() as u64) << available as u32; + available += 8; + } + } + val got := (window & ((1u << count as u64) - 1)) as u32; + window >>= count; + available -= count as i32; + this.end_window = window as u32; + this.nend_bits = available; + this.nbits_total += count as i32; + return got; +} + +# How many bits a number needs: 0 for 0, else its highest one's place and one. +def ilog(v: u32): i32 { + return v == 0 ? 0 : 32 - leading_zeros(v) as i32; +} diff --git a/audio/opus/silk.sakura b/audio/opus/silk.sakura new file mode 100644 index 0000000..26e3b4a --- /dev/null +++ b/audio/opus/silk.sakura @@ -0,0 +1,1216 @@ +#! Contains SILK's decoder, which Opus codes speech with, and the band below +#! 8 kHz of its hybrid frames, as RFC 6716's section 4.2 has it and libopus +#! decodes it, in fixed point, bit for bit: each frame's side information read, +#! its gains, its LPC filter as NLSFs, and where it's voiced its pitch lags and +#! LTP filter; its excitation read as pulses, by shells of 16; then the +#! excitation through the LTP and LPC filters. Stereo is coded as mid and side, +#! the side predicted from the mid. Each channel is resampled from SILK's rate, +#! 8, 12, or 16 kHz, to 48, by an all-pass halfband filter and an interpolating +#! FIR, as libopus's resampler does. +#! +#! A lost frame is decoded as silence, rather than concealed; and a frame's +#! redundant copy, for loss, is read past rather than used. + +import std::math; +module malunal::audio::opus; + + +const silk_max_order: u64 = 16; +const ltp_order: i32 = 5; +const max_frame: u64 = 320; + +# A frame's signal type. +const type_no_voice: i32 = 0; +const type_unvoiced: i32 = 1; +const type_voiced: i32 = 2; + +# How a frame's side information is coded: alone; alone, without the LTP +# scaled; or from the frame before. +const code_independently: i32 = 0; +const code_independently_no_ltp_scaling: i32 = 1; +const code_conditionally: i32 = 2; + +# The offsets of a quantized excitation, in Q10, of unvoiced and voiced frames, low and high. +const silk_quantization_offsets_q10: i16[4] = [100, 240, 32, 100]; + +# Its constants of gains. +const gain_offset: i32 = 2090; +const inv_scale_q16: i32 = 1907825; + +# What a frame's side information says: libopus's `SideInfoIndices`. +struct silk_indices { + var gains: i32[4]; + var ltp_index: i32[4]; + var nlsf: i32[17]; + var lag_index: i32; + var contour: i32; + var signal_type: i32; + var quant_offset_type: i32; + var nlsf_interp_q2: i32; + var per_index: i32; + var ltp_scale_index: i32; + var seed: i32; +} + +# A frame's parameters, decoded: libopus's `silk_decoder_control`. +struct silk_control { + var pitch_l: i32[4]; + var gains_q16: i32[4]; + var pred_coef_q12: i32[32]; # Of each half of the frame. + var ltp_coef_q14: i32[20]; + var ltp_scale_q14: i32; +} + +# A resampler from SILK's rate to 48 kHz. +struct silk_resampler { + var s_iir: i32[6]; + var s_fir: i32[8]; + var delay_buf: i32[16]; + var input_delay: i32; + var fs_in_khz: i32; + var batch_size: i32; + var inv_ratio: i32; +} + +# One channel's decoder, mid's or side's: libopus's `silk_decoder_state`. +struct silk_channel { + var prev_gain_q16: i32; + var exc_q14: i32[320]; + var slpc_q14_buf: i32[16]; + var out_buf: i32[480]; + var lag_prev: i32; + var last_gain_index: i32; + var fs_khz: i32; + var fs_api_hz: i32; + var nb_subfr: i32; + var frame_length: i32; + var subfr_length: i32; + var ltp_mem_length: i32; + var lpc_order: i32; + var prev_nlsf_q15: i32[16]; + var first_after_reset: bool; + var frames_decoded: i32; + var frames_per_packet: i32; + var ec_prev_type: i32; + var ec_prev_lag: i32; + var vad_flags: bool[3]; + var lbrr_flag: bool; + var lbrr_flags: bool[3]; + var resampler: silk_resampler; + var prev_signal_type: i32; + var indices: silk_indices; +} + +# Back to the state of a decoder that's decoded nothing. +def silk_channel::reset(&mut this): void { + val blank := silk_channel{}; + this = blank; + this.first_after_reset = true; + this.prev_gain_q16 = 65536; +} + +# The state stereo keeps between frames. +struct silk_stereo { + var pred_prev_q13: i32[2]; + var s_mid: i32[2]; + var s_side: i32[2]; +} + +struct silk_decoder { + var states: silk_channel[2]; + var stereo: silk_stereo; + var channels_api: i32; + var channels_internal: i32; + var prev_only_middle: bool; + var pulses: i32[320]; + var frame: i32[320]; # A channel's frame, decoded. + var mid: i32[322]; # Each channel's frame, after two samples of the frame before. + var side: i32[322]; + var resampled: i32[960]; + var ltp: i32[320]; + var ltp_q15: i32[640]; + var lpc_q14: i32[96]; +} + +def silk_decoder::new(): silk_decoder { + var made := silk_decoder{}; + made.reset(); + return made; +} + +# Forgets every frame before. +def silk_decoder::reset(&mut this): void { + this.states[0].reset(); + this.states[1].reset(); + this.stereo = silk_stereo{}; + this.prev_only_middle = false; +} + +# Decodes a SILK frame of a packet, resampled to 48 kHz: libopus's `silk_Decode`. +# @param lost Whether the frame is lost, so concealed. +# @param first Whether it's the packet's first. +# @param internal_channels The packet's channels. +# @param internal_rate SILK's rate: 8000, 12000, or 16000. +# @param payload_ms The packet's frames' length: 10, 20, 40, or 60. +# @param api_channels The channels given. +# @param out Where its frames go, `api_channels` each. +# @returns Its frames, or -1 where the packet's malformed. +def silk_decoder::decode(&mut this, rd: &mut range_decoder, lost: bool, first: bool, internal_channels: i32, internal_rate: i32, payload_ms: i32, api_channels: i32, out: slice): i32 { + var only_middle := false; + var ms_pred: i32[2] = [0, 0]; + if first { + for n in 0..internal_channels { + this.states[n as u64].frames_decoded = 0; + } + } + if internal_channels > this.channels_internal { + this.states[1].reset(); + } + val stereo_to_mono := internal_channels == 1 && this.channels_internal == 2 && internal_rate == 1000 * this.states[0].fs_khz; + if this.states[0].frames_decoded == 0 { + for n in 0..internal_channels { + val at := &mut this.states[n as u64]; + if payload_ms == 0 || payload_ms == 10 { + at.frames_per_packet = 1; + at.nb_subfr = 2; + } else if payload_ms == 20 { + at.frames_per_packet = 1; + at.nb_subfr = 4; + } else if payload_ms == 40 { + at.frames_per_packet = 2; + at.nb_subfr = 4; + } else if payload_ms == 60 { + at.frames_per_packet = 3; + at.nb_subfr = 4; + } else { + return -1; + } + at.set_fs((internal_rate >> 10) + 1, 48000); + } + } + if api_channels == 2 && internal_channels == 2 && (this.channels_api == 1 || this.channels_internal == 1) { + this.stereo.pred_prev_q13 = [0, 0]; + this.stereo.s_side = [0, 0]; + this.states[1].resampler = this.states[0].resampler; + } + this.channels_api = api_channels; + this.channels_internal = internal_channels; + + if !lost && this.states[0].frames_decoded == 0 { + # The packet's voice activity and redundancy flags. + for n in 0..internal_channels { + val at := &mut this.states[n as u64]; + for i in 0..at.frames_per_packet { + at.vad_flags[i as u64] = rd.bit_logp(1); + } + at.lbrr_flag = rd.bit_logp(1); + } + for n in 0..internal_channels { + val at := &mut this.states[n as u64]; + at.lbrr_flags = [false, false, false]; + if at.lbrr_flag { + if at.frames_per_packet == 1 { + at.lbrr_flags[0] = true; + } else { + val symbol := (at.frames_per_packet == 2 ? rd.icdf(silk_lbrr_flags_2_icdf[0:3], 8) : rd.icdf(silk_lbrr_flags_3_icdf[0:7], 8)) + 1; + for i in 0..at.frames_per_packet { + at.lbrr_flags[i as u64] = ((symbol >> i as u32) & 1) != 0; + } + } + } + } + # The redundant frames, read past. + for i in 0..this.states[0].frames_per_packet { + for n in 0..internal_channels { + if this.states[n as u64].lbrr_flags[i as u64] { + if internal_channels == 2 && n == 0 { + stereo_decode_pred(rd, &mut ms_pred); + if !this.states[1].lbrr_flags[i as u64] { + _ = rd.icdf(silk_stereo_only_code_mid_icdf[0:2], 8); + } + } + val cond := i > 0 && this.states[n as u64].lbrr_flags[(i - 1) as u64] ? code_conditionally : code_independently; + this.states[n as u64].decode_indices(rd, i, true, cond); + decode_pulses(rd, &mut this.pulses, this.states[n as u64].indices.signal_type, this.states[n as u64].indices.quant_offset_type, this.states[n as u64].frame_length); + } + } + } + } + + if internal_channels == 2 { + if !lost { + stereo_decode_pred(rd, &mut ms_pred); + if !this.states[1].vad_flags[this.states[0].frames_decoded as u64] { + only_middle = rd.icdf(silk_stereo_only_code_mid_icdf[0:2], 8) != 0; + } + } else { + ms_pred = this.stereo.pred_prev_q13; + } + } + # The side's prediction forgets what's before its first frame coded. + if internal_channels == 2 && !only_middle && this.prev_only_middle { + val side := &mut this.states[1]; + for i in 0..480 { + side.out_buf[i] = 0; + } + for i in 0..16 { + side.slpc_q14_buf[i] = 0; + } + side.lag_prev = 100; + side.last_gain_index = 10; + side.prev_signal_type = type_no_voice; + side.first_after_reset = true; + } + val has_side := !lost ? !only_middle : !this.prev_only_middle; + var n_out: i32 = 0; + for n in 0..internal_channels { + if n == 0 || has_side { + val frame_index := this.states[0].frames_decoded - n; + var cond := code_conditionally; + if frame_index <= 0 { + cond = code_independently; + } else if n > 0 && this.prev_only_middle { + cond = code_independently_no_ltp_scaling; + } + n_out = this.decode_frame(n, rd, lost, cond); + } else { + for i in 0..n_out { + this.frame[i as u64] = 0; + } + } + for i in 0..n_out { + if n == 0 { + this.mid[(i + 2) as u64] = this.frame[i as u64]; + } else { + this.side[(i + 2) as u64] = this.frame[i as u64]; + } + } + this.states[n as u64].frames_decoded++; + } + + val fs_khz := this.states[0].fs_khz; + if api_channels == 2 && internal_channels == 2 { + stereo_ms_to_lr(&mut this.stereo, &mut this.mid, &mut this.side, &ms_pred, fs_khz, n_out); + } else { + this.mid[0] = this.stereo.s_mid[0]; + this.mid[1] = this.stereo.s_mid[1]; + this.stereo.s_mid[0] = this.mid[n_out as u64]; + this.stereo.s_mid[1] = this.mid[(n_out + 1) as u64]; + } + + val made := n_out * 48000 / (fs_khz * 1000); + for n in 0..math::min(api_channels, internal_channels) { + val from := n == 0 ? &this.mid : &this.side; + resample(&mut this.states[n as u64].resampler, &mut this.resampled, from, 1, n_out); + for i in 0..made { + out[(n + api_channels * i) as u64] = this.resampled[i as u64] as i16; + } + } + if api_channels == 2 && internal_channels == 1 { + if stereo_to_mono { + resample(&mut this.states[1].resampler, &mut this.resampled, &this.mid, 1, n_out); + for i in 0..made { + out[(1 + 2 * i) as u64] = this.resampled[i as u64] as i16; + } + } else { + for i in 0..made { + out[(1 + 2 * i) as u64] = out[(2 * i) as u64]; + } + } + } + if lost { + for n in 0..this.channels_internal { + this.states[n as u64].last_gain_index = 10; + } + } else { + this.prev_only_middle = only_middle; + } + return made; +} + +# Sets a channel's rate and frame length, its resampler and tables with them. +def silk_channel::set_fs(&mut this, fs_khz: i32, fs_api_hz: i32): void { + this.subfr_length = 5 * fs_khz; + val frame_length := this.nb_subfr * this.subfr_length; + if this.fs_khz != fs_khz || this.fs_api_hz != fs_api_hz { + this.resampler = silk_resampler::of(fs_khz * 1000); + this.fs_api_hz = fs_api_hz; + } + if this.fs_khz != fs_khz || frame_length != this.frame_length { + if this.fs_khz != fs_khz { + this.ltp_mem_length = 20 * fs_khz; + this.lpc_order = fs_khz == 16 ? 16 : 10; + this.first_after_reset = true; + this.lag_prev = 100; + this.last_gain_index = 10; + this.prev_signal_type = type_no_voice; + for i in 0..480 { + this.out_buf[i] = 0; + } + for i in 0..16 { + this.slpc_q14_buf[i] = 0; + } + } + this.fs_khz = fs_khz; + this.frame_length = frame_length; + } +} + +# Decodes one channel's frame: libopus's `silk_decode_frame`. +def silk_decoder::decode_frame(&mut this, n: i32, rd: &mut range_decoder, lost: bool, cond: i32): i32 { + val length := this.states[n as u64].frame_length; + var control := silk_control{}; + if !lost { + this.states[n as u64].decode_indices(rd, this.states[n as u64].frames_decoded, false, cond); + decode_pulses(rd, &mut this.pulses, this.states[n as u64].indices.signal_type, this.states[n as u64].indices.quant_offset_type, length); + this.states[n as u64].decode_parameters(&mut control, cond); + this.decode_core(n, &control); + this.states[n as u64].prev_signal_type = this.states[n as u64].indices.signal_type; + this.states[n as u64].first_after_reset = false; + } else { + for i in 0..length { + this.frame[i as u64] = 0; + } + control.pitch_l[(this.states[n as u64].nb_subfr - 1) as u64] = this.states[n as u64].lag_prev; + } + val at := &mut this.states[n as u64]; + val kept := at.ltp_mem_length - length; + for i in 0..kept { + at.out_buf[i as u64] = at.out_buf[(i + length) as u64]; + } + for i in 0..length { + at.out_buf[(kept + i) as u64] = this.frame[i as u64]; + } + at.lag_prev = control.pitch_l[(at.nb_subfr - 1) as u64]; + return length; +} + +# Reads a frame's side information: libopus's `silk_decode_indices`. +def silk_channel::decode_indices(&mut this, rd: &mut range_decoder, frame_index: i32, redundant: bool, cond: i32): void { + val into := &mut this.indices; + var ix: i32 = 0; + if redundant || this.vad_flags[frame_index as u64] { + ix = rd.icdf(silk_type_offset_vad_icdf[0:4], 8) + 2; + } else { + ix = rd.icdf(silk_type_offset_no_vad_icdf[0:2], 8); + } + into.signal_type = ix >> 1; + into.quant_offset_type = ix & 1; + + # Gains. + if cond == code_conditionally { + into.gains[0] = rd.icdf(silk_delta_gain_icdf[0:41], 8); + } else { + into.gains[0] = rd.icdf(silk_gain_icdf[(into.signal_type * 8) as u64:8], 8) << 3; + into.gains[0] += rd.icdf(silk_uniform8_icdf[0:8], 8); + } + for i in 1..this.nb_subfr { + into.gains[i as u64] = rd.icdf(silk_delta_gain_icdf[0:41], 8); + } + + # NLSFs. + val wide := this.lpc_order == 16; + val first_stage := wide ? silk_nlsf_cb1_icdf_wb[((into.signal_type >> 1) * 32) as u64:32] : silk_nlsf_cb1_icdf_nb_mb[((into.signal_type >> 1) * 32) as u64:32]; + into.nlsf[0] = rd.icdf(first_stage, 8); + var ec_ix: i32[16]; + var pred_q8: i32[16]; + nlsf_unpack(&mut ec_ix, &mut pred_q8, wide, into.nlsf[0]); + for i in 0..this.lpc_order { + val second := wide ? silk_nlsf_cb2_icdf_wb[ec_ix[i as u64] as u64:72 - ec_ix[i as u64] as u64] : silk_nlsf_cb2_icdf_nb_mb[ec_ix[i as u64] as u64:72 - ec_ix[i as u64] as u64]; + var value := rd.icdf(second, 8); + if value == 0 { + value -= rd.icdf(silk_nlsf_ext_icdf[0:7], 8); + } else if value == 8 { + value += rd.icdf(silk_nlsf_ext_icdf[0:7], 8); + } + into.nlsf[(i + 1) as u64] = value - 4; + } + into.nlsf_interp_q2 = this.nb_subfr == 4 ? rd.icdf(silk_nlsf_interpolation_factor_icdf[0:5], 8) : 4; + + if into.signal_type == type_voiced { + # Pitch lags. + var absolute := true; + if cond == code_conditionally && this.ec_prev_type == type_voiced { + var delta := rd.icdf(silk_pitch_delta_icdf[0:21], 8); + if delta > 0 { + delta -= 9; + into.lag_index = this.ec_prev_lag + delta; + absolute = false; + } + } + if absolute { + into.lag_index = rd.icdf(silk_pitch_lag_icdf[0:32], 8) * (this.fs_khz >> 1); + into.lag_index += this.fs_khz == 16 ? rd.icdf(silk_uniform8_icdf[0:8], 8) : this.fs_khz == 12 ? rd.icdf(silk_uniform6_icdf[0:6], 8) : rd.icdf(silk_uniform4_icdf[0:4], 8); + } + this.ec_prev_lag = into.lag_index; + if this.fs_khz == 8 { + into.contour = this.nb_subfr == 4 ? rd.icdf(silk_pitch_contour_nb_icdf[0:11], 8) : rd.icdf(silk_pitch_contour_10_ms_nb_icdf[0:3], 8); + } else { + into.contour = this.nb_subfr == 4 ? rd.icdf(silk_pitch_contour_icdf[0:34], 8) : rd.icdf(silk_pitch_contour_10_ms_icdf[0:12], 8); + } + + # LTP gains. + into.per_index = rd.icdf(silk_ltp_per_index_icdf[0:3], 8); + for k in 0..this.nb_subfr { + into.ltp_index[k as u64] = into.per_index == 0 ? rd.icdf(silk_ltp_gain_icdf_0[0:8], 8) : into.per_index == 1 ? rd.icdf(silk_ltp_gain_icdf_1[0:16], 8) : rd.icdf(silk_ltp_gain_icdf_2[0:32], 8); + } + into.ltp_scale_index = cond == code_independently ? rd.icdf(silk_ltp_scale_icdf[0:3], 8) : 0; + } + this.ec_prev_type = into.signal_type; + into.seed = rd.icdf(silk_uniform4_icdf[0:4], 8); +} + +# Where each NLSF's residual's distribution is, and its predictor, as the +# first stage's vector says. +def nlsf_unpack(ec_ix: &mut i32[16], pred_q8: &mut i32[16], wide: bool, index: i32): void { + val order: i32 = wide ? 16 : 10; + var i: i32 = 0; + while i < order { + val at := (index * order / 2 + i / 2) as u64; + val entry := (wide ? silk_nlsf_cb2_select_wb[at] : silk_nlsf_cb2_select_nb_mb[at]) as i32; + ec_ix[i as u64] = ((entry >> 1) & 7) * 9; + pred_q8[i as u64] = nlsf_pred(wide, i + (entry & 1) * (order - 1)); + ec_ix[(i + 1) as u64] = ((entry >> 5) & 7) * 9; + pred_q8[(i + 1) as u64] = nlsf_pred(wide, i + ((entry >> 4) & 1) * (order - 1) + 1); + i += 2; + } +} + +def nlsf_pred(wide: bool, at: i32): i32 { + return (wide ? silk_nlsf_pred_wb_q8[at as u64] : silk_nlsf_pred_nb_mb_q8[at as u64]) as i32; +} + +# Reads a frame's excitation: its rate level, its pulses a block of 16 by +# shells, their lower bits, and their signs. +def decode_pulses(rd: &mut range_decoder, pulses: &mut i32[320], signal_type: i32, quant_offset_type: i32, frame_length: i32): void { + val rate_level := rd.icdf(silk_rate_levels_icdf[((signal_type >> 1) * 9) as u64:9], 8); + var blocks := frame_length >> 4; + if blocks * 16 < frame_length { + blocks++; + } + var sums: i32[20]; + var shifts: i32[20]; + for i in 0..blocks { + shifts[i as u64] = 0; + sums[i as u64] = rd.icdf(silk_pulses_per_block_icdf[(rate_level * 18) as u64:18], 8); + while sums[i as u64] == 17 { + shifts[i as u64]++; + val from := (9 * 18 + (shifts[i as u64] == 10 ? 1 : 0)) as u64; + sums[i as u64] = rd.icdf(silk_pulses_per_block_icdf[from:180 - from], 8); + } + } + for i in 0..blocks { + if sums[i as u64] > 0 { + shell_decoder(pulses, (i * 16) as u64, rd, sums[i as u64]); + } else { + for k in 0..16 { + pulses[(i * 16 + k) as u64] = 0; + } + } + } + for i in 0..blocks { + val nls := shifts[i as u64]; + if nls > 0 { + for k in 0..16 { + val at := (i * 16 + k) as u64; + var abs_q := pulses[at]; + for _ in 0..nls { + abs_q = (abs_q << 1) + rd.icdf(silk_lsb_icdf[0:2], 8); + } + pulses[at] = abs_q; + } + sums[i as u64] |= nls << 5; + } + } + # Signs. + val base := (7 * (quant_offset_type + (signal_type << 1))) as u64; + val count := (frame_length + 8) >> 4; + for i in 0..count { + val p := sums[i as u64]; + if p > 0 { + val icdf: u8[2] = [silk_sign_icdf[base + math::min(p & 0x1F, 6) as u64], 0]; + for j in 0..16 { + val at := (i * 16 + j) as u64; + if pulses[at] > 0 { + pulses[at] *= (rd.icdf(icdf[0:2], 8) << 1) - 1; + } + } + } + } +} + +# A block's 16 pulses, from their count, split in halves down to each. +def shell_decoder(pulses: &mut i32[320], at: u64, rd: &mut range_decoder, pulses4: i32): void { + var pulses3: i32[2]; + var pulses2: i32[4]; + var pulses1: i32[8]; + decode_split(&mut pulses3[0], &mut pulses3[1], rd, pulses4, 3); + decode_split(&mut pulses2[0], &mut pulses2[1], rd, pulses3[0], 2); + decode_split(&mut pulses1[0], &mut pulses1[1], rd, pulses2[0], 1); + decode_split(&mut pulses[at], &mut pulses[at + 1], rd, pulses1[0], 0); + decode_split(&mut pulses[at + 2], &mut pulses[at + 3], rd, pulses1[1], 0); + decode_split(&mut pulses1[2], &mut pulses1[3], rd, pulses2[1], 1); + decode_split(&mut pulses[at + 4], &mut pulses[at + 5], rd, pulses1[2], 0); + decode_split(&mut pulses[at + 6], &mut pulses[at + 7], rd, pulses1[3], 0); + decode_split(&mut pulses2[2], &mut pulses2[3], rd, pulses3[1], 2); + decode_split(&mut pulses1[4], &mut pulses1[5], rd, pulses2[2], 1); + decode_split(&mut pulses[at + 8], &mut pulses[at + 9], rd, pulses1[4], 0); + decode_split(&mut pulses[at + 10], &mut pulses[at + 11], rd, pulses1[5], 0); + decode_split(&mut pulses1[6], &mut pulses1[7], rd, pulses2[3], 1); + decode_split(&mut pulses[at + 12], &mut pulses[at + 13], rd, pulses1[6], 0); + decode_split(&mut pulses[at + 14], &mut pulses[at + 15], rd, pulses1[7], 0); +} + +def decode_split(child1: &mut i32, child2: &mut i32, rd: &mut range_decoder, p: i32, table: i32): void { + if p > 0 { + val offset := silk_shell_code_table_offsets[p as u64] as u64; + val split := match table { + 0 => silk_shell_code_table0[offset:152 - offset], + 1 => silk_shell_code_table1[offset:152 - offset], + 2 => silk_shell_code_table2[offset:152 - offset], + else => silk_shell_code_table3[offset:152 - offset], + }; + child1 = rd.icdf(split, 8); + child2 = p - child1; + } else { + child1 = 0; + child2 = 0; + } +} + +# A frame's parameters from its side information: libopus's `silk_decode_parameters`. +def silk_channel::decode_parameters(&mut this, control: &mut silk_control, cond: i32): void { + gains_dequant(control, &this.indices, &mut this.last_gain_index, cond == code_conditionally, this.nb_subfr); + val wide := this.lpc_order == 16; + var nlsf_q15: i32[16]; + nlsf_decode(&mut nlsf_q15, &this.indices.nlsf, wide); + var second: i32[16]; + nlsf2a(&mut second, &nlsf_q15, this.lpc_order); + for i in 0..16 { + control.pred_coef_q12[16 + i] = second[i]; + } + if this.first_after_reset { + this.indices.nlsf_interp_q2 = 4; + } + if this.indices.nlsf_interp_q2 < 4 { + # The first half's, interpolated from the frame before's. + var nlsf0_q15: i32[16]; + for i in 0..this.lpc_order { + val at := i as u64; + nlsf0_q15[at] = to_i16(this.prev_nlsf_q15[at] + ((this.indices.nlsf_interp_q2 * (nlsf_q15[at] - this.prev_nlsf_q15[at])) >> 2)); + } + var first: i32[16]; + nlsf2a(&mut first, &nlsf0_q15, this.lpc_order); + for i in 0..16 { + control.pred_coef_q12[i] = first[i]; + } + } else { + for i in 0..16 { + control.pred_coef_q12[i] = second[i]; + } + } + this.prev_nlsf_q15 = nlsf_q15; + + if this.indices.signal_type == type_voiced { + decode_pitch(this.indices.lag_index, this.indices.contour, &mut control.pitch_l, this.fs_khz, this.nb_subfr); + for k in 0..this.nb_subfr { + val entry := this.indices.ltp_index[k as u64]; + for i in 0..ltp_order { + val at := (entry * ltp_order + i) as u64; + val tap: i32 = this.indices.per_index == 0 ? silk_ltp_gain_vq_0[at] as i32 : this.indices.per_index == 1 ? silk_ltp_gain_vq_1[at] as i32 : silk_ltp_gain_vq_2[at] as i32; + control.ltp_coef_q14[(k * ltp_order + i) as u64] = tap << 7; + } + } + control.ltp_scale_q14 = silk_ltp_scales_table_q14[this.indices.ltp_scale_index as u64] as i32; + } else { + for i in 0..4 { + control.pitch_l[i] = 0; + } + for i in 0..20 { + control.ltp_coef_q14[i] = 0; + } + this.indices.per_index = 0; + control.ltp_scale_q14 = 0; + } +} + +# The subframes' gains, from their indices, each as a change from the one +# before but the first of a frame coded alone. +def gains_dequant(control: &mut silk_control, indices: &silk_indices, prev: &mut i32, conditional: bool, nb_subfr: i32): void { + for k in 0..nb_subfr { + val index := indices.gains[k as u64]; + if k == 0 && !conditional { + # Down 16 steps at most. + prev = math::max(index, prev - 16); + } else { + val tmp := index - 4; + val threshold := 2 * 36 - 64 + prev; + if tmp > threshold { + prev += (tmp << 1) - threshold; + } else { + prev += tmp; + } + } + prev = silk_limit(prev, 0, 63); + control.gains_q16[k as u64] = log2lin(math::min(smulwb(inv_scale_q16, prev) + gain_offset, 3967)); + } +} + +# A frame's NLSFs, in Q15, from its two stages' indices, stabilized. +def nlsf_decode(out: &mut i32[16], indices: &i32[17], wide: bool): void { + val order: i32 = wide ? 16 : 10; + var ec_ix: i32[16]; + var pred_q8: i32[16]; + nlsf_unpack(&mut ec_ix, &mut pred_q8, wide, indices[0]); + # The residuals, each predicted from the next. + var res_q10: i32[16]; + val step: i32 = wide ? 9830 : 11796; + var out_q10: i32 = 0; + var i := order - 1; + while i >= 0 { + val pred_q10 := smulbb(out_q10, pred_q8[i as u64]) >> 8; + out_q10 = indices[(i + 1) as u64] << 10; + if out_q10 > 0 { + out_q10 = to_i16(out_q10 - 102); + } else if out_q10 < 0 { + out_q10 = to_i16(out_q10 + 102); + } + out_q10 = smlawb(pred_q10, out_q10, step); + res_q10[i as u64] = to_i16(out_q10); + i--; + } + # Weighted, and added to the first stage's vector. + for k in 0..order { + val at := (indices[0] * order + k) as u64; + val weight := (wide ? silk_nlsf_cb1_wght_wb_q9[at] : silk_nlsf_cb1_wght_nb_mb_q9[at]) as i32; + val element := (wide ? silk_nlsf_cb1_wb_q8[at] : silk_nlsf_cb1_nb_mb_q8[at]) as i32; + val tmp := ((res_q10[k as u64] << 14) / weight) + (element << 7); + out[k as u64] = silk_limit(tmp, 0, 32767); + } + nlsf_stabilize(out, wide, order); +} + +def delta_min(wide: bool, at: i32): i32 { + return (wide ? silk_nlsf_delta_min_wb_q15[at as u64] : silk_nlsf_delta_min_nb_mb_q15[at as u64]) as i32; +} + +# NLSFs moved apart where they're too close, and from the ends. +def nlsf_stabilize(nlsf: &mut i32[16], wide: bool, l: i32): void { + var loops: i32 = 0; + while loops < 20 { + var min_diff := nlsf[0] - delta_min(wide, 0); + var at: i32 = 0; + for i in 1..l { + val diff := nlsf[i as u64] - (nlsf[(i - 1) as u64] + delta_min(wide, i)); + if diff < min_diff { + min_diff = diff; + at = i; + } + } + val last := (1 << 15) - (nlsf[(l - 1) as u64] + delta_min(wide, l)); + if last < min_diff { + min_diff = last; + at = l; + } + return if min_diff >= 0; + if at == 0 { + nlsf[0] = delta_min(wide, 0); + } else if at == l { + nlsf[(l - 1) as u64] = (1 << 15) - delta_min(wide, l); + } else { + var min_center: i32 = 0; + for k in 0..at { + min_center += delta_min(wide, k); + } + min_center += delta_min(wide, at) >> 1; + var max_center: i32 = 1 << 15; + var k := l; + while k > at { + max_center -= delta_min(wide, k); + k--; + } + max_center -= delta_min(wide, at) >> 1; + val center := to_i16(silk_limit(rshift_round(nlsf[(at - 1) as u64] + nlsf[at as u64], 1), min_center, max_center)); + nlsf[(at - 1) as u64] = center - (delta_min(wide, at) >> 1); + nlsf[at as u64] = nlsf[(at - 1) as u64] + delta_min(wide, at); + } + loops++; + } + # Sorted, then spaced, as a last resort. + for i in 1..l { + val value := nlsf[i as u64]; + var j := i - 1; + while j >= 0 && value < nlsf[j as u64] { + nlsf[(j + 1) as u64] = nlsf[j as u64]; + j--; + } + nlsf[(j + 1) as u64] = value; + } + nlsf[0] = math::max(nlsf[0], delta_min(wide, 0)); + for i in 1..l { + nlsf[i as u64] = math::max(nlsf[i as u64], sat16(nlsf[(i - 1) as u64] + delta_min(wide, i))); + } + nlsf[(l - 1) as u64] = math::min(nlsf[(l - 1) as u64], (1 << 15) - delta_min(wide, l)); + var i := l - 2; + while i >= 0 { + nlsf[i as u64] = math::min(nlsf[i as u64], nlsf[(i + 1) as u64] - delta_min(wide, i + 1)); + i--; + } +} + +const ordering16: u8[16] = [0, 15, 8, 7, 4, 11, 12, 3, 2, 13, 10, 5, 6, 9, 14, 1]; +const ordering10: u8[10] = [0, 9, 6, 3, 4, 5, 8, 1, 2, 7]; + +# An LPC filter, in Q12, from NLSFs, made stable. +def nlsf2a(a_q12: &mut i32[16], nlsf: &i32[16], d: i32): void { + var cos_lsf: i32[16]; + for k in 0..d { + val f := nlsf[k as u64]; + val f_int := f >> 8; + val f_frac := f - (f_int << 8); + val cos_val := silk_lsf_cos_tab_q12[f_int as u64] as i32; + val delta := silk_lsf_cos_tab_q12[(f_int + 1) as u64] as i32 - cos_val; + val to := (d == 16 ? ordering16[k as u64] : ordering10[k as u64]) as u64; + cos_lsf[to] = rshift_round((cos_val << 8) + delta * f_frac, 4); + } + val dd := d >> 1; + var p: i32[9]; + var q: i32[9]; + find_poly(&mut p, &cos_lsf, 0, dd); + find_poly(&mut q, &cos_lsf, 1, dd); + var a32: i32[16]; + for k in 0..dd { + val ptmp := p[(k + 1) as u64] + p[k as u64]; + val qtmp := q[(k + 1) as u64] - q[k as u64]; + a32[k as u64] = -qtmp - ptmp; + a32[(d - k - 1) as u64] = qtmp - ptmp; + } + lpc_fit(a_q12, &mut a32, 12, 17, d); + var i: i32 = 0; + while lpc_inverse_pred_gain(a_q12, d) == 0 && i < 16 { + # Too near unstable: widened, then measured again. + bwexpander_32(&mut a32, d, 65536 - (2 << i as u32)); + for k in 0..d { + a_q12[k as u64] = to_i16(rshift_round(a32[k as u64], 5)); + } + i++; + } +} + +# A polynomial of interleaved cosines, in Q16. +def find_poly(out: &mut i32[9], c: &i32[16], from: u64, dd: i32): void { + out[0] = 1 << 16; + out[1] = -c[from]; + for k in 1..dd { + val ftmp := c[from + (2 * k) as u64]; + out[(k + 1) as u64] = (out[(k - 1) as u64] << 1) - rshift_round64(ftmp as i64 * out[k as u64] as i64, 16) as i32; + var n := k; + while n > 1 { + out[n as u64] += out[(n - 2) as u64] - rshift_round64(ftmp as i64 * out[(n - 1) as u64] as i64, 16) as i32; + n--; + } + out[1] -= ftmp; + } +} + +# 32-bit coefficients to 16, widened until they fit. +def lpc_fit(a_out: &mut i32[16], a_in: &mut i32[16], q_out: i32, q_in: i32, d: i32): void { + var i: i32 = 0; + var index: i32 = 0; + while i < 10 { + var maxabs: i32 = 0; + for k in 0..d { + val absval := silk_abs(a_in[k as u64]); + if absval > maxabs { + maxabs = absval; + index = k; + } + } + maxabs = rshift_round(maxabs, q_in - q_out); + break if maxabs <= 32767; + maxabs = math::min(maxabs, 163838); + val chirp_q16 := 65470 - ((maxabs - 32767) << 14) / ((maxabs * (index + 1)) >> 2); + bwexpander_32(a_in, d, chirp_q16); + i++; + } + if i == 10 { + for k in 0..d { + a_out[k as u64] = sat16(rshift_round(a_in[k as u64], q_in - q_out)); + a_in[k as u64] = a_out[k as u64] << (q_in - q_out) as u32; + } + } else { + for k in 0..d { + a_out[k as u64] = to_i16(rshift_round(a_in[k as u64], q_in - q_out)); + } + } +} + +# A filter's coefficients scaled by powers of a chirp, widening its bandwidth. +def bwexpander_32(ar: &mut i32[16], d: i32, given_chirp: i32): void { + var chirp := given_chirp; + val chirp_minus_one := chirp - 65536; + for i in 0..d - 1 { + ar[i as u64] = smulww(chirp, ar[i as u64]); + chirp += rshift_round(chirp * chirp_minus_one, 16); + } + ar[(d - 1) as u64] = smulww(chirp, ar[(d - 1) as u64]); +} + +# The inverse of a filter's prediction gain, in Q30, or 0 where it's unstable. +def lpc_inverse_pred_gain(a_q12: &i32[16], order: i32): i32 { + var a_qa: i32[16]; + var dc_resp: i32 = 0; + for k in 0..order { + dc_resp += a_q12[k as u64]; + a_qa[k as u64] = a_q12[k as u64] << 12; + } + return 0 if dc_resp >= 4096; + val a_limit: i32 = 16773022; + val least_gain: i32 = 107374; + var inv_gain_q30: i32 = 1 << 30; + var k := order - 1; + while k > 0 { + return 0 if a_qa[k as u64] > a_limit || a_qa[k as u64] < -a_limit; + val rc_q31 := -(a_qa[k as u64] << 7); + val rc_mult1_q30 := (1 << 30) - smmul(rc_q31, rc_q31); + inv_gain_q30 = smmul(inv_gain_q30, rc_mult1_q30) << 2; + return 0 if inv_gain_q30 < least_gain; + val mult2q := 32 - clz32(silk_abs(rc_mult1_q30)); + val rc_mult2 := inverse32_varq(rc_mult1_q30, mult2q + 30); + for n in 0..(k + 1) >> 1 { + val tmp1 := a_qa[n as u64]; + val tmp2 := a_qa[(k - n - 1) as u64]; + var tmp64 := rshift_round64(sub_sat32(tmp1, rshift_round64(tmp2 as i64 * rc_q31 as i64, 31) as i32) as i64 * rc_mult2 as i64, mult2q); + return 0 if tmp64 > silk_int32_max as i64 || tmp64 < silk_int32_min as i64; + a_qa[n as u64] = tmp64 as i32; + tmp64 = rshift_round64(sub_sat32(tmp2, rshift_round64(tmp1 as i64 * rc_q31 as i64, 31) as i32) as i64 * rc_mult2 as i64, mult2q); + return 0 if tmp64 > silk_int32_max as i64 || tmp64 < silk_int32_min as i64; + a_qa[(k - n - 1) as u64] = tmp64 as i32; + } + k--; + } + return 0 if a_qa[0] > a_limit || a_qa[0] < -a_limit; + val rc_q31 := -(a_qa[0] << 7); + val rc_mult1_q30 := (1 << 30) - smmul(rc_q31, rc_q31); + inv_gain_q30 = smmul(inv_gain_q30, rc_mult1_q30) << 2; + return 0 if inv_gain_q30 < least_gain; + return inv_gain_q30; +} + +# A voiced frame's pitch lag of each subframe, from its lag and contour. +def decode_pitch(lag_index: i32, contour: i32, pitch_l: &mut i32[4], fs_khz: i32, nb_subfr: i32): void { + val min_lag := 2 * fs_khz; + val max_lag := 18 * fs_khz; + val lag := min_lag + lag_index; + for k in 0..nb_subfr { + var offset: i32 = 0; + if fs_khz == 8 { + offset = nb_subfr == 4 ? silk_cb_lags_stage2[(k * 11 + contour) as u64] as i32 : silk_cb_lags_stage2_10_ms[(k * 3 + contour) as u64] as i32; + } else { + offset = nb_subfr == 4 ? silk_cb_lags_stage3[(k * 34 + contour) as u64] as i32 : silk_cb_lags_stage3_10_ms[(k * 12 + contour) as u64] as i32; + } + pitch_l[k as u64] = silk_limit(lag + offset, min_lag, max_lag); + } +} + +# The excitation through the LTP and LPC filters, scaled by each subframe's +# gain: libopus's `silk_decode_core`. +def silk_decoder::decode_core(&mut this, n: i32, control: &silk_control): void { + val at := &mut this.states[n as u64]; + val offset_q10 := silk_quantization_offsets_q10[((at.indices.signal_type >> 1) * 2 + at.indices.quant_offset_type) as u64] as i32; + val interpolated := at.indices.nlsf_interp_q2 < 4; + # The excitation, of the pulses and pseudorandom signs. + var rand_seed := at.indices.seed; + for i in 0..at.frame_length { + val k := i as u64; + rand_seed = silk_rand(rand_seed); + var exc := this.pulses[k] << 14; + if exc > 0 { + exc -= 80 << 4; + } else if exc < 0 { + exc += 80 << 4; + } + exc += offset_q10 << 4; + if rand_seed < 0 { + exc = -exc; + } + at.exc_q14[k] = exc; + rand_seed = wrap32(rand_seed as i64 + this.pulses[k] as i64); + } + for i in 0..16 { + this.lpc_q14[i] = at.slpc_q14_buf[i]; + } + val order := at.lpc_order; + val subfr := at.subfr_length; + val ltp_mem := at.ltp_mem_length; + var ltp_idx := ltp_mem; + for k in 0..at.nb_subfr { + val a := ((k >> 1) * 16) as u64; + val b := (k * ltp_order) as u64; + val signal_type := at.indices.signal_type; + val gain := control.gains_q16[k as u64]; + val gain_q10 := gain >> 6; + var inv_gain_q31 := inverse32_varq(gain, 47); + var gain_adj_q16: i32 = 1 << 16; + if gain != at.prev_gain_q16 { + gain_adj_q16 = div32_varq(at.prev_gain_q16, gain, 16); + for i in 0..16 { + this.lpc_q14[i] = smulww(gain_adj_q16, this.lpc_q14[i]); + } + } + at.prev_gain_q16 = gain; + + var lag: i32 = 0; + if signal_type == type_voiced { + lag = control.pitch_l[k as u64]; + if k == 0 || (k == 2 && interpolated) { + # Rewhitened with the new filter. + val start := ltp_mem - lag - order - ltp_order / 2; + if k == 2 { + for i in 0..2 * subfr { + at.out_buf[(ltp_mem + i) as u64] = this.frame[i as u64]; + } + } + lpc_analysis_filter(&mut this.ltp, start, &at.out_buf, start + k * subfr, control, a, ltp_mem - start, order); + if k == 0 { + # The LTP scaled down, so a packet depends less on those before. + inv_gain_q31 = smulwb(inv_gain_q31, control.ltp_scale_q14) << 2; + } + for i in 0..lag + ltp_order / 2 { + this.ltp_q15[(ltp_idx - i - 1) as u64] = smulwb(inv_gain_q31, this.ltp[(ltp_mem - i - 1) as u64]); + } + } else if gain_adj_q16 != 1 << 16 { + for i in 0..lag + ltp_order / 2 { + val p := (ltp_idx - i - 1) as u64; + this.ltp_q15[p] = smulww(gain_adj_q16, this.ltp_q15[p]); + } + } + } + + # Long-term prediction, into the LPC's excitation. + val exc_at := (k * subfr) as u64; + var res_q14: i32[80]; + if signal_type == type_voiced { + var pred_lag := ltp_idx - lag + ltp_order / 2; + for i in 0..subfr { + var ltp_pred: i32 = 2; + for j in 0..ltp_order { + ltp_pred = smlawb(ltp_pred, this.ltp_q15[(pred_lag - j) as u64], control.ltp_coef_q14[b + j as u64]); + } + pred_lag++; + res_q14[i as u64] = at.exc_q14[exc_at + i as u64] + (ltp_pred << 1); + this.ltp_q15[ltp_idx as u64] = res_q14[i as u64] << 1; + ltp_idx++; + } + } else { + for i in 0..subfr { + res_q14[i as u64] = at.exc_q14[exc_at + i as u64]; + } + } + + # Short-term prediction. + for i in 0..subfr { + var lpc_pred: i32 = order >> 1; + for j in 0..order { + lpc_pred = smlawb(lpc_pred, this.lpc_q14[(16 + i - 1 - j) as u64], control.pred_coef_q12[a + j as u64]); + } + val value := add_sat32(res_q14[i as u64], lshift_sat32(lpc_pred, 4)); + this.lpc_q14[(16 + i) as u64] = value; + this.frame[(k * subfr + i) as u64] = sat16(rshift_round(smulww(value, gain_q10), 8)); + } + for i in 0..16 { + this.lpc_q14[i] = this.lpc_q14[i as u64 + subfr as u64]; + } + } + for i in 0..16 { + at.slpc_q14_buf[i] = this.lpc_q14[i]; + } +} + +# The LPC filter's residual of past output, for the LTP to predict from. +def lpc_analysis_filter(out: &mut i32[320], out_at: i32, input: &i32[480], in_at: i32, control: &silk_control, a: u64, len: i32, d: i32): void { + for ix in d..len { + var acc: i64 = 0; + for j in 0..d { + acc += smulbb(input[(in_at + ix - 1 - j) as u64], control.pred_coef_q12[a + j as u64]) as i64; + } + val out32_q12 := wrap32(((input[(in_at + ix) as u64] as i64) << 12) - wrap32(acc) as i64); + out[(out_at + ix) as u64] = sat16(rshift_round(out32_q12, 12)); + } + for ix in 0..d { + out[(out_at + ix) as u64] = 0; + } +} + +# Stereo's predictors, of mid into side. +def stereo_decode_pred(rd: &mut range_decoder, pred_q13: &mut i32[2]): void { + var ix: i32[6]; + val joint := rd.icdf(silk_stereo_pred_joint_icdf[0:25], 8); + ix[2] = joint / 5; + ix[5] = joint - 5 * ix[2]; + for n in 0..2 { + ix[(n * 3) as u64] = rd.icdf(silk_uniform3_icdf[0:3], 8); + ix[(n * 3 + 1) as u64] = rd.icdf(silk_uniform5_icdf[0:5], 8); + } + for n in 0..2 { + val first := ix[(n * 3) as u64] + 3 * ix[(n * 3 + 2) as u64]; + val low_q13 := silk_stereo_pred_quant_q13[first as u64] as i32; + val step_q13 := smulwb(silk_stereo_pred_quant_q13[(first + 1) as u64] as i32 - low_q13, 6554); + pred_q13[n as u64] = smlabb(low_q13, step_q13, 2 * ix[(n * 3 + 1) as u64] + 1); + } + pred_q13[0] -= pred_q13[1]; +} + +# Mid and side to left and right, the side predicted from the mid, the +# predictors interpolated over the first 8 ms. +def stereo_ms_to_lr(state: &mut silk_stereo, x1: &mut i32[322], x2: &mut i32[322], pred_q13: &i32[2], fs_khz: i32, frame_length: i32): void { + x1[0] = state.s_mid[0]; + x1[1] = state.s_mid[1]; + x2[0] = state.s_side[0]; + x2[1] = state.s_side[1]; + state.s_mid[0] = x1[frame_length as u64]; + state.s_mid[1] = x1[(frame_length + 1) as u64]; + state.s_side[0] = x2[frame_length as u64]; + state.s_side[1] = x2[(frame_length + 1) as u64]; + var pred0_q13 := state.pred_prev_q13[0]; + var pred1_q13 := state.pred_prev_q13[1]; + val interp := 8 * fs_khz; + val denom_q16 := (1 << 16) / interp; + val delta0_q13 := rshift_round(smulbb(pred_q13[0] - state.pred_prev_q13[0], denom_q16), 16); + val delta1_q13 := rshift_round(smulbb(pred_q13[1] - state.pred_prev_q13[1], denom_q16), 16); + for n in 0..frame_length { + if n < interp { + pred0_q13 += delta0_q13; + pred1_q13 += delta1_q13; + } else if n == interp { + pred0_q13 = pred_q13[0]; + pred1_q13 = pred_q13[1]; + } + val at := n as u64; + var sum := (x1[at] + x1[at + 2] + (x1[at + 1] << 1)) << 9; + sum = smlawb(x2[at + 1] << 8, sum, pred0_q13); + sum = smlawb(sum, x1[at + 1] << 11, pred1_q13); + x2[at + 1] = sat16(rshift_round(sum, 8)); + } + state.pred_prev_q13[0] = pred_q13[0]; + state.pred_prev_q13[1] = pred_q13[1]; + for n in 0..frame_length { + val at := (n + 1) as u64; + val sum := x1[at] + x2[at]; + val diff := x1[at] - x2[at]; + x1[at] = sat16(sum); + x2[at] = sat16(diff); + } +} + +# A resampler from a rate of SILK's to 48 kHz. +def silk_resampler::of(fs_hz_in: i32): silk_resampler { + var made := silk_resampler{ fs_in_khz = fs_hz_in / 1000 }; + made.input_delay = fs_hz_in == 8000 ? 0 : fs_hz_in == 12000 ? 4 : 7; + made.batch_size = made.fs_in_khz * 10; + made.inv_ratio = ((fs_hz_in << 15) / 48000) << 2; + while smulww(made.inv_ratio, 48000) < fs_hz_in << 1 { + made.inv_ratio++; + } + return made; +} + +# Resamples a frame to 48 kHz, through a millisecond's delay, so SILK's frames +# line up with CELT's. +def resample(state: &mut silk_resampler, out: &mut i32[960], input: &i32[322], from: u64, in_len: i32): void { + val n_samples := state.fs_in_khz - state.input_delay; + for i in 0..n_samples { + state.delay_buf[(state.input_delay + i) as u64] = input[from + i as u64]; + } + var buf: i32[322]; + for i in 0..state.fs_in_khz { + buf[i as u64] = state.delay_buf[i as u64]; + } + iir_fir(state, out, 0, &buf, 0, state.fs_in_khz); + iir_fir(state, out, 48, input, from + n_samples as u64, in_len - state.fs_in_khz); + for i in 0..state.input_delay { + state.delay_buf[i as u64] = input[from + (in_len - state.input_delay + i) as u64]; + } +} + +# Upsampled by two, then interpolated by the FIR, in batches. +def iir_fir(state: &mut silk_resampler, out: &mut i32[960], given_at: u64, input: &i32[322], from: u64, given_len: i32): void { + var at := given_at; + var buf: i32[328]; + for i in 0..8 { + buf[i] = state.s_fir[i]; + } + var in_at := from; + var len := given_len; + var n: i32 = 0; + while true { + n = math::min(len, state.batch_size); + up2_hq(state, &mut buf, input, in_at, n); + val max_index_q16 := n << 17; + var index_q16: i32 = 0; + while index_q16 < max_index_q16 { + val table_index := smulwb(index_q16 & 0xFFFF, 12); + val p := (index_q16 >> 16) as u64; + val t0 := (table_index * 4) as u64; + val t1 := ((11 - table_index) * 4) as u64; + var res_q15 := smulbb(buf[p], silk_resampler_frac_fir_12[t0] as i32); + res_q15 = smlabb(res_q15, buf[p + 1], silk_resampler_frac_fir_12[t0 + 1] as i32); + res_q15 = smlabb(res_q15, buf[p + 2], silk_resampler_frac_fir_12[t0 + 2] as i32); + res_q15 = smlabb(res_q15, buf[p + 3], silk_resampler_frac_fir_12[t0 + 3] as i32); + res_q15 = smlabb(res_q15, buf[p + 4], silk_resampler_frac_fir_12[t1 + 3] as i32); + res_q15 = smlabb(res_q15, buf[p + 5], silk_resampler_frac_fir_12[t1 + 2] as i32); + res_q15 = smlabb(res_q15, buf[p + 6], silk_resampler_frac_fir_12[t1 + 1] as i32); + res_q15 = smlabb(res_q15, buf[p + 7], silk_resampler_frac_fir_12[t1] as i32); + out[at] = sat16(rshift_round(res_q15, 15)); + at++; + index_q16 += state.inv_ratio; + } + in_at += n as u64; + len -= n; + break if len <= 0; + for i in 0..8 { + buf[i] = buf[(n << 1) as u64 + i as u64]; + } + } + for i in 0..8 { + state.s_fir[i] = buf[(n << 1) as u64 + i as u64]; + } +} + +const up2_hq_0: i32[3] = [1746, 14986, 39083 - 65536]; +const up2_hq_1: i32[3] = [6854, 25769, 55542 - 65536]; + +# Upsampled by two, by all-pass sections for the even and odd samples. +def up2_hq(state: &mut silk_resampler, buf: &mut i32[328], input: &i32[322], from: u64, len: i32): void { + val s := &mut state.s_iir; + for k in 0..len { + val in32 := input[from + k as u64] << 10; + var y := in32 - s[0]; + var x := smulwb(y, up2_hq_0[0]); + var out32_1 := s[0] + x; + s[0] = in32 + x; + y = out32_1 - s[1]; + x = smulwb(y, up2_hq_0[1]); + var out32_2 := s[1] + x; + s[1] = out32_1 + x; + y = out32_2 - s[2]; + x = smlawb(y, y, up2_hq_0[2]); + out32_1 = s[2] + x; + s[2] = out32_2 + x; + buf[(8 + 2 * k) as u64] = sat16(rshift_round(out32_1, 10)); + + y = in32 - s[3]; + x = smulwb(y, up2_hq_1[0]); + out32_1 = s[3] + x; + s[3] = in32 + x; + y = out32_1 - s[4]; + x = smulwb(y, up2_hq_1[1]); + out32_2 = s[4] + x; + s[4] = out32_1 + x; + y = out32_2 - s[5]; + x = smlawb(y, y, up2_hq_1[2]); + out32_1 = s[5] + x; + s[5] = out32_2 + x; + buf[(8 + 2 * k + 1) as u64] = sat16(rshift_round(out32_1, 10)); + } +} diff --git a/audio/opus/silk_math.sakura b/audio/opus/silk_math.sakura new file mode 100644 index 0000000..4c7f9c8 --- /dev/null +++ b/audio/opus/silk_math.sakura @@ -0,0 +1,145 @@ +#! Contains SILK's fixed-point arithmetic, as libopus's 64-bit builds have it: +#! multiplies of 32 by 16 bits and 32 by 32, kept to their top bits, shifts +#! that round, saturating sums, its approximate divisions and inverses, and +#! its piecewise 2 to the power of. + +module malunal::audio::opus; + + +const silk_int32_max: i32 = 0x7FFFFFFF; +const silk_int32_min: i32 = -0x7FFFFFFF - 1; + +# A 64-bit number's low 32 bits, signed, as C's conversion wraps it. +def wrap32(x: i64): i32 { + val low := x & 0xFFFFFFFF; + return (low >= 0x80000000 ? low - 0x100000000 : low) as i32; +} + +# A number's low 16 bits, signed, as C's conversion to `opus_int16` wraps it. +def to_i16(x: i32): i32 { + val low := x & 0xFFFF; + return low >= 0x8000 ? low - 0x10000 : low; +} + +# (a * (int16) b) >> 16. +def smulwb(a: i32, b: i32): i32 { + return ((a as i64 * to_i16(b) as i64) >> 16) as i32; +} + +def smlawb(a: i32, b: i32, c: i32): i32 { + return wrap32(a as i64 + ((b as i64 * to_i16(c) as i64) >> 16)); +} + +# (a * b) >> 16. +def smulww(a: i32, b: i32): i32 { + return wrap32((a as i64 * b as i64) >> 16); +} + +def smlaww(a: i32, b: i32, c: i32): i32 { + return wrap32(a as i64 + ((b as i64 * c as i64) >> 16)); +} + +def smulbb(a: i32, b: i32): i32 { + return to_i16(a) * to_i16(b); +} + +def smlabb(a: i32, b: i32, c: i32): i32 { + return wrap32(a as i64 + smulbb(b, c) as i64); +} + +# (a * b) >> 32. +def smmul(a: i32, b: i32): i32 { + return ((a as i64 * b as i64) >> 32) as i32; +} + +def rshift_round(a: i32, shift: i32): i32 { + return shift == 1 ? (a >> 1) + (a & 1) : ((a >> (shift - 1) as u32) + 1) >> 1; +} + +def rshift_round64(a: i64, shift: i32): i64 { + return shift == 1 ? (a >> 1) + (a & 1) : ((a >> (shift - 1) as u32) + 1) >> 1; +} + +def sat16(a: i32): i32 { + return a > 32767 ? 32767 : a < -32768 ? -32768 : a; +} + +def silk_limit(a: i32, limit1: i32, limit2: i32): i32 { + if limit1 > limit2 { + return a > limit1 ? limit1 : a < limit2 ? limit2 : a; + } + return a > limit2 ? limit2 : a < limit1 ? limit1 : a; +} + +def add_sat32(a: i32, b: i32): i32 { + val sum := a as i64 + b as i64; + return sum > silk_int32_max as i64 ? silk_int32_max : sum < silk_int32_min as i64 ? silk_int32_min : sum as i32; +} + +def sub_sat32(a: i32, b: i32): i32 { + val difference := a as i64 - b as i64; + return difference > silk_int32_max as i64 ? silk_int32_max : difference < silk_int32_min as i64 ? silk_int32_min : difference as i32; +} + +def lshift_sat32(a: i32, shift: i32): i32 { + return silk_limit(a, silk_int32_min >> shift as u32, silk_int32_max >> shift as u32) << shift as u32; +} + +def silk_abs(a: i32): i32 { + return a > 0 ? a : -a; +} + +# The leading zeros of a 32-bit number. +def clz32(a: i32): i32 { + return a == 0 ? 32 : 32 - ilog(a as u32); +} + +# SILK's pseudorandom numbers. +def silk_rand(seed: i32): i32 { + return wrap32(907633515 + seed as i64 * 196314165); +} + +# A good approximation of (a << q) / b. +def div32_varq(a32: i32, b32: i32, qres: i32): i32 { + val a_headrm := clz32(silk_abs(a32)) - 1; + var a32_nrm := a32 << a_headrm as u32; + val b_headrm := clz32(silk_abs(b32)) - 1; + val b32_nrm := b32 << b_headrm as u32; + # The inverse of b, to 14 bits. + val b32_inv := (silk_int32_max >> 2) / (b32_nrm >> 16); + var result := smulwb(a32_nrm, b32_inv); + # What's left, which may wrap, as it ends small. + a32_nrm = wrap32(a32_nrm as i64 - wrap32((smmul(b32_nrm, result) as i64) << 3) as i64); + result = smlawb(result, a32_nrm, b32_inv); + val lshift := 29 + a_headrm - b_headrm - qres; + return lshift_sat32(result, -lshift) if lshift < 0; + return lshift < 32 ? result >> lshift as u32 : 0; +} + +# A good approximation of (1 << q) / b. +def inverse32_varq(b32: i32, qres: i32): i32 { + val b_headrm := clz32(silk_abs(b32)) - 1; + val b32_nrm := b32 << b_headrm as u32; + val b32_inv := (silk_int32_max >> 2) / (b32_nrm >> 16); + var result := b32_inv << 16; + val err_q32 := ((1 << 29) - smulwb(b32_nrm, b32_inv)) << 3; + result = smlaww(result, err_q32, b32_inv); + val lshift := 61 - b_headrm - qres; + return lshift_sat32(result, -lshift) if lshift <= 0; + return lshift < 32 ? result >> lshift as u32 : 0; +} + +# 2 to the power of a number in Q7, piecewise parabolic. +def log2lin(in_log_q7: i32): i32 { + return 0 if in_log_q7 < 0; + return silk_int32_max if in_log_q7 >= 3967; + var out: i32 = 1 << (in_log_q7 >> 7) as u32; + val frac_q7 := in_log_q7 & 0x7F; + val bend := smlawb(frac_q7, smulbb(frac_q7, 128 - frac_q7), -174); + if in_log_q7 < 2048 { + out = out + ((out * bend) >> 7); + } else { + out = out + (out >> 7) * bend; + } + return out; +} diff --git a/audio/opus/silk_tables.sakura b/audio/opus/silk_tables.sakura new file mode 100644 index 0000000..f9ebc2c --- /dev/null +++ b/audio/opus/silk_tables.sakura @@ -0,0 +1,659 @@ +#! Contains the tables SILK is decoded by: the distributions its symbols are +#! read with, its NLSF codebooks, its LTP codebooks, its pitch contours, its +#! cosine table, and its resampler's filter, each as libopus keeps them, +#! generated from its sources. +#! +#! libopus is Copyright 2001-2023 Xiph.Org, Skype Limited, Octasic, Jean-Marc +#! Valin, Timothy B. Terriberry, CSIRO, Gregory Maxwell, Mark Borgerding, Erik +#! de Castro Lopo, Mozilla, and Amazon, under the 3-clause BSD license; see +#! `opus.sakura`. + +module malunal::audio::opus; + +# A frame's signal type and offset, with voice activity. +const silk_type_offset_vad_icdf: u8[4] = [ + 232, 158, 10, 0, +]; + +# Without. +const silk_type_offset_no_vad_icdf: u8[2] = [ + 230, 0, +]; + +# A first subframe's gain's top bits, of each signal type. +const silk_gain_icdf: u8[24] = [ + 224, 112, 44, 15, 3, 2, 1, 0, + 254, 237, 192, 132, 70, 23, 4, 0, + 255, 252, 226, 155, 61, 11, 2, 0, +]; + +# A gain's change from the subframe before. +const silk_delta_gain_icdf: u8[41] = [ + 250, 245, 234, 203, 71, 50, 42, 38, 35, 33, 31, 29, 28, 27, 26, 25, + 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, + 8, 7, 6, 5, 4, 3, 2, 1, 0, +]; + +# Evenly likely symbols, of 3, 4, 5, 6, and 8. +const silk_uniform3_icdf: u8[3] = [ + 171, 85, 0, +]; + +# +const silk_uniform4_icdf: u8[4] = [ + 192, 128, 64, 0, +]; + +# +const silk_uniform5_icdf: u8[5] = [ + 205, 154, 102, 51, 0, +]; + +# +const silk_uniform6_icdf: u8[6] = [ + 213, 171, 128, 85, 43, 0, +]; + +# +const silk_uniform8_icdf: u8[8] = [ + 224, 192, 160, 128, 96, 64, 32, 0, +]; + +# An NLSF residual past the codebook's reach. +const silk_nlsf_ext_icdf: u8[7] = [ + 100, 40, 16, 7, 3, 1, 0, +]; + +# How a frame's first half's NLSFs are interpolated. +const silk_nlsf_interpolation_factor_icdf: u8[5] = [ + 243, 221, 192, 181, 0, +]; + +# A pitch lag's change from the frame before. +const silk_pitch_delta_icdf: u8[21] = [ + 210, 208, 206, 203, 199, 193, 183, 168, 142, 104, 74, 52, 37, 27, 20, 14, + 10, 6, 4, 2, 0, +]; + +# A pitch lag's top bits. +const silk_pitch_lag_icdf: u8[32] = [ + 253, 250, 244, 233, 212, 182, 150, 131, 120, 110, 98, 85, 72, 60, 49, 40, + 32, 25, 19, 15, 13, 11, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, +]; + +# The pitch contours: of 20 ms frames above 8 kHz, at 8 kHz, then of 10 ms frames. +const silk_pitch_contour_icdf: u8[34] = [ + 223, 201, 183, 167, 152, 138, 124, 111, 98, 88, 79, 70, 62, 56, 50, 44, + 39, 35, 31, 27, 24, 21, 18, 16, 14, 12, 10, 8, 6, 4, 3, 2, + 1, 0, +]; + +# +const silk_pitch_contour_nb_icdf: u8[11] = [ + 188, 176, 155, 138, 119, 97, 67, 43, 26, 10, 0, +]; + +# +const silk_pitch_contour_10_ms_icdf: u8[12] = [ + 165, 119, 80, 61, 47, 35, 27, 20, 14, 9, 4, 0, +]; + +# +const silk_pitch_contour_10_ms_nb_icdf: u8[3] = [ + 113, 63, 0, +]; + +# Which LTP codebook a frame uses. +const silk_ltp_per_index_icdf: u8[3] = [ + 179, 99, 0, +]; + +# Each LTP codebook's entries. +const silk_ltp_gain_icdf_0: u8[8] = [ + 71, 56, 43, 30, 21, 12, 6, 0, +]; + +# +const silk_ltp_gain_icdf_1: u8[16] = [ + 199, 165, 144, 124, 109, 96, 84, 71, 61, 51, 42, 32, 23, 15, 8, 0, +]; + +# +const silk_ltp_gain_icdf_2: u8[32] = [ + 241, 225, 211, 199, 187, 175, 164, 153, 142, 132, 123, 114, 105, 96, 88, 80, + 72, 64, 57, 50, 44, 38, 33, 29, 24, 20, 16, 12, 9, 5, 2, 0, +]; + +# Each LTP codebook's five taps an entry, in Q7. +const silk_ltp_gain_vq_0: i8[40] = [ + 4, 6, 24, 7, 5, + 0, 0, 2, 0, 0, + 12, 28, 41, 13, -4, + -9, 15, 42, 25, 14, + 1, -2, 62, 41, -9, + -10, 37, 65, -4, 3, + -6, 4, 66, 7, -8, + 16, 14, 38, -3, 33, +]; + +# +const silk_ltp_gain_vq_1: i8[80] = [ + 13, 22, 39, 23, 12, + -1, 36, 64, 27, -6, + -7, 10, 55, 43, 17, + 1, 1, 8, 1, 1, + 6, -11, 74, 53, -9, + -12, 55, 76, -12, 8, + -3, 3, 93, 27, -4, + 26, 39, 59, 3, -8, + 2, 0, 77, 11, 9, + -8, 22, 44, -6, 7, + 40, 9, 26, 3, 9, + -7, 20, 101, -7, 4, + 3, -8, 42, 26, 0, + -15, 33, 68, 2, 23, + -2, 55, 46, -2, 15, + 3, -1, 21, 16, 41, +]; + +# +const silk_ltp_gain_vq_2: i8[160] = [ + -6, 27, 61, 39, 5, + -11, 42, 88, 4, 1, + -2, 60, 65, 6, -4, + -1, -5, 73, 56, 1, + -9, 19, 94, 29, -9, + 0, 12, 99, 6, 4, + 8, -19, 102, 46, -13, + 3, 2, 13, 3, 2, + 9, -21, 84, 72, -18, + -11, 46, 104, -22, 8, + 18, 38, 48, 23, 0, + -16, 70, 83, -21, 11, + 5, -11, 117, 22, -8, + -6, 23, 117, -12, 3, + 3, -8, 95, 28, 4, + -10, 15, 77, 60, -15, + -1, 4, 124, 2, -4, + 3, 38, 84, 24, -25, + 2, 13, 42, 13, 31, + 21, -4, 56, 46, -1, + -1, 35, 79, -13, 19, + -7, 65, 88, -9, -14, + 20, 4, 81, 49, -29, + 20, 0, 75, 3, -17, + 5, -9, 44, 92, -8, + 1, -3, 22, 69, 31, + -6, 95, 41, -12, 5, + 39, 67, 16, -4, 1, + 0, -6, 120, 55, -36, + -13, 44, 122, 4, -24, + 81, 5, 11, 3, 7, + 2, 0, 9, 10, 88, +]; + +# The LTP's scaling, and its scales in Q14. +const silk_ltp_scale_icdf: u8[3] = [ + 128, 64, 0, +]; + +# +const silk_ltp_scales_table_q14: i16[3] = [ + 15565, 12288, 8192, +]; + +# A frame's rate level, of unvoiced then voiced frames. +const silk_rate_levels_icdf: u8[18] = [ + 241, 190, 178, 132, 87, 74, 41, 14, 0, + 223, 193, 157, 140, 106, 57, 39, 18, 0, +]; + +# The pulses of a block of 16, of each rate level. +const silk_pulses_per_block_icdf: u8[180] = [ + 125, 51, 26, 18, 15, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, + 198, 105, 45, 22, 15, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, + 213, 162, 116, 83, 59, 43, 32, 24, 18, 15, 12, 9, 7, 6, 5, 3, 2, 0, + 239, 187, 116, 59, 28, 16, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, + 250, 229, 188, 135, 86, 51, 30, 19, 13, 10, 8, 6, 5, 4, 3, 2, 1, 0, + 249, 235, 213, 185, 156, 128, 103, 83, 66, 53, 42, 33, 26, 21, 17, 13, 10, 0, + 254, 249, 235, 206, 164, 118, 77, 46, 27, 16, 10, 7, 5, 4, 3, 2, 1, 0, + 255, 253, 249, 239, 220, 191, 156, 119, 85, 57, 37, 23, 15, 10, 6, 4, 2, 0, + 255, 253, 251, 246, 237, 223, 203, 179, 152, 124, 98, 75, 55, 40, 29, 21, 15, 0, + 255, 254, 253, 247, 220, 162, 106, 67, 42, 28, 18, 12, 9, 6, 4, 3, 2, 0, +]; + +# How a count of pulses splits in halves, of 2, 4, 8, and 16 samples. +const silk_shell_code_table0: u8[152] = [ + 128, 0, 214, 42, 0, 235, 128, 21, 0, 244, 184, 72, 11, 0, 248, 214, + 128, 42, 7, 0, 248, 225, 170, 80, 25, 5, 0, 251, 236, 198, 126, 54, + 18, 3, 0, 250, 238, 211, 159, 82, 35, 15, 5, 0, 250, 231, 203, 168, + 128, 88, 53, 25, 6, 0, 252, 238, 216, 185, 148, 108, 71, 40, 18, 4, + 0, 253, 243, 225, 199, 166, 128, 90, 57, 31, 13, 3, 0, 254, 246, 233, + 212, 183, 147, 109, 73, 44, 23, 10, 2, 0, 255, 250, 240, 223, 198, 166, + 128, 90, 58, 33, 16, 6, 1, 0, 255, 251, 244, 231, 210, 181, 146, 110, + 75, 46, 25, 12, 5, 1, 0, 255, 253, 248, 238, 221, 196, 164, 128, 92, + 60, 35, 18, 8, 3, 1, 0, 255, 253, 249, 242, 229, 208, 180, 146, 110, + 76, 48, 27, 14, 7, 3, 1, 0, +]; + +# +const silk_shell_code_table1: u8[152] = [ + 129, 0, 207, 50, 0, 236, 129, 20, 0, 245, 185, 72, 10, 0, 249, 213, + 129, 42, 6, 0, 250, 226, 169, 87, 27, 4, 0, 251, 233, 194, 130, 62, + 20, 4, 0, 250, 236, 207, 160, 99, 47, 17, 3, 0, 255, 240, 217, 182, + 131, 81, 41, 11, 1, 0, 255, 254, 233, 201, 159, 107, 61, 20, 2, 1, + 0, 255, 249, 233, 206, 170, 128, 86, 50, 23, 7, 1, 0, 255, 250, 238, + 217, 186, 148, 108, 70, 39, 18, 6, 1, 0, 255, 252, 243, 226, 200, 166, + 128, 90, 56, 30, 13, 4, 1, 0, 255, 252, 245, 231, 209, 180, 146, 110, + 76, 47, 25, 11, 4, 1, 0, 255, 253, 248, 237, 219, 194, 163, 128, 93, + 62, 37, 19, 8, 3, 1, 0, 255, 254, 250, 241, 226, 205, 177, 145, 111, + 79, 51, 30, 15, 6, 2, 1, 0, +]; + +# +const silk_shell_code_table2: u8[152] = [ + 129, 0, 203, 54, 0, 234, 129, 23, 0, 245, 184, 73, 10, 0, 250, 215, + 129, 41, 5, 0, 252, 232, 173, 86, 24, 3, 0, 253, 240, 200, 129, 56, + 15, 2, 0, 253, 244, 217, 164, 94, 38, 10, 1, 0, 253, 245, 226, 189, + 132, 71, 27, 7, 1, 0, 253, 246, 231, 203, 159, 105, 56, 23, 6, 1, + 0, 255, 248, 235, 213, 179, 133, 85, 47, 19, 5, 1, 0, 255, 254, 243, + 221, 194, 159, 117, 70, 37, 12, 2, 1, 0, 255, 254, 248, 234, 208, 171, + 128, 85, 48, 22, 8, 2, 1, 0, 255, 254, 250, 240, 220, 189, 149, 107, + 67, 36, 16, 6, 2, 1, 0, 255, 254, 251, 243, 227, 201, 166, 128, 90, + 55, 29, 13, 5, 2, 1, 0, 255, 254, 252, 246, 234, 213, 183, 147, 109, + 73, 43, 22, 10, 4, 2, 1, 0, +]; + +# +const silk_shell_code_table3: u8[152] = [ + 130, 0, 200, 58, 0, 231, 130, 26, 0, 244, 184, 76, 12, 0, 249, 214, + 130, 43, 6, 0, 252, 232, 173, 87, 24, 3, 0, 253, 241, 203, 131, 56, + 14, 2, 0, 254, 246, 221, 167, 94, 35, 8, 1, 0, 254, 249, 232, 193, + 130, 65, 23, 5, 1, 0, 255, 251, 239, 211, 162, 99, 45, 15, 4, 1, + 0, 255, 251, 243, 223, 186, 131, 74, 33, 11, 3, 1, 0, 255, 252, 245, + 230, 202, 158, 105, 57, 24, 8, 2, 1, 0, 255, 253, 247, 235, 214, 179, + 132, 84, 44, 19, 7, 2, 1, 0, 255, 254, 250, 240, 223, 196, 159, 112, + 69, 36, 15, 6, 2, 1, 0, 255, 254, 253, 245, 231, 209, 176, 136, 93, + 55, 27, 11, 3, 2, 1, 0, 255, 254, 253, 252, 239, 221, 194, 158, 117, + 76, 42, 18, 4, 3, 2, 1, 0, +]; + +# Where each count's split begins. +const silk_shell_code_table_offsets: u8[17] = [ + 0, 0, 2, 5, 9, 14, 20, 27, 35, 44, 54, 65, 77, 90, 104, 119, + 135, +]; + +# A pulse's lower bits. +const silk_lsb_icdf: u8[2] = [ + 120, 0, +]; + +# A pulse's sign, by signal type, offset, and pulses in its block. +const silk_sign_icdf: u8[42] = [ + 254, 49, 67, 77, 82, 93, 99, 198, 11, 18, 24, 31, 36, 45, 255, 46, + 66, 78, 87, 94, 104, 208, 14, 21, 32, 42, 51, 66, 255, 94, 104, 109, + 112, 115, 118, 248, 53, 69, 80, 88, 95, 102, +]; + +# Which frames of 2 or 3 have redundant copies. +const silk_lbrr_flags_2_icdf: u8[3] = [ + 203, 150, 0, +]; + +# +const silk_lbrr_flags_3_icdf: u8[7] = [ + 215, 195, 166, 125, 110, 82, 0, +]; + +# Stereo's predictors, their coarse steps together. +const silk_stereo_pred_joint_icdf: u8[25] = [ + 249, 247, 246, 245, 244, 234, 210, 202, 201, 200, 197, 174, 82, 59, 56, 55, + 54, 46, 22, 12, 11, 10, 9, 7, 0, +]; + +# Stereo's predictors' steps, in Q13. +const silk_stereo_pred_quant_q13: i16[16] = [ + -13732, -10050, -8266, -7526, -6500, -5000, -2950, -820, 820, 2950, 5000, 6500, 7526, 8266, 10050, 13732, +]; + +# Whether a stereo frame has only its mid. +const silk_stereo_only_code_mid_icdf: u8[2] = [ + 64, 0, +]; + +# The NLSF codebook of narrow and medium band, of 32 vectors of 10: its first stage, in Q8. +const silk_nlsf_cb1_nb_mb_q8: u8[320] = [ + 12, 35, 60, 83, 108, 132, 157, 180, 206, 228, + 15, 32, 55, 77, 101, 125, 151, 175, 201, 225, + 19, 42, 66, 89, 114, 137, 162, 184, 209, 230, + 12, 25, 50, 72, 97, 120, 147, 172, 200, 223, + 26, 44, 69, 90, 114, 135, 159, 180, 205, 225, + 13, 22, 53, 80, 106, 130, 156, 180, 205, 228, + 15, 25, 44, 64, 90, 115, 142, 168, 196, 222, + 19, 24, 62, 82, 100, 120, 145, 168, 190, 214, + 22, 31, 50, 79, 103, 120, 151, 170, 203, 227, + 21, 29, 45, 65, 106, 124, 150, 171, 196, 224, + 30, 49, 75, 97, 121, 142, 165, 186, 209, 229, + 19, 25, 52, 70, 93, 116, 143, 166, 192, 219, + 26, 34, 62, 75, 97, 118, 145, 167, 194, 217, + 25, 33, 56, 70, 91, 113, 143, 165, 196, 223, + 21, 34, 51, 72, 97, 117, 145, 171, 196, 222, + 20, 29, 50, 67, 90, 117, 144, 168, 197, 221, + 22, 31, 48, 66, 95, 117, 146, 168, 196, 222, + 24, 33, 51, 77, 116, 134, 158, 180, 200, 224, + 21, 28, 70, 87, 106, 124, 149, 170, 194, 217, + 26, 33, 53, 64, 83, 117, 152, 173, 204, 225, + 27, 34, 65, 95, 108, 129, 155, 174, 210, 225, + 20, 26, 72, 99, 113, 131, 154, 176, 200, 219, + 34, 43, 61, 78, 93, 114, 155, 177, 205, 229, + 23, 29, 54, 97, 124, 138, 163, 179, 209, 229, + 30, 38, 56, 89, 118, 129, 158, 178, 200, 231, + 21, 29, 49, 63, 85, 111, 142, 163, 193, 222, + 27, 48, 77, 103, 133, 158, 179, 196, 215, 232, + 29, 47, 74, 99, 124, 151, 176, 198, 220, 237, + 33, 42, 61, 76, 93, 121, 155, 174, 207, 225, + 29, 53, 87, 112, 136, 154, 170, 188, 208, 227, + 24, 30, 52, 84, 131, 150, 166, 186, 203, 229, + 37, 48, 64, 84, 104, 118, 156, 177, 201, 230, +]; + +# Its weights, in Q9. +const silk_nlsf_cb1_wght_nb_mb_q9: i16[320] = [ + 2897, 2314, 2314, 2314, 2287, 2287, 2314, 2300, 2327, 2287, + 2888, 2580, 2394, 2367, 2314, 2274, 2274, 2274, 2274, 2194, + 2487, 2340, 2340, 2314, 2314, 2314, 2340, 2340, 2367, 2354, + 3216, 2766, 2340, 2340, 2314, 2274, 2221, 2207, 2261, 2194, + 2460, 2474, 2367, 2394, 2394, 2394, 2394, 2367, 2407, 2314, + 3479, 3056, 2127, 2207, 2274, 2274, 2274, 2287, 2314, 2261, + 3282, 3141, 2580, 2394, 2247, 2221, 2207, 2194, 2194, 2114, + 4096, 3845, 2221, 2620, 2620, 2407, 2314, 2394, 2367, 2074, + 3178, 3244, 2367, 2221, 2553, 2434, 2340, 2314, 2167, 2221, + 3338, 3488, 2726, 2194, 2261, 2460, 2354, 2367, 2207, 2101, + 2354, 2420, 2327, 2367, 2394, 2420, 2420, 2420, 2460, 2367, + 3779, 3629, 2434, 2527, 2367, 2274, 2274, 2300, 2207, 2048, + 3254, 3225, 2713, 2846, 2447, 2327, 2300, 2300, 2274, 2127, + 3263, 3300, 2753, 2806, 2447, 2261, 2261, 2247, 2127, 2101, + 2873, 2981, 2633, 2367, 2407, 2354, 2194, 2247, 2247, 2114, + 3225, 3197, 2633, 2580, 2274, 2181, 2247, 2221, 2221, 2141, + 3178, 3310, 2740, 2407, 2274, 2274, 2274, 2287, 2194, 2114, + 3141, 3272, 2460, 2061, 2287, 2500, 2367, 2487, 2434, 2181, + 3507, 3282, 2314, 2700, 2647, 2474, 2367, 2394, 2340, 2127, + 3423, 3535, 3038, 3056, 2300, 1950, 2221, 2274, 2274, 2274, + 3404, 3366, 2087, 2687, 2873, 2354, 2420, 2274, 2474, 2540, + 3760, 3488, 1950, 2660, 2897, 2527, 2394, 2367, 2460, 2261, + 3028, 3272, 2740, 2888, 2740, 2154, 2127, 2287, 2234, 2247, + 3695, 3657, 2025, 1969, 2660, 2700, 2580, 2500, 2327, 2367, + 3207, 3413, 2354, 2074, 2888, 2888, 2340, 2487, 2247, 2167, + 3338, 3366, 2846, 2780, 2327, 2154, 2274, 2287, 2114, 2061, + 2327, 2300, 2181, 2167, 2181, 2367, 2633, 2700, 2700, 2553, + 2407, 2434, 2221, 2261, 2221, 2221, 2340, 2420, 2607, 2700, + 3038, 3244, 2806, 2888, 2474, 2074, 2300, 2314, 2354, 2380, + 2221, 2154, 2127, 2287, 2500, 2793, 2793, 2620, 2580, 2367, + 3676, 3713, 2234, 1838, 2181, 2753, 2726, 2673, 2513, 2207, + 2793, 3160, 2726, 2553, 2846, 2513, 2181, 2394, 2221, 2181, +]; + +# Its first stage's vectors, of unvoiced then voiced frames. +const silk_nlsf_cb1_icdf_nb_mb: u8[64] = [ + 212, 178, 148, 129, 108, 96, 85, 82, 79, 77, 61, 59, 57, 56, 51, 49, + 48, 45, 42, 41, 40, 38, 36, 34, 31, 30, 21, 12, 10, 3, 1, 0, + 255, 245, 244, 236, 233, 225, 217, 203, 190, 176, 175, 161, 149, 136, 125, 114, + 102, 91, 81, 71, 60, 52, 43, 35, 28, 20, 19, 18, 12, 11, 5, 0, +]; + +# Which second stage each pair of coefficients of each vector reads. +const silk_nlsf_cb2_select_nb_mb: u8[160] = [ + 16, 0, 0, 0, 0, + 99, 66, 36, 36, 34, + 36, 34, 34, 34, 34, + 83, 69, 36, 52, 34, + 116, 102, 70, 68, 68, + 176, 102, 68, 68, 34, + 65, 85, 68, 84, 36, + 116, 141, 152, 139, 170, + 132, 187, 184, 216, 137, + 132, 249, 168, 185, 139, + 104, 102, 100, 68, 68, + 178, 218, 185, 185, 170, + 244, 216, 187, 187, 170, + 244, 187, 187, 219, 138, + 103, 155, 184, 185, 137, + 116, 183, 155, 152, 136, + 132, 217, 184, 184, 170, + 164, 217, 171, 155, 139, + 244, 169, 184, 185, 170, + 164, 216, 223, 218, 138, + 214, 143, 188, 218, 168, + 244, 141, 136, 155, 170, + 168, 138, 220, 219, 139, + 164, 219, 202, 216, 137, + 168, 186, 246, 185, 139, + 116, 185, 219, 185, 138, + 100, 100, 134, 100, 102, + 34, 68, 68, 100, 68, + 168, 203, 221, 218, 168, + 167, 154, 136, 104, 70, + 164, 246, 171, 137, 139, + 137, 155, 218, 219, 139, +]; + +# Its second stages. +const silk_nlsf_cb2_icdf_nb_mb: u8[72] = [ + 255, 254, 253, 238, 14, 3, 2, 1, 0, + 255, 254, 252, 218, 35, 3, 2, 1, 0, + 255, 254, 250, 208, 59, 4, 2, 1, 0, + 255, 254, 246, 194, 71, 10, 2, 1, 0, + 255, 252, 236, 183, 82, 8, 2, 1, 0, + 255, 252, 235, 180, 90, 17, 2, 1, 0, + 255, 248, 224, 171, 97, 30, 4, 1, 0, + 255, 254, 236, 173, 95, 37, 7, 1, 0, +]; + +# Its residuals' predictors, in Q8. +const silk_nlsf_pred_nb_mb_q8: u8[18] = [ + 179, 138, 140, 148, 151, 149, 153, 151, 163, + 116, 67, 82, 59, 92, 72, 100, 89, 92, +]; + +# The least space between its NLSFs, in Q15. +const silk_nlsf_delta_min_nb_mb_q15: i16[11] = [ + 250, 3, 6, 3, 3, 3, 4, 3, 3, 3, 461, +]; + +# The NLSF codebook of wide band, of 32 vectors of 16, as above. +const silk_nlsf_cb1_wb_q8: u8[512] = [ + 7, 23, 38, 54, 69, 85, 100, 116, 131, 147, 162, 178, 193, 208, 223, 239, + 13, 25, 41, 55, 69, 83, 98, 112, 127, 142, 157, 171, 187, 203, 220, 236, + 15, 21, 34, 51, 61, 78, 92, 106, 126, 136, 152, 167, 185, 205, 225, 240, + 10, 21, 36, 50, 63, 79, 95, 110, 126, 141, 157, 173, 189, 205, 221, 237, + 17, 20, 37, 51, 59, 78, 89, 107, 123, 134, 150, 164, 184, 205, 224, 240, + 10, 15, 32, 51, 67, 81, 96, 112, 129, 142, 158, 173, 189, 204, 220, 236, + 8, 21, 37, 51, 65, 79, 98, 113, 126, 138, 155, 168, 179, 192, 209, 218, + 12, 15, 34, 55, 63, 78, 87, 108, 118, 131, 148, 167, 185, 203, 219, 236, + 16, 19, 32, 36, 56, 79, 91, 108, 118, 136, 154, 171, 186, 204, 220, 237, + 11, 28, 43, 58, 74, 89, 105, 120, 135, 150, 165, 180, 196, 211, 226, 241, + 6, 16, 33, 46, 60, 75, 92, 107, 123, 137, 156, 169, 185, 199, 214, 225, + 11, 19, 30, 44, 57, 74, 89, 105, 121, 135, 152, 169, 186, 202, 218, 234, + 12, 19, 29, 46, 57, 71, 88, 100, 120, 132, 148, 165, 182, 199, 216, 233, + 17, 23, 35, 46, 56, 77, 92, 106, 123, 134, 152, 167, 185, 204, 222, 237, + 14, 17, 45, 53, 63, 75, 89, 107, 115, 132, 151, 171, 188, 206, 221, 240, + 9, 16, 29, 40, 56, 71, 88, 103, 119, 137, 154, 171, 189, 205, 222, 237, + 16, 19, 36, 48, 57, 76, 87, 105, 118, 132, 150, 167, 185, 202, 218, 236, + 12, 17, 29, 54, 71, 81, 94, 104, 126, 136, 149, 164, 182, 201, 221, 237, + 15, 28, 47, 62, 79, 97, 115, 129, 142, 155, 168, 180, 194, 208, 223, 238, + 8, 14, 30, 45, 62, 78, 94, 111, 127, 143, 159, 175, 192, 207, 223, 239, + 17, 30, 49, 62, 79, 92, 107, 119, 132, 145, 160, 174, 190, 204, 220, 235, + 14, 19, 36, 45, 61, 76, 91, 108, 121, 138, 154, 172, 189, 205, 222, 238, + 12, 18, 31, 45, 60, 76, 91, 107, 123, 138, 154, 171, 187, 204, 221, 236, + 13, 17, 31, 43, 53, 70, 83, 103, 114, 131, 149, 167, 185, 203, 220, 237, + 17, 22, 35, 42, 58, 78, 93, 110, 125, 139, 155, 170, 188, 206, 224, 240, + 8, 15, 34, 50, 67, 83, 99, 115, 131, 146, 162, 178, 193, 209, 224, 239, + 13, 16, 41, 66, 73, 86, 95, 111, 128, 137, 150, 163, 183, 206, 225, 241, + 17, 25, 37, 52, 63, 75, 92, 102, 119, 132, 144, 160, 175, 191, 212, 231, + 19, 31, 49, 65, 83, 100, 117, 133, 147, 161, 174, 187, 200, 213, 227, 242, + 18, 31, 52, 68, 88, 103, 117, 126, 138, 149, 163, 177, 192, 207, 223, 239, + 16, 29, 47, 61, 76, 90, 106, 119, 133, 147, 161, 176, 193, 209, 224, 240, + 15, 21, 35, 50, 61, 73, 86, 97, 110, 119, 129, 141, 175, 198, 218, 237, +]; + +# +const silk_nlsf_cb1_wght_wb_q9: i16[512] = [ + 3657, 2925, 2925, 2925, 2925, 2925, 2925, 2925, 2925, 2925, 2925, 2925, 2963, 2963, 2925, 2846, + 3216, 3085, 2972, 3056, 3056, 3010, 3010, 3010, 2963, 2963, 3010, 2972, 2888, 2846, 2846, 2726, + 3920, 4014, 2981, 3207, 3207, 2934, 3056, 2846, 3122, 3244, 2925, 2846, 2620, 2553, 2780, 2925, + 3516, 3197, 3010, 3103, 3019, 2888, 2925, 2925, 2925, 2925, 2888, 2888, 2888, 2888, 2888, 2753, + 5054, 5054, 2934, 3573, 3385, 3056, 3085, 2793, 3160, 3160, 2972, 2846, 2513, 2540, 2753, 2888, + 4428, 4149, 2700, 2753, 2972, 3010, 2925, 2846, 2981, 3019, 2925, 2925, 2925, 2925, 2888, 2726, + 3620, 3019, 2972, 3056, 3056, 2873, 2806, 3056, 3216, 3047, 2981, 3291, 3291, 2981, 3310, 2991, + 5227, 5014, 2540, 3338, 3526, 3385, 3197, 3094, 3376, 2981, 2700, 2647, 2687, 2793, 2846, 2673, + 5081, 5174, 4615, 4428, 2460, 2897, 3047, 3207, 3169, 2687, 2740, 2888, 2846, 2793, 2846, 2700, + 3122, 2888, 2963, 2925, 2925, 2925, 2925, 2963, 2963, 2963, 2963, 2925, 2925, 2963, 2963, 2963, + 4202, 3207, 2981, 3103, 3010, 2888, 2888, 2925, 2972, 2873, 2916, 3019, 2972, 3010, 3197, 2873, + 3760, 3760, 3244, 3103, 2981, 2888, 2925, 2888, 2972, 2934, 2793, 2793, 2846, 2888, 2888, 2660, + 3854, 4014, 3207, 3122, 3244, 2934, 3047, 2963, 2963, 3085, 2846, 2793, 2793, 2793, 2793, 2580, + 3845, 4080, 3357, 3516, 3094, 2740, 3010, 2934, 3122, 3085, 2846, 2846, 2647, 2647, 2846, 2806, + 5147, 4894, 3225, 3845, 3441, 3169, 2897, 3413, 3451, 2700, 2580, 2673, 2740, 2846, 2806, 2753, + 4109, 3789, 3291, 3160, 2925, 2888, 2888, 2925, 2793, 2740, 2793, 2740, 2793, 2846, 2888, 2806, + 5081, 5054, 3047, 3545, 3244, 3056, 3085, 2944, 3103, 2897, 2740, 2740, 2740, 2846, 2793, 2620, + 4309, 4309, 2860, 2527, 3207, 3376, 3376, 3075, 3075, 3376, 3056, 2846, 2647, 2580, 2726, 2753, + 3056, 2916, 2806, 2888, 2740, 2687, 2897, 3103, 3150, 3150, 3216, 3169, 3056, 3010, 2963, 2846, + 4375, 3882, 2925, 2888, 2846, 2888, 2846, 2846, 2888, 2888, 2888, 2846, 2888, 2925, 2888, 2846, + 2981, 2916, 2916, 2981, 2981, 3056, 3122, 3216, 3150, 3056, 3010, 2972, 2972, 2972, 2925, 2740, + 4229, 4149, 3310, 3347, 2925, 2963, 2888, 2981, 2981, 2846, 2793, 2740, 2846, 2846, 2846, 2793, + 4080, 4014, 3103, 3010, 2925, 2925, 2925, 2888, 2925, 2925, 2846, 2846, 2846, 2793, 2888, 2780, + 4615, 4575, 3169, 3441, 3207, 2981, 2897, 3038, 3122, 2740, 2687, 2687, 2687, 2740, 2793, 2700, + 4149, 4269, 3789, 3657, 2726, 2780, 2888, 2888, 3010, 2972, 2925, 2846, 2687, 2687, 2793, 2888, + 4215, 3554, 2753, 2846, 2846, 2888, 2888, 2888, 2925, 2925, 2888, 2925, 2925, 2925, 2963, 2888, + 5174, 4921, 2261, 3432, 3789, 3479, 3347, 2846, 3310, 3479, 3150, 2897, 2460, 2487, 2753, 2925, + 3451, 3685, 3122, 3197, 3357, 3047, 3207, 3207, 2981, 3216, 3085, 2925, 2925, 2687, 2540, 2434, + 2981, 3010, 2793, 2793, 2740, 2793, 2846, 2972, 3056, 3103, 3150, 3150, 3150, 3103, 3010, 3010, + 2944, 2873, 2687, 2726, 2780, 3010, 3432, 3545, 3357, 3244, 3056, 3010, 2963, 2925, 2888, 2846, + 3019, 2944, 2897, 3010, 3010, 2972, 3019, 3103, 3056, 3056, 3010, 2888, 2846, 2925, 2925, 2888, + 3920, 3967, 3010, 3197, 3357, 3216, 3291, 3291, 3479, 3704, 3441, 2726, 2181, 2460, 2580, 2607, +]; + +# +const silk_nlsf_cb1_icdf_wb: u8[64] = [ + 225, 204, 201, 184, 183, 175, 158, 154, 153, 135, 119, 115, 113, 110, 109, 99, + 98, 95, 79, 68, 52, 50, 48, 45, 43, 32, 31, 27, 18, 10, 3, 0, + 255, 251, 235, 230, 212, 201, 196, 182, 167, 166, 163, 151, 138, 124, 110, 104, + 90, 78, 76, 70, 69, 57, 45, 34, 24, 21, 11, 6, 5, 4, 3, 0, +]; + +# +const silk_nlsf_cb2_select_wb: u8[256] = [ + 0, 0, 0, 0, 0, 0, 0, 1, + 100, 102, 102, 68, 68, 36, 34, 96, + 164, 107, 158, 185, 180, 185, 139, 102, + 64, 66, 36, 34, 34, 0, 1, 32, + 208, 139, 141, 191, 152, 185, 155, 104, + 96, 171, 104, 166, 102, 102, 102, 132, + 1, 0, 0, 0, 0, 16, 16, 0, + 80, 109, 78, 107, 185, 139, 103, 101, + 208, 212, 141, 139, 173, 153, 123, 103, + 36, 0, 0, 0, 0, 0, 0, 1, + 48, 0, 0, 0, 0, 0, 0, 32, + 68, 135, 123, 119, 119, 103, 69, 98, + 68, 103, 120, 118, 118, 102, 71, 98, + 134, 136, 157, 184, 182, 153, 139, 134, + 208, 168, 248, 75, 189, 143, 121, 107, + 32, 49, 34, 34, 34, 0, 17, 2, + 210, 235, 139, 123, 185, 137, 105, 134, + 98, 135, 104, 182, 100, 183, 171, 134, + 100, 70, 68, 70, 66, 66, 34, 131, + 64, 166, 102, 68, 36, 2, 1, 0, + 134, 166, 102, 68, 34, 34, 66, 132, + 212, 246, 158, 139, 107, 107, 87, 102, + 100, 219, 125, 122, 137, 118, 103, 132, + 114, 135, 137, 105, 171, 106, 50, 34, + 164, 214, 141, 143, 185, 151, 121, 103, + 192, 34, 0, 0, 0, 0, 0, 1, + 208, 109, 74, 187, 134, 249, 159, 137, + 102, 110, 154, 118, 87, 101, 119, 101, + 0, 2, 0, 36, 36, 66, 68, 35, + 96, 164, 102, 100, 36, 0, 2, 33, + 167, 138, 174, 102, 100, 84, 2, 2, + 100, 107, 120, 119, 36, 197, 24, 0, +]; + +# +const silk_nlsf_cb2_icdf_wb: u8[72] = [ + 255, 254, 253, 244, 12, 3, 2, 1, 0, + 255, 254, 252, 224, 38, 3, 2, 1, 0, + 255, 254, 251, 209, 57, 4, 2, 1, 0, + 255, 254, 244, 195, 69, 4, 2, 1, 0, + 255, 251, 232, 184, 84, 7, 2, 1, 0, + 255, 254, 240, 186, 86, 14, 2, 1, 0, + 255, 254, 239, 178, 91, 30, 5, 1, 0, + 255, 248, 227, 177, 100, 19, 2, 1, 0, +]; + +# +const silk_nlsf_pred_wb_q8: u8[30] = [ + 175, 148, 160, 176, 178, 173, 174, 164, 177, 174, 196, 182, 198, 192, 182, + 68, 62, 66, 60, 72, 117, 85, 90, 118, 136, 151, 142, 160, 142, 155, +]; + +# +const silk_nlsf_delta_min_wb_q15: i16[17] = [ + 100, 3, 40, 3, 3, 3, 5, 14, 14, 10, 11, 3, 8, 9, 7, 3, + 347, +]; + +# Twice the cosine of an NLSF, in Q12, of 128 steps. +const silk_lsf_cos_tab_q12: i16[129] = [ + 8192, 8190, 8182, 8170, 8152, 8130, 8104, 8072, 8034, 7994, 7946, 7896, 7840, 7778, 7714, 7644, + 7568, 7490, 7406, 7318, 7226, 7128, 7026, 6922, 6812, 6698, 6580, 6458, 6332, 6204, 6070, 5934, + 5792, 5648, 5502, 5352, 5198, 5040, 4880, 4718, 4552, 4382, 4212, 4038, 3862, 3684, 3502, 3320, + 3136, 2948, 2760, 2570, 2378, 2186, 1990, 1794, 1598, 1400, 1202, 1002, 802, 602, 402, 202, + 0, -202, -402, -602, -802, -1002, -1202, -1400, -1598, -1794, -1990, -2186, -2378, -2570, -2760, -2948, + -3136, -3320, -3502, -3684, -3862, -4038, -4212, -4382, -4552, -4718, -4880, -5040, -5198, -5352, -5502, -5648, + -5792, -5934, -6070, -6204, -6332, -6458, -6580, -6698, -6812, -6922, -7026, -7128, -7226, -7318, -7406, -7490, + -7568, -7644, -7714, -7778, -7840, -7896, -7946, -7994, -8034, -8072, -8104, -8130, -8152, -8170, -8182, -8190, + -8192, +]; + +# The pitch contours' lags, of each subframe: of 20 ms frames at 8 kHz, above, then of 10 ms. +const silk_cb_lags_stage2: i8[44] = [ + 0, 2, -1, -1, -1, 0, 0, 1, 1, 0, 1, + 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, + 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, + 0, -1, 2, 1, 0, 1, 1, 0, 0, -1, -1, +]; + +# +const silk_cb_lags_stage3: i8[136] = [ + 0, 0, 1, -1, 0, 1, -1, 0, -1, 1, -2, 2, -2, -2, 2, -3, 2, 3, -3, -4, 3, -4, 4, 4, -5, 5, -6, -5, 6, -7, 6, 5, 8, -9, + 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, -1, 1, 0, 0, 1, -1, 0, 1, -1, -1, 1, -1, 2, 1, -1, 2, -2, -2, 2, -2, 2, 2, 3, -3, + 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, -1, 1, 0, 0, 2, 1, -1, 2, -1, -1, 2, -1, 2, 2, -1, 3, -2, -2, -2, 3, + 0, 1, 0, 0, 1, 0, 1, -1, 2, -1, 2, -1, 2, 3, -2, 3, -2, -2, 4, 4, -3, 5, -3, -4, 6, -4, 6, 5, -5, 8, -6, -5, -7, 9, +]; + +# +const silk_cb_lags_stage2_10_ms: i8[6] = [ + 0, 1, 0, + 0, 0, 1, +]; + +# +const silk_cb_lags_stage3_10_ms: i8[24] = [ + 0, 0, 1, -1, 1, -1, 2, -2, 2, -2, 3, -3, + 0, 1, 0, 1, -1, 2, -1, 2, -2, 3, -2, 3, +]; + +# The resampler's interpolating filter, half of each of 12 phases, in Q15. +const silk_resampler_frac_fir_12: i16[48] = [ + 189, -600, 617, 30567, + 117, -159, -1070, 29704, + 52, 221, -2392, 28276, + -4, 529, -3350, 26341, + -48, 758, -3956, 23973, + -80, 905, -4235, 21254, + -99, 972, -4222, 18278, + -107, 967, -3957, 15143, + -103, 896, -3487, 11950, + -91, 773, -2865, 8798, + -71, 611, -2143, 5784, + -46, 425, -1375, 2996, +]; diff --git a/audio/output.sakura b/audio/output.sakura new file mode 100644 index 0000000..38fee55 --- /dev/null +++ b/audio/output.sakura @@ -0,0 +1,177 @@ +#! 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, as `wasapi.sakura` says: the one asked +#! for, by its name or id, or the default, followed as another is made the +#! default. A device lost, as headphones unplugged are, is opened again as soon +#! as there's one to open; 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. + var wanted: string; # The name or id of the device asked for, or none, for the default. +} + +#! A device the system plays sound to. +pub struct audio_device { + pub var name: string; #! What the system calls it, as its sound settings show it. + pub var id: string; #! What it's known by, which stays the same as its name may not. + pub var is_default: bool; #! Whether it's the system's default. +} + +#! 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. +} + +#! The devices the system plays sound to, those plugged in and on: none where +#! there's no audio service, or elsewhere than Windows yet. +pub def audio_output::devices(): vector { + return system_devices(); +} + +#! Opens an 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. +#! @param device The device's name or id, as `devices` gives them; or none, +#! for the system's default, followed as another is made the +#! default. +#! @returns The output, mixing at the device's rate, or why the device couldn't +#! be opened: `no_device` where there's none, or none of the name, or +#! no audio service, and `refused` where it wouldn't play as asked. +pub def audio_output::open(latency: f32 = 0.02, device: strview = ""): result { + var made := audio_output::made(48000, latency); + made.shared.get().wanted = string::from(device, nothing{}); + 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), wanted = string::new(nothing{}), + }; + 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.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 a compressed 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.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/streams.sakura b/audio/streams.sakura new file mode 100644 index 0000000..b7e30a3 --- /dev/null +++ b/audio/streams.sakura @@ -0,0 +1,94 @@ +#! Contains `stream`, the decoder of a file of any format played as it's +#! decoded, which a mixer's streamed voices read: Ogg Vorbis, FLAC, or MP3. + +module malunal::audio; + + +# The decoder a stream holds, one field for each format. +union stream_decoder { + var vorbis: audio::vorbis::decoder; + var flac: audio::flac::decoder; + var mp3: audio::mp3::decoder; + var opus: audio::opus::decoder; +} + +#! Reads a file's frames as it's asked for them, whichever format it's in, as +#! its format's decoder does. Its bytes must stay where they are while it reads +#! them. +pub struct stream { + var held: stream_decoder; +} + +#! Opens a stream, of a format its bytes' first few say. +#! @param bytes The file's bytes, which must stay where they are while it's +#! read. +#! @returns The stream, or why it can't be read: `unsupported` for WAV, which is +#! read whole, and otherwise as its format's decoder says. +pub def stream::open(bytes: span): result { + val which := format_of(bytes) else { return audio_error::unrecognized; }; + match which { + vorbis => { + var made := audio::vorbis::decoder::open(bytes) else (e) { return e; }; + return stream{ held = stream_decoder{ vorbis = move(&mut made) } }; + } + flac => { + var made := audio::flac::decoder::open(bytes) else (e) { return e; }; + return stream{ held = stream_decoder{ flac = move(&mut made) } }; + } + mp3 => { + var made := audio::mp3::decoder::open(bytes) else (e) { return e; }; + return stream{ held = stream_decoder{ mp3 = move(&mut made) } }; + } + opus => { + var made := audio::opus::decoder::open(bytes) else (e) { return e; }; + return stream{ held = stream_decoder{ opus = move(&mut made) } }; + } + else => return audio_error::unsupported; + } +} + +#! How many channels the frames read have: one, or two. +pub val stream::channels: u32 { + get => match this.held { vorbis(&d) => d.channels, flac(&d) => d.channels, mp3(&d) => d.channels, opus(&d) => d.channels }; +} + +#! Frames a second. +pub val stream::rate: u32 { + get => match this.held { vorbis(&d) => d.rate, flac(&d) => d.rate, mp3(&d) => d.rate, opus(&d) => d.rate }; +} + +#! How many frames the stream has, or 0 where it says nothing. +pub val stream::frames: u64 { + get => match this.held { vorbis(&d) => d.frames, flac(&d) => d.frames, mp3(&d) => d.frames, opus(&d) => d.frames }; +} + +#! Where the stream says a voice playing it loops. +pub val stream::loop_points: loop_range { + get => match this.held { vorbis(&d) => d.loop_points, flac(&d) => d.loop_points, mp3(&d) => d.loop_points, opus(&d) => d.loop_points }; +} + +#! 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 stream::read(&mut this, into: slice): result { + return match this.held { vorbis(&mut d) => d.read(into), flac(&mut d) => d.read(into), mp3(&mut d) => d.read(into), opus(&mut d) => d.read(into) }; +} + +#! Reads the stream again from its first frame. +pub def stream::rewind(&mut this): void { + match this.held { + vorbis(&mut d) => d.rewind(); + flac(&mut d) => d.rewind(); + mp3(&mut d) => d.rewind(); + opus(&mut d) => d.rewind(); + } +} + +#! Reads on from a frame of the stream, as exactly as from its start, or of +#! Opus's, within a few ten-thousandths, as its decoder settles. +#! @param frame The frame, past the end where the stream ends there. +#! @returns Nothing, or why the stream couldn't be read. +pub def stream::seek(&mut this, frame: u64): result { + return match this.held { vorbis(&mut d) => d.seek(frame), flac(&mut d) => d.seek(frame), mp3(&mut d) => d.seek(frame), opus(&mut d) => d.seek(frame) }; +} diff --git a/audio/tags.sakura b/audio/tags.sakura new file mode 100644 index 0000000..3a17ff4 --- /dev/null +++ b/audio/tags.sakura @@ -0,0 +1,100 @@ +#! Contains what files say of their sounds besides their samples: where a +#! looping voice goes back to, as the comments of Vorbis, FLAC, and Opus say +#! it, and how far an ID3v2 tag before a file's audio reaches. + +module malunal::audio; + + +#! Reads where a sound loops of a block of comments, as Vorbis, FLAC, and Opus +#! keep them: its vendor's text, then each comment, `KEY=value`, each length +#! four bytes, lowest first. `LOOPSTART` says where a looping voice goes back +#! to, and `LOOPLENGTH`, how far past that it goes back from, or `LOOPEND`, +#! where, each in frames, as RPG Maker and the tools after it write them; their +#! names in any case. +#! @param block The comments, after any header naming them. +#! @returns Where it loops: all of it where they say nothing, or are broken. +pub def loop_of_comments(block: span): loop_range { + var start: u64 = 0; + var length: u64 = 0; + var end: u64 = 0; + var said := false; + return loop_range{} if block.length < 8; + var at := 4 + little_endian(block, 0) as u64; + return loop_range{} if at + 4 > block.length; + val count := little_endian(block, at); + at += 4; + for _ in 0..count { + break if at + 4 > block.length; + val size := little_endian(block, at) as u64; + at += 4; + break if at + size > block.length; + val comment := block[at:size]; + at += size; + var equals := comment.length; + for i in 0..comment.length { + if comment[i] == '=' { + equals = i; + break; + } + } + continue if equals == comment.length; + val value := number_of(comment[equals + 1:comment.length - equals - 1]) else { continue; }; + val key := comment[0:equals]; + if named(key, "LOOPSTART") { + start = value; + said = true; + } else if named(key, "LOOPLENGTH") { + length = value; + } else if named(key, "LOOPEND") { + end = value; + } + } + return loop_range{} if !said; + if length > 0 { + end = start + length; + } + return loop_range{} if end != 0 && end <= start; + return loop_range{ start = start, end = end }; +} + +#! Where a file's audio begins past an ID3v2 tag at its start, as MP3 and FLAC +#! files may have, or 0 where it has none. +#! @param bytes The file's bytes. +#! @returns Where the bytes after the tag begin. +pub def past_id3(bytes: span): u64 { + return 0 if bytes.length < 10 || bytes[0] != 'I' || bytes[1] != 'D' || bytes[2] != '3'; + # Its size, of four bytes of seven bits each, then its footer where a flag says. + val size := (bytes[6] as u64 & 0x7F) << 21 | (bytes[7] as u64 & 0x7F) << 14 | (bytes[8] as u64 & 0x7F) << 7 | (bytes[9] as u64 & 0x7F); + val footer: u64 = (bytes[5] & 0x10) != 0 ? 10 : 0; + val end := 10 + size + footer; + return end < bytes.length ? end : bytes.length; +} + +# A number of four bytes, lowest first. +def little_endian(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); +} + +# Whether text is a name, whatever the case of its letters. +def named(text: span, name: strview): bool { + return false if text.length != name.length; + for i in 0..text.length { + var c := text[i]; + if c >= 'a' && c <= 'z' { + c -= 32; + } + return false if c != name[i] as u8; + } + return true; +} + +# A whole number written in decimal, or nothing where it isn't one. +def number_of(text: span): maybe { + return nothing {} if text.length == 0 || text.length > 18; + var value: u64 = 0; + for i in 0..text.length { + return nothing {} if text[i] < '0' || text[i] > '9'; + value = value * 10 + (text[i] - '0') as u64; + } + return value; +} diff --git a/audio/voices.sakura b/audio/voices.sakura new file mode 100644 index 0000000..dc01c37 --- /dev/null +++ b/audio/voices.sakura @@ -0,0 +1,245 @@ +#! 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.span; + var opened := stream::open(bytes) else (_) { return voice{}; }; + var made := streaming{ decoding = move(opened), window = vector::::new(), marks = vector::::new() }; + made.marks.append(stream_mark{}); + 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.waiting = how.delay > 0 ? (how.delay * this.mix_rate as f32) as u64 : 0u; + at.filtering = filters{}; + 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: of a +#! looping one, how far into it this time. +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; + if at.stream is some(&s) { + val marks := &s.get().marks; + var sound := at.position; + for i in 0..marks.length { + break if marks[i].voice as f64 > at.position; + sound = marks[i].sound as f64 + (at.position - marks[i].voice as f64); + } + return sound / rate; + } + return at.position / rate; +} + +#! Plays a voice on from a place in its sound, decoded or streamed, as exactly +#! as from its start, or, streamed of Opus, within a few ten-thousandths; past +#! its end, it ends, or, looping, goes back to where it loops. +#! @param which The voice. +#! @param seconds How far into its sound. +#! @returns Nothing, or why a streamed sound couldn't be read there, which ends +#! the voice. +pub def mixer::seek(&mut this, which: voice, seconds: f64): result { + return if !this.playing(which); + val held := &this.bank[this.voices[which.index as u64].sound.index as u64]; + val rate := held.rate as f64; + var frame := math::max(seconds, 0.0) * rate; + val looped := held.loop_points; + val end := looped.end != 0 && (held.frames == 0 || looped.end < held.frames) ? looped.end : held.frames; + if end > looped.start && frame >= end as f64 && this.voices[which.index as u64].how.looping { + val length := (end - looped.start) as f64; + val past := frame - looped.start as f64; + frame = looped.start as f64 + past - math::floor(past / length) * length; + } + val at := &mut this.voices[which.index as u64]; + if at.stream is some(&mut s) { + val window := &mut s.get(); + # The voice's own frames go on from where it is, its sound's from the frame. + val now := math::floor(at.position) as u64; + val whole := math::floor(frame); + window.window.clear(); + window.base = now; + window.ended = false; + window.marks.clear(); + window.marks.append(stream_mark{ voice = now, sound = whole as u64 }); + window.at = whole as u64; + at.position = now as f64 + (frame - whole); + window.decoding.seek(whole as u64) else (e) { + this.end_voice(which.index as u64); + return e; + }; + return; + } + at.position = frame; + return; +} + +#! 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; +} + +#! A bus's effects, or none of a bus there isn't. +pub def mixer::bus_effects(&this, which: u32): bus_effects { + return which < bus_count ? this.bus_states[which as u64].effects : bus_effects{}; +} + +#! Changes a bus's effects, put on what its voices mix into it, and what's +#! sent to it, before its gain: filters at once, and reverb as soon as the +#! next frames are mixed, its echoes going on after what feeds it ends. +pub def mixer::set_bus_effects(&mut this, which: u32, effects: bus_effects): void { + return if which >= bus_count; + this.bus_states[which as u64].effects = effects; +} + +#! The limiter on the mix, off at first. +pub val mixer::limiting: limiter { + get => this.limits; +} + +#! Changes the limiter on the mix, which, on, has the mix its `lookahead` late. +pub def mixer::set_limiter(&mut this, how: limiter): void { + if how.lookahead != this.limits.lookahead || !how.on { + this.limited = nothing {}; + } + this.limits = how; +} + +#! 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.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..c014b51 --- /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.span, block, this.re.slice, this.im.slice, this.folded.slice); + } else { + this.short.inverse(spectrum.span, 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.span, 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/residues.sakura b/audio/vorbis/residues.sakura new file mode 100644 index 0000000..b95b76b --- /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..f4b015e --- /dev/null +++ b/audio/vorbis/setup.sakura @@ -0,0 +1,252 @@ +#! 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; +} + +# A little-endian u32 at a place. +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/vorbis.sakura b/audio/vorbis/vorbis.sakura new file mode 100644 index 0000000..1d22136 --- /dev/null +++ b/audio/vorbis/vorbis.sakura @@ -0,0 +1,271 @@ +#! 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. Where its +#! comments say it loops, as `audio::loop_of_comments` reads them, so does a +#! voice playing it. A stream is sought by halving the pages between where it +#! could be, by their granule positions. + +import std::math; +import malunal::audio::ogg; +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. + var from: u64; # The frame a seek asked for, before which what's decoded is left out. + var looped: loop_range; # Where its comments say it loops. +} + +#! 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); + made.looped = audio::loop_of_comments(next.data[7:next.data.length - 7]); + } 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 = ogg::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; +} + +#! Where the stream says a voice playing it loops, as its comments say. +pub val decoder::loop_points: loop_range { + get => this.looped; +} + +#! 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; + # What a seek passed, once it's known where it is. + if held > 0 && this.timed && this.from > 0 && this.clock - held < this.from { + val before := this.from - (this.clock - held); + this.taken += (before < held ? before : held) * width; + continue; + } + 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; + this.from = 0; +} + +#! Reads on from a frame of the stream: from the page halving its pages finds +#! a long block or more before it, the frames between left out, as decoding +#! from a page takes a packet before it gives any. +#! @param frame The frame, past the end where the stream ends there. +#! @returns Nothing, or why the stream couldn't be read. +pub def decoder::seek(&mut this, frame: u64): result { + this.rewind(); + this.from = frame; + val margin := this.head.sizes[1] as u64 * 2; + return if frame <= margin; + # From the last page whose granule position is a margin or more before the frame. + this.stream.rewind(ogg::resume_at(this.stream.bytes, this.stream.serial, this.audio_at, frame - margin)); + return; +} + +# 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), loop_points = reading.loop_points }; +} + +# 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..e651db7 --- /dev/null +++ b/audio/wasapi.sakura @@ -0,0 +1,397 @@ +#! Contains the device an output plays to on Windows: a render endpoint of +#! WASAPI's, the one asked for by its name or id, or the default, 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. Playing to the default, it +#! looks every quarter second at which device that is, and moves to another +#! made the default, as the system's settings or headphones plugged in make it. +#! +#! COM's objects are reached through their tables of functions, a method by its +#! place in its interface, as `IMMDeviceEnumerator`, `IMMDeviceCollection`, +#! `IMMDevice`, `IPropertyStore`, `IAudioClient`, and `IAudioRenderClient` +#! order them. + +import system; +import system::windows; +import std::thread; +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; + +# The property of a device's friendly name, `PKEY_Device_FriendlyName`. +const friendly_name: guid = guid{ a = 0xA45C254E, b = 0xDF1C, c = 0x4EFD, d = [0x80, 0x20, 0x67, 0xD1, 0x46, 0xA8, 0x50, 0xE0] }; +const friendly_name_id: u32 = 14; +# COM's error where a thread's COM was begun otherwise, which leaves it begun. +const changed_mode: i32 = -2147417850; + +type release_fn = cfn; +type default_endpoint_fn = cfn; +type endpoints_fn = cfn; +type item_fn = cfn; +type id_fn = cfn; +type store_fn = cfn; +type value_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, its buffer's size, +# and what it's known by. +struct device { + var enumerator: u64; + var endpoint: u64; + var client: u64; + var render: u64; + var event: u64; + var rate: u32; + var frames: u32; + var id: string; +} + +# Text of UTF-16, ending in a zero, as UTF-8. +def text_of(units: *u16): string { + var text := string::new(nothing{}); + return text if units == null; + var count := 0u; + while units[count] != 0 { + count++; + } + return text if count == 0; + val size := WideCharToMultiByte(65001, 0, units, count as i32, null, 0, null, null); + var bytes := vector::::new(); + bytes.resize(size as u64); + _ = WideCharToMultiByte(65001, 0, units, count as i32, bytes.data, size, null, null); + for &byte in bytes { + text.push(byte); + } + return text; +} + +# What a device is known by, which `GetId` gives. +def id_of(endpoint: u64): string { + var units: u64 = 0; + val get_id := method(endpoint, 5) as id_fn; + return string::new(nothing{}) if get_id(endpoint, &mut units) < 0; + val made := text_of(units as *u16); + CoTaskMemFree(units); + return made; +} + +# What the system calls a device, as its property store's friendly name says. +def name_of(endpoint: u64): string { + var store: u64 = 0; + val open_store := method(endpoint, 4) as store_fn; + return string::new(nothing{}) if open_store(endpoint, 0, &mut store) < 0; + # A PROPERTYKEY: the GUID, then its number. + var key: u8[20]; + val name := friendly_name; + memcpy(address(&key) as u64 as *mut u8, address(&name) as u64 as *u8, 16); + for i in 0u..4u { + key[16 + i] = (friendly_name_id >> (i * 8) as u32) as u8; + } + # A PROPVARIANT: its type, then, of text, where the text is. + var value: u8[24]; + val get_value := method(store, 5) as value_fn; + var made := string::new(nothing{}); + if get_value(store, address(&key) as u64 as *u8, address(&mut value) as u64 as *mut u8) >= 0 { + val kind := value[0] as u32 | (value[1] as u32) << 8; + if kind == 31 { + var at: u64 = 0; + for i in 0u..8u { + at = at | (value[8 + i] as u64) << (i * 8) as u32; + } + made = text_of(at as *u16); + } + _ = PropVariantClear(address(&mut value) as u64 as *mut u8); + } + release(store); + return made; +} + +# The system's devices to play to, those plugged in and on, as their names and +# ids say, the default's marked; none where its audio service isn't there. +def system_devices(): vector { + var found := vector::::new(); + val begun := CoInitializeEx(null, COINIT_MULTITHREADED); + var enumerator: u64 = 0; + if CoCreateInstance(&enumerator_class, 0, CLSCTX_ALL, &enumerator_interface, &mut enumerator) >= 0 { + var standing := string::new(nothing{}); + var first: u64 = 0; + val default_endpoint := method(enumerator, 4) as default_endpoint_fn; + if default_endpoint(enumerator, 0, 0, &mut first) >= 0 { + standing = id_of(first); + release(first); + } + var all: u64 = 0; + val endpoints := method(enumerator, 3) as endpoints_fn; + if endpoints(enumerator, 0, 1, &mut all) >= 0 { + var count: u32 = 0; + val get_count := method(all, 3) as count_fn; + _ = get_count(all, &mut count); + val item := method(all, 4) as item_fn; + for i in 0..count { + var endpoint: u64 = 0; + continue if item(all, i, &mut endpoint) < 0; + var id := id_of(endpoint); + val chosen := id.span == standing.span; + found.append(audio_device{ name = name_of(endpoint), id = move(&mut id), is_default = chosen }); + release(endpoint); + } + release(all); + } + release(enumerator); + } + if begun >= 0 { + CoUninitialize(); + } + return found; +} + +# The id of the device a name or id names, among the system's to play to. +def endpoint_named(enumerator: u64, wanted: strview): maybe { + var all: u64 = 0; + val endpoints := method(enumerator, 3) as endpoints_fn; + return nothing {} if endpoints(enumerator, 0, 1, &mut all) < 0; + var count: u32 = 0; + val get_count := method(all, 3) as count_fn; + _ = get_count(all, &mut count); + val item := method(all, 4) as item_fn; + var chosen: maybe = nothing {}; + for i in 0..count { + var endpoint: u64 = 0; + continue if item(all, i, &mut endpoint) < 0; + if id_of(endpoint).span == wanted || name_of(endpoint).span == wanted { + chosen = endpoint; + break; + } + release(endpoint); + } + release(all); + return chosen; +} + +# 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 device a name or id names, or the default where it's empty, and +# starts it. +def open_device(latency: f32, wanted: strview): result { + var d := device{ id = string::new(nothing{}) }; + if CoCreateInstance(&enumerator_class, 0, CLSCTX_ALL, &enumerator_interface, &mut d.enumerator) < 0 { + return audio_error::no_device; + } + if wanted.length == 0 { + 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; + } + } else { + d.endpoint = endpoint_named(d.enumerator, wanted) else { + close_device(&mut d); + return audio_error::no_device; + }; + } + d.id = id_of(d.endpoint); + 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); + val wanted := s.wanted.span; + val following := wanted.length == 0; + var d := open_device(s.latency, wanted) 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); + + # Time is told by the frames played, and the waits that timed out, as the + # thread reads no clock. + var open := true; + var moving := false; # Whether the default moved, so another is opened at once. + var since: u32 = 0; # Frames since which device is the default was looked at. + while s.running.load(order::acquire) == 1 { + if !open { + if !moving { + Sleep(250); + } + moving = false; + var tried := open_device(s.latency, wanted); + if tried is value(&mut again) { + d = move(&mut again); + open = true; + var held := s.mixing.lock(); + held.value().set_rate(d.rate); + } + continue; + } + # Which device is the default, every quarter second, where it's followed. + if following && since >= d.rate / 4 { + since = 0; + var now: u64 = 0; + val endpoint := method(d.enumerator, 4) as default_endpoint_fn; + if endpoint(d.enumerator, 0, 0, &mut now) >= 0 { + val other := id_of(now).span != d.id.span; + release(now); + if other { + close_device(&mut d); + open = false; + moving = true; + continue; + } + } + } + if WaitForSingleObject(d.event, 50) != 0 { + since += d.rate / 20; + } + 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); + since += free; + } + 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..8e67493 --- /dev/null +++ b/audio/wav/wav.sakura @@ -0,0 +1,236 @@ +#! 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. A +#! `smpl` chunk's first loop says where a looping voice goes back to, and from +#! where. Other chunks, as `LIST`, are skipped. +#! +#! A sound is written as PCM of 16 bits, rounded, or as 32-bit floats, and +#! its loop points, where it has any, as a `smpl` chunk's loop. + +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 loop_points := loop_range{}; + 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] == 's' && id[1] == 'm' && id[2] == 'p' && id[3] == 'l' { + # The first loop of a sampler's chunk, its end the last frame it plays. + if size >= 60 && body + 60 <= bytes.length && u32_at(bytes, body + 28) > 0 { + loop_points = loop_range{ start = u32_at(bytes, body + 44) as u64, end = u32_at(bytes, body + 48) as u64 + 1 }; + } + } 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), loop_points = loop_points } 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] = audio::standard_speaker(channels, c); + } + } + var two := vector::::new(); + two.resize(frames * 2); + audio::downmix(samples.span, frames, speakers[0:channels as u64], two.slice); + return sound{ rate = rate, channels = 2, samples = move(two), loop_points = loop_points }; +} + +#! 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; + val looped := played.loop_points; + val sampler: u64 = looped.start != 0 || looped.end != 0 ? 68 : 0; + return audio_error::too_large if data_length + 36 + sampler > 0xFFFFFFFF; + + var out := vector::::new(); + out.reserve(44 + data_length); + put_text(&mut out, "RIFF"); + put_u32(&mut out, (36 + data_length + sampler) 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); + } + } + if sampler > 0 { + # One loop, forward, its end the last frame it plays. + put_text(&mut out, "smpl"); + put_u32(&mut out, 60); + for _ in 0..7 { + put_u32(&mut out, 0); + } + put_u32(&mut out, 1); + put_u32(&mut out, 0); + put_u32(&mut out, 0); + put_u32(&mut out, 0); + val end := looped.end != 0 ? looped.end : played.frames; + put_u32(&mut out, looped.start as u32); + put_u32(&mut out, (end - 1) as u32); + put_u32(&mut out, 0); + put_u32(&mut out, 0); + } + 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; +} + + +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..2c7635d --- /dev/null +++ b/audio/windows/ole32.sakura @@ -0,0 +1,24 @@ +#! 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 def PropVariantClear(value: *mut u8): i32; + +pub const COINIT_MULTITHREADED: u32 = 0; +pub const CLSCTX_ALL: u32 = 0x17; diff --git a/blossomfile b/blossomfile new file mode 100644 index 0000000..7847cbc --- /dev/null +++ b/blossomfile @@ -0,0 +1,60 @@ +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 + +# 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/flacs.sakura + - tests/flac.sakura + - tests/mp3.sakura + - tests/opus.sakura + - tests/mixer.sakura + - tests/effects.sakura + - tests/output.sakura + +exports: +- malunal.audio + +package: + desc: Sound read from WAV, Ogg Vorbis, FLAC, MP3, and Ogg Opus, mixed, filtered, reverberated, limited, and played, as voices of a mixer a device pulls from, compressed files streamed and sought as they play. + auth: John Christman diff --git a/tests/effects.sakura b/tests/effects.sakura new file mode 100644 index 0000000..48acbec --- /dev/null +++ b/tests/effects.sakura @@ -0,0 +1,100 @@ +#! Contains the tests of effects: voices and buses filtered, low and high pass; +#! a voice sent to a bus of reverb, whose echoes go on after it ends and die +#! away; and the limiter, holding the mix at its ceiling, and passing what's +#! below it as it is, its lookahead late. + +import std::math; +import std::testing; +import malunal::audio; + +# The root of the mean of the squares of the left of frames, from one to +# another. +def left_level(frames: &vector, from: u64, to: u64): f32 { + var sum: f64 = 0; + for i in from..to { + sum += (frames[i * 2] * frames[i * 2]) as f64; + } + return math::sqrt(sum / (to - from) as f64) as f32; +} + +@test def filters_voices_and_buses(t: &mut tester): void { + var m := mixer::new(48000); + val low := m.add(sound::tone(100, 1, 48000, 1)); + val high := m.add(sound::tone(5000, 1, 48000, 1)); + # A sine of 1 has a level of 0.707. + val v := m.play(high, playback{ pan = -1, low_pass = 500 }); + val muffled := mixed(&mut m, 4800); + t.expects(left_level(&muffled, 2400, 4800) < 0.01); + m.change(v, playback{ pan = -1 }); + val clear := mixed(&mut m, 4800); + t.expects(math::abs(left_level(&clear, 2400, 4800) - 0.707) < 0.01); + m.stop(v); + + val w := m.play(low, playback{ pan = -1, high_pass = 1000 }); + val thin := mixed(&mut m, 4800); + t.expects(left_level(&thin, 2400, 4800) < 0.01); + m.stop(w); + + # A bus's filters put on every voice of it. + m.set_bus_effects(2, bus_effects{ low_pass = 500 }); + t.expects(m.bus_effects(2).low_pass == 500); + _ = m.play(high, playback{ pan = -1, bus = 2 }); + _ = m.play(low, playback{ pan = -1, bus = 2 }); + val both := mixed(&mut m, 4800); + t.expects(math::abs(left_level(&both, 2400, 4800) - 0.707) < 0.03); +} + +@test def sends_voices_to_a_bus_of_reverb(t: &mut tester): void { + var m := mixer::new(48000); + val impulse: f32[4] = [1, 0, 0, 0]; + val click := m.add(sound::of(48000, 1, impulse[:])); + m.set_bus_effects(1, bus_effects{ reverb = reverb{ wet = 1, dry = 0, room = 0.8 } }); + t.expects(m.bus_effects(1).reverb.wet == 1); + _ = m.play(click, playback{ pan = -1, send = 1, send_bus = 1 }); + val heard := mixed(&mut m, 48000); + # The click, then its echoes, after it ended, dying away. + t.expects(heard[0] == 1 && m.voice_count() == 0); + val early := left_level(&heard, 2000, 6000); + val late := left_level(&heard, 40000, 44000); + t.expects(early > 0.001 && late < early / 4 && late > 0); + + # Unsent, a voice has no echoes. + var plain := mixer::new(48000); + val again := plain.add(sound::of(48000, 1, impulse[:])); + plain.set_bus_effects(1, bus_effects{ reverb = reverb{ wet = 1, dry = 0 } }); + _ = plain.play(again, playback{ pan = -1 }); + val dry := mixed(&mut plain, 6000); + t.expects(left_level(&dry, 2000, 6000) == 0); +} + +@test def limits_the_mix_to_its_ceiling(t: &mut tester): void { + var m := mixer::new(48000); + val loud := m.add(sound::tone(200, 1, 48000, 0.6)); + m.set_limiter(limiter{ on = true, ceiling = 0.9, lookahead = 0.001 }); + t.expects(m.limiting.on && m.limiting.ceiling == 0.9); + for _ in 0..3 { + _ = m.play(loud, playback{ pan = -1 }); + } + # Three of 0.6 would reach 1.8: none past 0.9, and near it at the peaks. + val out := mixed(&mut m, 9600); + var most: f32 = 0; + for i in 0..9600u { + most = math::max(most, math::abs(out[i * 2])); + } + t.expects(most <= 0.9 + 1e-5 && most > 0.85); + + # What's below the ceiling is as it was, 48 frames late. + var calm := mixer::new(48000); + val soft := calm.add(sound::tone(200, 1, 48000, 0.5)); + calm.set_limiter(limiter{ on = true, ceiling = 0.9, lookahead = 0.001 }); + _ = calm.play(soft, playback{ pan = -1 }); + val late := mixed(&mut calm, 4800); + var unlimited := mixer::new(48000); + _ = unlimited.play(unlimited.add(sound::tone(200, 1, 48000, 0.5)), playback{ pan = -1 }); + val plain := mixed(&mut unlimited, 4800); + var worst: f32 = 0; + for i in 48..4800u { + worst = math::max(worst, math::abs(late[i * 2] - plain[(i - 48) * 2])); + } + t.expects(worst < 1e-6 && late[0] == 0); +} diff --git a/tests/files/tone.mp3 b/tests/files/tone.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..47208e6c9dc437e3f0a5ec64e2bb10482353a75b GIT binary patch literal 18853 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 TBz}`bnt3A-^-aPd!?6DWd%In~ literal 0 HcmV?d00001 diff --git a/tests/files/tone16.opus b/tests/files/tone16.opus new file mode 100644 index 0000000000000000000000000000000000000000..c29d4cb6e52ba08921da1ac9cb591d5d961c9d02 GIT binary patch literal 2071 zcmY+Fc|6qJ7st&rDHJ8i&d?)d8QXY>u`^#}OQf=d8Geyz2EVK`1|drk5z1riifI^G z$~H0Rp;wkdj5XWH60)m2#?-IZ@4W7Pz0N(K_dWOCbN@KjUS4)=f3W>D@z0hmOgB|_ ziUQ)Z#{AbGK)E47AWaZK_W-eG;{P)y4%%Ox`M#MC(qQ73+`Rm`_ahhFZhLB|Dyi%b zWo0J9zduoEk6TETAN>DBRz^bIzP@kFjLh4-RpnAwJ+Ce&13jmt0F_fvmsXThP>_|E zmQhetmX}e0oDr8477!H_gGh==3Wx~{3JM8{2%H9@(3}jljzM?s)L^J=IGVvumW|D_ z=nTkE06z(Ck<4r)b;yObZtF{z4!$CgR0Vu%=WfwlQfwgrIenCNgXm1OZ0%>P1`IhU zS5|p;MurW}jDZvXBi?-GeOszM-#ZxOgMl_D0v3I11xb zwm4oGp`<%;jSe5GDfzUGCXfq+tF^0)AVMKL*Nu$H&xK_>!<9QT{oCp0&1JCK>?zNz_^e1%UY{MOk9COQ z$p}#{N1DwCf;$txwR}gq%}2)1$bCn}iTcetNOtKpnN|@MV3V57zD1XQ6D?JIoe82a zs2e{z5?aesoU@@Ryo&)66HW4R@^i7}M6Au;*(PWkJv=NbfW~4E>fp#_l3O8a;b;2S zu1CbMgP%N>C(w{T!C3${Z5~ytljqw#XEhnNTk-}dj1>2?HmH{Hnzt2WKsOf+IF>3T zjJ%4Ei8h&`x4J{qzf8ISMIMw`DHt8I(oiA6mJ-P{U>PKjKms5 z7Htl^;8VL2H+>c}eb-y?NU{rNIZ6L+gtNam{ZldD$! zH+mtmM>b_6fb`D?yaBL}Ik2s$1g#3nj=IHg!iKU2IqT#Iil>JXd&vgji_1zNzK(df z^jw}B6(B_yjYy{Z3uTs7wtTJ^&d{TyHEg`KtslUQ<_bgfwfNS#k}g<kf;Z0=7`9+dF)GdRUURz6j;048Gi#-PR z=BT^#522Bhhg>A;&#u13ax4A)Uj4B+DVxz-`Nvr#pc4oIs;? z*kqwUvR<7*4rezWhm4d1rWq+&A1Od(V{gy<;@B}y&`BO)D>1Y5Kt%hN;yWqR>hAQ% zHp^CV-=jp3dMCOSaqd8^_0Q93y|v*RM_1Y5UqIWUxoc8_d}MrM3LK>WU@c@GsI`k>KKGKw>GSK| zEp|U@LT`91!+~0xGhb&9!`?Vo%IElY>*R|P&3Z0!Xq%Oj0ifC@l}ivInvO8|vUB-{ zNC-Lm{@zAu0r28#yb6U{rU!l21o;An&p>Z0`*ZT8sgsQHRDe>~HsP#yb@V9Ex&}fMW%Pg5?mTw9Xf9d^cWNrX~1rt1G>G0O$sGg7IMb&PYaI72TFot%se?{?sJ8x~(H?YK@V?vr{VEA`0;s}RcTfglnIb4!GQ*beFYAoQ!2kdN literal 0 HcmV?d00001 diff --git a/tests/files/tone22.mp3 b/tests/files/tone22.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..e1b1bb0a22eea0d4c035adb8cd8ca814daa726c6 GIT binary patch literal 4511 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 r4_W`Ik-`Q6s$Lfeh;*@j|6(Eon;A0z%BFXuGZ literal 0 HcmV?d00001 diff --git a/tests/files/tone_mono.opus b/tests/files/tone_mono.opus new file mode 100644 index 0000000000000000000000000000000000000000..dee3522085aa70198f9e3347c132b18ddea87259 GIT binary patch literal 3874 zcmeH~cQo8<8pmfu?}j2cF}Y6yZG zVF-fgT@n(#4|e88cF$(_uRZsi-9PSge*O16-}ik#=X>6B9s?(*n*b8PS-hudn; z3Bn;RPD}w2P6vdYhrNTB(!c!tu6QO7ASx1PV>!;GEorBws;&-Gg{#R+%g9P!lan{I zQP)z}(9qD<)PlqHwRLo~f4T&O)!+d$y9~kr0G-J&t{TE4t4$RY=8h)C2JA_lD}tH7 zppQxFji1d=LSIr^3pky%)k5pB*pi0QkEMd3%R7!=lONC`#4b?Djh4I7-3dy+c}IS? zP}ESia_jdL`t2ACi0lUMvo zSB46DY_ARSJcgx6Bm--j&NP6^X000_$!ezgHk8HHeD!|Hnc~pWBE`E#XwLh;&j~*F z5ub9(mgoorJ9?-`q+AAiLZ!^jKo`Fe7ebhXVdd^~1V>CoY#^JlFg1J6J34iYb`uSk z`e8z<-$&^;x)pH<@C|v~gI}?bZwR+t_|V><<#(8`zN5efUVbNN95>JPUTTxv0pYrVP_g0sfz+h` zSTO3um6_>F;U4|iH%k3POAkns%Zf+L9JpRX1~_}&i$RAij9Y2Al8X$N*Q!14O(eQi zuH+v9&vf2nY_19|9AF9J;L0isvXSKlYr%wYg&vcefwZi~n*>EOZVDiPS=@LUsHQ@4Ucj^=mhsv$A*h_n*Q-_RdbyY8xdsa|@8evL@ znhP0`iDy;DbFG?oEP$mbGLO;}%7iuA^)=F&+}L+*oUX;cy=BC7-(!qZ=R zWK1X`^5|@6zdA{Y5}ZIbAJ|QElYbc66H!=hqYZEJ!2l<=vv^-G|t^&tcFaP!m%b_FT`C{ntr}@EVYBzIT&+%SQHFJenRRL1I zJZ{|C>ac+;!4530QMW&c*xS|ifJY3(oJv}ca_r!}=U_vze&z6M`^r(iiSS`zcb}f< zHUm#fq!Z1qRjxD#J4$zRvmLKji;d+i(_si36xz-3piHWJ{VjVSN1rwXmvqIGiZAYI zS0)m3L7QF#k%pW* zUEN72^FPl-5fO+nap`qu!wGQ;32if%A-0(7+DYn*6lW}YD&M=|Ck#!-7?`#WBP-w1 zZ8U+7a_A|lUdqW0$L~(8e(GkuA7}qnG;uxD@-%S0eK%Y<5_RvC?r&l&b*;*uDW#vZ zB-MZU;?fY5V^j;U7wVHc#L*%LcG8AC*gR5fZRh=*f-&go!aJWEj87)3J;lT&oYi|- zkM+#;V8YJt04vM{nb=~mc;JqD7 zv-5wb!-YkUa`DG?v@|vSjnb+!xY}Si$&{t89Z)}v3d%u$tje5{p;jp(>Ug1(sf(kB-l6O&RQ%V_GOm!@p8DyQOG=j2_XFSt@Io3 z^)0*KvzN?7jq*XQi$_O49iC8>@L|W=vCdrH(_*XBA~7PzYA?l6KEvGLG5^m#@e_C~ z1+3Nc+P6gJx;MVGS^iG^G|f7rl{#vazN1ecOMDT@`o;tb+u?*gtbyo9EL$M2W@d6V z4@Ou(3cI>2FIJo^uVefOWRuuqAk}JrkQFC)XZKcAV_u9WZ32(%z|pQB_oj3$U?B>= zZy(D{qmXV4%(d{)La>p>R7U2Y8hh^MdECn5Vr7xT=Z+r@g~9)Ut(R$nfOQ;xKet@B z)RG%#pQ9#}8qc*9$KzU0zboU>!!|UC zh+CDtg{e6^m}qGBZ)%>?N|yprUXhQkCk4x0H>kir^U5+))96644Qd6+oi>rJRrvX` z@2?~vWbr2)PRFN>mhZIVgc($sl^+T z&q4efOBsFzy!OZGAYYxSnEFoYXJlX5D+H2;VEL`M5pYR-;-ExC9(pZ4Fam49$yU6* zzw@lOuCSegZ1#t#vr*HM@%iiBkkq23EI|fXHho(P0&2NCbBorCSKdg|s@jfH;t6-F z`~6_uH&Q|E-3)oQ)Ba*L`Q;?kZJ0L%iA@9wp{WFpOWbywo@`XPU z`Cl&o%jG{dmj6qa|IrVU)-@5DKtd4v!E=QBh3zdRpzmmR`T$D}-7ec8iQ>Mm;^70U zRQD55pYE$zE&je4kM4ejPvh*-qea28jJv&S{0LMueu~tyEm>PXw!41ww7F&I#*v}{ zerhtE1v1ecWvvf2_E8OyDHAZ&Ia*lQd}Le=!E}C!EWG7hA1IN@A-b<5w8Q*&HHTNd literal 0 HcmV?d00001 diff --git a/tests/flac.sakura b/tests/flac.sakura new file mode 100644 index 0000000..bed29b9 --- /dev/null +++ b/tests/flac.sakura @@ -0,0 +1,104 @@ +#! Contains the tests of FLAC: streams the tests make, of every kind of +#! subframe, channel assignment, and residual, decoded to exactly the samples +#! they were made of; of 24 bits, wasted bits, and blocks of every size; of six +#! channels mixed down; sought by a seek table and by searching; their loop +#! points read of their comments; and broken streams refused. +#! +#! Real encoders' files were checked apart from these: 31 of them, each decoded +#! to the samples its STREAMINFO's MD5 is of. + +import std::testing; +import malunal::audio; + +def no_comments(): span { + return span::::blank(); +} + +@test def decodes_every_kind_of_subframe_exactly(t: &mut tester): void { + val plans := every_kind(24, 576, 2); + val made := made_flac(2, 16, plans.span, false, false, no_comments()); + val read := audio::decode(made.bytes.span) else (e) { t.expects(false); return; }; + t.expects(read.rate == 48000 && read.channels == 2 && read.frames == 24 * 576); + t.expects(apart(read.samples.span, made.expected.span) == 0); +} + +@test def decodes_24_bits_wasted_and_blocks_of_every_size(t: &mut tester): void { + val sizes: u64[6] = [300, 1000, 64, 2048, 96, 777]; + val kinds: coding[2] = [coding::fixed, coding::lpc]; + var plans := vector::::new(); + var first: u64 = 0; + for i in 0..12u { + val block := sizes[i % 6]; + plans.append(frame_plan{ + first = first, block = block, kind = kinds[i % 2], order = 2 + (i % 3) as u32, wasted = 3, + partitions = block % 4 == 0 ? 2u : 0u, escape = i == 5, + }); + first += block; + } + val made := made_flac(1, 24, plans.span, true, false, no_comments()); + val read := audio::decode(made.bytes.span) else (e) { t.expects(false); return; }; + t.expects(read.channels == 1 && read.frames == first); + t.expects(apart(read.samples.span, made.expected.span) == 0); +} + +@test def mixes_six_channels_down(t: &mut tester): void { + val plans := every_kind(8, 512, 6); + val made := made_flac(6, 16, plans.span, false, false, no_comments()); + val read := audio::decode(made.bytes.span) else (e) { t.expects(false); return; }; + t.expects(read.channels == 2 && read.frames == 8 * 512); + var speakers: speaker[6]; + for c in 0..6u { + speakers[c] = audio::standard_speaker(6, c as u32); + } + var two := vector::::new(); + two.resize(read.frames * 2); + audio::downmix(made.expected.span, read.frames, speakers[:], two.slice); + t.expects(apart(read.samples.span, two.span) < 1e-6); +} + +@test def seeks_by_its_table_and_by_searching_its_headers(t: &mut tester): void { + for table in [false, true] { + val plans := every_kind(200, 1152, 2); + val made := made_flac(2, 16, plans.span, false, table, no_comments()); + var reading := audio::flac::decoder::open(made.bytes.span) else (e) { t.expects(false); return; }; + val total := reading.frames; + t.expects(total == 200 * 1152); + var piece := vector::::new(); + piece.resize(3000 * 2); + val targets: u64[8] = [0, 1, 1151, 1152, 50000, 123456, 230399, 230400]; + for &target in targets { + t.expects(reading.seek(target) is value(_)); + val count := reading.read(piece.slice) else (e) { t.expects(false); return; }; + val wanted: u64 = total - target < 3000 ? total - target : 3000; + t.expects(count == wanted); + t.expects(apart(piece.span[0:count * 2], made.expected.span[target * 2:count * 2]) == 0); + } + } +} + +@test def reads_where_it_loops_of_its_comments(t: &mut tester): void { + val comments: strview[3] = ["TITLE=tone", "LOOPSTART=1000", "loopend=5000"]; + val made := made_flac(1, 16, every_kind(10, 1024, 1).span, false, false, comments[:]); + val read := audio::decode(made.bytes.span) else (e) { t.expects(false); return; }; + t.expects(read.loop_points.start == 1000 && read.loop_points.end == 5000); + val plain := made_flac(1, 16, every_kind(4, 1024, 1).span, false, false, no_comments()); + val unlooped := audio::decode(plain.bytes.span) else (e) { t.expects(false); return; }; + t.expects(unlooped.loop_points.start == 0 && unlooped.loop_points.end == 0); +} + +@test def refuses_broken_flac(t: &mut tester): void { + # A byte of its last frame changed, so its CRC-16 is wrong. + var changed := made_flac(2, 16, every_kind(4, 576, 2).span, false, false, no_comments()); + changed.bytes[changed.bytes.length - 5] ^= 0x10; + t.expects(fails(audio::decode(changed.bytes.span), audio_error::malformed)); + + # Cut short, partway through its last frame. + var cut := made_flac(2, 16, every_kind(4, 576, 2).span, false, false, no_comments()); + cut.bytes.resize(cut.bytes.length - 40); + t.expects(fails(audio::decode(cut.bytes.span), audio_error::malformed)); + + # Not FLAC. + var other := made_flac(1, 16, every_kind(1, 576, 1).span, false, false, no_comments()); + other.bytes[3] = 'X' as u8; + t.expects(fails(audio::decode(other.bytes.span), audio_error::unrecognized)); +} diff --git a/tests/flacs.sakura b/tests/flacs.sakura new file mode 100644 index 0000000..83e75e5 --- /dev/null +++ b/tests/flacs.sakura @@ -0,0 +1,423 @@ +#! Contains FLAC streams made by a small encoder of the tests' own, of every +#! kind of subframe, channel assignment, and residual, and the frames each +#! decodes to, which, FLAC being lossless, are the samples it was made of. + +import std::math; +import malunal::audio; + +# Bits written highest first. +struct flac_bits { + var bytes: vector; + var byte: u32; + var held: u32; +} + +def flac_bits::new(): flac_bits { + return flac_bits{ bytes = vector::::new() }; +} + +def flac_bits::put(&mut this, value: u64, count: u32): void { + var k := count; + while k > 0 { + k--; + this.byte = (this.byte << 1) | ((value >> k) & 1) as u32; + this.held++; + if this.held == 8 { + this.bytes.append(this.byte as u8); + this.byte = 0; + this.held = 0; + } + } +} + +def flac_bits::signed(&mut this, value: i64, count: u32): void { + val masked := count >= 64 ? value as u64 : (value as u64) & (((1 as u64) << count) - 1); + this.put(masked, count); +} + +def flac_bits::align(&mut this): void { + while this.held != 0 { + this.put(0, 1); + } +} + +# How a channel of a frame is coded. +enum coding: u8 { constant, verbatim, fixed, lpc } + +# A frame to make: its first frame of the stream, its block, how its channels +# are assigned, and how each subframe is coded, of what order, of how many +# wasted bits, residual partitions, and whether those are raw. +struct frame_plan { + var first: u64; + var block: u64; + var assignment: u32; + var kind: coding; + var order: u32; + var wasted: u32; + var partitions: u32; # Their order. + var escape: bool; +} + +# The coefficients of the tests' linear prediction, of 12 bits shifted by 9, +# by its order. +def lpc_coefficients(order: u32): vector { + val all: i64[6] = [870, -410, 140, -90, 40, -20]; + var made := vector::::new(); + for j in 0..order as u64 { + made.append(all[j]); + } + return made; +} + +# The prediction of a sample by those before it. +def predicted(s: &vector, i: u64, kind: coding, order: u32): i64 { + if kind == coding::fixed { + return match order { + 0 => 0, + 1 => s[i - 1], + 2 => 2 * s[i - 1] - s[i - 2], + 3 => 3 * s[i - 1] - 3 * s[i - 2] + s[i - 3], + else => 4 * s[i - 1] - 6 * s[i - 2] + 4 * s[i - 3] - s[i - 4], + }; + } + val c := lpc_coefficients(order); + var sum: i64 = 0; + for j in 0..order as u64 { + sum += c[j] * s[i - 1 - j]; + } + return sum >> 9; +} + +# Writes a subframe of samples, of so many bits a sample. +def put_subframe(w: &mut flac_bits, samples: &vector, bits: u32, plan: &frame_plan): void { + val block := samples.length; + var kind := plan.kind; + var code: u32 = 1; + if kind == coding::constant { + code = 0; + } else if kind == coding::fixed { + code = 8 + plan.order; + } else if kind == coding::lpc { + code = 31 + plan.order; + } + w.put(0, 1); + w.put(code, 6); + # Wasted bits: the samples are all multiples of their power of two. + var shifted := vector::::new(); + for i in 0..block { + shifted.append(samples[i] >> plan.wasted); + } + if plan.wasted > 0 { + w.put(1, 1); + w.put(0, plan.wasted - 1); + w.put(1, 1); + } else { + w.put(0, 1); + } + val width := bits - plan.wasted; + if kind == coding::constant { + w.signed(shifted[0], width); + return; + } + if kind == coding::verbatim { + for i in 0..block { + w.signed(shifted[i], width); + } + return; + } + val order := plan.order as u64; + for i in 0..order { + w.signed(shifted[i], width); + } + if kind == coding::lpc { + w.put(11, 4); + w.signed(9, 5); + val c := lpc_coefficients(plan.order); + for j in 0..order { + w.signed(c[j], 12); + } + } + var residual := vector::::new(); + for i in order..block { + residual.append(shifted[i] - predicted(&shifted, i, kind, plan.order)); + } + # The residual: partitions of Rice codes of a parameter each, or raw. + w.put(1, 2); + w.put(plan.partitions, 4); + val count: u64 = (1 as u64) << plan.partitions; + val each := block / count; + var at: u64 = 0; + for p in 0..count { + val length := p == 0 ? each - order : each; + var largest: u64 = 0; + for i in 0..length { + largest = math::max(largest, math::abs(residual[at + i]) as u64); + } + if plan.escape { + var raw: u32 = 1; + while ((1 as u64) << (raw - 1)) <= largest { + raw++; + } + w.put(31, 5); + w.put(raw, 5); + for i in 0..length { + w.signed(residual[at + i], raw); + } + } else { + var k: u32 = 0; + while ((1 as u64) << (k + 1)) <= largest && k < 20 { + k++; + } + w.put(k, 5); + for i in 0..length { + val v := residual[at + i]; + val folded: u64 = v >= 0 ? (v as u64) << 1 : ((-v) as u64 << 1) - 1; + val high := folded >> k; + w.put(0, high as u32); + w.put(1, 1); + w.put(folded, k); + } + } + at += length; + } +} + +# The CRC-8 and CRC-16 of FLAC's frames. +def test_crc8(bytes: span): u32 { + var crc: u32 = 0; + for i in 0..bytes.length { + crc = crc ^ bytes[i] as u32; + for _ in 0..8 { + crc = (crc & 0x80) != 0 ? ((crc << 1) ^ 0x07) & 0xFF : (crc << 1) & 0xFF; + } + } + return crc; +} + +def test_crc16(bytes: span): u32 { + var crc: u32 = 0; + for i in 0..bytes.length { + crc = crc ^ ((bytes[i] as u32) << 8); + for _ in 0..8 { + crc = (crc & 0x8000) != 0 ? ((crc << 1) ^ 0x8005) & 0xFFFF : (crc << 1) & 0xFFFF; + } + } + return crc; +} + +# Writes a frame of each channel's samples of the stream, from its first. +def put_frame(out: &mut vector, channels: &vector>, bits: u32, plan: &frame_plan, variable: bool, number: u64): void { + var w := flac_bits::new(); + w.put(0xFFF8 | (variable ? 1u : 0u), 16); + w.put(7, 4); # its block size, 16 bits, after the number + w.put(0, 4); # its rate, the stream's + w.put(plan.assignment, 4); + w.put(bits == 16 ? 4u : bits == 24 ? 6u : 0u, 3); + w.put(0, 1); + # The number, as UTF-8 codes it. + if number < 0x80 { + w.put(number, 8); + } else if number < 0x800 { + w.put(0xC0 | (number >> 6), 8); + w.put(0x80 | (number & 0x3F), 8); + } else if number < 0x10000 { + w.put(0xE0 | (number >> 12), 8); + w.put(0x80 | ((number >> 6) & 0x3F), 8); + w.put(0x80 | (number & 0x3F), 8); + } else { + w.put(0xF0 | (number >> 18), 8); + w.put(0x80 | ((number >> 12) & 0x3F), 8); + w.put(0x80 | ((number >> 6) & 0x3F), 8); + w.put(0x80 | (number & 0x3F), 8); + } + w.put(plan.block - 1, 16); + w.put(test_crc8(w.bytes.span) as u64, 8); + + # Each channel, of the frame's samples, a side channel made of two. + var parts := vector::>::new(); + for c in 0..channels.length { + var part := vector::::new(); + for i in 0..plan.block { + part.append(channels[c][plan.first + i]); + } + parts.append(move(part)); + } + if plan.assignment >= 8 { + var a := vector::::new(); + var b := vector::::new(); + for i in 0..plan.block { + val l := parts[0][i]; + val r := parts[1][i]; + if plan.assignment == 8 { + a.append(l); + b.append(l - r); + } else if plan.assignment == 9 { + a.append(l - r); + b.append(r); + } else { + a.append((l + r) >> 1); + b.append(l - r); + } + } + parts[0] = move(a); + parts[1] = move(b); + } + for c in 0..parts.length { + val side := (plan.assignment == 8 && c == 1) || (plan.assignment == 9 && c == 0) || (plan.assignment == 10 && c == 1); + put_subframe(&mut w, &parts[c], side ? bits + 1 : bits, plan); + } + w.align(); + val crc := test_crc16(w.bytes.span); + w.put(crc as u64, 16); + out.extend(w.bytes.span); +} + +# A FLAC stream made by the tests: its bytes, and the frames it decodes to. +struct flac_stream { + var bytes: vector; + var expected: vector; + var channels: vector>; +} + +# The samples of a channel: two sines and noise, of so many bits, or a run all +# the same where `flat` says, as a constant subframe codes. +def flac_samples(channel: u64, count: u64, bits: u32, wasted: u32): vector { + var made := vector::::new(); + var noise: u64 = 0x9E3779B97F4A7C15 + channel; + val peak := ((1 as i64) << (bits - 2)) as f64; + for i in 0..count { + noise = math::wrapping_add(math::wrapping_mul(noise, 6364136223846793005), 1442695040888963407); + val wobble := ((noise >> 40) & 0xFFF) as f64 / 4096.0 - 0.5; + val x := i as f64; + var v := math::round(peak * (0.6 * math::sin(x * (0.01 + 0.003 * channel as f64)) + 0.3 * math::sin(x * 0.17) + 0.05 * wobble)) as i64; + v = (v >> wasted) << wasted; + made.append(v); + } + return made; +} + +# Makes a FLAC stream of channels of samples, coded as the plans say, its +# blocks fixed in size, numbered by frame, or varying, numbered by sample; with +# a seek table where `table` says, and comments where `comments` gives them. +def made_flac(channels: u32, bits: u32, plans: span, variable: bool, table: bool, comments: span): flac_stream { + var total: u64 = 0; + var most: u64 = 0; + var least: u64 = 0xFFFF; + for &plan in plans { + total = math::max(total, plan.first + plan.block); + most = math::max(most, plan.block); + least = math::min(least, plan.block); + } + var samples := vector::>::new(); + for c in 0..channels as u64 { + samples.append(flac_samples(c, total, bits, plans[0].wasted)); + # A block coded constant is all its first sample. + for &plan in plans { + continue if plan.kind != coding::constant; + for i in plan.first..plan.first + plan.block { + samples[c][i] = samples[c][plan.first]; + } + } + } + + var out := vector::::new(); + for &letter in ['f', 'L', 'a', 'C'] { + out.append(letter as u8); + } + # STREAMINFO, then the seek table and comments where asked, the last marked. + var info := flac_bits::new(); + info.put(variable ? least : most, 16); + info.put(most, 16); + info.put(0, 24); + info.put(0, 24); + info.put(48000, 20); + info.put((channels - 1) as u64, 3); + info.put((bits - 1) as u64, 5); + info.put(total, 36); + info.put(0, 64); + info.put(0, 64); + val blocks := 1 + (table ? 1u : 0u) + (comments.length > 0 ? 1u : 0u); + out.append((blocks == 1 ? 0x80 : 0) as u8); + out.append(0); + out.append(0); + out.append(34); + out.extend(info.bytes.span); + + # The frames, written first, so the seek table knows where each is. + var frames := vector::::new(); + var starts := vector::::new(); + for i in 0..plans.length { + starts.append(frames.length); + put_frame(&mut frames, &samples, bits, &plans[i], variable, variable ? plans[i].first : i); + } + if table { + var points := flac_bits::new(); + for i in 0..plans.length { + continue if i % 3 != 0; + points.put(plans[i].first, 64); + points.put(starts[i], 64); + points.put(plans[i].block, 16); + } + points.put(0xFFFFFFFFFFFFFFFF, 64); # a placeholder, of none + points.put(0, 64); + points.put(0, 16); + val last := comments.length == 0; + out.append((last ? 0x83 : 3) as u8); + out.append((points.bytes.length >> 16) as u8); + out.append((points.bytes.length >> 8) as u8); + out.append(points.bytes.length as u8); + out.extend(points.bytes.span); + } + if comments.length > 0 { + var block := vector::::new(); + put_le(&mut block, 4); + for &letter in ['t', 'e', 's', 't'] { + block.append(letter as u8); + } + put_le(&mut block, comments.length as u32); + for &each in comments { + put_le(&mut block, each.length as u32); + for i in 0..each.length { + block.append(each[i] as u8); + } + } + out.append(0x84); + out.append((block.length >> 16) as u8); + out.append((block.length >> 8) as u8); + out.append(block.length as u8); + out.extend(block.span); + } + out.extend(frames.span); + + # What it decodes to: the samples, as floats. + var expected := vector::::new(); + val scale := 1.0 / ((1 as u64) << (bits - 1)) as f64; + for i in 0..total { + for c in 0..channels as u64 { + expected.append((samples[c][i] as f64 * scale) as f32); + } + } + return flac_stream{ bytes = move(out), expected = move(expected), channels = move(samples) }; +} + +def put_le(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); +} + +# Plans of every kind of subframe and channel assignment in turn, a block each +# of so many frames. +def every_kind(count: u64, block: u64, channels: u32): vector { + val kinds: coding[4] = [coding::constant, coding::verbatim, coding::fixed, coding::lpc]; + var made := vector::::new(); + for i in 0..count { + var plan := frame_plan{ first = i * block, block = block, kind = kinds[i % 4], partitions = (i % 3) as u32, escape = i % 5 == 4 }; + plan.order = plan.kind == coding::fixed ? ((i / 4) % 5) as u32 : plan.kind == coding::lpc ? 1 + ((i / 4) % 6) as u32 : 0u; + val stereo: u32[4] = [1, 8, 9, 10]; + plan.assignment = channels == 2 ? stereo[i % 4] : channels - 1; + made.append(plan); + } + return made; +} 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..5a29ab2 --- /dev/null +++ b/tests/mixer.sakura @@ -0,0 +1,230 @@ +#! Contains the tests of `mixer`: voices mixed at their gains, panned, ramped +#! as they change, ended or looped at their sounds' ends or loop points, +#! resampled and pitched, faded, on buses, streamed as they play, and sought. + +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.span) else (e) { t.expects(false); return; }; + var whole := audio::decode(made.bytes.span) 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.span, from_sound.span) < 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.span) 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))); +} +# A sound of one channel, each frame its place over 1000. +def ramp(frames: u64, looped: loop_range): sound { + var samples := vector::::new(); + for i in 0..frames { + samples.append(i as f32 / 1000); + } + return sound{ rate = 48000, channels = 1, samples = move(samples), loop_points = looped }; +} + +@test def loops_between_its_sounds_loop_points(t: &mut tester): void { + var m := mixer::new(48000); + val id := m.add(ramp(1000, loop_range{ start = 200, end = 600 })); + val v := m.play(id, playback{ pan = -1, looping = true }); + val out := mixed(&mut m, 1400); + t.expects(math::abs(out[2 * 599] - 0.599) < 1e-6 && math::abs(out[2 * 600] - 0.2) < 1e-6); + t.expects(math::abs(out[2 * 999] - 0.599) < 1e-6 && math::abs(out[2 * 1000] - 0.2) < 1e-6); + t.expects(math::abs(m.position(v) - 200.0 / 48000) < 1e-9); + # Not looping, it plays to its end. + m.stop(v); + val once := m.play(id, playback{ pan = -1 }); + val whole := mixed(&mut m, 1001); + t.expects(math::abs(whole[2 * 999] - 0.999) < 1e-6 && !m.playing(once)); + + # Streamed, it loops so too, as the decoded sound does. + val comments: strview[2] = ["LOOPSTART=1000", "LOOPEND=5000"]; + val made := made_flac(2, 16, every_kind(10, 1024, 2).span, false, false, comments[:]); + val streamed := m.add_streamed(made.bytes.span) else (e) { t.expects(false); return; }; + val decoded := m.add(audio::decode(made.bytes.span) else (e) { t.expects(false); return; }); + m.stop_all(); + val a := m.play(streamed, playback{ looping = true }); + val from_stream := mixed(&mut m, 13000); + m.stop(a); + val b := m.play(decoded, playback{ looping = true }); + val from_sound := mixed(&mut m, 13000); + t.expects(apart(from_stream.span, from_sound.span) == 0); + t.expects(from_sound[2 * 5000] == made.expected[2 * 1000] && from_sound[2 * 9000] == made.expected[2 * 1000]); + t.expects(math::abs(m.position(b) - 1000.0 / 48000) < 1e-9); +} + +@test def seeks_decoded_and_streamed_voices(t: &mut tester): void { + val made := made_flac(2, 16, every_kind(100, 1152, 2).span, false, true, no_comments()); + var m := mixer::new(48000); + val streamed := m.add_streamed(made.bytes.span) else (e) { t.expects(false); return; }; + val decoded := m.add(audio::decode(made.bytes.span) else (e) { t.expects(false); return; }); + for &id in [streamed, decoded] { + val v := m.play(id); + _ = mixed(&mut m, 100); + t.expects(m.seek(v, 1.0) is value(_)); + val out := mixed(&mut m, 2000); + t.expects(apart(out.span, made.expected.span[48000 * 2:4000]) == 0); + t.expects(math::abs(m.position(v) - (48000.0 + 2000) / 48000) < 1e-9); + m.stop(v); + } +} +@test def delays_voices_and_moves_silent_ones_on_unheard(t: &mut tester): void { + var m := mixer::new(48000); + val id := m.add(ramp(1000, loop_range{})); + # Heard 0.002 s, 96 frames, late. + _ = m.play(id, playback{ pan = -1, delay = 0.002 }); + val late := mixed(&mut m, 200); + t.expects(late[2 * 95] == 0 && late[2 * 96] == 0 && math::abs(late[2 * 97] - 0.001) < 1e-6); + m.stop_all(); + + # Silent, it moves on as it would play, and is heard from there. + val v := m.play(id, playback{ pan = -1, silent = true }); + val quiet := mixed(&mut m, 300); + t.expects(quiet[2 * 299] == 0 && math::abs(m.position(v) - 300.0 / 48000) < 1e-9); + m.change(v, playback{ pan = -1 }); + val heard := mixed(&mut m, 300); + t.expects(math::abs(heard[2 * 299] - 0.599) < 1e-6 && heard[0] < 0.3); +} \ No newline at end of file diff --git a/tests/mp3.sakura b/tests/mp3.sakura new file mode 100644 index 0000000..68cc537 --- /dev/null +++ b/tests/mp3.sakura @@ -0,0 +1,86 @@ +#! Contains the tests of MP3: files of the tests' own, `tests/files`, tones +#! LAME encoded of sines, decoded to as many frames as the tones had, LAME's +#! delays cut, near their samples; sought anywhere, exactly as decoded from +#! the start; and what isn't MP3 refused. +#! +#! Real encoders' files were checked apart from these: 73 of them, and 54 LAME +#! made of every rate of MPEG-1, 2, and 2.5, of one channel and two, of 16 to +#! 160 kilobits a second, each decoded to as many frames as FFmpeg decodes it +#! to, every sample within 6.4e-6 of FFmpeg's. + +import std::io; +import std::math; +import std::testing; +import malunal::audio; + +# A file of the tests', its bytes, or none where it can't be read. +def test_file(name: strview): vector { + var made := vector::::new(); + val at := path::parse($"tests/files/{name}") else (_) { return made; }; + val read := io::read_file(&at) else (_) { return made; }; + made.extend(read.span); + return made; +} + +# How far a decoded tone strays from the sines of 0.4 it was made of, each +# channel its own, as the root of their squares' mean, past its first and last +# 2000 frames, where an encoder's filters ring. +def tone_error(read: &sound, frequencies: span): f64 { + val width := read.channels as u64; + var sum: f64 = 0; + var count: f64 = 0; + for i in 2000..read.frames - 2000 { + for c in 0..width { + val want := 0.4 * math::sin(math::tau * frequencies[c] * i as f64 / read.rate as f64); + val off := read.samples[i * width + c] as f64 - want; + sum += off * off; + count += 1; + } + } + return math::sqrt(sum / count); +} + +@test def decodes_mp3_to_the_tone_it_was_made_of(t: &mut tester): void { + val stereo := test_file("tone.mp3"); + val found := audio::format_of(stereo.span) else { t.expects(false); return; }; + t.expects(found == format::mp3); + val read := audio::decode(stereo.span) else (e) { t.expects(false); return; }; + t.expects(read.rate == 44100 && read.channels == 2 && read.frames == 66150); + val both: f64[2] = [440, 660]; + # LAME's own noise strays 0.014; a frame early or late, 0.026. + t.expects(tone_error(&read, both[:]) < 0.02); + + val mono := test_file("tone22.mp3"); + val low := audio::decode(mono.span) else (e) { t.expects(false); return; }; + t.expects(low.rate == 22050 && low.channels == 1 && low.frames == 22050); + val one: f64[1] = [330]; + t.expects(tone_error(&low, one[:]) < 0.02); +} + +@test def seeks_mp3_exactly(t: &mut tester): void { + val bytes := test_file("tone.mp3"); + val whole := audio::decode(bytes.span) else (e) { t.expects(false); return; }; + var reading := audio::mp3::decoder::open(bytes.span) else (e) { t.expects(false); return; }; + var piece := vector::::new(); + piece.resize(2000 * 2); + val total := whole.frames; + val targets: u64[6] = [0, 1, 1000, 30000, 66149, 66150]; + for &target in targets { + t.expects(reading.seek(target) is value(_)); + val count := reading.read(piece.slice) else (e) { t.expects(false); return; }; + val wanted: u64 = total - target < 2000 ? total - target : 2000; + t.expects(count == wanted); + t.expects(apart(piece.span[0:count * 2], whole.samples.span[target * 2:count * 2]) == 0); + } +} + +@test def refuses_what_isnt_mp3(t: &mut tester): void { + var bytes := test_file("tone.mp3"); + # An ID3 tag before nothing of MP3's. + val tagged: u8[16] = [73, 68, 51, 3, 0, 0, 0, 0, 0, 4, 97, 98, 99, 100, 101, 102]; + t.expects(fails(audio::decode(tagged[:]), audio_error::unrecognized)); + # Cut short, it gives what it has. + bytes.resize(bytes.length / 2); + val half := audio::decode(bytes.span) else (e) { t.expects(false); return; }; + t.expects(half.frames > 20000 && half.frames < 40000); +} diff --git a/tests/opus.sakura b/tests/opus.sakura new file mode 100644 index 0000000..b153897 --- /dev/null +++ b/tests/opus.sakura @@ -0,0 +1,186 @@ +#! Contains the tests of Ogg Opus: files of the tests' own, `tests/files`, +#! tones libopus encoded through FFmpeg of sines, of CELT in stereo, of SILK of +#! one channel at 16 kHz, and of one channel moving from hybrid frames to +#! SILK's to CELT's, each decoded near the sines it was made of; streams made +#! again of their packets, a page each, sought by halving their pages, and +#! played streamed as they play decoded; their heads' gain and their comments' +#! loop points read; and what isn't read refused. +#! +#! RFC 8251's test vectors were checked apart from these: each of the 12, +#! decoded in stereo, within one step of 16 bits of libopus's own output, those +#! of SILK alone exactly; decoded in one channel, 63 dB or nearer to libopus's +#! mix of it. + +import std::math; +import std::testing; +import malunal::audio; +import malunal::audio::ogg; + +# The packets of the first stream of an Ogg file. +def packets_of(bytes: span): vector> { + var made := vector::>::new(); + val first := ogg::page_at(bytes, 0) else (_) { return made; }; + var stream := ogg::packets::of(bytes, first.serial, 0); + var next := ogg::packet{}; + while true { + val had := stream.next(&mut next) else (_) { break; }; + break if !had; + var copy := vector::::new(); + copy.extend(next.data); + made.append(move(copy)); + } + return made; +} + +# An Opus head, of 48 kHz. +def opus_head(version: u8, channels: u8, pre_skip: u32, gain: i32, family: u8): vector { + var made := vector::::new(); + for c in "OpusHead" { + made.append(c as u8); + } + made.append(version); + made.append(channels); + made.append((pre_skip & 0xFF) as u8); + made.append((pre_skip >> 8) as u8); + put_u32(&mut made, 48000); + val bits := (gain < 0 ? gain + 65536 : gain) as u32; + made.append((bits & 0xFF) as u8); + made.append((bits >> 8) as u8); + made.append(family); + return made; +} + +# Opus comments. +def opus_tags(comments: span): vector { + var made := vector::::new(); + for c in "OpusTags" { + made.append(c as u8); + } + put_u32(&mut made, 5); + for c in "tests" { + made.append(c as u8); + } + put_u32(&mut made, comments.length as u32); + for comment in comments { + put_u32(&mut made, comment.length as u32); + for c in comment { + made.append(c as u8); + } + } + return made; +} + +# An Ogg Opus file of a head, comments, and packets of audio, a page each, +# their granule positions counted on but the last's, which is `end`. +def opus_file(head: span, tags: span, audio: span>, end: u64): vector { + var made := vector::::new(); + val none: u8[1] = [0]; + page_of(&mut made, 2, 0, 0, head, none[0:0]); + page_of(&mut made, 0, 0, 1, tags, none[0:0]); + var granule: u64 = 0; + for i in 0..audio.length { + val last := i + 1 == audio.length; + granule += 960; + page_of(&mut made, last ? 4 : 0, last ? end : granule, (i + 2) as u32, audio[i].span, none[0:0]); + } + return made; +} + +@test def decodes_opus_to_the_tone_it_was_made_of(t: &mut tester): void { + val stereo := test_file("tone.opus"); + val found := audio::format_of(stereo.span) else { t.expects(false); return; }; + t.expects(found == format::opus); + val read := audio::decode(stereo.span) else (e) { t.expects(false); return; }; + t.expects(read.rate == 48000 && read.channels == 2 && read.frames == 72000); + val both: f64[2] = [440, 660]; + t.expects(tone_error(&read, both[:]) < 0.005); + + # SILK's, and one moving between SILK's, hybrid, and CELT's frames. + val one: f64[1] = [330]; + for name in ["tone16.opus", "tone_mono.opus"] { + val bytes := test_file(name); + val low := audio::decode(bytes.span) else (e) { t.expects(false); return; }; + t.expects(low.rate == 48000 && low.channels == 1 && low.frames == 48000); + t.expects(tone_error(&low, one[:]) < 0.04); + } +} + +@test def seeks_opus_by_its_pages(t: &mut tester): void { + val original := test_file("tone.opus"); + val whole := audio::decode(original.span) else (e) { t.expects(false); return; }; + val packets := packets_of(original.span); + t.expects(packets.length == 78); + val bytes := opus_file(packets[0].span, packets[1].span, packets.span[2:76], 72000 + 312); + val again := audio::decode(bytes.span) else (e) { t.expects(false); return; }; + t.expects(again.frames == 72000 && apart(again.samples.span, whole.samples.span) == 0); + + # From half a second before, which settles near the tone decoded through. + var reading := audio::opus::decoder::open(bytes.span) else (e) { t.expects(false); return; }; + var piece := vector::::new(); + piece.resize(2000 * 2); + val targets: u64[6] = [0, 1, 1000, 30000, 71999, 72000]; + for &target in targets { + t.expects(reading.seek(target) is value(_)); + val count := reading.read(piece.slice) else (e) { t.expects(false); return; }; + val wanted: u64 = 72000 - target < 2000 ? 72000 - target : 2000; + t.expects(count == wanted); + t.expects(apart(piece.span[0:count * 2], whole.samples.span[target * 2:count * 2]) < 1e-3); + } + # A stream plays as the sound decoded whole. + var m := mixer::new(48000); + val streamed := m.add_streamed(bytes.span) else (e) { t.expects(false); return; }; + val decoded := m.add(audio::decode(bytes.span) else (e) { t.expects(false); return; }); + _ = m.play(streamed); + val from_stream := mixed(&mut m, 72010); + _ = m.play(decoded); + val from_sound := mixed(&mut m, 72010); + t.expects(apart(from_stream.span, from_sound.span) < 1e-6); +} + +@test def reads_opus_gain_and_loop_points(t: &mut tester): void { + val original := test_file("tone.opus"); + val whole := audio::decode(original.span) else (e) { t.expects(false); return; }; + val packets := packets_of(original.span); + # Louder by 6 dB, in Q8. + val head := opus_head(1, 2, 312, 6 * 256, 0); + val comments: strview[2] = ["LOOPSTART=4800", "LOOPLENGTH=9600"]; + val tags := opus_tags(comments[:]); + val bytes := opus_file(head.span, tags.span, packets.span[2:76], 72000 + 312); + val louder := audio::decode(bytes.span) else (e) { t.expects(false); return; }; + t.expects(louder.loop_points.start == 4800 && louder.loop_points.end == 14400); + val gain := math::pow(10.0, 6.0 / 20); + var worst: f64 = 0; + for i in 0..whole.samples.length { + worst = math::max(worst, math::abs(louder.samples[i] as f64 - whole.samples[i] as f64 * gain)); + } + t.expects(worst < 1e-5); +} + +@test def refuses_what_isnt_opus(t: &mut tester): void { + val original := test_file("tone.opus"); + val packets := packets_of(original.span); + val tags := opus_tags(no_comments()); + # More than two channels, a mapping family other than 0, and a later version. + val heads: u8[9] = [1, 3, 0, 1, 2, 1, 16, 2, 0]; + for k in 0..3 { + val head := opus_head(heads[k * 3], heads[k * 3 + 1], 312, 0, heads[k * 3 + 2]); + val bytes := opus_file(head.span, tags.span, packets.span[2:76], 72312); + t.expects(fails(audio::decode(bytes.span), audio_error::unsupported)); + } + # A packet of frames of no count. + var broken := vector::>::new(); + for i in 2u..10u { + var copy := vector::::new(); + copy.extend(packets[i].span); + broken.append(move(copy)); + } + broken[3].clear(); + broken[3].append(0xFB); + broken[3].append(0x00); + val bad := opus_file(packets[0].span, tags.span, broken.span, 8 * 960); + t.expects(fails(audio::decode(bad.span), audio_error::malformed)); + # Cut short, partway through its last page. + var cut := test_file("tone.opus"); + cut.truncate(); + t.expects(fails(audio::decode(cut.span), audio_error::malformed)); +} diff --git a/tests/output.sakura b/tests/output.sakura new file mode 100644 index 0000000..4b9c005 --- /dev/null +++ b/tests/output.sakura @@ -0,0 +1,65 @@ +#! Contains the tests of `audio_output`: one of no device, mixed as the test +#! asks; the system's default device, where there is one; and the system's +#! devices listed, one opened by its name, and a name of none refused. + +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); +} + +@test def opens_a_device_by_its_name(t: &mut tester): void { + val devices := audio_output::devices(); + var defaults: u32 = 0; + for &each in devices { + t.expects(each.name.length > 0 && each.id.length > 0); + if each.is_default { + defaults++; + } + } + t.expects(defaults <= 1); + t.expects(fails(audio_output::open(0.02, "no device is named this"), audio_error::no_device)); + # A machine of no audio device, as a build server, has none to open. + return if devices.empty; + var out := audio_output::open(0.02, devices[0].name.span) else (e) { + t.expects(false); + return; + }; + 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..db66060 --- /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.span, body.span); +} + +# 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..9486633 --- /dev/null +++ b/tests/sounds.sakura @@ -0,0 +1,60 @@ +#! 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("FLAC").unwrap() == audio::format::flac); + t.expects(audio::format_named("mp3").unwrap() == audio::format::mp3); + t.expects(audio::format_named("aiff") 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..24c4201 --- /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 count := residues.length; + val sizes: u64[2] = [64, 256]; + var centers := vector::::new(); + var center := sizes[pattern[(0) % 9] ? 1 : 0] / 2; + for k in 0..count { + if k > 0 { + center += sizes[pattern[(k - 1) % 9] ? 1 : 0] / 4 + sizes[pattern[(k) % 9] ? 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) % 9]; + 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) % 9]; + val after_short := long && k + 1 < count && !pattern[(k + 1) % 9]; + 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..e08f306 --- /dev/null +++ b/tests/streams.sakura @@ -0,0 +1,204 @@ +#! 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. +# @param count How many packets of audio, the pattern of blocks again and again. +# @param looped Whether its comments say it loops, from frame 100 for 300. +def made_vorbis(channels: u32, trimmed: u64, floor_zero: bool = false, count: u64 = 9, looped: bool = false): made_stream { + val sizes: u64[2] = [64, 256]; + + # 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(4, 32); + comment.text("test"); + comment.put(looped ? 3 : 0, 32); + if looped { + for &each in ["TITLE=tone", "LoopStart=100", "LOOPLENGTH=300"] { + comment.put(each.length as u32, 32); + comment.text(each); + } + } + 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) % 9]; + 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) % 9] ? 1 : 0, 1); + w.put(k + 1 == count || pattern[(k + 1) % 9] ? 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.span, span::::blank()); + sequence++; + val comments := comment.finish(); + val setups := setup.finish(); + page_of(&mut bytes, 0, 0, sequence, comments.span, setups.span); + 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) % 9] ? 1 : 0] / 4 + sizes[pattern[(j) % 9] ? 1 : 0] / 4; + } + lace(&mut lacing, packets[j].length); + body.extend(packets[j].span); + } + val last := end == count; + page_laced(&mut bytes, last ? 4 : 0, last ? decoded - trimmed : decoded, sequence, lacing.span, body.span); + 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..81f7d17 --- /dev/null +++ b/tests/vorbis.sakura @@ -0,0 +1,100 @@ +#! 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; sought anywhere; their loop points read of their comments; 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.span) 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.span, made.expected.span) < 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.span) else (e) { t.expects(false); return; }; + t.expects(read.channels == 1 && read.frames == made.expected.length); + t.expects(apart(read.samples.span, made.expected.span) < 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.span) else (e) { t.expects(false); return; }; + t.expects(read.frames == made.expected.length / 2); + t.expects(apart(read.samples.span, made.expected.span) < 1e-4); + val opened := audio::vorbis::decoder::open(made.bytes.span) 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.span) 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.span, made.expected.span) < 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.span), 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.span), audio_error::malformed)); + + # A floor of type 0. + val old := made_vorbis(1, 0, true); + t.expects(fails(audio::decode(old.bytes.span), audio_error::unsupported)); + + # An Ogg file of something besides Vorbis. + var other := vector::::new(); + page_of(&mut other, 2, 0, 0, "\x80theora", span::::blank()); + t.expects(fails(audio::decode(other.span), audio_error::unrecognized)); +} + +@test def seeks_anywhere_in_a_stream(t: &mut tester): void { + val made := made_vorbis(2, 0, false, 300); + var reading := audio::vorbis::decoder::open(made.bytes.span) else (e) { t.expects(false); return; }; + val total := made.expected.length / 2; + t.expects(reading.frames == total); + var piece := vector::::new(); + piece.resize(2000 * 2); + val targets: u64[7] = [0, 10, 600, 5000, 12345, total - 100, total]; + for &target in targets { + t.expects(reading.seek(target) is value(_)); + val count := reading.read(piece.slice) else (e) { t.expects(false); return; }; + val wanted: u64 = total - target < 2000 ? total - target : 2000; + t.expects(count == wanted); + t.expects(apart(piece.span[0:count * 2], made.expected.span[target * 2:count * 2]) < 1e-4); + } +} + +@test def reads_where_a_stream_loops_of_its_comments(t: &mut tester): void { + val made := made_vorbis(1, 0, false, 9, true); + val read := audio::decode(made.bytes.span) else (e) { t.expects(false); return; }; + t.expects(read.loop_points.start == 100 && read.loop_points.end == 400); + val plain := audio::decode(made_vorbis(1, 0).bytes.span) else (e) { t.expects(false); return; }; + t.expects(plain.loop_points.start == 0 && plain.loop_points.end == 0); +} \ No newline at end of file diff --git a/tests/wav.sakura b/tests/wav.sakura new file mode 100644 index 0000000..6821a44 --- /dev/null +++ b/tests/wav.sakura @@ -0,0 +1,145 @@ +#! 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.span) else (_) { t.expects(false); return; }; + t.expects(back.rate == 44100 && back.channels == 1 && back.frames == tone.frames); + t.expects(apart(back.samples.span, tone.samples.span) == 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.span) else (_) { t.expects(false); return; }; + t.expects(apart(rounded.samples.span, tone.samples.span) < 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.span) 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.span) 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.span) 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.span) 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.span) 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.span) 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.span) 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.span), 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.span), audio_error::malformed)); + val wrong := wav_of(1, 2, 8000, 12, zeros[:]); + t.expects(fails(audio::decode(wrong.span), 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; +} + +@test def keeps_where_a_sound_loops_in_a_sampler_chunk(t: &mut tester): void { + var looped := sound::tone(440, 0.1); + looped.loop_points = loop_range{ start = 480, end = 4000 }; + val bytes := audio::wav::encode(&looped) else (e) { t.expects(false); return; }; + val read := audio::decode(bytes.span) else (e) { t.expects(false); return; }; + t.expects(read.loop_points.start == 480 && read.loop_points.end == 4000 && read.frames == looped.frames); + val plain := audio::wav::encode(&sound::tone(440, 0.1)) else (e) { t.expects(false); return; }; + val unlooped := audio::decode(plain.span) else (e) { t.expects(false); return; }; + t.expects(unlooped.loop_points.end == 0 && plain.length == 44 + looped.frames * 2); +} \ No newline at end of file diff --git a/tools/bench.sakura b/tools/bench.sakura new file mode 100644 index 0000000..bf85018 --- /dev/null +++ b/tools/bench.sakura @@ -0,0 +1,82 @@ +#! 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 the +#! compressed files given as its arguments, 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.span); + }); + report("WAV, 16-bit, written and read", 10, wav); + + for at in args { + val named := path::parse(at) else (_) { exit(2); }; + val file := io::read_file(&named) else (e) { io::println($"unreadable: {e}"); exit(1); }; + val length := stream::open(file.span) else (e) { io::println($"{at}: not streamed: {e}"); exit(1); }; + val which := audio::format_of(file.span) else { exit(1); }; + val seconds := length.frames as f64 / length.rate as f64; + val whole := best(def(): void { + _ = audio::decode(file.span); + }); + report($"{which} decoded whole", seconds, whole); + val streamed := best(def(): void { + var m := mixer::new(48000); + val id := m.add_streamed(file.span) else (_) { return; }; + val v := m.play(id); + var frames := vector::::new(); + frames.resize(480 * 2); + while m.playing(v) { + m.mix(frames.slice); + } + }); + report($"{which} streamed, at 48 kHz", seconds, streamed); + } +}