#! 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); } }