|
1 | | -pub fn add(left: u64, right: u64) -> u64 { |
2 | | - left + right |
| 1 | +use std::{ |
| 2 | + net::{Ipv4Addr, SocketAddr, ToSocketAddrs, UdpSocket}, |
| 3 | + process::{Child, Command}, |
| 4 | +}; |
| 5 | + |
| 6 | +pub const HANDSHAKE: [u8; 4] = [0x43, 0x41, 0x57, 0x0]; |
| 7 | + |
| 8 | +// Based on the max number of bytes that can somewhat reliably be sent over UDP (508) divided by 4 |
| 9 | +// as we'll be sending f32's. That gives us 127, but since we're actually sending pairs of f32's, |
| 10 | +// reduce this to an even number. |
| 11 | +const MAX_SAMPLES_TO_SEND: usize = 126; |
| 12 | + |
| 13 | +// TODO |
| 14 | +const PROGRAM_NAME: &str = "/Users/s/src/caw/target/release/caw_viz_udp_app"; |
| 15 | + |
| 16 | +fn wait_for_handshake(socket: &UdpSocket) -> anyhow::Result<SocketAddr> { |
| 17 | + let mut buf = [0; 8]; |
| 18 | + loop { |
| 19 | + let (size, client_addr) = socket.recv_from(&mut buf)?; |
| 20 | + if size == HANDSHAKE.len() && buf[0..HANDSHAKE.len()] == HANDSHAKE { |
| 21 | + return Ok(client_addr); |
| 22 | + } |
| 23 | + } |
| 24 | +} |
| 25 | + |
| 26 | +fn samples_to_ne_bytes(samples: &[f32], out: &mut Vec<u8>) { |
| 27 | + out.clear(); |
| 28 | + for sample in samples { |
| 29 | + out.extend_from_slice(&sample.to_ne_bytes()); |
| 30 | + } |
| 31 | +} |
| 32 | + |
| 33 | +fn samples_from_ne_bytes(bytes: &[u8], out: &mut Vec<f32>) { |
| 34 | + if bytes.len() % 4 != 0 { |
| 35 | + log::error!( |
| 36 | + "Received a buffer of bytes that is not a multiple of 4 bytes in length (length is {}).", |
| 37 | + bytes.len() |
| 38 | + ); |
| 39 | + } |
| 40 | + out.clear(); |
| 41 | + let mut buf = [0; 4]; |
| 42 | + for w in bytes.chunks_exact(4) { |
| 43 | + buf.copy_from_slice(w); |
| 44 | + out.push(f32::from_ne_bytes(buf)); |
| 45 | + } |
| 46 | +} |
| 47 | + |
| 48 | +fn start_client_app(socket: &UdpSocket) -> anyhow::Result<Child> { |
| 49 | + let mut command = Command::new(PROGRAM_NAME); |
| 50 | + command.args(["--server".to_string(), socket.local_addr()?.to_string()]); |
| 51 | + Ok(command.spawn()?) |
| 52 | +} |
| 53 | + |
| 54 | +pub struct VizUdpServer { |
| 55 | + socket: UdpSocket, |
| 56 | + buf: Vec<u8>, |
3 | 57 | } |
4 | 58 |
|
5 | | -#[cfg(test)] |
6 | | -mod tests { |
7 | | - use super::*; |
| 59 | +impl VizUdpServer { |
| 60 | + pub fn new() -> anyhow::Result<Self> { |
| 61 | + let socket = UdpSocket::bind((Ipv4Addr::UNSPECIFIED, 0))?; |
| 62 | + log::info!("Viz udp server address: {:?}", socket.local_addr()); |
| 63 | + let _client_process = start_client_app(&socket)?; |
| 64 | + let client_address = wait_for_handshake(&socket)?; |
| 65 | + log::info!("Viz udp client address: {:?}", client_address); |
| 66 | + socket.connect(client_address)?; |
| 67 | + socket.set_nonblocking(true)?; |
| 68 | + Ok(Self { |
| 69 | + socket, |
| 70 | + buf: Vec::new(), |
| 71 | + }) |
| 72 | + } |
| 73 | + |
| 74 | + pub fn send_samples(&mut self, samples: &[f32]) -> anyhow::Result<()> { |
| 75 | + for samples_chunk in samples.chunks(MAX_SAMPLES_TO_SEND) { |
| 76 | + samples_to_ne_bytes(samples_chunk, &mut self.buf); |
| 77 | + // TODO: gracefully handle case when the client dissapears |
| 78 | + let bytes_sent = self.socket.send(&self.buf)?; |
| 79 | + if bytes_sent != samples.len() { |
| 80 | + log::error!( |
| 81 | + "Failed to send all samples to viz udp client. Tried to send {}. Actually sent {}.", |
| 82 | + samples.len(), |
| 83 | + bytes_sent |
| 84 | + ); |
| 85 | + } |
| 86 | + } |
| 87 | + Ok(()) |
| 88 | + } |
| 89 | +} |
| 90 | + |
| 91 | +pub struct VizUdpClient { |
| 92 | + socket: UdpSocket, |
| 93 | + buf_raw: Vec<u8>, |
| 94 | + buf: Vec<f32>, |
| 95 | +} |
| 96 | + |
| 97 | +impl VizUdpClient { |
| 98 | + pub fn new<A: ToSocketAddrs>(server_address: A) -> anyhow::Result<Self> { |
| 99 | + let socket = UdpSocket::bind((Ipv4Addr::UNSPECIFIED, 0))?; |
| 100 | + socket.connect(server_address)?; |
| 101 | + assert_eq!(socket.send(&HANDSHAKE)?, HANDSHAKE.len()); |
| 102 | + socket.set_nonblocking(true)?; |
| 103 | + Ok(Self { |
| 104 | + socket, |
| 105 | + buf_raw: vec![0; 32768], |
| 106 | + buf: Vec::new(), |
| 107 | + }) |
| 108 | + } |
| 109 | + |
| 110 | + pub fn recv_sample(&mut self) -> anyhow::Result<bool> { |
| 111 | + match self.socket.recv(&mut self.buf_raw) { |
| 112 | + Ok(size) => { |
| 113 | + samples_from_ne_bytes(&self.buf_raw[0..size], &mut self.buf); |
| 114 | + Ok(true) |
| 115 | + } |
| 116 | + Err(e) => match e.kind() { |
| 117 | + std::io::ErrorKind::WouldBlock => Ok(false), |
| 118 | + _ => anyhow::bail!(e), |
| 119 | + }, |
| 120 | + } |
| 121 | + } |
8 | 122 |
|
9 | | - #[test] |
10 | | - fn it_works() { |
11 | | - let result = add(2, 2); |
12 | | - assert_eq!(result, 4); |
| 123 | + pub fn pairs(&self) -> impl Iterator<Item = (f32, f32)> { |
| 124 | + self.buf.chunks_exact(2).map(|c| (c[0], c[1])) |
13 | 125 | } |
14 | 126 | } |
0 commit comments