Skip to content

Instantly share code, notes, and snippets.

@boxofrox
Last active October 31, 2020 16:57
Show Gist options
  • Save boxofrox/d3e55e7e68ce5e39ff675d999e990e67 to your computer and use it in GitHub Desktop.
Save boxofrox/d3e55e7e68ce5e39ff675d999e990e67 to your computer and use it in GitHub Desktop.
Debugging streaming audio over TCP

Debugging sending audio over TCP from rust forums [1] and gist [2].

[1]: https://users.rust-lang.org/t/data-become-corrupted-through-tcp/35462/3
[2]: https://gist.github.com/solindev/bf4d89b7f8adc2949ba5e300b73cf083/raw/f934cc71c69230bcf6fabf493b9265b88195271a/sender.rs

Simplified the gist to test only the TCP connection with a sequence of numbers.

Setup

  1. Create a new project with cargo --bin --name project or some such.
  2. Create folder ./examples inside project.
  3. Copy sender.rs and receiver.rs into ./examples.

Run test on Linux

cd project
diff -u <(sleep 1; cargo run --example sender) <(cargo run --example receiver)

Notes

  1. Without sleep 1, sender will transmit numbers that are never received.
  2. With sleep 1, diff shows all bytes encoded and transfered without issue.
use std::io::Read;
use std::net::{TcpListener, TcpStream};
fn handle_connection(mut stream: TcpStream) {
loop {
let mut buffer: [u8; 5] = [0, 0, 0, 0, 0];
match stream.read_exact(&mut buffer) {
Ok(()) => {
let decoded: Option<f32> = bincode::deserialize(&buffer).unwrap();
let res : f32 = match decoded {
Some(x) => x,
_ => 0.0,
};
//eprintln!("{:?}\t{:?}", &buffer, res);
println!("{:?}", &buffer);
}
Err(error) => match error.kind() {
std::io::ErrorKind::UnexpectedEof => return,
_ => panic!("failed"),
}
}
}
}
fn main() {
let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
for stream in listener.incoming() {
handle_connection(stream.unwrap());
// eprintln!("stream closed");
break;
}
eprintln!("Done!");
}
use std::io::prelude::*;
use std::net::TcpStream;
fn main() -> Result<(), anyhow::Error> {
let mut stream = TcpStream::connect("127.0.0.1:7878")?;
for sample in (0..1024).map(|x| Some(x as f32)) {
//println!("{:?}", sample);
let encoded : Vec<u8> = bincode::serialize(&sample).unwrap();
let mut msg : [u8; 5] = [0,0,0,0,0];
for (i, item) in encoded.iter().enumerate() {
msg[i] = *item;
//stream.write(&[*item]);
}
println!("{:?}", msg);
stream.write_all(&msg).unwrap();
}
// eprintln!("Done!");
Ok(())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment