Initial Commit

This commit is contained in:
SoraKatadzuma committed 2026-11-14 15:37:01 -06:00
commit b5aa91db1d
64 files changed
+14785

No files matched your search

+100
View File
@@ -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<f32>, 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);
}
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+104
View File
@@ -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<strview> {
return span::<strview>::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::<frame_plan>::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::<f32>::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::<f32>::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));
}
+423
View File
@@ -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<u8>;
var byte: u32;
var held: u32;
}
def flac_bits::new(): flac_bits {
return flac_bits{ bytes = vector::<u8>::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<i64> {
val all: i64[6] = [870, -410, 140, -90, 40, -20];
var made := vector::<i64>::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<i64>, 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<i64>, 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::<i64>::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::<i64>::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<u8>): 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<u8>): 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<u8>, channels: &vector<vector<i64>>, 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::<vector<i64>>::new();
for c in 0..channels.length {
var part := vector::<i64>::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::<i64>::new();
var b := vector::<i64>::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<u8>;
var expected: vector<f32>;
var channels: vector<vector<i64>>;
}
# 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<i64> {
var made := vector::<i64>::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<frame_plan>, variable: bool, table: bool, comments: span<strview>): 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::<vector<i64>>::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::<u8>::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::<u8>::new();
var starts := vector::<u64>::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::<u8>::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::<f32>::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<u8>, 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<frame_plan> {
val kinds: coding[4] = [coding::constant, coding::verbatim, coding::fixed, coding::lpc];
var made := vector::<frame_plan>::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;
}
+10
View File
@@ -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 `--test TEXT` those whose name
#! holds the text.
import system;
import std::testing;
def main(args: span<strview>): void {
exit(tester::run(args));
}
+230
View File
@@ -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::<f32>::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<f32> {
var out := vector::<f32>::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::<f32>::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);
}
+86
View File
@@ -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<u8> {
var made := vector::<u8>::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>): 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::<f32>::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);
}
+186
View File
@@ -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<u8>): vector<vector<u8>> {
var made := vector::<vector<u8>>::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::<u8>::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<u8> {
var made := vector::<u8>::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<strview>): vector<u8> {
var made := vector::<u8>::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<u8>, tags: span<u8>, audio: span<vector<u8>>, end: u64): vector<u8> {
var made := vector::<u8>::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::<f32>::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::<vector<u8>>::new();
for i in 2u..10u {
var copy := vector::<u8>::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));
}
+65
View File
@@ -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::<f32>::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);
}
+108
View File
@@ -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<u8>;
var held: u32;
var count: u32;
}
def bit_writer::new(): bit_writer {
return bit_writer{ bytes = vector::<u8>::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<u8> {
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<u8>, 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<u8>, flags: u8, granule: u64, sequence: u32, one: span<u8>, two: span<u8>): void {
var lacing := vector::<u8>::new();
var body := vector::<u8>::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<u8>, flags: u8, granule: u64, sequence: u32, lacing: span<u8>, body: span<u8>): 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<u8>, value: u32): void {
for i in 0u..4u {
out.append((value >> (i * 8) as u32) as u8);
}
}
+60
View File
@@ -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);
}
+104
View File
@@ -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<f32>>): vector<f32> {
val count := residues.length;
val sizes: u64[2] = [64, 256];
var centers := vector::<u64>::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::<f64>::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::<f64>::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::<f32>::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;
}
+204
View File
@@ -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<u8>;
var expected: vector<f32>; # 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::<vector<u8>>::new();
var residues := vector::<vector<f32>>::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::<f32>::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::<u8>::new();
var sequence: u32 = 0;
val ident := id.finish();
page_of(&mut bytes, 2, 0, sequence, ident.span, span::<u8>::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::<u8>::new();
var lacing := vector::<u8>::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 };
}
+24
View File
@@ -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<T>(made: result<T, audio_error>, 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<f32>, b: span<f32>): 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;
}
+100
View File
@@ -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::<f32>::new();
var piece := vector::<f32>::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::<u8>::new();
page_of(&mut other, 2, 0, 0, "\x80theora", span::<u8>::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::<f32>::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);
}
+145
View File
@@ -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<u8>, extensible: bool = false, mask: u32 = 0): vector<u8> {
var out := vector::<u8>::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<u8>, value: strview): void {
for c in value {
out.append(c as u8);
}
}
def number(out: &mut vector<u8>, 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::<u8>::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<void, audio_error>, 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);
}